unit-testing - 在 Flask 单元 pytest 中模拟 current_app

标签 unit-testing flask mocking pytest

我想对以下功能进行单元测试:

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/

相关文章:

c# - "Any"对象上的 MOQ stub 属性值

python - 仅当测试通过时才在 git 中提交

c# - 由于 'System.DateTime' 准确度,成组运行时单元测试运行速度过快

python - 我不需要 Flask 应用程序中的 run() 方法?

python - 模拟 subprocess.Popen 而不执行

java - 测试需要模拟成员方法并使用 PowerMockito 抑制单例构造函数的静态方法

java - Sonar 中的单元测试执行时间非常长

unit-testing - 如何使用VS2015 Preview运行xUnit单元测试?

python - 删除后 SQLAlchemy 仍然能够从 session 中获取对象

python - 重新生成所有 flask session 而不注销用户