pytest簡單介紹
pytest:Pytest是一個使創建簡單及可擴展性測試用例變得非常方便的框架。測試用例清晰、易讀而無需大量的繁瑣代碼。只要幾分鍾你就可以對你的應用程序或者庫展開一個小型的單元測試或者復雜的功能測試。pytest支持第三方插件,靈活性較高。
官方文檔:https://pypi.org/project/pytest/5.1.0/
python支持版本:Python2.0,python3.0+
pytest功能:
- 通過python編寫腳本,簡單方便
- pytest支持調用unittest用例
- pytest支持參數化
- pytest支持並發運行
- 執行特定的用例順序
- 利用插件生成html報告
安裝: pip install pytest
查看版本號: pytest --version
快速上手
這里就直接編寫代碼了
class Test: def test_01(self): print('這是用例01') assert 1 == 1 def test_02(self): print('這是用例02') assert 2 == 2 def test_03(self): print('這是用例03') assert 1 == 2
執行代碼可以通過cmd打開文件地址也可以通過pycharm下的Terminal打開進行輸入pytest
E:\auto_test>pytest ======================================================================== test session starts ======================================================================== platform win32 -- Python 3.7.7, pytest-6.1.2, py-1.9.0, pluggy-0.13.1 rootdir: E:\auto_test collected 3 items test_01.py ..F [100%] ============================================================================= FAILURES ============================================================================== ___________________________________________________________________________ Test.test_03 ____________________________________________________________________________ self = <test_01.Test object at 0x0000020F9536F788> def test_03(self): print('這是用例03') > assert 1 == 2 E assert 1 == 2 test_01.py:12: AssertionError ----------------------------------------------------------------------- Captured stdout call ------------------------------------------------------------------------ 這是用例03 ====================================================================== short test summary info ====================================================================== FAILED test_01.py::Test::test_03 - assert 1 == 2 ==================================================================== 1 failed, 2 passed in 0.07s ====================================================================
結果解析:
我們可以從上面執行結果看到,執行了多少個用例,有多少個失敗的,且運行時間以及報錯內容
這里的執行用例規則是通過查找當前目錄下的test_*.py或者*_test.py文件,找到后進行查找test開頭的類以及test開頭的函數進行執行
知識總結
- pytest執行規則是通過調用目錄下文件名為test_*.py文件
- pytest執行時類名必須是通過Test開頭,函數也必須是test為前綴,且類Test下不能有__init__方法
- pytest斷言是通過assert進行調用
- pytest執行通過cmd進行在當前目錄執行
原文鏈接:
https://www.cnblogs.com/qican/p/13959626.html