簡體   English   中英

自定義 pytest 參數化測試名稱

[英]Customizing pytest parameterized test name

我有以下測試:

@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

我想自定義測試名稱以包含輸入數組。 我已經閱讀了pytest 文檔,以及這個問題這個問題,但沒有人回答以下問題:

  1. 傳遞給 id 函數的是什么? 在我上面的代碼中,第一個測試需要一個參數,第二個測試需要兩個。
  2. pytest 文檔使用頂級 function 作為 id,而我想將我的測試放在 class 中並使用@staticmethod 嘗試從TestClass內部使用TestClass.static_method引用 static 方法會導致 PyCharm 出現錯誤; 這樣做的正確語法是什么?

編輯:創建https://github.com/pytest-dev/pytest/issues/8448

當為ids關鍵字使用可調用對象時,將使用單個參數調用它:被參數化的測試參數的值。 可調用的ids返回一個字符串,該字符串將在方括號中用作測試名稱后綴。

如果測試對多個值進行參數化,則 function 仍將使用單個參數調用,但每次測試將調用多次。 生成的名稱將與破折號相連,例如

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

例如:

test_something[val1-val2-val3]

這是 pytest 源中的連接

要使用 static 方法,此語法有效:

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]

我喜歡wims的回答,這是對他的回答的評論(我沒有發表評論的要點)。 這對我來說似乎更pythonic。 它還有助於避免使用 static 方法。

class TestExample:
    @pytest.mark.parametrize(
        "x, y",
        [
            [1, 2],
            ["a", "b"],
        ],
        ids= lamba val : f"foo{val}"
    )
    def test_vals(self, x, y):
        assert x
        assert y

這將具有相同的 output:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM