我正在使用 pytest,并且我有 5 个以上的测试,它们的前五行完全相同。是否可以为重复的代码创建一个设置函数?
@mock.patch('abcde.xyz')
def test_1(mocked_function):
x_mock = mock.Mock(X)
x_mock.producer = mock.Mock()
x_mock.producer.func2 = lambda : None
mocked_function.return_value = x_mock # xyz() returns x_mock
......
@mock.patch('abcde.xyz')
def test_2(mocked_function):
x_mock = mock.Mock(X)
x_mock.producer = mock.Mock()
x_mock.producer.func2 = lambda : None
mocked_function.return_value = x_mock
......
@mock..... # more
最佳答案
您应该考虑使用 fixture正如它推荐的经典安装/拆卸方法。
来自 pytest documentation :
While these setup/teardown methods are simple and familiar to those coming from a unittest or nose background, you may also consider using pytest’s more powerful fixture mechanism which leverages the concept of dependency injection, allowing for a more modular and more scalable approach for managing test state, especially for larger projects and for functional testing.
对于您的示例 - 考虑到 mocked_function
本身就是一个固定装置 - 它将是:
@pytest.fixture()
def mock_abcde_xyz(mocker):
mocker.patch("abcde.xyz")
@pytest.fixture()
@pytest.mark.usefixtures("mock_abcde_xyz")
def patched_mocked_function(mocker, mocked_function):
x_mock = mocker.Mock(X)
x_mock.producer = mocker.Mock()
x_mock.producer.func2 = lambda : None
mocked_function.return_value = x_mock
return mocked_function
def test_1(patched_mocked_function):
......
def test_2(patched_mocked_function):
......
请注意,我使用了 pytest-mock而不是模拟,以便您可以使用“mocker”装置。
如果你不想pytest-mock ,只需执行:
@pytest.fixture()
@mock.patch('abcde.xyz')
def patched_mocked_function(mocked_function):
x_mock = mock.Mock(X)
x_mock.producer = mock.Mock()
x_mock.producer.func2 = lambda : None
mocked_function.return_value = x_mock
return mocked_function
def test_1(patched_mocked_function):
......
def test_2(patched_mocked_function):
......
关于python - 用于模拟对象设置的 pytest 固定装置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64253531/