Python測試框架pytest介紹
一、Pytest簡介
Pytest is a mature full-featured Python testing tool that helps you write better programs.The pytest framework makes it easy to write small tests, yet scales to support complex functional testing for applications and libraries.
通過官方網(wǎng)站介紹我們可以了解到,Pytest是一個非常成熟的全功能的python測試框架,主要有以下幾個特點:
- 簡單靈活易上手
- 支持參數(shù)化
- 支持簡單的單元測試和復(fù)雜的功能測試,還可以用來做自動化測試
- 具有很多第三方插件,并且可以自定義擴展
- 測試用例的skip和xfail處理
- 可以很好的和Jenkins集成
- 支持運行由Nose、UnitTest編寫的測試用例
二、Pytest安裝
1.直接使用pip命令安裝:
pip install -U pytest ? ?# -U是如果已安裝會自動升級最新版本
2.驗證安裝結(jié)果:
pytest --version ? ?# 展示當(dāng)前安裝版本 C:\Users\edison>pytest --version pytest 6.2.5
3.在pytest測試框架中,要遵循以下約束:
測試文件名要符合test_.py或_test.py格式(例如test_min.py)
測試類要以Test開頭,且不能帶有init方法
在單個測試類中,可以包含一個或多個test_開頭的函數(shù)
三、Pytest測試執(zhí)行
pytest進行測試比較簡單,我們來看一個實例:
import pytest ? ?# 導(dǎo)入pytest包
def test_001(): ? ?# 函數(shù)以test_開頭
? ? print("test_01")
def test_002():
? ? print("test_02")
if __name__ == '__main__':
? ? pytest.main(["-v","test_1214.py"]) ? ?# 調(diào)用pytest的main函數(shù)執(zhí)行測試這里我們定義了兩個測試函數(shù),直接打印出結(jié)果,下面執(zhí)行測試:
============================= test session starts ============================= platform win32 -- Python 3.8.0, pytest-6.2.5, py-1.11.0, pluggy-1.0.0 -- D:\Code\venv\Scripts\python.exe cachedir: .pytest_cache rootdir: D:\Code collecting ... collected 2 items test_1214.py::test_001 PASSED ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?[ 50%] test_1214.py::test_002 PASSED ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?[100%] ============================== 2 passed in 0.11s ============================== Process finished with exit code 0
輸出結(jié)果中顯示執(zhí)行了多少條案例、對應(yīng)的測試模塊、通過條數(shù)以及執(zhí)行耗時。
四、測試類主函數(shù)
pytest.main(["-v","test_1214.py"])
通過python代碼執(zhí)行pytest.main():
直接執(zhí)行pytest.main() 【自動查找當(dāng)前目錄下,以test_開頭的文件或者以_test結(jié)尾的py文件】;
設(shè)置pytest的執(zhí)行參數(shù) pytest.main([’–html=./report.html’,‘test_login.py’])【執(zhí)行test_login.py文件,并生成html格式的報告】。
main()括號內(nèi)可傳入執(zhí)行參數(shù)和插件參數(shù),通過[]進行分割,[]內(nèi)的多個參數(shù)通過‘逗號,’進行分割:
運行目錄及子包下的所有用例 pytest.main([‘目錄名’])
運行指定模塊所有用例 pytest.main([‘test_reg.py’])
運行指定模塊指定類指定用例pytest.main([‘test_reg.py::TestClass::test_method’]) 冒號分割
- -m=xxx: 運行打標簽的用例
- -reruns=xxx:失敗重新運行
- -q: 安靜模式, 不輸出環(huán)境信息
- -v: 豐富信息模式, 輸出更詳細的用例執(zhí)行信息
- -s: 顯示程序中的
print/logging輸出
–resultlog=./log.txt 生成log
–junitxml=./log.xml 生成xml報告
五、斷言方法
pytest斷言主要使用Python原生斷言方法,主要有以下幾種:
- == 內(nèi)容和類型必須同時滿足相等
- in 實際結(jié)果包含預(yù)期結(jié)果
- is 斷言前后兩個值相等
import pytest ? ?# 導(dǎo)入pytest包 def add(x,y): ? ?# 定義以test_開頭函數(shù) ? ? return x + y def test_add(): ? ? assert add(1,2) == 3 ? ?# 斷言成功 str1 = "Python,Java,Ruby" def test_in(): ? ? assert "PHP" in str1 ? ?# 斷言失敗 if __name__ == '__main__': ? ? pytest.main(["-v","test_pytest.py"]) ? ?# 調(diào)用main函數(shù)執(zhí)行測試
============================= test session starts ============================= platform win32 -- Python 3.8.0, pytest-6.2.5, py-1.11.0, pluggy-1.0.0 -- D:\Code\venv\Scripts\python.exe cachedir: .pytest_cache rootdir: D:\Code collecting ... collected 2 items test_pytest.py::test_add PASSED ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?[ 50%] test_pytest.py::test_in FAILED ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? [100%] ================================== FAILURES =================================== ___________________________________ test_in ___________________________________ ? ? def test_in(): > ? ? ? assert "PHP" in str1 E ? ? ? AssertionError: assert 'PHP' in 'Python,Java,Ruby' test_pytest.py:11: AssertionError =========================== short test summary info =========================== FAILED test_pytest.py::test_in - AssertionError: assert 'PHP' in 'Python,Java... ========================= 1 failed, 1 passed in 0.18s ========================= Process finished with exit code 0
可以看到運行結(jié)果中明確指出了錯誤原因是“AssertionError”,因為PHP不在str1中。
六、常用命令詳解
1.運行指定案例:
if __name__ == '__main__': ? ? pytest.main(["-v","-s","test_1214.py"])
2.運行當(dāng)前文件夾包括子文件夾所有用例:
if __name__ == '__main__': ? ? pytest.main(["-v","-s","./"])
3.運行指定文件夾(code目錄下所有用例):
if __name__ == '__main__': ? ? pytest.main(["-v","-s","code/"])
4.運行模塊中指定用例(運行模塊中test_add用例):
if __name__ == '__main__': ? ? pytest.main(["-v","-s","test_pytest.py::test_add"])
5.執(zhí)行失敗的最大次數(shù)
使用表達式"–maxfail=num"來實現(xiàn)(注意:表達式中間不能存在空格),表示用例失敗總數(shù)等于num 時停止運行。


