Python測試框架pytest高階用法全面詳解
前言
Python測試框架之前一直用的是unittest+HTMLTestRunner,聽到有人說pytest很好用,所以這段時間就看了看pytest文檔,在這里做個記錄。
官方文檔介紹:
Pytest is a framework that makes building simple and scalable tests easy. Tests are expressive and readable—no boilerplate code required. Get started in minutes with a small unit test or complex functional test for your application or library.
pytest是一個非常成熟的全功能的Python測試框架,主要有以下幾個特點:
- 簡單靈活,容易上手
- 支持參數(shù)化
- 能夠支持簡單的單元測試和復雜的功能測試,還可以用來做selenium/appnium等自動化測試、接口自
- 動化測試(pytest+requests)
- pytest具有很多第三方插件,并且可以自定義擴展,比較好用的如pytest-selenium(集成
- selenium)、pytest-html(完美html測試報告生成)、pytest-rerunfailures(失敗case重復執(zhí)
- 行)、pytest-xdist(多CPU分發(fā))等
- 測試用例的skip和xfail處理
- 可以很好的和jenkins集成
- report框架----allure 也支持了pytest
1.pytest安裝
1.1安裝
pip install -U pytest
1.2驗證安裝
pytest --version # 會展示當前已安裝版本
1.3pytest文檔
官方文檔:https://docs.pytest.org/en/latest/contents.html
在pytest框架中,有如下約束:
- 所有的單測文件名都需要滿足test_*.py格式或*_test.py格式。
- 在單測文件中,測試類以Test開頭,并且不能帶有 init
方法(注意:定義class時,需要以T開頭,不然pytest是不會去運行該class的) - 在單測類中,可以包含一個或多個test_開頭的函數(shù)。
- 在執(zhí)行pytest命令時,會自動從當前目錄及子目錄中尋找符合上述約束的測試函數(shù)來執(zhí)行。
1.4 Pytest運行方式
# file_name: test_abc.py import pytest # 引入pytest包 def test_a(): # test開頭的測試函數(shù) print("------->test_a") assert 1 # 斷言成功 def test_b(): print("------->test_b") assert 0 # 斷言失敗 if __name__ == '__main__': pytest.main("-s test_abc.py") # 調(diào)用pytest的main函數(shù)執(zhí)行測試
1.測試類主函數(shù)模式
pytest.main("-s test_abc.py")
2.命令行模式
pytest 文件路徑/測試文件名 例如:pytest ./test_abc.py
1.5 Pytest Exit Code 含義清單
Exit code 0 所有用例執(zhí)行完畢,全部通過
Exit code 1 所有用例執(zhí)行完畢,存在Failed的測試用例
Exit code 2 用戶中斷了測試的執(zhí)行
Exit code 3 測試執(zhí)行過程發(fā)生了內(nèi)部錯誤
Exit code 4 pytest 命令行使用錯誤
Exit code 5 未采集到可用測試用例文件
1.6 如何獲取幫助信息
查看 pytest 版本
pytest --version
顯示可用的內(nèi)置函數(shù)參數(shù)
pytest --fixtures
通過命令行查看幫助信息及配置文件選項
pytest --help
1.7 控制測試用例執(zhí)行
1.在第N個用例失敗后,結(jié)束測試執(zhí)行
pytest -x # 第01次失敗,就停止測試 pytest --maxfail=2 # 出現(xiàn)2個失敗就終止測試
2.指定測試模塊
pytest test_mod.py
3.指定測試目錄
pytest testing/
4.通過關鍵字表達式過濾執(zhí)行
pytest -k "MyClass and not method"
這條命令會匹配文件名、類名、方法名匹配表達式的用例,這里這條命令會運行 TestMyClass.test_something, 不會執(zhí)行 TestMyClass.test_method_simple
5.通過 node id 指定測試用例
nodeid由模塊文件名、分隔符、類名、方法名、參數(shù)構(gòu)成,舉例如下:
運行模塊中的指定用例
pytest test_mod.py::test_func
運行模塊中的指定方法
ytest test_mod.py::TestClass::test_method
6.通過標記表達式執(zhí)行
pytest -m slow
這條命令會執(zhí)行被裝飾器 @pytest.mark.slow 裝飾的所有測試用例
7.通過包執(zhí)行測試
pytest --pyargs pkg.testing
這條命令會自動導入包 pkg.testing,并使用該包所在的目錄,執(zhí)行下面的用例。
1.8 多進程運行cases
當cases量很多時,運行時間也會變的很長,如果想縮短腳本運行的時長,就可以用多進程來運行。
安裝pytest-xdist:
pip install -U pytest-xdist
運行模式:
pytest test_se.py -n NUM
其中NUM填寫并發(fā)的進程數(shù)。
1.9 重試運行cases
在做接口測試時,有事會遇到503或短時的網(wǎng)絡波動,導致case運行失敗,而這并非是我們期望的結(jié)果,此時可以就可以通過重試運行cases的方式來解決。
安裝pytest-rerunfailures:
pip install -U pytest-rerunfailures
運行模式:
pytest test_se.py --reruns NUM
NUM填寫重試的次數(shù)。
1.10 顯示print內(nèi)容
在運行測試腳本時,為了調(diào)試或打印一些內(nèi)容,我們會在代碼中加一些print內(nèi)容,但是在運行pytest時,這些內(nèi)容不會顯示出來。如果帶上-s,就可以顯示了。
運行模式:
pytest test_se.py -s
另外,pytest的多種運行模式是可以疊加執(zhí)行的,比如說,你想同時運行4個進程,又想打印出print的內(nèi)容。可以用:
pytest test_se.py -s -n 4
2.Pytest的setup和teardown函數(shù)
1.setup和teardown主要分為:模塊級,類級,功能級,函數(shù)級。
2.存在于測試類內(nèi)部
代碼示例:
函數(shù)級別setup()/teardown()
運行于測試方法的始末,即:運行一次測試函數(shù)會運行一次setup和teardown
import pytest class Test_ABC: # 函數(shù)級開始 def setup(self): print("------->setup_method") # 函數(shù)級結(jié)束 def teardown(self): print("------->teardown_method") def test_a(self): print("------->test_a") assert 1 def test_b(self): print("------->test_b") if __name__ == '__main__': pytest.main("-s test_abc.py")
執(zhí)行結(jié)果: test_abc.py ------->setup_method # 第一次 setup() ------->test_a . ------->teardown_method # 第一次 teardown() ------->setup_method # 第二次 setup() ------->test_b . ------->teardown_method # 第二次 teardown()
類級別
運行于測試類的始末,即:在一個測試內(nèi)只運行一次setup_class和teardown_class,不關心測試類內(nèi)有多少個測試函數(shù)。
代碼示例:
import pytest class Test_ABC: # 測試類級開始 def setup_class(self): print("------->setup_class") # 測試類級結(jié)束 def teardown_class(self): print("------->teardown_class") def test_a(self): print("------->test_a") assert 1 def test_b(self): print("------->test_b") if __name__ == '__main__': pytest.main("-s test_abc.py")
執(zhí)行結(jié)果: test_abc.py ------->setup_class # 第一次 setup_class() ------->test_a . ------->test_b F ------->teardown_class # 第一次 teardown_class()
3.Pytest配置文件
pytest的配置文件通常放在測試目錄下,名稱為pytest.ini,命令行運行時會使用該配置文件中的配置.
#配置pytest命令行運行參數(shù) [pytest] addopts = -s ... # 空格分隔,可添加多個命令行參數(shù) -所有參數(shù)均為插件包的參數(shù)配置測試搜索的路徑 testpaths = ./scripts # 當前目錄下的scripts文件夾 -可自定義 #配置測試搜索的文件名稱 python_files = test*.py #當前目錄下的scripts文件夾下,以test開頭,以.py結(jié)尾的所有文件 -可自定義 配置測試搜索的測試類名 python_classes = Test_* #當前目錄下的scripts文件夾下,以test開頭,以.py結(jié)尾的所有文件中,以Test開頭的類 -可自定義 配置測試搜索的測試函數(shù)名 python_functions = test_* #當前目錄下的scripts文件夾下,以test開頭,以.py結(jié)尾的所有文件中,以Test開頭的類內(nèi),以test_開頭的方法 -可自定義
4 Pytest常用插件
插件列表網(wǎng)址:https://plugincompat.herokuapp.com
包含很多插件包,大家可依據(jù)工作的需求選擇使用。
4.1 前置條件:
1.文件路徑:
- Test_App - - test_abc.py - - pytest.ini
2.pyetst.ini配置文件內(nèi)容:
[pytest] # 命令行參數(shù) addopts = -s # 搜索文件名 python_files = test_*.py # 搜索的類名 python_classes = Test_* #搜索的函數(shù)名 python_functions = test_*
4.2 Pytest測試報告
pytest-HTML是一個插件,pytest用于生成測試結(jié)果的HTML報告。兼容Python 2.7,3.6
安裝方式:pip install pytest-html
pip install pytest-html
通過命令行方式,生成xml/html格式的測試報告,存儲于用戶指定路徑。插件名稱:pytest-html
使用方法: 命令行格式:pytest --html=用戶路徑/report.html
示例:
import pytest class Test_ABC: def setup_class(self): print("------->setup_class") def teardown_class(self): print("------->teardown_class") def test_a(self): print("------->test_a") assert 1 def test_b(self): print("------->test_b") assert 0 # 斷言失敗``` 運行方式: 1.修改Test_App/pytest.ini文件,添加報告參數(shù),即:addopts = -s --html=./report.html # -s:輸出程序運行信息 # --html=./report.html 在當前目錄下生成report.html文件 ? 若要生成xml文件,可將--html=./report.html 改成 --html=./report.xml 2.命令行進入Test_App目錄 3.執(zhí)行命令: pytest 執(zhí)行結(jié)果: 1.在當前目錄會生成assets文件夾和report.html文件
5.pytest的高階用法(一)
前置條件:
1.文件路徑:
Test_App - - test_abc.py - - pytest.ini
2.pyetst.ini配置文件內(nèi)容:
[pytest] 命令行參數(shù) addopts = -s 搜索文件名 python_files = test*.py 搜索的類名 python_classes = Test* 搜索的函數(shù)名 python_functions = test_*
5.1pytest之fixture
fixture修飾器來標記固定的工廠函數(shù),在其他函數(shù),模塊,類或整個工程調(diào)用它時會被激活并優(yōu)先執(zhí)行,通常會被用于完成預置處理和重復操作。
方法:
fixture(scope="function", params=None, autouse=False, ids=None, name=None)
常用參數(shù):
scope:被標記方法的作用域
function(default):作用于每個測試方法,每個test都運行一次
class:作用于整個類,每個class的所有test只運行一次
module:作用于整個模塊,每個module的所有test只運行一次
session:作用于整個session(慎用),每個session只運行一次
params:(list類型)提供參數(shù)數(shù)據(jù),供調(diào)用標記方法的函數(shù)使用
autouse:是否自動運行,默認為False不運行,設置為True自動運行
5.2fixture第一個例子(通過參數(shù)引用)
示例:
class Test_ABC: @pytest.fixture() def before(self): print("------->before") def test_a(self,before): # ? test_a方法傳入了被fixture標識的函數(shù),已變量的形式 print("------->test_a") assert 1 if __name__ == '__main__': pytest.main("-s test_abc.py") 執(zhí)行結(jié)果: test_abc.py ------->before # 發(fā)現(xiàn)before會優(yōu)先于測試函數(shù)運行 ------->test_a .
5.3.fixture第二個例子(通過函數(shù)引用)
示例:
import pytest @pytest.fixture() # fixture標記的函數(shù)可以應用于測試類外部 def before(): print("------->before") @pytest.mark.usefixtures("before") class Test_ABC: def setup(self): print("------->setup") def test_a(self): print("------->test_a") assert 1 if __name__ == '__main__': pytest.main("-s test_abc.py") 執(zhí)行結(jié)果: test_abc.py ------->before # 發(fā)現(xiàn)before會優(yōu)先于測試類運行 ------->setup ------->test_a .
5.4.fixture第三個例子(默認設置為運行)
示例:
import pytest @pytest.fixture(autouse=True) # 設置為默認運行 def before(): print("------->before") class Test_ABC: def setup(self): print("------->setup") def test_a(self): print("------->test_a") assert 1 if __name__ == '__main__': pytest.main("-s test_abc.py") 執(zhí)行結(jié)果: test_abc.py ------->before # 發(fā)現(xiàn)before自動優(yōu)先于測試類運行 ------->setup ------->test_a .
5.5.fixture第四個例子(設置作用域為function)
示例:
import pytest @pytest.fixture(scope='function',autouse=True) # 作用域設置為function,自動運行 def before(): print("------->before") class Test_ABC: def setup(self): print("------->setup") def test_a(self): print("------->test_a") assert 1 def test_b(self): print("------->test_b") assert 1 if __name__ == '__main__': pytest.main("-s test_abc.py") 執(zhí)行結(jié)果: test_abc.py ------->before # 運行第一次 ------->setup ------->test_a .------->before # 運行第二次 ------->setup ------->test_b .
5.6.fixture第五個例子(設置作用域為class)
示例:
import pytest @pytest.fixture(scope='class',autouse=True) # 作用域設置為class,自動運行 def before(): print("------->before") class Test_ABC: def setup(self): print("------->setup") def test_a(self): print("------->test_a") assert 1 def test_b(self): print("------->test_b") assert 1 if __name__ == '__main__': pytest.main("-s test_abc.py") 執(zhí)行結(jié)果: test_abc.py ------->before # 發(fā)現(xiàn)只運行一次 ------->setup ------->test_a . ------->setup ------->test_b .
5.7.fixture第六個例子(返回值)
示例一:
import pytest @pytest.fixture() def need_data(): return 2 # 返回數(shù)字2 class Test_ABC: def test_a(self,need_data): print("------->test_a") assert need_data != 3 # 拿到返回值做一次斷言 if __name__ == '__main__': pytest.main("-s test_abc.py") 執(zhí)行結(jié)果: test_abc.py ------->test_a . ``
示例二:
import pytest @pytest.fixture(params=[1, 2, 3]) def need_data(request): # 傳入?yún)?shù)request 系統(tǒng)封裝參數(shù) return request.param # 取列表中單個值,默認的取值方式 class Test_ABC: def test_a(self,need_data): print("------->test_a") assert need_data != 3 # 斷言need_data不等于3 if __name__ == '__main__': pytest.main("-s test_abc.py") 執(zhí)行結(jié)果: # 可以發(fā)現(xiàn)結(jié)果運行了三次 test_abc.py 1 ------->test_a . 2 ------->test_a . 3 ------->test_a F
6.Pytest高階用法(二)
前置條件:
1.文件路徑:
- Test_App - - test_abc.py - - pytest.ini
2.pyetst.ini配置文件內(nèi)容:
[pytest] 命令行參數(shù) addopts = -s 搜索文件名 python_files = test_*.py 搜索的類名 python_classes = Test_* 搜索的函數(shù)名 python_functions = test_*
6.1.跳過測試函數(shù)
根據(jù)特定的條件,不執(zhí)行標識的測試函數(shù).
方法:
skipif(condition, reason=None)
參數(shù):
condition
:跳過的條件,必傳參數(shù)
reason
:標注原因,必傳參數(shù)
使用方法:
@pytest.mark.skipif(condition, reason="xxx")
示例:
import pytest class Test_ABC: def setup_class(self): print("------->setup_class") def teardown_class(self): print("------->teardown_class") def test_a(self): print("------->test_a") assert 1 @pytest.mark.skipif(condition=2>1,reason = "跳過該函數(shù)") # 跳過測試函數(shù)test_b def test_b(self): print("------->test_b") assert 0 執(zhí)行結(jié)果: test_abc.py ------->setup_class ------->test_a #只執(zhí)行了函數(shù)test_a . ------->teardown_class s # 跳過函數(shù)```
6.2 標記為預期失敗函數(shù)
標記測試函數(shù)為失敗函數(shù)
方法:
xfail(condition=None, reason=None, raises=None, run=True, strict=False)
常用參數(shù):
condition
:預期失敗的條件,必傳參數(shù)
reason
:失敗的原因,必傳參數(shù)
使用方法:
@pytest.mark.xfail(condition, reason="xx")
示例:
import pytest class Test_ABC: def setup_class(self): print("------->setup_class") def teardown_class(self): print("------->teardown_class") def test_a(self): print("------->test_a") assert 1 @pytest.mark.xfail(2 > 1, reason="標注為預期失敗") # 標記為預期失敗函數(shù)test_b def test_b(self): print("------->test_b") assert 0 執(zhí)行結(jié)果: test_abc.py ------->setup_class ------->test_a . ------->test_b ------->teardown_class x # 失敗標記
6.3 函數(shù)數(shù)據(jù)參數(shù)化
方便測試函數(shù)對測試屬于的獲取。
方法:
parametrize(argnames, argvalues, indirect=False, ids=None, scope=None)
常用參數(shù):
argnames
:參數(shù)名
argvalues
:參數(shù)對應值,類型必須為list
當參數(shù)為一個時格式:[value]
當參數(shù)個數(shù)大于一個時,格式為:
[(param_value1,param_value2.....),(param_value1,param_value2.....)]
使用方法:
@pytest.mark.parametrize(argnames,argvalues)
參數(shù)值為N個,測試方法就會運行N次
單個參數(shù)示例:
import pytest class Test_ABC: def setup_class(self): print("------->setup_class") def teardown_class(self): print("------->teardown_class")
@pytest.mark.parametrize("a",[3,6]) # a參數(shù)被賦予兩個值,函數(shù)會運行兩遍 def test_a(self,a): # 參數(shù)必須和parametrize里面的參數(shù)一致 print("test data:a=%d"%a) assert a%3 == 0 執(zhí)行結(jié)果: test_abc.py ------->setup_class test data:a=3 # 運行第一次取值a=3 . test data:a=6 # 運行第二次取值a=6 . ------->teardown_class
多個參數(shù)示例:
import pytest class Test_ABC: def setup_class(self): print("------->setup_class") def teardown_class(self): print("------->teardown_class")
@pytest.mark.parametrize("a,b",[(1,2),(0,3)]) # 參數(shù)a,b均被賦予兩個值,函數(shù)會運行兩遍 def test_a(self,a,b): # 參數(shù)必須和parametrize里面的參數(shù)一致 print("test data:a=%d,b=%d"%(a,b)) assert a+b == 3 執(zhí)行結(jié)果: test_abc.py ------->setup_class test data:a=1,b=2 # 運行第一次取值 a=1,b=2 . test data:a=0,b=3 # 運行第二次取值 a=0,b=3 . ------->teardown_class
函數(shù)返回值類型示例:
import pytest def return_test_data(): return [(1,2),(0,3)] class Test_ABC: def setup_class(self): print("------->setup_class") def teardown_class(self): print("------->teardown_class")
@pytest.mark.parametrize("a,b",return_test_data()) # 使用函數(shù)返回值的形式傳入?yún)?shù)值 def test_a(self,a,b): print("test data:a=%d,b=%d"%(a,b)) assert a+b == 3 執(zhí)行結(jié)果: test_abc.py ------->setup_class test data:a=1,b=2 # 運行第一次取值 a=1,b=2 . test data:a=0,b=3 # 運行第二次取值 a=0,b=3 . ------->teardown_class
6.4 修改 Python traceback 輸出
pytest --showlocals # show local variables in tracebacks pytest -l # show local variables (shortcut) pytest --tb=auto # (default) 'long' tracebacks for the first and last # entry, but 'short' style for the other entries pytest --tb=long # exhaustive, informative traceback formatting pytest --tb=short # shorter traceback format pytest --tb=line # only one line per failure pytest --tb=native # Python standard library formatting pytest --tb=no # no traceback at all
--full-trace參數(shù)會打印更多的錯誤輸出信息,比參數(shù) --tb=long 還多,即使是 Ctrl+C 觸發(fā)的錯誤,也會打印出來
6.5 執(zhí)行失敗的時候跳轉(zhuǎn)到 PDB
執(zhí)行用例的時候,跟參數(shù) --pdb,這樣失敗的時候,每次遇到失敗,會自動跳轉(zhuǎn)到 PDB
pytest --pdb # 每次遇到失敗都跳轉(zhuǎn)到 PDB pytest -x --pdb # 第一次遇到失敗就跳轉(zhuǎn)到 PDB,結(jié)束測試執(zhí)行 pytest --pdb --maxfail=3 # 只有前三次失敗跳轉(zhuǎn)到 PDB
6.6 設置斷點
在用例腳本中加入如下python代碼,pytest會自動關閉執(zhí)行輸出的抓取,這里,其他test腳本不會受到影響,帶斷點的test上一個test正常輸出
import pdb; pdb.set_trace()
6.7 獲取用例執(zhí)行性能數(shù)據(jù)
獲取最慢的10個用例的執(zhí)行耗時
pytest --durations=10
6.8 生成 JUnitXML 格式的結(jié)果文件
這種格式的結(jié)果文件可以被Jenkins或其他CI工具解析
pytest --junitxml=path
6.9禁用插件
例如,關閉 doctest 插件
pytest -p no:doctest
6.10 從Python代碼中調(diào)用pytest
pytest.main() # 基本用法 pytest.main(['-x', 'mytestdir']) # 傳入配置參數(shù) // 指定自定義的或額外的插件 # content of myinvoke.py import pytest class MyPlugin(object): def pytest_sessionfinish(self): print("*** test run reporting finishing") pytest.main(["-qq"], plugins=[MyPlugin()])
6.11 測試腳本遷移后快速部署包含pytest的virtualenv
例如你從Gitlab倉庫里clone了項目組的刀刀同學編寫的測試腳本到你自己的電腦里,你想修改些東西,并調(diào)試,咋辦?可以通過下面的操作快速創(chuàng)建 VirtualEnv
cd <repository> pip install -e .
This will set up a symlink to your code in site-packages, allowing you to edit your code while
your tests run against it as if it were installed.
Setting up your project in development mode lets you avoid having to reinstall every time you want to run your tests,
and is less brittle than mucking about with sys.path to point your tests at local code.
Also consider using tox
遇到的問題
pytest可以輸出覆蓋率的html報告
使用命令如下:
pytest -vv --cov=./ --cov-report=html open htmlcov/index.html
有可能遇到報錯:
(venv) zhangxiaofans-MacBook-Pro:mgap-mendel joe$ pytest --cov-report=html usage: pytest [options] [file_or_dir] [file_or_dir] [...] pytest: error: unrecognized arguments: --cov-report=html inifile: None rootdir: /Users/joe/workspace/platform/mgap-mendel/mgap-mendel
原因:
缺少pytest cov的包
解決方法
pip install pytest-cov
以上就是Python測試框架pytest高階用法全面詳解的詳細內(nèi)容,更多關于Python測試框架pytest的資料請關注腳本之家其它相關文章!
相關文章
Python+pandas編寫命令行腳本操作excel的tips詳情
這篇文章主要介紹了Python+pandas編寫命令行腳本操作excel的tips詳情,文章圍繞主題展開詳細的內(nèi)容介紹,具有一定的參考價值,需要的朋友可以參考一下2022-07-07python 找出list中最大或者最小幾個數(shù)的索引方法
今天小編就為大家分享一篇python 找出list中最大或者最小幾個數(shù)的索引方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-10-10解鎖Python中神器vars內(nèi)置函數(shù)的使用
vars()函數(shù)是一個內(nèi)置函數(shù),用于返回對象的__字典__,其中包含對象的__屬性__,本文主要為大家詳細介紹了vars()函數(shù)的具體使用,需要的小伙伴可以了解下2023-11-11pytorch模型的定義、修改、讀取、斷點續(xù)訓深入解析
模型定義是深度學習中重要的一環(huán),PyTorch提供了強大而靈活的工具和函數(shù),使我們能夠輕松定義各種類型的深度學習模型,通過深入理解模型定義的原理和應用,我們能夠更好地理解和設計自己的模型,從而提升深度學習任務的性能和效果2024-03-03Python之tkinter列表框Listbox與滾動條Scrollbar解讀
這篇文章主要介紹了Python之tkinter列表框Listbox與滾動條Scrollbar解讀,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-05-05