[Pytest] Marker
2 min readFeb 5, 2023
Markers are used to set various features or attributes to tests, and can use related API to set metadata on tests.
usefixtures
- Import fixture into tests.
import pytest
@pytest.fixture()
def init_funtion():
print("INIT")
@pytest.mark.usefixtures("init_funtion")
class TestCases():
def test_case1(self):
print("Case1")
"""
Result
"""
# INIT
# Case1
filterwarnings
- Filter certain warnings of test
import pytest
import warnings
def warn_function():
warnings.warn("WARNING", DeprecationWarning)
@pytest.mark.filterwarnings("ignore::DeprecationWarning")
def test_case1():
warn_function()
skip / skipif
- Always skip a test or a certain condition is met
import pytest
@pytest.fixture(scope="class")
def init_funtion():
print("INIT")
@pytest.mark.usefixtures("init_funtion")
class TestCases():
@pytest.mark.skip(reason="SKIP")
def test_case1(self):
print("Case1")
def test_case2(self):
print("Case2")
"""
Result
"""
# INIT
# SKIP
# Case2
import sys
import pytest
@pytest.fixture(scope="class")
def init_funtion():
print("INIT")
@pytest.mark.usefixtures("init_funtion")
class TestCases():
# Skipped when run on an interpreter earlier than Python3.10
@pytest.mark.skipif(sys.version_info < (3, 10), reason="SKIP")
def test_case1(self):
print("Case1")
def test_case2(self):
print("Case2")
"""
Result
"""
# INIT
# SKIP
# Case2
xfail
- Produce an expected failure outcome if a certain condition is met
import sys
import pytest
@pytest.fixture(scope="class")
def init_funtion():
print("INIT")
@pytest.mark.usefixtures("init_funtion")
class TestCases():
@pytest.mark.xfail(reason="Expected")
def test_case1(self):
print("Case1")
assert "A" == "B"
# Expected Fail when run on an interpreter earlier than Python3.10
@pytest.mark.xfail(sys.version_info < (3, 10), reason="Version Too Old")
def test_case2(self):
print("Case2")
# If a test should be marked as XFAIL but should not be even executed
@pytest.mark.xfail(run=False)
def test_case3(self):
print("Case3")
@pytest.mark.xfail(reason="Expected")
def test_case4(self):
print("Case4")
"""
Result
"""
# INIT
# Case1
# XFAIL (Expected)
# Case2
# XPASS (Version Too Old)
# XFAIL ([NOTRUN])
# Case4
# XPASS (Expected)
parametrize
- Perform multiple calls to the same test
import pytest
@pytest.fixture(scope="class")
def init_funtion():
print("INIT")
@pytest.mark.usefixtures("init_funtion")
class TestCases():
@pytest.mark.parametrize("a,b,c", [(1, 2, 3), (1, 2, 4)])
def test_case1(self, a, b, c):
print("Case1")
assert a + b == c
"""
Result
"""
# INIT
# Case1
# PASSED
# Case1
# FAILED