python-3.x - 如何断言在 pytest 中调用了猴子补丁?

标签 python-3.x python-requests mocking pytest monkeypatching

考虑以下:

class MockResponse:
    status_code = 200

    @staticmethod
    def json():
        return {'key': 'value'}
                                  # where api_session is a fixture
def test_api_session_get(monkeypatch, api_session) -> None:
    def mock_get(*args, **kwargs):
        return MockResponse()

    monkeypatch.setattr(requests.Session, 'get', mock_get)
    response = api_session.get('endpoint/') # My wrapper around requests.Session
    assert response.status_code == 200
    assert response.json() == {'key': 'value'}
    monkeypatch.assert_called_with(
        'endpoint/',
        headers={
            'user-agent': 'blah',
        },
    )
我如何断言 get我正在修补被调用 '/endpoint'headers ?当我现在运行测试时,我收到以下失败消息:FAILED test/utility/test_api_session.py::test_api_session_get - AttributeError: 'MonkeyPatch' object has no attribute 'assert_called_with'我在这里做错了什么?感谢所有提前回复的人。

最佳答案

将添加另一个使用monkeypatch 而不是“你不能使用monkeypatch”的响应
由于 python 有闭包,这里是我可怜的人用 Monkeypatch 做这些事情的方式:

patch_called = False

def _fake_delete(keyname):
    nonlocal patch_called
    patch_called = True
    assert ...

monkeypatch.setattr("mymodule._delete", _fake_delete)
res = client.delete(f"/.../{delmeid}"). # this is a flask client
assert res.status_code == 200
assert patch_called
在您的情况下,由于我们正在通过修补 HTTP 服务器方法处理程序做类似的事情,您可以执行以下操作(不是说这很漂亮):
param_called = None

def _fake_delete(param):
    nonlocal param_called
    patch_called = param
    assert ...

monkeypatch.setattr("mymodule._delete", _fake_delete)
res = client.delete(f"/.../{delmeid}")
assert res.status_code == 200
assert param_called == "whatever this should be"

关于python-3.x - 如何断言在 pytest 中调用了猴子补丁?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65308318/

相关文章:

Python:在创建字典时用作字典值时调用方法

python - 请求返回字节,我无法解码它们

Python - 在多线程中使用随机数

python - 如何用 mox 模拟类属性?

java 。模拟数据访问对象

python - 读取操纵杆功能

python - 我的 Python 无法正确读取 XML

python - 是否可以添加带有列表理解的 where 子句?

python - 在 json 中发出不带双引号的 HTTP 请求

python - 在 Python 单元测试中分别模拟多个 API 请求