pytest.ini 創(chuàng)建在項(xiàng)目根目錄
pytest默認(rèn)的測(cè)試用例收集規(guī)則
- 文件名以 test_*.py 文件和 *_test.py
- 以 test_ 開頭的函數(shù)
- 以 Test 開頭的類,不能包含 init 方法
- 以 test_ 開頭的類里面的方法
我們是可以修改或者添加這個(gè)用例收集規(guī)則的扔嵌;當(dāng)然啦,是建議在原有的規(guī)則上添加的碱蒙,如下配置
[pytest]
python_files = test_* *_test test*
python_classes = Test* test*
python_functions = test_* test*
一 標(biāo)簽注冊(cè)
[pytest]
markers =
smoke:marks tests as smoke.
demo:marks tests asa demo.
備注:冒號(hào)之后是描述信息(可寫可不寫)。
打標(biāo)記的范圍:測(cè)試用例从祝、測(cè)試類舞痰、模塊文件
1.方法一
在測(cè)試用例/測(cè)試類前加上:@pytest.mark.標(biāo)記名
import pytest
@pytest.mark.smoke
def test_add_01():
b = 1 + 2
assert 3 == b
@pytest.mark.demo
def test_add_02():
b = 1 + 2
assert 0 == b
@pytest.mark.smoke
class TestAdd:
def test_add_03(self):
b = 1 + 2
assert 3 == b
def test_add_04(self):
b = 1 + 1
assert 2 == b
也可以在一個(gè)用例上打多個(gè)標(biāo)簽,多次使用@pytest.mark.標(biāo)簽名
@pytest.mark.demo
@pytest.mark.smoke
def test_add_02():
b = 1 + 2
assert 0 == b
2.方法二
- 在測(cè)試類里面荸哟,使用以下聲明(測(cè)試類下,所有用例都被打上了該標(biāo)簽):
@pytest.mark.demo
def test_add_02():
b = 1 + 2
assert 0 == b
class TestAdd:
pytestmark = pytest.mark.smoke
def test_add_03(self):
b = 1 + 2
print(f'b=')
assert 3 == b
def test_add_04(self):
b = 1 + 1
print(f'b=鞍历')
assert 2 == b
多標(biāo)簽?zāi)J剑簆ytestmark = [pytest.mark.標(biāo)簽1, pytest.mark.標(biāo)簽2......]
class TestAdd:
pytestmark = [pytest.mark.smoke, pytest.mark.demo]
def test_add_03(self):
b = 1 + 2
print(f'b=舵抹')
assert 3 == b
def test_add_04(self):
b = 1 + 1
print(f'b=')
assert 2 == b
在模塊文件里劣砍,同理(py文件下惧蛹,所有測(cè)試函數(shù)和測(cè)試類里的測(cè)試函數(shù),都有該標(biāo)簽):
import pytest
pytestmark = pytest.mark.smoke
pytestmark = [pytest.mark.smoke, pytest.mark.demo] # 多標(biāo)簽?zāi)J?
三刑枝、命令行
根據(jù)測(cè)試用例/測(cè)試類/測(cè)試模塊赊淑,標(biāo)記了對(duì)應(yīng)的標(biāo)簽后,使用對(duì)應(yīng)的命令行在cmd中或者Pycharm中的Terminal中運(yùn)行仅讽,即可進(jìn)行用例的篩選,命令行為:
pytest -m 標(biāo)簽名
pytest - m "smoke or demo"
只運(yùn)行smoke 和 demo標(biāo)簽
跳過用例
@pytest.mark.skip(reason='跳過的原因')
打在測(cè)試類或者測(cè)試用例上面
- 打在測(cè)試類上面钾挟,下面的用例都不會(huì)執(zhí)行洁灵。
- 打在測(cè)試用例上面,這個(gè)用例不會(huì)執(zhí)行掺出。
@pytest.mark.skipif("sys.platform=='win32'",reason='第三方不想測(cè)')
eval(self,condition) condition是一個(gè)eval脫衣可以執(zhí)行的徽千,如果為True就跳過
condition是一個(gè)條件可以是字符串eval脫衣服的表達(dá)式,還可以直接是表達(dá)式比如:condition = 2>1
pytestmark =pytest,mark.skip()
變量pytestmark這個(gè)變量不可更改
- 模塊級(jí)跳過測(cè)試用例
myskip = pytest.mark.skip()
自定義跳過裝飾器汤锨,使用一個(gè)變量接收對(duì)象双抽。使用的時(shí)候直接@變量 打在被跳過的函數(shù)或者類