我通过查看Flask-Testing 扩展 TestCase 设置自己的方式找到了我正在寻找的答案,即将测试上下文推送到从其方法_ctx
中调用的函数内的堆栈中__call__
。
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