【问题标题】:How to group redundant values in pytest parametrize test?如何在 pytest 参数化测试中对冗余值进行分组?
【发布时间】:2022-11-11 05:42:07
【问题描述】:

我正在尝试删除参数化测试中的冗余行。冗余 - 我的意思是我一直重复这种代码。

这是我的测试示例:

1  @pytest.mark.parametrize("field, violations", [
2      (None, [NULL_VIOLATION]),
3      (True, []),
4      (False, [])
5  ])
6  def test_validate_field(field: str, violations: [str]):
7      ...

如您所见,第 2、3、4 行是对我的控制器类中注释 @NotNull 的简单测试。
第 2 行是坏路测试和线 3,4 是幸福的道路.


当我需要检查 @NotNull 时,我会在每次测试中重复这 3 行
有可能以某种方式内联吗?


我想要实现的是类似于该伪代码的东西:

1  @pytest.mark.parametrize("field, violations", [
2      check_not_null_constraint()
3  ])
4  def test_validate_field(field: str, violations: [str]):
5      ...

我不想摆脱参数化,因为我没有检查 not_null 我正在测试许多其他东西,比如大小等。我正在测试每个参数的所有内容。因此,对类中的 1 个参数进行 1 次测试。

【问题讨论】:

    标签: python python-3.x pytest


    【解决方案1】:

    这可以使用pytest_generate_tests 来完成,请参阅:https://docs.pytest.org/en/6.2.x/parametrize.html

    此测试设置:

    import pytest
    
    @pytest.mark.parametrize(
        "a, b",[(1,10),(2,20)]
    )
    def test_param_func1(a, b):
        assert 10*a == b
    
    @pytest.mark.parametrize(
        "a, b",[(1,10),(2,20)]
    )
    def test_param_func2(a, b):
        assert a in (1,2)  
        assert b in (10,20)
    
    $ pytest -v -k "test_param"
    test_param.py::test_param_func1[1-10] PASSED [ 25%] 
    test_param.py::test_param_func1[2-20] PASSED [ 50%] 
    test_param.py::test_param_func2[1-10] PASSED [ 75%] 
    test_param.py::test_param_func2[2-20] PASSED [100%]
    

    也可以这样实现:

    import pytest
    
    def pytest_generate_tests(metafunc):
        # This hook function runs once per test function
        metafunc.parametrize("a, b",[(1,10),(2,20)])
    
    def test_param_func3(a, b):
        assert 10*a == b
    
    def test_param_func4(a, b):
        assert a in (1,2)  
        assert b in (10,20)
    
    $ pytest -v -k "test_param"
    test_param.py::test_param_func3[1-10] PASSED [ 25%] 
    test_param.py::test_param_func3[2-20] PASSED [ 50%] 
    test_param.py::test_param_func4[1-10] PASSED [ 75%] 
    test_param.py::test_param_func5[2-20] PASSED [100%]
    

    您可以更进一步,使用metafunc.config.getoption("--yourflag") (Pytest Generate Tests Based on Arguments) 根据命令行参数有条件地参数化您的测试

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多