在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: 测试状态查询接口")
选择最适合你需求的方法即可实现只测试特定接口的目的。