【发布时间】:2018-09-06 13:38:23
【问题描述】:
我们正在使用一些自定义命令扩展 Flask-cli。命令test 就是其中之一:
# run.py: specified by FLASK_APP
# This is the Flask application object
app = create_app(os.getenv('FLASK_ENV') or 'default')
@app.cli.command()
def test():
"""Run the unit tests."""
tests = unittest.TestLoader().discover('tests')
test_runner = unittest.TextTestRunner()
test_runner.run(tests)
然而,一个典型的测试(使用 Python 的内置 unittest 模块)看起来像 这是基于here 描述的样式。
# some-tests.py: unittest-based test case.
class SomeTestCase(unittest.TestCase):
def setUp(self):
self.app = create_app('testing')
self.app_context = self.app.app_context()
self.app_context.push()
def tearDown(self):
self.app_context.pop()
def test_load(self):
pass
我显然在这里遇到了一个反模式:我已经使用默认 (development) 配置初始化了一个烧瓶对象,因为我需要它用于 @app.cli.command() 装饰器,这一切都发生在 run.py 中。但是,一旦我在some-tests.py 中运行测试设置函数,我就必须以某种方式使用testing 配置获取一个 Flask 对象,例如通过使用 testing 配置重新创建一个 Flask 应用程序,就像现在发生的那样。
我想知道如何实现flask-cli 测试命令,其中只创建一个Flask 对象,该对象在各种测试用例中重复使用,而无需明确地将环境设置为testing 在我在命令行上运行 flask test 之前。
【问题讨论】:
标签: python-3.x testing flask flask-cli