References: https://www.jianshu.com/p/a754e3d47671html
1. ***** Why Pytest ***** django
1) 簡單靈活,方便使用;可以支持簡單的單元測試和複雜的功能測試,還能夠用來作selenium/appnium等自動化測試、接口自動化測試(pytest+requests);
2) pytest具備不少第三方插件,而且能夠自定義擴展,比較好用的如pytest-selenium(集成selenium)、pytest-html(完美html測試報告生成)、pytest-rerunfailures(失敗case重複執行)、pytest-xdist(多CPU分發)等;
3) 測試用例的skip和xfail處理;
4) 能夠很好的和CI工具結合,例如jenkins;session
5) 兼容unitest和nose。app
3. 編寫規則:
編寫pytest測試樣例很是簡單,只須要按照下面的規則:
1) 測試文件名以test_開頭(或以_test結尾), 即測試文件名爲:test_*.py或*_test.py;
2) 測試文件中能夠包括測試函數和測試類:
a. 測試類以Test開頭,而且不能帶有 init 方法;
b. 測試函數以test_開頭;
c.一個測試類中能夠有多個test_開頭的測試函數;
3) 測試函數以test_開頭, 一個測試文件中能夠包含多個
4) 斷言使用基本的assert便可框架
4. 編寫和執行pytest函數
在執行pytest命令時,會自動從當前目錄及子目錄中尋找符合上述約束的測試函數來執行。工具
示例:
1) 編寫代碼:test_myPyTest.py以下:
class TestClass(object):
def test_one(self):
x = "this"
assert 'h' in x
def test_two(self):
x = "hello"
assert not hasattr(x, 'check')
2) 命令行,cd到test_myPyTest.py路徑,執行:pytest,則上面兩個test_函數都被執行,且輸出結果以下:
>pytest
============================= test session starts =============================
platform win32 -- Python 2.7.11, pytest-4.3.0, py-1.8.0, pluggy-0.9.0
rootdir: C:\Users\tracy.tan\workspace\TracyTest\src\PY\tests\my, inifile:
collected 2 items單元測試
test_myPyTest.py .. [100%]開發工具
========================== 2 passed in 0.06 seconds ===========================測試
5. 執行pytest不一樣的參數:
1) 文件/路徑相關參數
pytest # 運行當前文件夾下全部test_開頭的函數
pytest test_mod.py # 運行module 文件test_mod.py中test_開頭的函數 run tests in module file test_mod.py
pytest somepath # 運行指定路徑(somepath,如:./tests/)中test_開頭的函數
pytest -k stringexpr # 只運行函數命中匹配stringexpr的test_開頭的函數(須要測試證實)
pytest test_mod.py::test_func # 只運行知足須要的函數 (須要測試證實)
2) Console參數介紹
-v 用於顯示每一個測試函數的執行結果
-q 只顯示總體測試結果
-s 用於顯示測試函數中print()函數輸出
-x, --exitfirst, exit instantly on first error or failed test
-h 幫助
6. pytest經常使用插件:
pytest-django: 針對Django框架的單測框架
pytest-twisted: 針對twisted框架的單測框架
pytest-cov: 產生覆蓋率報告
pytest-instafail: 發送錯誤時報告錯誤信息
pytest-bdd 測試驅動開發工具
pytest-konira 測試驅動開發工具
pytest-timeout: 支持超時功能
pytest-pep8: 支持PEP8檢查
pytest-flakes: 結合pyflakes進行代碼檢查
7. 測試報告
pytest能夠方便的生成測試報告,便可以生成HTML的測試報告,也能夠生成XML格式的測試報告用來與持續集成工具集成。
1) 生成HTML格式報告:
pytest --resultlog=path
2) 生成XML格式的報告:
py.test --junitxml=path
八、如何獲取幫助信息
py.test --version # shows where pytest was imported frompy.test --fixtures # show available builtin function argumentspy.test -h | --help # show help on command line and config file options