Flask应用单元测试断言E

2024-04-29 07:33:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我读了很长时间,但这是我第一次发帖。在

好的,所以我试着在Flask中对一个演示应用程序进行单元测试,我不知道我做错了什么。在

这些是我在一个名为经理.py

@app.route('/')
@app.route('/index')
def hello():
    return render_template('base.html')


@app.route('/hello/<username>')
def hello_username(username):
    return "Hello %s" % username 

第一条路线是装货基本.html模板呈现一个“hi”消息,该消息在单元测试中正常工作,但第二个路由得到一个断言错误。在

这是我的测试文件管理_测试.py:

^{pr2}$

此单元的输出为:

.F
======================================================================
FAIL: test_username (tests.manage_tests.ManagerTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Users/albertogg/Dropbox/code/Python/flask-bootstrap/tests/manage_tests.py", line 15, in test_username
    assert "Hello alberto" in rv.data
AssertionError

----------------------------------------------------------------------
Ran 2 tests in 0.015s

FAILED (failures=1)

我想知道你们能不能帮我!我做错了什么或者错过了什么?在

编辑

我做了这件事而且很管用


    class ManagerTestCase(unittest.TestCase):

    def setUp(self):
        self.app = app.test_client()

    def t_username(self, username):
        return self.app.get('/hello/%s' % (username), follow_redirects=True')
        # either that or the Advanced string formatting from the answer are working.

    def test_username(self):
        rv = self.t_username('alberto')
        assert "Hello alberto" in rv.data

    def test_empty_db(self):
        rv = self.app.get('/')
        assert 'hi' in rv.data


Tags: inpytestselfapphelloreturndef
1条回答
网友
1楼 · 发布于 2024-04-29 07:33:52

您应该将hello_username更改为以下内容:

@app.route('/hello/', methods=['POST'])
def hello_username():
    return "Hello %s" % request.form.get('username', 'nobody')

请确保from flask import request。在

还有一个例子,展示了它的工作原理:

^{2}$

你的测试应该是:

def test_username(self, username):
    return self.app.post('/hello', data={"username":username})

编辑
根据您的评论:

@app.route('/hello/<username>', methods=['POST'])
def hello_username(username):
    print request.args
    return "Hello %s" % username

但是,我不知道你为什么要用POST,因为这本质上是一个没有任何POST主体的POST。在

> curl -X POST -i 'http://localhost:2000/hello/alberto'           
HTTP/1.0 200 OK
Content-Type: text/html; charset=utf-8
Content-Length: 13
Server: Werkzeug/0.8.3 Python/2.7.2
Date: Fri, 21 Dec 2012 06:29:25 GMT

Hello alberto

在这种情况下,我将取消对POST数据的所有要求:

@app.route('/hello/<username>', methods=['POST'])
def hello_username(username):
    print request.args
    return "Hello %s" % username


> curl -i 'http://localhost:2000/hello/alberto'           
HTTP/1.0 200 OK
Content-Type: text/html; charset=utf-8
Content-Length: 13
Server: Werkzeug/0.8.3 Python/2.7.2
Date: Fri, 21 Dec 2012 06:31:10 GMT

使用GET的测试将是

def test_username(self, username):
    return self.app.get('/hello/%s' % (username), follow_redirects=True)

或者,假设你有2.6+

def test_username(self, username):
    return self.app.get('/hello/{username}'.format(username=username), follow_redirects=True)

相关问题 更多 >