pytest單元測試基本使用
一.pytest安裝
pip install pytest:安裝
pip install pytest==version:指定版本安裝
pytest --version:檢視版本
pip install -u pytest:更新
pip install pytest-html:安裝html報告外掛
pytest --html=url:生成html報告
二.定義檔案,類,函式規範
1.定函式時,函式名字前加個test_,如:def test_one: print "xxxxx"
2.定義class的時候Test...,以Test開頭,如:Testclasee
3.定義.py檔案的時候以test_開頭,如:test_case
三.pytest常用引數
pytest -h:檢視幫助
pytest --collect-only package名:收集要執行檔案中的哪些函式,但是不執行
pytest -vpackage名:-v可檢視具體哪個檔案下的哪個函式執行錯誤或失敗
pytest -k “函式1 or 函式2”:指定一些test_函式執行
pytest -m “引數“ package名:指定引數執行函式(可在函式上方標記引數@pytest.mark.引數)
pytest -x package:遇到一個錯誤時停止執行(在-x 後加個-v可檢視具體哪個檔案下的哪個函式執行錯誤或失敗)
pytest --maxfail=x package名:設定最大錯誤數,當執行錯誤大於x後停止執行
pytest -s package名:列印函式中的print顯示在命令列
pytest --lf package名:顯示執行錯誤的函式資訊
pytest --ff package名:正確的錯誤的都顯示出來
5.fixture
1.pytest.fixture可用在普通函式上面,test_函式引用時可直接使用函式名引用返回值
2.fixture優先順序執行
(1).在根目錄下新建配置檔案conftest.py
(2)在conftest.py檔案下編寫執行前後的程式
所有用例執行前後
每個檔案.py執行前後
每個class執行前後
每個function執行前後
6.parametrize引數化(資料驅動)
若引數場景過多時可以匯入csv檔案或連線資料庫
7.pytest-order排序
(1).安裝
pip install pytest-order
(2).編寫
可定義在class和function上,數字也可為-1,-2,-3,-表示倒數執行
若編寫好執行順序後需要在中間插入一條case,before=“函式名”