python - 防止测试代码因为参数不同而出现 "duplication"

标签 python python-3.x pytest

在我的测试套件中,我有不同的集成和稳定性测试。

例如,

@pytest.mark.integration
def test_integration_total_devices(settings, total_devices):
    assert total_devices == settings['integration']['nodes']['total']

@pytest.mark.stability
def test_stability_total_devices(settings, total_devices):
    assert total_devices == settings['stability']['nodes']['total']

正如您所注意到的,它是完全相同的代码,只是从配置中读取不同的参数。

如何防止这种重复代码的情况?设置的值不同,所以我不能只是:

@pytest.mark.integration
@pytest.mark.stability
def test_integration_total_devices(settings, total_devices):
    assert total_devices == settings['nodes']['total']

我忘了提及(感谢 @dzejdzej 提醒我),似乎 pytest parametrize 并不能解决问题。当我想运行两个“标记”时,它可以工作,但标记的目的是能够独立运行其中一个的测试,例如,pytest -m Integration。然而,据我测试,每当我设置参数化时,它都会运行。

@pytest.mark.parametrize('type', (
    pytest.param('stability', marks=pytest.mark.stability),
    pytest.param('integration', marks=pytest.mark.integration),
))
@pytest.mark.integration
@pytest.mark.stability
def test_total_devices(settings, total_devices, type):
    assert total_devices == settings[type]['nodes']['total']

最佳答案

请看一下 pytest 参数化 https://docs.pytest.org/en/latest/parametrize.html

应该可以按照这些思路做某事:

@pytest.mark.parametrize('area,total_devices', (
    pytest.param('stability', 10, marks=pytest.mark.stability),
    pytest.param('integration', 15, marks=pytest.mark.integration),
))
def test_integration_total_devices(area, total_devices):
    assert total_devices == settings.get(area)['nodes']['total']

关于python - 防止测试代码因为参数不同而出现 "duplication",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50448724/

相关文章:

python - 碎片:可见下拉菜单可点击但不可选择

python - 无法通过迭代器设置数组值

python - 我应该在抽象方法的主体中放什么?

python - 运行 py.test 时的 .coveragerc 文件位置

python - 如何在列表理解中使用多个条件子句?

自动化

python - 修改python列表中的所有元素,并将类型从字符串更改为整数

python - 使用键重新组合 pandas 中的数据框。比迭代行更快的方法?

python - pytest参数化类方法执行顺序

python - FastAPI 测试客户端在 POST 或 PUT 时重定向请求