"pytest"的"嘲弄者"从何而来?



我正在关注这个关于pytest-mock的迷你教程/博客。 我无法理解mocker是如何工作的,因为它没有导入 - 特别是函数声明def test_mocking_constant_a(mocker):

import mock_examples.functions
from mock_examples.functions import double
def test_mocking_constant_a(mocker):
mocker.patch.object(mock_examples.functions, 'CONSTANT_A', 2)
expected = 4  
actual = double()  # now it returns 4, not 2
assert expected == actual

不知何故,mocker具有pytest-mocker.mocker的属性/功能:特别是mocker.patch.object。但是,如果没有导入语句,怎么可能呢?

mocker变量是一个 Pytest 灯具。夹具不是使用导入,而是使用依赖注入提供 - 也就是说,Pytest 负责为您创建 mocker 对象,并在运行测试时将其提供给测试函数。

Pytest-mock 在这里定义了"mocker"灯具,使用 Pytestfixture装饰器。在这里,fixture装饰器用作常规功能,这是一种稍微不寻常的方式。使用fixture装饰器的更典型方式如下所示:

@pytest.fixture()
def mocker(pytestconfig: Any) -> Generator[MockerFixture, None, None]:
"""
Return an object that has the same interface to the `mock` module, but
takes care of automatically undoing all patches after each test method.
"""
result = MockerFixture(pytestconfig)
yield result
result.stopall()
fixture

装饰器向 Pytest 注册"mocker"函数,当 Pytest 使用名为"mocker"的参数运行测试时,它会为您插入"mocker"函数的结果。

Pytest 可以做到这一点,因为它使用 Python 的自省功能在调用测试函数之前查看参数列表,包括名称。它将参数的名称与已注册的灯具名称进行比较,如果名称匹配,则为测试函数的该参数提供相应的对象。

最新更新