python - 用于模拟对象设置的 pytest 固定装置?

标签 python pytest

我正在使用 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/

相关文章:

python-3.x - 使用pytest-mock在python中使用SQLalchemy模拟数据库调用

python - 当有 javascript 按钮时,如何从互联网下载 csv 文件?

python - 列表的最小值和最大值(不使用最小/最大函数)

python - 还有比 pandas fillna() 更快的方法吗?

python - 如何在测试中检查返回值的类型

python - 如果测试覆盖率低于 x%,是否有标准方法使 pytest 失败

python - Discord.py 机器人命令仅获取上下文

python - 使用最小二乘法拟合权重衰减回归中的偏差

visual-studio-code - 如何让 Pytest 调用 VSCode 断点 View 而不是 PDB

python - 在特定的 pytest 标记上禁用 autouse fixtures