6.錯誤信息在一行展示。
在實際項目中如果有很多用例執(zhí)行失敗,查看報錯信息將會很麻煩。使用"–tb=line"命令,可以很好解決這個問題。

七、接口調(diào)用
本地寫一個查詢用戶信息的接口,通過pytest來調(diào)用,并進行接口斷言。
?# -*- coding: utf-8 -*-
?import pytest
?import requests
?
?def test_agent():
? ? ?r = requests.post(
? ? ? ? ?url="http://127.0.0.1:9000/get_user",
? ? ? ? ?data={
? ? ? ? ? ? ?"name": "吳磊",
? ? ? ? ? ? "sex": 1
? ? ? ? },
? ? ? ? headers={"Content-Type": "application/json"}
? ? )
? ? print(r.text)
? ? assert r.json()['data']['retCode'] == "00" and r.json()['data']['retMsg'] == "調(diào)用成功"
if __name__ == "__main__":
? ? pytest.main(["-v","test_api.py"])?
到此這篇關(guān)于Python測試框架pytest介紹的文章就介紹到這了,更多相關(guān)Python測試框架pytest內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Scrapy基于selenium結(jié)合爬取淘寶的實例講解
今天小編就為大家分享一篇Scrapy基于selenium結(jié)合爬取淘寶的實例講解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-06-06
關(guān)于matplotlib-legend 位置屬性 loc 使用說明
這篇文章主要介紹了關(guān)于matplotlib-legend 位置屬性 loc 使用說明,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-05-05
Python?EasyDict庫以屬性方式訪問字典元素(無需使用方括號和鍵)
在Python中,字典(dict)是一種常用的數(shù)據(jù)結(jié)構(gòu),用于存儲鍵值對,然而,有時候我們希望以屬性的方式訪問字典中的元素,而無需使用方括號和鍵,這就是EasyDict庫的用武之地,本文將深入介紹EasyDict庫,展示其強大的功能和如何通過示例代碼更好地利用它2023-12-12
Python實現(xiàn)LSTM學(xué)習(xí)的三維軌跡
這篇文章主要為大家詳細介紹了如何使用LSTM來學(xué)習(xí)和預(yù)測三維軌跡,并提供詳細的Python實現(xiàn)示例,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2024-12-12

