在pytest中,mark(標記)是用于對測試用例進行分類、篩選或附加元數據的重要功能。以下是其核心使用方法:
1. ?基本標記定義與使用?
?注冊標記?:在pytest.ini中預先定義標記(避免運行時警告):
[pytest]
markers =smoke: 冒煙測試用例slow: 執行耗時較長的用例
?標記測試函數/類?:
@pytest.mark.smoke
def test_login():assert True@pytest.mark.slow
class TestPerformance:def test_response_time(self):assert True
2. ?常用內置標記?
?跳過測試?:
@pytest.mark.skip(reason="功能暫未完成")
def test_unimplemented():pass
?預期失敗?:
@pytest.mark.xfail(reason="已知兼容性問題")
def test_legacy_feature():assert False
3. ?參數化標記(數據驅動)?
@pytest.mark.parametrize("input,expected", [(1, 2), (3, 4)])
def test_add_one(input, expected):assert input + 1 == expected
4. ?自定義標記的篩選?
命令行執行特定標記的測試:
pytest -m "smoke" # 只運行冒煙測試
pytest -m "not slow" # 排除耗時用例
pytest -m "smoke or slow" # 組合邏輯
5. ?動態添加標記?
通過鉤子函數動態標記(如根據執行時間):
def pytest_collection_modifyitems(items):for item in items:if "api" in item.nodeid:item.add_marker(pytest.mark.api)
注意事項:
未注冊的自定義標記會觸發警告,需在pytest.ini中聲明。
標記支持繼承(類標記會應用到所有方法)。
可通過pytest --markers查看所有可用標記。