如何在烧瓶测试中模拟Flask应用程序的视图模块的依赖关系?

时间:2015-10-09 19:52:37

标签: python unit-testing flask flask-testing

作为一个最小的例子,我的Flask应用程序有一个views模块,如

from flask import render_template
from something import some_service

def home():
    foo = some_service.do_thing('bar')
    return render_template('index.html', foo=foo)

我有一个像

这样的测试设置
from application import app
from flask.ext.testing import TestCase

class MyTest(TestCase):

    def create_app(self):
        app.config['TESTING'] = True
        app.config['WTF_CSRF_ENABLED'] = False
        return app

    def setUp(self):
        self.app = app.test_client()

    def test_home(self):
        rv = self.app.get('/home')
        ???

如何编写test_home以断言some_service.do_thing('bar')被调用?

1 个答案:

答案 0 :(得分:0)

您可以在mock模块的元素上使用Python views,方法是通过测试模块中导入的application模块访问它。您的测试模块应该是这样的:

import application
from flask.ext.testing import TestCase

class MyTest(TestCase):

    def create_app(self):
        application.app.config['TESTING'] = True
        application.app.config['WTF_CSRF_ENABLED'] = False
        return application.app

    def setUp(self):
        self.app = application.app.test_client()

    def test_home(self):
        mock_service = mock.MagicMock()
        application.views.some_service = mock_service
        self.app.get('/home')
        mock_service.do_thing.assert_called_with('bar')