[英]Can I have all of my unit tests run in the Flask app context?
对于我编写的所有使用我的应用程序模型的测试,我似乎都必须使用当前的应用程序上下文:
SomeTestCase(unittest2.TestCase):
setUp(self):
self.app = Flask(__name__)
...
test_something(self):
with self.app.app_context():
# Do something
有没有办法告诉我所有的测试使用当前的应用程序上下文运行,以节省我在所有测试中使用这一行?
我通过查看Flask-Testing扩展TestCase设置自己的方式找到了我正在寻找的答案, _ctx
测试上下文推_ctx
从__call__
方法中__call__
的函数内的_ctx
堆栈。
class BaseTestCase(unittest2.TestCase):
def __call__(self, result=None):
try:
self._pre_setup()
super(BaseTestCase, self).__call__(result)
finally:
self._post_teardown()
def _pre_setup(self):
self.app = create_app()
self.client = self.app.test_client()
self._ctx = self.app.test_request_context()
self._ctx.push()
def _post_teardown(self):
if getattr(self, '_ctx') and self._ctx is not None:
self._ctx.pop()
del self._ctx
而我的测试:
class SomeTestCase(BaseTestCase):
test_something(self):
# Test something - we're using the right app context here
你可以试试下面的东西。
免责声明:我只是想出了一个主意,尽管似乎可行,但并未彻底测试该解决方案。 这也是恕我直言,相当丑陋。
from functools import wraps
def with_context(test):
@wraps(test)
def _with_context(self):
with self.app.app_context():
test(self)
return _with_context
SomeTestCase(unittest2.TestCase):
setUp(self):
self.app = Flask(__name__)
...
@with_context
test_something(self):
# Do something
根据您的测试方式,您可能可以使用测试客户端 。 例:
SomeTestCase(unittest2.TestCase):
setUp(self):
self.app = Flask(__name__)
self.client = self.app.text_client()
test_something(self):
response = self.client.get('/something')
# check response
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.