新手撰写集成测试
这是我的测试文件:
from flask import Flask
from flask.ext.testing import TestCase
class TestInitViews(TestCase):
render_templates = False
def create_app(self):
app = Flask(__name__)
app.config['TESTING'] = True
return app
def test_root_route(self):
self.client.get('/')
self.assert_template_used('index.html')
这是完整的错误追踪信息:
$ nosetests tests/api/client/test_init_views.py
F
======================================================================
FAIL: test_root_route (tests.api.client.test_init_views.TestInitViews)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/dmonsewicz/dev/autoresponders/tests/api/client/test_init_views.py", line 17, in test_root_route
self.assert_template_used('index.html')
File "/Users/dmonsewicz/.virtualenvs/autoresponders-api/lib/python2.7/site-packages/flask_testing.py", line 120, in assertTemplateUsed
raise AssertionError("template %s not used" % name)
AssertionError: template index.html not used
----------------------------------------------------------------------
Ran 1 test in 0.012s
FAILED (failures=1)
我刚开始学Python,遇到了一些问题。我的目标很简单,就是写一个测试,访问根路径 /
,然后确认使用的模板确实是 index.html
我尝试使用 LiveServerTestCase
来实现这个测试
from flask import Flask
from flask.ext.testing import LiveServerTestCase
class TestInitViews(LiveServerTestCase):
render_templates = False
def create_app(self):
app = Flask(__name__)
app.config['TESTING'] = True
app.config['LIVESERVER_PORT'] = 6765
return app
def setUp(self):
self.app = self.app.test_client()
def test_root_route(self):
res = self.app.get('/')
print(res)
self.assert_template_used('index.html')
我在用 Flask-Testing
的版本 0.4
,但不知道为什么在我的导入中找不到 LiveServerTestCase
有效的代码
from flask import Flask
from flask.ext.testing import TestCase
from api.client import blueprint
class TestInitViews(TestCase):
render_templates = False
def create_app(self):
app = Flask(__name__)
app.config['TESTING'] = True
app.register_blueprint(blueprint)
return app
def test_root_route(self):
res = self.client.get('/')
self.assert_template_used('index.html')
1 个回答
1
你需要运行命令 pip install blinker,并确保你的 Flask 版本大于 0.6。
看起来你忘了设置 app.config['TESTING'] = True 这个选项。
我成功运行了以下测试,来验证这个断言是正确的:
#!/usr/bin/python
import unittest
from flask import Flask
from flask.ext.testing import TestCase
from flask import render_template
class MyTest(TestCase):
def create_app(self):
app = Flask(__name__)
app.config['TESTING'] = True
@app.route('/')
def hello_world():
return render_template('index.html')
return app
def test_root_route(self):
self.client.get('/')
self.assert_template_used('index.html')
if __name__ == '__main__':
unittest.main()