數據驅動測試 (Data-Driven Testing) 的是使用不同的數據輸入來進行多次相同的測試,在pytest中,數據驅動測試可以透過以下兩種方式實現:
- 使用標記:pytest.mark.parametrize
- 使用參數化的Fixtures:通過pytest.fixture提供多組測試資料
使用參數化的Fixtures (request.param)
request.param是pytest中的一個強大特性,通過request物件來實現參數化測試。pytest會將當前測試所需的測試資料從fixture中的params列表傳遞給fixture,而request.param就是用來訪問這些測試資料的屬性。
@pytest.fixture(params=[(3, 4), [3, 5]], ids=['tuple', 'list'])def fixture01(request):return request.paramdef test_fix_param01(fixture01):assert (type(fixture01)) in [tuple, list]
- 我們使用params參數來指定不同的測試資料,在此它將測試兩組測試資料 (3, 4) 和 [3, 5] 。
- ids指定了測試資料的識別名稱,分別為'tuple'和'list'。這樣在測試結果中會顯示這兩個名字,幫助識別是哪一組測試資料。
- request.param會根據當前測試的情況,回傳對應的測試資料。在第一次執行測試時,request.param回傳 (3, 4),而在第二次執行時,它會回傳 [3, 5]。
- 測試函式test_fix_param01使用fixture01並斷言回傳測試資料的類型是tuple或list。
當pytest進行這個測試時,它會自動生成兩個測試案例,每個案例使用不同的測試資料。測試結果將顯示每組測試資料對應的id,如tuple和list,使結果更加易讀。
多個Fixture參數化
我們可以擴充fixture的數目,進行更複雜的測試。在此新增了一個名為fixture02的fixture,它會回傳四組測試資料:
@pytest.fixture(params=["access", "slice", "assign", "len"])def fixture02(request):return request.param
下面的測試函式使用了fixture01和fixture02,並根據fixture02的值進行不同的操作:
def test_fix_param02(fixture01, fixture02):if (fixture02 == "access"):assert (fixture01[0])elif (fixture02 == "slice"):assert fixture01[::-1]elif (fixture02 == "assign"):fixture01[0] = 99assert Trueelif (fixture02 == "len"):assert len(fixture01)
fixture01和fixture02分別有兩組和四組測試資料。pytest會自動組合所有可能的測試資料並執行對應的測試組合,總共會執行8個測試 (2組 fixture01 乘以4組 fixture02):
- fixture01 = (3, 4),fixture02 = "access"
- fixture01 = (3, 4),fixture02 = "slice"
- fixture01 = (3, 4),fixture02 = "assign"
- fixture01 = (3, 4),fixture02 = "len"
- fixture01 = [3, 5],fixture02 = "access"
- fixture01 = [3, 5],fixture02 = "slice"
- fixture01 = [3, 5],fixture02 = "assign"
- fixture01 = [3, 5],fixture02 = "len"
具體來說,fixture02的四個值"access", "slice", "assign", 和 "len"會依據fixture01的每一組資料進行測試。每個測試組合的行為如下:
沒有留言:
張貼留言