可以使用pytest.mark.parametrize裝飾器來對測試用例進行參數化。
對列表中的對象進行循環,然后一一賦值,這個對象可以是列表,元組,字典。
import pytest def add(a, b): return a + b @pytest.mark.parametrize("a,b,expect", [ [1, 1, 2], [2, 3, 5], [4, 5, 7] ]) def test_add(a, b, expect): assert add(a, b) == expect
執行結果:

還可以對每組參數進行標識,如下:
import pytest def add(a, b): return a + b @pytest.mark.parametrize('a,b,expect', [ pytest.param(1, 1, 2, id="first case"), pytest.param(2, 3, 5, id="second case"), pytest.param(4, 5, 8, id="third case") ]) def test_add(a, b, expect): assert add(a, b) == expect
或者用ids進行統一標記
import pytest def add(a, b): return a + b @pytest.mark.parametrize("a,b,expect", [ [1, 1, 2], [2, 3, 5], [4, 5, 9] ],ids=["第一個測試用例","第二個測試用例","第三個測試用例"]) def test_add(a, b, expect): assert add(a, b) == expect
解決標記中文顯示unicode編碼
標記時,中文在控制台顯示unicode編碼

在項目目錄下新建一個conftest.py文件,添加如下函數:
def pytest_collection_modifyitems(items): for item in items: item.name = item.name.encode('utf-8').decode('unicode-escape') item._nodeid = item.nodeid.encode('utf-8').decode('unicode-escape')
再次執行就可以顯示中文了

使用mark.xfail對參數進行標識
import pytest def add(a, b): return a + b @pytest.mark.parametrize('a,b,expect', [ pytest.param(1, 1, 2, id="first case"), pytest.param(2, 3, 5, id="second case"), pytest.param(4, 5, 8, id="third case", marks=pytest.mark.xfail(reason="這是個bug")) ]) def test_add(a, b, expect): assert add(a, b) == expect
執行結果:

讀取外部數據進行參數化
在自動化測試用例編寫中,我們一般遵循數據分離的原則,在使用pytest.mark.parametrize裝飾器進行參數化時,數據來源也可以是json,yaml,csv等文件。
如下:
我們把數據放在json文件中
# param.json { "par": [ {"a": 1,"b": 2,"expect": 3}, {"a": 2,"b": 4,"expect": 6}, {"a": 4,"b": 5,"expect": 9} ] }
測試用例:
import pytest import json def read_json(): with open("param.json", "r") as f: return json.load(f)["par"] def add(a, b): return a + b @pytest.mark.parametrize('data', read_json()) def test_add(data): a = data.get("a") b = data.get("b") expect = data.get("expect") assert add(a, b) == expect
