【发布时间】:2020-02-05 22:22:00
【问题描述】:
这可能是一个微不足道的问题,但我找不到合适的解决方案,也不知道如何解决。我简化了问题,所以我有两个文件 my_module.py 和 test_module.py 在同一个本地化。
import numpy as _np
class MyClass:
def __init__(self) -> None:
self.attribute = 1
self.method()
def method(self) -> None:
arr = _np.arange(9).reshape(-1, 3)
self.attribute = 2
from unittest.mock import Mock, patch
import pytest
from my_module import MyClass
@pytest.fixture
def init_mock():
with patch.object(MyClass, '__init__', return_value=None) as init:
yield init
@pytest.fixture
def method_mock():
with patch.object(MyClass, 'method') as method:
yield method
@pytest.fixture
def my_class_init_mock(init_mock):
yield MyClass()
@pytest.fixture
def my_class_method_mock(method_mock):
yield MyClass()
def test_init(my_class_method_mock):
assert my_class_method_mock.attribute == 1
def test_method(my_class_init_mock):
my_class_init_mock.method()
assert my_class_init_mock.attribute == 2
两项测试全部通过。此外,我需要检查是否使用 -1, 3 参数调用了一次 _np.arange(9).reshape。我发现我应该从my_module.py直接引用numpy。我试图在最后一个测试上方添加@patch('my_module._np')。我还尝试将模块的夹具传递给my_class_method_mock 的夹具。不幸的是,当我触发.method() 函数时,我无法调用这个模拟。如何在它们之间建立联系?
【问题讨论】:
标签: python mocking pytest patch fixtures