在pytest中只測試特定接口有以下幾種常用方法:
1. 通過測試函數名精確匹配
直接指定測試文件和函數名:
pytest test_api.py::test_upload_image_with_library
這將只運行test_api.py
文件中名為test_upload_image_with_library
的測試函數。
2. 使用關鍵字匹配(-k參數)
通過函數名中的關鍵字篩選測試:
pytest test_api.py -k 'upload'
這會運行所有函數名中包含upload
的測試用例。
3. 使用標記(Mark)篩選
首先在測試函數上添加標記(需要在conftest.py
中注冊標記,pytest插件):
# test_api.py
import pytest@pytest.mark.image_upload
def test_upload_image_with_library(client):# 測試代碼...@pytest.mark.status
def test_library_status(client):# 測試代碼...
然后使用-m
參數運行特定標記的測試:
pytest test_api.py -m 'image_upload'
4. 運行單個測試類(如果使用類組織測試)
如果測試用例是按類組織的:
pytest test_api.py::TestImageAPI::test_upload_image
注意事項
- 確保測試函數名具有明確的語義,便于識別和篩選
- 標記功能需要在
pytest.ini
或conftest.py
中注冊,避免警告:# conftest.py def pytest_configure(config):config.addinivalue_line("markers", "image_upload: 測試圖像上傳接口")config.addinivalue_line("markers", "status: 測試狀態查詢接口")
選擇最適合你需求的方法即可實現只測試特定接口的目的。