在pytest和monkeypatching的帮助下,我正在尝试模拟我正在调用的函数的返回值。
我为我的mock类设置了fixture,并且我正试图“覆盖”这个类中的一个方法。
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_called_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'我的monkeypatching逻辑中有没有什么地方我放错了地方?
发布于 2018-11-30 20:00:42
从我的评论中跟进。您基本上是在尝试创建一个行为类似于mock的mock (以便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。
https://stackoverflow.com/questions/53554056
复制相似问题