防止 "duplication" 测试代码仅仅因为一个参数不同

Prevent "duplication" of test code just because a parameter is different

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

例如,

@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 似乎不能解决问题。当我想 运行 和 "marks" 时它起作用,但标记的目的是能够 运行 独立地测试其中一个,例如 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']