我可以在Flask应用程序上下文中运行所有单元测试吗?

时间:2013-09-02 01:58:40

标签: python unit-testing flask

对于我编写的每个使用我的应用程序模型的测试,我似乎必须使用当前的应用程序上下文:

SomeTestCase(unittest2.TestCase):

    setUp(self):
        self.app = Flask(__name__)
        ...

    test_something(self):
        with self.app.app_context():
            # Do something

有没有办法告诉我所有测试都使用当前的应用程序上下文来保存我在所有测试中都有这条线?

3 个答案:

答案 0 :(得分:4)

我通过查看way the Flask-Testing extensions TestCase sets itself up找到了我正在寻找的答案,即将测试上下文推送到从_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

答案 1 :(得分:2)

您可以尝试以下内容。

免责声明:我刚想出这个想法,并没有彻底测试这个解决方案,尽管它似乎有效。这也是恕我直言,相当难看。

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

答案 2 :(得分:1)

根据您的测试方式,您可以使用test client。例如:

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