一、pytestmark是什麼?
pytestmark是pytest框架提供的裝飾器,可以用來裝飾整個文件或文件中的某些函數,其作用是將標記(mark)與被裝飾的函數或文件相關聯。
在pytest中,標記是一種在運行測試用例時動態影響測試用例執行的工具。通過pytestmark,可以在pytest命令行中使用不同的標記,例如-s,-m等
二、pytestmark的使用場景
1、使用pytestmark標記來提供一些默認的參數:可通過pytestmark為整個文件設置pytest.fixture()標記。這樣,已被標記為fixture的函數,就可以在文件中被其他測試用例函數直接使用。
import pytest
@pytest.fixture()
def foo_fixture():
return 'foo module'
pytestmark = pytest.mark.usefixtures("foo_fixture")
def test_foo():
assert "foo module" == "foo module"
在上述代碼中,我們為整個文件設置了pytest.fixture()標記,並在pytestmark中使用了usefixtures。當運行test_foo函數時,將先運行foo_fixture()函數,因此test_foo函數中的代碼可以有效地使用foo_fixture()。
2、使用pytestmark標記來指定測試用例的實例化方式:可通過pytestmark將測試用例與類或函數進行關聯。
import pytest
@pytest.mark.webtest
class TestSomething:
def test_one(self):
pass
def test_two(self):
pass
@pytest.mark.nighttest
class TestAnother:
def test_three(self):
pass
def test_four(self):
pass
在上述代碼中,我們通過pytestmark將TestSomething和TestAnother類與不同的mark(webtest和nighttest)關聯。在運行測試時,我們可以通過-m選項來執行哪種類型的測試用例。
3、使用pytestmark指定fixture執行範圍:我們可以通過@pytest.mark.用於指定Fixture的使用範圍。
import pytest
@pytest.fixture(scope="module")
def foo():
return 'foo'
def test_foo1(foo):
assert foo == 'foo'
def test_foo2(foo):
assert foo == 'foo'
pytestmark = pytest.mark.usefixtures("foo")
在上述代碼中,我們將foo fixture設置為『module』級別的fixture,在pytestmark中使用了usefixtures指定它的使用範圍。在test_foo1和test_foo2中我們分別使用了foo fixture,它將在整個module的範圍內使用。
三、pytestmark相關參數的使用方法
pytestmark也可以使用多個參數來定義一組標記列表
import pytest
@pytest.mark.parametrize("test_input, expected_output", [("3+5", 8), ("2+4", 6), ("6*9", 54)])
def test_eval(test_input, expected_output):
assert eval(test_input) == expected_output
pytestmark = [pytest.mark.number, pytest.mark.eval]
在上述代碼中,我們使用pytest.mark.parameterize指定的參數值為test_input, expected_output。在pytestmark中,我們使用了一個長度為2的列表,分別包含了由number和eval標記所組成的標記列表。當我們運行測試用例時,可以通過「-m」參數來只運行標記為其中之一的測試用例。
四、pytestmark的多層嵌套標記
pytestmark也可以實現多層嵌套標記,使得多個標記可以被同時匹配
import pytest
@pytest.mark.parametrize("num", [1, 2, 3])
@pytest.mark.parametrize("letter", ["a", "b", "c"])
def test_multi_tag(num, letter):
pass
pytestmark = pytest.mark.beta
在上述代碼中,我們使用pytest.mark.parameterize指定了兩個參數值,num和letter。在pytestmark中,我們使用了beta標記。運行時可以使用「-m」參數指定beta標記,同時也可以使用「-k」參數通過一個測試用例的名稱鍵值對來指定需要運行的測試用例。
五、pytestmark的跨文件標記
pytestmark還可以實現跨文件標記,從而為整個測試套件添加標記。
我們可以在conftest.py文件中定義標記,在整個測試套件中使用。pytest也會自動載入相應的標記,從而使整個測試套件具有相同的屬性。
#在conftest.py文件中
import pytest
# 為整個測試套件設置webtest標記
pytestmark = pytest.mark.webtest
在上述代碼中,我們在conftest.py文件中定義了webtest標記。pytestmark的值設置為pytest.mark.webmark,從而為整個測試套件添加了webtest標記。在執行整個測試套件時,pytest會自動載入conftest.py文件並實現webtest標記。
六、結論
通過以上內容我們可以看出,pytestmark可以在許多方面提高測試用例的復用性和靈活性。通過使用pytestmark和標記參數,開發人員可以使pytest的整體測試環境更加高效和精準。
原創文章,作者:KLQVO,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/313337.html