【发布时间】:2012-12-21 05:30:53
【问题描述】:
我已经阅读了很长时间,但这是我第一次发帖。
好的,所以我正在尝试在 Flask 中对演示应用程序进行单元测试,但我不知道自己做错了什么。
这些是我在一个名为 manager.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
第一个路由正在加载 base.html 模板呈现“hi”消息,该消息在单元测试中有效,但第二个路由收到断言错误。
这是我的测试文件manage_test.py:
class ManagerTestCase(unittest.TestCase):
def setUp(self):
self.app = app.test_client()
def t_username(self, username):
return self.app.post('/hello/<username>', follow_redirects=True)
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
这是单元测试运行的输出:
.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
【问题讨论】:
-
一方面,您需要在 /hello 上允许 POST。另一方面,
hello_username的username参数不会自动将 POST 数据转换为方法参数。 -
另外,
t_username不会使用username参数设置帖子的数据。
标签: python unit-testing flask