我正在尝试在pytest
和monkeypatching的帮助下模拟我正在调用的函数的返回值。
我为我的模拟类设置了固定装置,并且我正在尝试“覆盖”所述类中的方法之一。
from foggycam import FoggyCam
from datetime import datetime
@pytest.fixture
def mock_foggycam():
return Mock(spec=FoggyCam)
def test_start(mock_foggycam, monkeypatch):
def get_mock_cookie():
temp = []
temp.append(Cookie(None, 'token', '000000000', None, None, 'somehost.com',
None, None, '/', None, False, False, 'TestCookie', None, None, None))
return temp
monkeypatch.setattr(FoggyCam, 'get_unpickled_cookies', get_mock_cookie)
cookies = mock_foggycam.get_unpickled_cookies()
mock_foggycam.get_unpickled_cookies.assert_called_with()
for pickled_cookie in cookies:
mock_foggycam.cookie_jar.set_cookie(pickled_cookie)
但是,我可能会遗漏一些东西,因为调用 assert_used_with
会引发错误:
________________________________________________________________ test_start ________________________________________________________________
mock_foggycam = <Mock spec='FoggyCam' id='4408272488'>, monkeypatch = <_pytest.monkeypatch.MonkeyPatch object at 0x106c0e5c0>
def test_start(mock_foggycam, monkeypatch):
def get_mock_cookie():
temp = []
temp.append(Cookie(None, 'token', '000000000', None, None, 'somehost.com',
None, None, '/', None, False, False, 'TestCookie', None, None, None))
return temp
monkeypatch.setattr(mock_foggycam, 'get_unpickled_cookies', get_mock_cookie)
cookies = mock_foggycam.get_unpickled_cookies()
> mock_foggycam.get_unpickled_cookies.assert_called_with()
E AttributeError: 'function' object has no attribute 'assert_called_with'
我的猴子补丁逻辑中是否有什么东西被我放错了?
最佳答案
跟进我的评论。您基本上是在尝试创建一个行为类似于模拟的模拟(以便 assert_called_with
可用)并执行您的 get_mock_cookie
(一个函数)。
这就是wraps
参数的作用。记录在这里:https://docs.python.org/3/library/unittest.mock.html#unittest.mock.Mock
你可以尝试这样的事情:
monkeypatch.setattr(mock_foggycam, "get_unpickled_cookies", Mock(wraps=get_mock_cookie))
您收到的错误基本上是告诉您您正在尝试对函数对象(您的 get_mock_cookie
)调用 assert_called_with
。
关于python - pytest & Monkeypatching - 无法获取返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53554056/