pytest文件5-引數化parametrize
阿新 • • 發佈:2021-07-01
pytest.mark.parametrize裝飾器可以實現測試用例引數化。
parametrizing
1.這裡是一個實現檢查一定的輸入和期望輸出測試功能的典型例子
# content of test_expectation.py
# coding:utf-8
import pytest
@pytest.mark.parametrize("test_input,expected",
[ ("3+5", 8),
("2+4", 6),
("6 * 9", 42),
])
def test_eval(test_input, expected):
assert eval(test_input) == expected
if __name__ == "__main__":
pytest.main(["-s", "test_canshu1.py"])
執行結果
================================== FAILURES ===================================
_____________________________ test_eval[6 * 9-42] _____________________________
test_input = '6 * 9', expected = 42
@pytest.mark.parametrize("test_input,expected",
[ ("3+5", 8),
("2+4", 6),
("6 * 9", 42),
])
def test_eval(test_input, expected):
> assert eval(test_input) == expected
E AssertionError: assert 54 == 42
E + where 54 = eval('6 * 9')
test_canshu1.py:11: AssertionError
===================== 1 failed, 2 passed in 1.98 seconds ======================
在這個例子中設計的,只有一條輸入/輸出值的簡單測試功能。和往常一樣
函式的引數,你可以在執行結果看到在輸入和輸出值
2.它也可以標記單個測試例項在引數化,例如使用內建的mark.xfail
# content of test_expectation.py
import pytest
@pytest.mark.parametrize("test_input,expected", [
("3+5", 8),
("2+4", 6),
pytest.param("6 * 9", 42, marks=pytest.mark.xfail),
])
def test_eval(test_input, expected):
print("-------開始用例------")
assert eval(test_input) == expected
if __name__ == "__main__":
pytest.main(["-s", "test_canshu1.py"])
執行結果:
test_canshu1.py -------開始用例------
.-------開始用例------
.-------開始用例------
x
===================== 2 passed, 1 xfailed in 1.84 seconds =====================
標記為失敗的用例,預期結果是失敗,實際執行也是失敗,顯示xfailed
引數組合
1.若要獲得多個引數化引數的所有組合,可以堆疊引數化裝飾器
import pytest
@pytest.mark.parametrize("x", [0, 1])
@pytest.mark.parametrize("y", [2, 3])
def test_foo(x, y):
print("測試資料組合:x->%s, y->%s" % (x, y))
if __name__ == "__main__":
pytest.main(["-s", "test_canshu1.py"])
執行結果
test_canshu1.py 測試資料組合:x->0, y->2
.測試資料組合:x->1, y->2
.測試資料組合:x->0, y->3
.測試資料組合:x->1, y->3
.
========================== 4 passed in 1.75 seconds ===========================
這將執行測試,引數設定為x=0/y=2,x=1/y=2,x=0/y=3,x=1/y=3組合引數。