如何断言在pytest中调用了猴子补丁?

考虑以下:

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'

我在这里做错了什么?感谢所有提前回复的人。

回答

您需要一个Mock对象来调用assert_called_with-monkeypatch不提供。您可以使用unittest.mock.patchwithside_effect来实现此目的:

from unittest import mock
import requests

...

@mock.patch('requests.Session.get')
def test_api_session_get(mocked, api_session) -> None:
    def mock_get(*args, **kwargs):
        return MockResponse()

    mocked.side_effect = mock_get
    response = api_session.get('endpoint/') 
    ...
    mocked.assert_called_with(
        'endpoint/',
        headers={
            'user-agent': 'blah',
        },
    )

side_effect仍然需要使用来获取模拟对象(mocked在本例中为 type MagickMock),而不仅仅是在 中设置您自己的对象patch,否则您将无法使用这些assert_called_...方法。


以上是如何断言在pytest中调用了猴子补丁?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>