我想对以下功能进行单元测试:
from flask import current_app
def fuu():
current_app.logger.info('hello world')
any = current_app.config['any']
在没有任何特殊上下文处理的情况下,我收到以下错误消息:
E This typically means that you attempted to use functionality that needed
E to interface with the current application object in some way. To solve
E this, set up an application context with app.app_context(). See the
E documentation for more information.
在阅读了 Flask 上下文之后,我想出了一个可行的解决方案:
@classmethod
def setUpClass(cls):
app = app_factory.create_app()
ctx = app.app_context()
ctx.push()
cls.app = app
但关键是我不想处理 中的任何 flask 上下文。单元测试 .我想要一个简单的单元测试,其中可以模拟所有协作者,以便被测系统只处理模拟实例,在这种情况下为
current_app
以及。拥有flask 上下文非常适合集成测试,但不适用于单元测试。
我正在寻找类似的东西:
@patch('flask.current_app')
有没有办法实现这一目标?
编辑 #1
@加布里埃尔C
服务.py
from flask import current_app
def fuu():
current_app.logger.info('hello world')
service_test.py
import unittest
from unittest.mock import patch
class TestService(unittest.TestCase):
@patch('flask.current_app')
def test_generate_image_happy_path(self, mock):
from service import fuu
fuu()
assert 1 == 1
由于相同的确切原因,这失败了:
E RuntimeError: Working outside of application context.
最佳答案
编辑:使用时正确的补丁 from flask import current_app
服务.py
from flask import current_app
def fuu():
current_app.logger.info('hello world')
service_test.py
import unittest
from unittest.mock import patch
class TestService(unittest.TestCase):
@patch('service.current_app')
def test_generate_image_happy_path(self, mock):
from service import fuu
fuu()
assert 1 == 1
关于unit-testing - 在 Flask 单元 pytest 中模拟 current_app,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57947935/