python - pytest & Monkeypatching - 无法获取返回值

标签 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_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/

相关文章:

python - 将多个正则表达式合并为一个可能为 "catch them all"

python - aiohttp.errors.ClientRequestError : Can not write request body

python - 将任意代码注入(inject) Python SimpleXMLRPC 服务器

未找到 PHPUnit 类

ruby-on-rails - 由于命名空间冲突而无法测试 RSpec?

asp.net - 直接使用 HttpContext 是一件坏事吗?

c - 被测非静态函数调用的模拟/包装静态函数

java - 如何在 Mockito 中测试具有相同参数的调用的特定顺序?

python - 如何用多行编写 python lambda?

Python3 单元测试模拟请求模块