十六單元 單元測(cè)試之pytest

前提:需要安裝pytest和pytest-html(生成html測(cè)試報(bào)告)

一.命名規(guī)則

**Pytest單元測(cè)試中的類名和方法名必須是以test開頭

importpytest

fromxml.domimportminidom

classTestPy01():

deftestPy001(self):

print("第一個(gè)pytest")

assert1==1

deftestPy002(self):

print("第二個(gè)pytest")

assert1==2

deftestPy003(self):

print("第三個(gè)pytest")

assert1==1

if__name__=='__main__':

pytest.main()

二、Pytest生成自帶的html測(cè)試報(bào)告

前提條件:需要下載pytest-html模塊(python自帶的生成測(cè)試報(bào)告模塊)

方式一:

pytest.main(["--html=./report.html","模塊.py"])

方式二:

pytest.main([‘--html=./report.html’,‘模塊.py::類::test_a_001'])

方式三:

pytst.main(['-x','--html=./report.html','t12est000.py'])

-x:出現(xiàn)一條測(cè)試用例失敗就退出測(cè)試

-v:豐富信息模式,輸出更詳細(xì)的用例執(zhí)行信息

-s:顯示print內(nèi)容

-q:簡(jiǎn)化結(jié)果信息,不會(huì)顯示每個(gè)用例的文件名



跳過該用例使用@pytest.mark.skip()

@pytest.mark.skip()

deftest001(self):

assert2==2

三、Pytest的運(yùn)行方式

.點(diǎn)號(hào),表示用例通過

F表示失敗Failure

E表示用例中存在異常Error

四、文件讀取

##讀取csv文件

importcsv#導(dǎo)入csv模塊

classReadCsv():

defread_csv(self):

item=[]#定義一個(gè)空列表

c=csv.reader(open("../commonDemo/test1.csv","r"))#得到csv文件對(duì)象

forcsv_iinc:

item.append(csv_i)#將獲取的數(shù)據(jù)添加到列表中

returnitem


r=ReadCsv()

print(r.read_csv())

##讀取xml文件

fromxml.domimportminidom

classReadxml():

defread_xml(self,filename,onename,twoname):

root=minidom.parse(filename)

firstnode=root.getElementsByTagName(onename)[0]

secondnode=firstnode.getElementsByTagName(twoname)[0].firstChild.data

returnsecondnode

五、Allure

Allure是一款輕量級(jí)并且非常靈活的開源測(cè)試報(bào)告框架,它支持絕大多數(shù)測(cè)試框架, 例如TestNG、Pytest、JUint等。它簡(jiǎn)單易用,易于集成

1.先下載Allure→配置Alluer環(huán)境變量→輸入allure檢驗(yàn)配置是否成功→安裝allure,輸入(pip install allure-pytest)

2.Allure常用的特性

@allure.feature# 用于描述被測(cè)試產(chǎn)品需求

@allure.story# 用于描述feature的用戶場(chǎng)景,即測(cè)試需求

withallure.step():# 用于描述測(cè)試步驟,將會(huì)輸出到報(bào)告中

allure.attach# 用于向測(cè)試報(bào)告中輸入一些附加的信息,通常是一些測(cè)試數(shù)據(jù),截圖等

案例:

importpytest,allure,os

classTestClass005():

@allure.feature("用戶登錄功能")#用于定義被測(cè)試的功能,被測(cè)產(chǎn)品的需求點(diǎn)

@allure.story("登錄成功")#用于定義被測(cè)功能的用戶場(chǎng)景,即子功能點(diǎn)

deftest_success(self):

assert1==1

@allure.feature("用戶登錄功能")#用于定義被測(cè)試的功能,被測(cè)產(chǎn)品的需求點(diǎn)

@allure.story("登錄失敗")#用于定義被測(cè)功能的用戶場(chǎng)景,即子功能點(diǎn)

deftest_fail(self):

assert1==2

if__name__=='__main__':

pytest.main(['--alluredir','report/result','test_06.py'])#生成json類型的測(cè)試報(bào)告

split='allure '+'generate '+'./report/result '+'-o '+'./report/html '+'--clean'#將測(cè)試報(bào)告轉(zhuǎn)為html格式

os.system(split)# system函數(shù)可以將字符串轉(zhuǎn)化成命令在服務(wù)器上運(yùn)行

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容