How do I mock dependencies of the views module of my Flask application in flask-testing?

喜欢而已 提交于 2019-12-11 20:09:28

问题


As a minimal example, my Flask application has a views module like

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)

I've got a test setup like

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')
        ???

How do I write test_home so that it asserts that some_service.do_thing('bar') was called?


回答1:


You can use Python mock on elements of the views module by accessing it through the application module imported in your test module. Your test module should read something like:

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')


来源:https://stackoverflow.com/questions/33046124/how-do-i-mock-dependencies-of-the-views-module-of-my-flask-application-in-flask

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!