簡體   English   中英

帶有多個斷言的pytest參數化夾具

[英]pytest parametrizing fixtures with multiple asserts

我有一個示例代碼,其中有一個帶有兩個斷言的參數化測試函數:

@pytest.mark.parametrize("test_input,expected", [
    ("3", 8),
    ("2", 6),
])
def test_eval(test_input, expected):
    assert test_input == expected # first assert
    assert test_input + 2 ==expected # second assert

所以我想要的輸出是(偽代碼):

assertion error 3==8
assertion error 5==8
assertion error 2==6
assertion error 4==6

在對所有組合執行測試時,即使第一個失敗,也有辦法達到第二個斷言嗎?

作為一種替代,我想知道是否有一種方法可以將其放入類,例如類似於以下內容的方法:

@pytest.mark.parametrize("test_input,expected", [
    ("3", 8),
    ("2", 6),
])
class TestFunc(object):
   def test_f1(test_input, expected):
     assert test_input==expected
   def test_f2(test_input, expected):
     assert test_input+2==expected

我想獲得與前面的案例相同的輸出:

assertion error 3==8
assertion error 5==8
assertion error 2==6
assertion error 4==6

pytest-expect插件可以做這種事情。

在類上使用@pytest.mark.parametrize概述的方法是開箱即用的,您只是忘了self

另一種可能性是僅編寫兩個測試並共享參數化:

eval_parametrize = pytest.mark.parametrize("test_input, expected", [
    ("3", 8),
    ("2", 6),
])

@eval_parametrize
def test_f1(test_input, expected):
    assert test_input == expected

@eval_parametrize
def test_f2(test_input, expected):
    assert test_input + 2 == expected

暫無
暫無

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

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