python - 在 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 的位置,则该对象是一个记录器,而不是我想要的模拟对象。
我也尝试在另一个夹具中制作模拟,但这也没有让它工作。
解决方案
推荐阅读
- javascript - 如果写入屏幕外画布,HTML Canvas 不会显示矩形
- amazon-web-services - 为用户组提供对 S3 存储桶的访问权限的方法
- python - 如何将 PayUMoney 付款从商户账户支付到任何用户的银行账户?
- abap - 如何获取当前语言环境(SET COUNTRY)?
- python - 在python中将集合转换为列表的算法复杂度
- debugging - 使用windbg调试Windows 10/7内核的最快连接方法是什么?
- django - 如何使用 FactoryBoy 实例化我的 Django AbstractBaseUser 的子类
- javascript - 使用jQuery通过前缀提取类名
- python - 使用 Python 连接到 SAP C4C Hybris
- python - 围绕数组的每个索引切片