前言
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組合參數。
---------------------------------pytest結合selenium自動化完整版-------------------------
全書購買地址 https://yuedu.baidu.com/ebook/902224ab27fff705cc1755270722192e4536582b
作者:上海-悠悠 QQ交流群:874033608
也可以關注下我的個人公眾號:yoyoketang