1.7 KiB
1.7 KiB
测试指南
运行测试
运行所有测试
pytest
运行特定测试文件
pytest tests/test_playlist_merge.py
运行特定测试类或函数
pytest tests/test_playlist_merge.py::TestPlaylistMergeLocalPriority
pytest tests/test_playlist_merge.py::TestPlaylistMergeLocalPriority::test_merge_local_priority
运行特定参数化测试用例
# 只运行 case1 的测试
pytest tests/test_playlist_merge.py -k "case_num-1"
查看详细输出
pytest -v # verbose
pytest -vv # more verbose
pytest -s # 显示 print 输出
查看测试覆盖率
pip install pytest-cov
pytest --cov=app --cov-report=html
然后在浏览器中打开 htmlcov/index.html
测试结构
test_playlist_merge.py- 播放列表合并功能的单元测试conftest.py- pytest fixtures 和配置pytest.ini- pytest 配置文件
编写新测试
- 在
tests/目录下创建test_*.py文件 - 创建以
Test开头的测试类 - 编写以
test_开头的测试函数 - 使用
assert进行断言 - 使用
@pytest.mark.parametrize进行参数化测试
示例:
import pytest
class TestMyFeature:
def test_basic_functionality(self):
result = my_function(input_data)
assert result == expected_output
@pytest.mark.parametrize("input,expected", [
(1, 2),
(2, 4),
(3, 6),
])
def test_with_multiple_inputs(self, input, expected):
assert my_function(input) == expected
调试测试
在测试失败时进入调试器
pytest --pdb
只运行上次失败的测试
pytest --lf
先运行失败的测试
pytest --ff