Python 自定义pytest参数化测试名称

Python 自定义pytest参数化测试名称,python,python-3.x,pytest,parameterized-unit-test,Python,Python 3.x,Pytest,Parameterized Unit Test,我进行了以下测试: @pytest.mark.parametrize( "nums", [[3, 1, 5, 4, 2], [2, 6, 4, 3, 1, 5], [1, 5, 6, 4, 3, 2]] ) def test_cyclic_sort(nums): pass @pytest.mark.parametrize( "nums, missing", [([4, 0, 3, 1], 2)] ) def te

我进行了以下测试:

@pytest.mark.parametrize(
    "nums",
    [[3, 1, 5, 4, 2], [2, 6, 4, 3, 1, 5], [1, 5, 6, 4, 3, 2]]
)
def test_cyclic_sort(nums):
    pass


@pytest.mark.parametrize(
    "nums, missing",
    [([4, 0, 3, 1], 2)]
)
def test_find_missing_number(nums, missing):
    pass
我想自定义测试名称以包括输入数组。我已经阅读了,但没有人回答以下问题:

  • 传递给id函数的是什么?在我上面的代码中,第一个测试使用一个参数,第二个测试使用两个参数
  • pytest文档对id使用顶级函数,而我希望将我的测试放在一个类中,并使用
    @staticmethod
    。试图使用
    TestClass引用静态方法。从内部
    TestClass
    引用静态方法会在PyCharm中出错;执行此操作的正确语法是什么
  • 编辑:
    已创建。

    当对
    ids
    关键字使用可调用时,将使用单个参数调用它:参数化的测试参数的值。可调用的
    ids
    返回一个字符串,该字符串将在方括号中用作测试名称后缀

    如果测试在多个值上进行参数化,则仍将使用单个参数调用该函数,但每个测试将调用多次。生成的名称将与破折号连接,类似

    "-".join([idfunc(val) for val in parameters])
    
    例如:

    test_something[val1-val2-val3]
    

    要使用静态方法,以下语法有效:

    class TestExample:
    
        @staticmethod
        def idfunc(val):
            return f"foo{val}"
    
        @pytest.mark.parametrize(
            "x, y",
            [
                [1, 2],
                ["a", "b"],
            ],
            ids=idfunc.__func__,
        )
        def test_vals(self, x, y):
            assert x
            assert y
    
    这将生成两个测试,如上所述调用
    idfunc
    四次

    TestExample::test_vals[foo1-foo2]
    TestExample::test_vals[fooa-foob]
    

    因此,在我的示例中,我不能对这两个测试使用相同的
    idfunc
    ,因为该方法无法区分来自
    test\u cyclic\u sort
    test\u find\u missing\u number
    的调用?换句话说,当为
    test\u find\u missing\u number
    使用
    2
    调用
    idfunc
    时,它无法忽略它。很明显是人为的。是的,idfunc只获取参数值,并且似乎不知道关联的参数名或任何更广泛的测试上下文。已创建。