首页 > 解决方案 > 在 Python 中模拟加载时间变量

问题描述

我正在尝试覆盖我的 Python 代码并测试我的 Flask 应用程序。不用太具体,让我们看一下这里的示例代码:

# from /my_project/app_demo/app.py
from private_module import logs
from flask import Flask

import logging

logs.init_logging()
logger = logging.getLogger(__name__)

app = Flask(__name__)

@app.route("/greet/<name:name>", methods=["GET"])
def greet(name):
    logger.info(f"{name} wants a greeting")
    return f"Hello, {name}!"

if __name__ == "__main__":
    app.run(debug=True)

如果我要为 greet 函数编写单元测试,我想模拟记录器以断言它在创建时和 info 方法被调用时被调用。对于此示例,源根文件夹是 app_demo,并且该 python 文件夹中有一个init .py。

# from /my_project/tests/test_app.py
import pytest
from unittest import mock

@pytest.fixture
def client():
    app.config['TESTING'] = True
    with app.test_client() as client:
        yield client

def test_greet(client):
    logs_mock = mock.patch("app_demo.app.logs.init_logging")
    logger_mock = mock.patch("app_demo.app.logging.getLogger")

    actual = client.get("George")
    assert "Hello, George!" == actual

    # these next assertions do not work
    logs_mock.assert_called_once_with()
    logging_mock.assert_called_once_with("app_demo.app") # not sure if this will be "__main__"
    logging_mock.return_value.info.assert_called_once_with("George wants a greeting")

如果我调试在 greet 函数中调用 logger.info 的位置,则该对象是一个记录器,而不是我想要的模拟对象。

我也尝试在另一个夹具中制作模拟,但这也没有让它工作。

标签: pythonflaskmockingpytest

解决方案


推荐阅读