1、介紹
pytest是python的一種單元測試框架,同自帶的unittest測試框架類似,相比于unittest框架使用起來更簡潔、效率更高
pip install -U pytest
特點:
1.非常容易上手,入門簡單,文檔豐富,文檔中有很多實例可以參考
2.支持簡單的單元測試和復雜的功能測試
3.支持參數化
4.執行測試過程中可以將某些測試跳過,或者對某些預期失敗的Case標記成失敗
5.支持重復執行失敗的Case
6.支持運行由Nose,Unittest編寫的測試Case
7.具有很多第三方插件,并且可以自定義擴展
8.方便的和持續集成工具集成
2、入門案例
import pytestdef test_a():print("test_a")return 1 * 0def test_b():print("test_b")return 1 / 0if __name__ == '__main__':pytest.main(["-s"])
3、配置文件
默認規則:
模塊名稱為 test_*.py
或 *_test.py
類名稱為Test
開頭
配置文件:pytest.ini
[pytest]
addopts = -s # 通常是- 或者 -- 開頭內容
testpaths = ./ # 測試模塊所在目錄
python_files = test_*.py *test.py # 測試模塊文件名稱規則,多個內容用空格分隔
python_classes = Tedt_* # 測試類名稱規則
python_functions = test_* # 測試類函數或者方法的名稱規則
4、標記跳過測試
無條件跳過:
@pytest.mark.skip(reason="我想跳過")
def test_b():print("test_b")return 1 / 0@pytest.mark.xfail(raises=ZeroDivisionError)
def test_c():print("test_b")return 1 / 0
有條件跳過:
@pytest.mark.skipif(2>10,reason="條件成立跳過)
def test_c():print("test_c")
5、參數化
對于相似的過程,但數據不一樣的時候,可以使用參數化
parameterize(self.argnames, argvalues, ids=None):
- argnames 參數名稱 列表或者元組
- argvalues 參數值 列表套元組
- ids 測試id,可省略
例子:
@pytest.mark.parametrize(["a", "b"], [(1, 2), (3, 4)])
def test_a(a, b):print("test_a++++++++++++++")assert a + b < 100
6、夾具(前后固件)
在測試之前和之后執行,用于固定測試環境,及清理回收測試資源
# 方法夾具
def setup_method(self):print("方法用例執行之前,需要的操作:熱身")def teardown_method(self):print("方法用例執行之前,需要的而操作:拉伸")# 類夾具
def setup_class(self):passdef teardown_class(self):pass# 函數夾具
def teardown_function():print("函數執行之前:拉伸")def setup_function():print("函數執行之前:熱身")# 摸塊夾具
def teardown_module():print("函數執行之前:拉伸")def setup_module():print("函數執行之前:熱身")
7、插件
生成測試報告
安裝:pip install pytest-html
使用:
1、命令行方式:pytest --html=存儲路徑/report.html
2、配置文件方式:
[pytest]
addopts = -s --html=./report.html
多線程運行:pytest-xdist
控制用例的執行順序:pytest-ordeing
失敗用例重跑:pytest-returnfailures
生成企業級專業版的測試報告:allure-pytest
測試框架本身:pytest
管理基礎路徑:pytest-base-url