pytest和monkeypatching-无法获得返回值

时间:2018-11-30 08:43:28

标签: python unit-testing mocking tdd pytest

我正在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_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逻辑中是否存在某些错误?

1 个答案:

答案 0 :(得分:3)

关注我的评论。您基本上是在尝试制作行为类似于模拟的模拟(以便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)) 

您得到的错误基本上是在告诉您您试图在函数对象(您的assert_called_with)上调用get_mock_cookie