前提:需要安裝pytest和pytest-html(生成html測試報告)
pip install pytest 和 pip install pytest-html?
一、命名規(guī)則
Pytest單元測試中的類名和方法名必須是以test開頭,執(zhí)行中只能找到test開頭的類和方法,比unittest更加嚴(yán)謹(jǐn)
案例
import pytest
from xml.dom import minidom
class TestPy01():
????def testPy001(self):????????print("第一個pytest")
????????assert1==1
????def testPy002(self):
????????print("第二個pytest")
????????assert1==2
????def testPy003(self):
????????print("第三個pytest")
????????assert1==1
if__name__=='__main__':
????pytest.main()
二、Pytest生成自帶的html測試報告
前提條件:需要下載pytest-html模塊(python自帶的生成測試報告模塊)
pip install pytest-html
2.1 方式一
格式
pytest.main("模塊.py")【運(yùn)行指定模塊下,運(yùn)行所有test開頭的類和測試用例】
pytest.main(["--html=./report.html","模塊.py"])
代碼:
pytest.main(["--html=../report1.html", "test_01.py"])

2.2 方式二
格式
運(yùn)行指定模塊指定類指定用例,冒號分割,并生成測試報告
pytest.main([‘--html=./report.html’,‘模塊.py::類::test_a_001'])
運(yùn)行指定模塊指定類指定用例,冒號分割,并生成測試報告
代碼
pytest.main(["--html=../report1.html", "test_01.py::TestPy01::testPy001"])
2.4 方式三
Pytest調(diào)用語句
pytst.main(['-x','--html=./report.html','t12est000.py'])
-x:出現(xiàn)一條測試用例失敗就退出測試
-v:豐富信息模式, 輸出更詳細(xì)的用例執(zhí)行信息
-s:顯示print內(nèi)容
-q:簡化結(jié)果信息,不會顯示每個用例的文件名
三、Pytest的運(yùn)行方式
.點(diǎn)號,表示用例通過
F表示失敗 Failure
E表示用例中存在異常 Error
四、Allure
Allure是一款輕量級并且非常靈活的開源測試報告框架。 它支持絕大多數(shù)測試框架, 例如TestNG、Pytest、JUint等。它簡單易用,易于集成。
首先配置allure的環(huán)境變量

image.png
驗(yàn)證allure是否配置成功

image.png
其次要安裝allure
pip install allure-pytest
allure-pytest是Pytest的一個插件,通過它我們可以生成Allure所需要的用于生成測試報告的數(shù)據(jù)
4.1 Allure常用的幾個特性
@allure.feature# 用于描述被測試產(chǎn)品需求@allure.story# 用于描述feature的用戶場景,即測試需求
with allure.step():# 用于描述測試步驟,將會輸出到報告中
allure.attach# 用于向測試報告中輸入一些附加的信息,通常是一些測試數(shù)據(jù),截圖等
案例
實(shí)現(xiàn)用戶登錄功能,場景為登錄成功和登錄失敗
import pytest, allure, osclass TestAllureDemo(object): @allure.feature('用戶登錄') @allure.story('登錄成功') def testLoginSuccess(self): print('登錄成功') assert 1 == 1 with allure.step("查看哈吉利系列車信息"): allure.attach("博越", "吉利") with allure.step("查看哈弗系列車信息"): allure.attach("H7", "哈弗") @allure.feature('用戶登錄') @allure.story('登錄失敗') def testLoginUnknown(self): print('登錄失敗') assert 1 == 2 @allure.feature('用戶登錄') @allure.story('登錄未知') def testLoginFail(self): print('登錄未知') assert 600 == 602if __name__ == '__main__': pytest.main(['--alluredir', 'report/result', 'allureDemomo.py']) # 生成json類型的測試報告 split = 'allure ' + 'generate ' + './report/result ' + '-o ' + './report/html ' + '--clean' # 將測試報告轉(zhuǎn)為html格式 os.system(split) # system函數(shù)可以將字符串轉(zhuǎn)化成命令在服務(wù)器上運(yùn)行
Pytest和allure效果展示

作者:Anwfly
鏈接:http://www.itdecent.cn/p/477c66abe55d
來源:簡書
著作權(quán)歸作者所有。商業(yè)轉(zhuǎn)載請聯(lián)系作者獲得授權(quán),非商業(yè)轉(zhuǎn)載請注明出處。