首页 > 解决方案 > 在 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.

标签: unit-testingflaskmockingpytest

解决方案


编辑:使用时更正补丁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

推荐阅读