了解 python 模拟框架

Understanding python mock framework

我在网上找不到很好的解释,我猜我遗漏了一些微不足道的东西,但我找不到,所以我来这里问专家:)

我有一个测试,我是否需要修补构造函数调用,据我所知阅读文档,这样的事情应该有效,但是:

import unittest.mock as mocker
import some_module

mock_class1 = mocker.patch('some_module.some_class')
print(mock_class1 is some_module.some_class)  # Returns False
print(mock_class1) # <unittest.mock._patch>
mock_instance1 = mock_class1.return_value # _patch object has no attr return_value

相反,如果我这样做,我会得到不同的输出

with mocker.patch('some_module.some_class') as mock_class2:
    print(mock_class2 is some_module.some_class)  # Returns True
    print(mock_class2) # <MagicMock name=...>
    mock_instance2 = mock_class2.return_value  # No problem
    print(mock_instance2) # <NonCallableMagicMock name=...>

现在,对于测试本身,我正在使用 pytest-mock 模块,它提供了一个模拟装置,其行为类似于第一个代码块。

我想知道:

  1. 为什么行为因调用模拟框架的方式而异

  2. 没有 with 子句,是否有一种干净的方法来触发第二个代码块的行为?

1) pytest 模拟插件正在开发中,以避免使用上下文管理器;并且可能不是每个人都喜欢标准模拟使用函数参数 2) 的方式。它旨在用作内容管理器或功能装饰器。 我认为可以在没有 pytest

的情况下使用 mocker 包

参考资料 https://github.com/pytest-dev/pytest-mock https://www.packtpub.com/mapt/book/application_development/9781847198846/5/ch05lvl1sec45/integrating-with-python-mocker

如何安装 pytest-mock 并创建这样的测试

import itertools

def test1(mocker):

    mock_class1 = mocker.patch('itertools.count')
    print(mock_class1 is itertools.count)
    print(mock_class1)
    mock_instance1 = mock_class1.return_value # Magic staff...

或者可能正在使用 monkeypatching?只是不要将标准 unittest.mock 与 pytest

一起使用