pytest測試函數標記
1.用例標簽tags:@pytest.mark.{marker_name}
描述:@pytest.mark.{marker_name}自定義一個mark,然后pytest -v -m {marker_name}只運行標記了{marker_name}的函數,pytest -v -m "not {marker_name}"來運行未標記{marker_name}的。
語法:
ep:
@pytest.mark.smoke
@pytest.mark.get
$pytest -m 'smoke'
僅運行標記smoke的函數
$pytest -m 'smoke and get'
運行標記smoke和get的函數
$pytest -m 'smoke or get'
運行標記smoke或get的函數
$pytest -m 'smoke and not get'
運行標記smoke和標記不是get的函數
2. 跳過用例:@pytest.mark.skip @pytest.mark.skipif
描述:skip和skipif可以標記無法在某些平台上運行的測試功能,或者您希望失敗的測試功能。要給跳過的測試添加理由和條件,應當使用skipif。
語法:
ep:
@pytest.mark.skipif(condition)
@pytest.mark.skipif(tasks.__version__<'0.2.0',reason = 'not supported until version 0.2.0)
使用skip和skipif標記,測試會直接跳過,而不會被執行。
3.標記函數參數化(測試用例方法前加測試數據):@pytest.mark.parametrize("a,b,expected", testdata)
語法:
- ep1 傳入單個參數
@pytest.mark.parametrize('參數名',lists)
- ep2 傳入兩個參數
@pytest.mark.parametrize('參數1','參數2',[(
參數1_data[0],參數2_data[0]),(
參數1_data[1],參數2_data[1])]
傳三個或者更多也是這樣傳。list的每個元素都是一個元祖,元祖里的每個元素和按參數順序一一對應。
實例1:傳兩個參數
1 import pytest 2 @pytest.mark.parametrize("test_input,expected", 3 [ ("3+5", 8), 4 ("2+4", 6), 5 ("6 * 9", 42), 6 ]) 7 def test_eval(test_input, expected): 8 assert eval(test_input) == expected 9 10 if __name__ == "__main__": 11 pytest.main(["-s", "test_canshu1.py"])
實例2:參數組合
1 import pytest 2 @pytest.mark.parametrize("x", [0, 1]) 3 @pytest.mark.parametrize("y", [2, 3]) 4 def test_foo(x, y): 5 print("測試數據組合:x->%s, y->%s" % (x, y)) 6 7 結果: 8 test_canshu1.py 測試數據組合:x->0, y->2 9 .測試數據組合:x->1, y->2 10 .測試數據組合:x->0, y->3 11 .測試數據組合:x->1, y->3 .
實例3:傳一個參數
1 import pytest 2 @pytest.mark.parametrize('task', tasks_to_try) 3 def test_add_4(task): 4 task_id = tasks.add(task) 5 t_from_db = tasks.get(task_id) 6 assert equivalent(t_from_db, task)
4.fixture參數化:@pytest.fixture(params=[{key11:value1,key12:value2} , {key21:value21,key22:value22}])
代碼實例:
import pytest @pytest.fixture(params=[{'userID':'00001','username':'jack'}, {'userID':'00002','username':'mike'}]) def getdata(request): #這里的request是固定參數名 #分別打印params的字典項:{'userID': '00001', 'username': 'jack'} #和{'userID':'00002','username':'mike'} print("request.param======",request.param) return request.param #這里的request.param也是固定的 class TestCase(): def test_case1(self, getdata): print("第1個用例輸出:{}".format(getdata)) def test_case2(self, getdata): print("第2個用例輸出:{}".format(getdata))
其他mark
-
標記用例執行順順序
pytest.mark.run(order=1)
(需安裝pytest-ordering) -
標記使用指定fixture(測試准備及清理方法)
@pytest.mark.usefixtures()
- 標記超時時間
@pytest.mark.timeout(60)
(需安裝pytest-timeout)- 或命令$pytest --timeout=300
- 標記失敗重跑次數
@pytest.mark.flaky(reruns=5, reruns_delay=1)
(需安裝pytest-rerunfailures)- 最多失敗重跑5次 & 如果失敗則延遲1秒后重跑(可以不傳)
- 或命令$pytest --reruns 5 --reruns-delay 1
- 標記類中用例按定義(書寫)順序執行(某一條失敗則后面的用例不會執行)
@pytest.mark.incremental