『德不孤』Pytest框架 — 5、Pytest失敗重試
- 2022 年 2 月 26 日
- 筆記
- 測試基礎技能 - Pytest測試框架
Pytest失敗重試就是,在執行一次測試腳本時,如果一個測試用例執行結果失敗了,則重新執行該測試用例。
前提:
Pytest測試框架失敗重試需要下載pytest-rerunfailures
插件。
安裝方式:pip install pytest-rerunfailures
。
Pytest實現失敗重試的方式:
方式一:在命令行或者main()函數中使用。
pytest.main(['-vs','test_a.py','--reruns=2'])
(這種方式沒有實現成功,可能自己環境的問題)
或者:
pytest -vs ./test_a.py --reruns 2 --reruns-delay 2
(可以)
表示:失敗重試2次,在每次重試前會等到2秒。
說明:
reruns
為重跑次數,reruns_delay
為間隔時間,單位s
方式二:在pytest.ini
配置文件中使用。(推薦)
在pytest.ini
配置文件中addopts
添加reruns
重試參數
[pytest]
addopts = -s --reruns 2 --reruns-delay 2
testpaths = scripts
python_files = test_01.py
python_classes = Test*
python_functions = test*
示例:使用第二種方式:
"""
1.學習目標
掌握pytest中用例失敗重試方法
2.操作步驟
2.1 安裝 pytest-rerunfailures
pip install pytest-rerunfailures
2.2 使用 在pytest.ini文件中,添加一個命令行參數
--reruns n # n表示重試次數
3.需求
"""
# 1.導入pytest
import pytest
# 2.編寫測試用例
@pytest.mark.run(order=2)
def test_login():
"""登錄用例"""
print("登錄步驟")
assert "abcd" in "abcdefg"
@pytest.mark.run(order=1)
def test_register():
"""註冊用例"""
print("註冊步驟")
assert False
@pytest.mark.run(order=4)
def test_shopping():
"""購物下單"""
print("購物流程")
assert True
@pytest.mark.run(order=3)
def test_cart():
"""購物車用例"""
print("購物車流程")
assert True
if __name__ == '__main__':
pytest.main(['-vs', 'test_01.py', '--reruns=2'])
# pytest ./pytest_demo/test_01.py --reruns 10 --reruns-delay 1
#
"""
執行結果:注意有兩個:2 rerun
==================== 1 failed, 3 passed, 2 rerun in 0.09s =====================
test_01.py::test_register 註冊步驟
RERUN
test_01.py::test_register 註冊步驟
RERUN
test_01.py::test_register 註冊步驟
FAILED
pytest_demo\test_01.py:20 (test_register)
@pytest.mark.run(order=1)
def test_register():
""註冊用例""
print("註冊步驟")
> assert False
E assert False
test_01.py:25: AssertionError
登錄步驟
PASSED購物車流程
PASSED購物流程
PASSED
"""
注意:如果設置失敗重試5次,在重試的過程中成功了,就不用全部跑完5次重試,這裡需要注意一下。