在 Flask 单元 pytest 中模拟 current_app

Chr*_*ill 7 unit-testing mocking pytest flask

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

from flask import current_app

def fuu():
    current_app.logger.info('hello world')
    any = current_app.config['any']
Run Code Online (Sandbox Code Playgroud)

如果没有任何特殊的上下文处理,我会收到以下错误消息:

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.
Run Code Online (Sandbox Code Playgroud)

在阅读了 Flask 上下文之后,我想出了一个可行的解决方案:

@classmethod
def setUpClass(cls):
    app = app_factory.create_app()
    ctx = app.app_context()
    ctx.push()
    cls.app = app
Run Code Online (Sandbox Code Playgroud)

但重点是我不想在UNIT 测试中处理任何 Flask 上下文。我想要一个简单的单元测试,其中所有协作者都可以被模拟,以便被测系统只处理模拟实例,在本例中current_app也是如此。拥有 Flask 上下文对于集成测试来说非常好,但对于单元测试则不然。

我正在寻找类似的东西:

 @patch('flask.current_app')
Run Code Online (Sandbox Code Playgroud)

有什么办法可以实现这一点吗?

编辑#1

@加布里埃尔C

服务.py

from flask import current_app

def fuu():
    current_app.logger.info('hello world')
Run Code Online (Sandbox Code Playgroud)

服务测试.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
Run Code Online (Sandbox Code Playgroud)

由于同样的原因,此操作失败了:

E           RuntimeError: Working outside of application context.
Run Code Online (Sandbox Code Playgroud)

Dar*_*res 7

为遇到同样问题的任何人解答。您可以做的是创建一个虚拟Flask应用程序并在测试中使用其上下文。无需修补任何东西。

import unittest
from service import fuu


class TestService(unittest.TestCase):
    app = Flask('test')

    def test_generate_image_happy_path(self):
        with app.app_context():
            fuu()
            assert 1 == 1
Run Code Online (Sandbox Code Playgroud)

当然,如果您想访问您的Flask配置,则必须将其传递给这个虚拟应用程序。