(1)Pytest中的Mark介紹
Mark主要用于在測試用例/測試類中給用例打標記狼速,實現測試分組功能娘扩,并能和其它插件配合設置測試方法執(zhí)行順序等肺素。
在實際工作當中先口,我們要寫的自動化用例會比較多型奥,而且不會都放在一個.py
文件里。
如下圖碉京,現在需要只執(zhí)行紅色部分的測試方法厢汹,其它方法不執(zhí)行。
(2)Mark的使用
在Pytest當中谐宙,先給用例打標記烫葬,在運行時,通過標記名來過濾測試用例。
步驟:
-
@pytest.mark.標簽名
標記在需要執(zhí)行的用力上搭综。(標簽名自定義) - 執(zhí)行測試:
pytest 測試套件名 -m 標簽名
- 這樣執(zhí)行會有警告垢箕,提示標簽未注冊。
示例:
# 如:在test_01.py文件的testa()方法上進行mark標識兑巾。
@pytest.mark.hellotest
def test_a():
"""購物下單"""
print("test_01文件的函數a")
assert True
# 其他兩個文件中的方法同理条获。
執(zhí)行命令
if __name__ == '__main__':
pytest.main(["-vs", "-m", "hellotest"])
# 同理也可以用命令行的方式執(zhí)行。
"""
執(zhí)行結果:
test_01.py::test_a test_01文件的函數a
PASSED
test_02.py::test_b test_02文件的函數b
PASSED
test_03.py::test_a test_03文件的函數a
PASSED
3 passed, 3 deselected, 3 warnings
說明:3個用例通過蒋歌,3個用例沒有選擇帅掘,有3個警告
"""
這樣就簡單的實現了Mark標記的使用,但是我們在工作中不這樣用奋姿,我們需要把Mark標記進行注冊锄开。
(3)Mark的注冊和使用
Mark標簽官方提供的注冊方式有2種素标,這里只提供一種最簡單直接的方式:
通過pytest.ini
配置文件注冊称诗。
在pytest.ini
文件當中配置:
[pytest] # 固定的section名
markers= # 固定的option名稱,注意縮進头遭。
標簽名1: 標簽名的說明內容寓免。
標簽名2: 不寫也可以
標簽名N
示例:還是上面的練習
pytest.ini
配置文件內容如下:
[pytest]
addopts = -vs
testpaths = scripts
python_files = test*
python_classes = Test*
python_functions = test*
markers=
hellotest: Mark Description
smoke
執(zhí)行命令
if __name__ == '__main__':
pytest.main(["-m", "hellotest"])
"""
執(zhí)行結果:
test_01.py::test_a test_01文件的函數a
PASSED
test_02.py::test_b test_02文件的函數b
PASSED
test_03.py::test_a test_03文件的函數a
PASSED
3 passed, 3 deselected,
說明:3個用例通過,3個用例沒有選擇计维,沒有警告了袜香。
"""
(4)使用Mark完成失敗重試
只執(zhí)行test_01.py
文件中的測試用例:
import pytest
@pytest.mark.hellotest
def test_a():
"""購物下單"""
print("test_01文件的函數a")
assert True
@pytest.mark.Fail_retry
def test_b():
"""購物下單"""
print("test_01文件的函數b")
assert False
if __name__ == '__main__':
pytest.main(["-m", "Fail_retry"])
"""
執(zhí)行結果:
test_01.py::test_b test_01文件的函數b
RERUN
test_01.py::test_b test_01文件的函數b
RERUN
test_01.py::test_b test_01文件的函數b
FAILED
1 failed, 1 deselected, 2 rerun
說明:1個失敗,1個取消選擇鲫惶,2次重跑用例
"""
下面是pytest.ini
配置文件內容:
[pytest]
addopts = -vs --reruns 2(配置重跑兩次)
testpaths = scripts
python_files = test_01.py
python_classes = Test*
python_functions = test*
markers=
hellotest: Mark Description
Fail_retry:
(5)擴展
1)多個Mark標簽可以用在同一個用例上蜈首。
@pytest.mark.hello
@pytest.mark.world
def test_a():
"""購物下單"""
print("test_01文件的函數a")
assert True
2)Mark標簽也可以用到測試類上。
@pytest.mark.hello
class Test_Mark:
@pytest.mark.world
def test_a(self):
"""購物下單"""
print("test_01文件的函數a")
assert True
工作中的使用場景:冒煙測試欠母,分模塊執(zhí)行測試用例欢策,分接接口執(zhí)行測試用例等。
參考: