如何在瓶测试中模拟我的Flask应用程序的视图模块的依赖关系? [英] How do I mock dependencies of the views module of my Flask application in flask-testing?

查看:184
本文介绍了如何在瓶测试中模拟我的Flask应用程序的视图模块的依赖关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

 <$ c ():$ b $ foo = some_service.do_thing('bar')
return render_template(' index.html',foo = foo)

我有一个像

  from application import app $ b $ from from flask.ext.testing 
$ b $ def create_app(self):
app.config ['TESTING'] = True
app.config ['WTF_CSRF_ENABLED'] = False
return app
$ b $ def setUp(self):
self.app = app.test_client()
$ b $ def test_home(self):
rv = self.app.get ('/ home')
???

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

解决方案

通过应用程序访问它,可以在 views 模块的元素上使用Python mock 在您的测试模块中导入模块。您的测试模块应该读取如下内容:

 从flask.ext.testing导入应用程序
import TestCase

class MyTest(TestCase):
$ b $ def create_app(self):
application.app.config ['TESTING'] = True
application.app.config [ 'WTF_CSRF_ENABLED'] = False
return application.app
$ b $ 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')


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?

解决方案

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

这篇关于如何在瓶测试中模拟我的Flask应用程序的视图模块的依赖关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