Pytest之自定義mark

27
2020-08
今天距2021年136天
這是ITester軟件測(cè)試小棧第153次推文

點(diǎn)擊上方藍(lán)字“ITester軟件測(cè)試小棧“關(guān)注我,每周一、三、五早上?08:30準(zhǔn)時(shí)推送,每月不定期贈(zèng)送技術(shù)書籍。
微信公眾號(hào)后臺(tái)回復(fù)“資源”、“測(cè)試工具包”領(lǐng)取測(cè)試資源,回復(fù)“微信群”一起進(jìn)群打怪。
本文2322字,閱讀約需6分鐘
skip、skipif、xfail的用法。以下主要介紹pytest自定義配置及用例運(yùn)行實(shí)戰(zhàn)。一個(gè)完整的項(xiàng)目,測(cè)試用例比較多,比如我們想將某些用例用來(lái)做冒煙測(cè)試,那該怎么辦呢?pytest中可以自定義配置文件,用例按照指定的方式去運(yùn)行。
配置文件
在項(xiàng)目根目錄下,創(chuàng)建一個(gè)文件:pytest.ini (固定名稱,不要修改)。
[pytest]
markers?=
????demo:?just?for?demo
????smoke
① 案例一:
之前在講解用例被標(biāo)記為@pytest.mark.xfail時(shí),如果用例運(yùn)行通過(guò),顯示XPASS。
test_demo.py
@pytest.mark.xfail()
def?test_demo02():
????print("這是test_demo02")
????assert?1?==?1
在配置文件中未配置xfail_strict = True時(shí),運(yùn)行結(jié)果如下:

在pytest.ini 中加上xfail_strict = True配置后
運(yùn)行結(jié)果為:

② 案例二:addopts
addopts參數(shù)可以更改默認(rèn)命令行選項(xiàng),省去手動(dòng)敲命令行參數(shù)。
比如命令行想輸出詳細(xì)信息、分布式執(zhí)行或最大失敗次數(shù),每次敲命令很麻煩,在配置里設(shè)置,以后命令直接輸入pytest即可。
現(xiàn)有如下用例:
test_demo.py
def?test_demo01():
????print("這是test_demo01")
????assert?1?==?2
def?test_demo02():
????print("這是test_demo02")
如果需要輸出信息更詳細(xì)、輸出調(diào)試信息及用例執(zhí)行錯(cuò)誤時(shí)立即退出,那么配置如下:
[pytest]
markers?=
????demo:?just?for?demo
????smoke
addopts?=?-v?-s?-x
命令行輸入:pytest
輸出結(jié)果為:

測(cè)試用例執(zhí)行實(shí)戰(zhàn)
比如我想從眾多用例中挑選出部分用例,作為冒煙測(cè)試用例,怎么配置呢?
pytest.ini
[pytest]
markers?=
????demo:?just?for?demo
????smoke
其中smoke為標(biāo)簽,用例前加上標(biāo)簽名smoke,即都屬于冒煙測(cè)試用例。
在模塊里加上標(biāo)簽,那么該模塊下的類、方法或函數(shù)都會(huì)帶上標(biāo)簽。
test_demo.py
import?pytest
pytestmark?=?pytest.mark.smoke
class?TestDemo:
????def?test_demo01(self):
????????print("這是test_demo01")
????def?test_demo02(self):
????????print("這是test_demo02")
????def?test_demo03(self):
????????print("這是test_demo03")
命令行輸入:pytest -v -m smoke。
輸出結(jié)果為:

在類上添加標(biāo)簽,則類下的所有方法都帶上標(biāo)簽
test_demo.py
import?pytest
@pytest.mark.smoke
class?TestDemo:
????def?test_demo01(self):
????????print("這是test_demo01")
????def?test_demo02(self):
????????print("這是test_demo02")
????def?test_demo03(self):
????????print("這是test_demo03")
def?test_demo04():
????print("這是test_demo04")
在命令行輸入:pytest -v -m smoke test_demo.py

在函數(shù)上添加標(biāo)簽,那么此函數(shù)帶上標(biāo)簽。
test_demo.py
import?pytest
class?TestDemo:
????def?test_demo01(self):
????????print("這是test_demo01")
????def?test_demo02(self):
????????print("這是test_demo02")
????def?test_demo03(self):
????????print("這是test_demo03")
@pytest.mark.smoke
def?test_demo04():
????print("這是test_demo04")
命令行輸入:pytest -v -m smoke test_demo.py
輸出結(jié)果為:



測(cè)試交流Q群:727998947

