pytest 常见问题解答 (FAQ)

pytest 常见问题解答 (FAQ)

1. 基础问题

Q1: 如何让 pytest 发现我的测试文件?

  • 测试文件命名需符合 test_*.py*_test.py 模式
  • 测试函数/方法需以 test_ 开头
  • 测试类需以 Test 开头(且不能有__init__方法)

Q2: 如何运行特定测试?

bash 复制代码
pytest path/to/test_file.py::test_func  # 运行单个测试
pytest -k "pattern"                     # 运行名称匹配的测试
pytest -m mark_name                     # 运行特定标记的测试

Q3: 如何查看详细的测试输出?

bash 复制代码
pytest -v      # 详细模式
pytest -s      # 显示print输出
pytest --tb=auto  # 控制错误回溯显示方式(native/short/no等)

2. 配置问题

Q4: 如何配置 pytest 默认选项?

在项目根目录创建 pytest.ini:

ini 复制代码
[pytest]
addopts = -v --tb=short
python_files = test_*.py
markers =
    slow: marks tests as slow

Q5: 如何跳过某些测试?

python 复制代码
@pytest.mark.skip(reason="Not implemented yet")
def test_feature():
    ...

@pytest.mark.skipif(sys.version_info < (3, 8), reason="requires Python 3.8+")
def test_py38_feature():
    ...

3. 高级用法问题

Q6: 什么是 fixture?如何使用?

Fixture 是 pytest 的依赖注入系统:

python 复制代码
@pytest.fixture
def db_connection():
    conn = create_connection()
    yield conn  # 测试执行前运行
    conn.close()  # 测试执行后清理

def test_query(db_connection):  # 自动注入fixture
    result = db_connection.query("SELECT 1")
    assert result == 1

Q7: 如何参数化测试?

python 复制代码
@pytest.mark.parametrize("input,expected", [
    ("3+5", 8),
    ("2+4", 6),
])
def test_eval(input, expected):
    assert eval(input) == expected

4. 常见错误解决

Q8: 遇到 "fixture not found" 错误?

  • 确保 fixture 名称拼写正确
  • 将常用 fixture 放在 conftest.py 文件中
  • 检查 fixture 作用域(如 module/session 级fixture不能用在函数级fixture中)

Q9: 如何解决插件冲突?

bash 复制代码
pip list | grep pytest  # 查看已安装插件
pytest --trace-config  # 查看加载的插件

5. 集成与扩展

Q10: 如何生成覆盖率报告?

bash 复制代码
pip install pytest-cov
pytest --cov=my_package --cov-report=html

Q11: 如何并行运行测试?

bash 复制代码
pip install pytest-xdist
pytest -n 4  # 使用4个worker

6. 调试技巧

Q12: 如何调试失败的测试?

bash 复制代码
pytest --pdb  # 失败时进入pdb调试
pytest --trace  # 立即进入调试在每个测试开始前

Q13: 如何查看fixture执行顺序?

bash 复制代码
pytest --setup-show test_file.py

7. 最佳实践

Q14: 如何组织大型测试套件?

  • 按功能模块组织测试文件
  • 使用 conftest.py 共享 fixture
  • 合理使用标记分类测试

Q15: 如何测试异常?

python 复制代码
def test_divide_by_zero():
    with pytest.raises(ZeroDivisionError):
        1 / 0
    # 也可以检查异常信息
    with pytest.raises(ValueError, match="invalid literal"):
        int("a")

8. 性能问题

Q16: 如何加速测试执行?

  • 使用 pytest-xdist 并行运行
  • 减少 I/O 操作,使用 mock
  • 将慢测试标记为 @pytest.mark.slow 并默认跳过
相关推荐
默_笙2 天前
🍙 给每个请求过安检:FastAPI 是怎么把校验写进类型注解的
python
小羊没烦恼!2 天前
初探性能优化——2个月到4小时的性能提升
java·开发语言·windows·算法·c#
qq_426003962 天前
启动playwright录制codegen生成自动化测试脚本
python·自动化
虎头金猫2 天前
4K 视频总卡在公网带宽?用 N1 + OpenList 把网盘播放链路重新理顺
运维·服务器·网络·python·容器·beautifulsoup·pandas
长沙三为智能科技2 天前
家政小程序开发从0到上线:五阶段交付流程与验收清单
python
伞伞悦读2 天前
【第38期】Python 模块与包详解:import、from、模块搜索路径、包结构和 __init__
开发语言·python
只睡四小时2 天前
Canvas 弹道联机实战:700 行 + 固定时间步长
python·websocket·html5·游戏开发·canvas
C语言小火车2 天前
C/C++ 为什么需要编译器?
开发语言·c++
奇思妙想聪明勤奋的小羊2 天前
DeepAgents第5章:子Agent 与上下文隔离—让 Agent学会委派
人工智能·python·学习·语言模型
lpfasd1232 天前
2026年第38周GitHub趋势周报
python·科技·github