unit-testing - 在 Flask 单元 pytest 中模拟 current_app
问题描述
我想对以下功能进行单元测试:
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
但关键是我不想在UNIT 测试中处理任何烧瓶上下文。我想要一个简单的单元测试,其中可以模拟所有协作者,以便被测系统只处理模拟实例,在这种情况下current_app
也是如此。拥有烧瓶上下文对于集成测试来说非常好,但对于单元测试来说却不是。
我正在寻找类似这样的东西:
@patch('flask.current_app')
有什么办法可以做到这一点?
编辑#1
@加布里埃尔C
服务.py
from flask import current_app
def fuu():
current_app.logger.info('hello world')
服务测试.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')
服务测试.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
推荐阅读
- python - 如何下载 BraST 2015 或 BraST 2013 脑肿瘤 MRI 图像?
- windows - 如何使用 PowerShell 获取所有已安装的 Windows 更新名称和 KB 编号?
- reactjs - 如何将此 DataPicker 转换为 Material UI 的 DataRangePicker?
- python - 你如何解决这个 python tkinter 错误?
- python - Streamlit、Python 和 Pandas:重复键和书写
- javascript - @babel/eslint-parser 与裸 js 项目
- python - 使用 for 循环递归地创建一个新的数据框
- salesforce - 如何以相反的顺序为字母数字字符返回字符数组,只有所有非字母数字字符需要保留原始位置
- r - 闪亮的模块导致发布错误-“找不到对象”
- python - 简化python中的复杂逻辑条件