news 2026/2/28 19:43:11

pytest 在命令行调试单个测试用例

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
pytest 在命令行调试单个测试用例

在进行 Python 测试时,我们经常需要针对性地运行或调试单个测试用例,而不是执行整个测试套件。pytest 提供了多种灵活的方式来实现这一需求。本文将详细介绍如何在命令行中精准地调试单个测试用例。

环境准备

创建示例测试文件test_math_operations.py

# test_math_operations.pydeftest_addition():"""测试加法运算"""assert1+2==3print("加法测试通过")deftest_subtraction():"""测试减法运算"""assert5-3==2print("减法测试通过")deftest_multiplication():"""测试乘法运算"""assert3*4==12print("乘法测试通过")deftest_division():"""测试除法运算"""assert10/2==5print("除法测试通过")classTestCalculator:"""计算器测试类"""deftest_power(self):"""测试幂运算"""assert2**3==8print("幂运算测试通过")deftest_square_root(self):"""测试平方根"""assert4**0.5==2print("平方根测试通过")

基础方法:直接指定测试用例

1. 运行单个测试函数

# 运行特定的测试函数pytest test_math_operations.py::test_addition# 使用详细模式查看详细信息pytest test_math_operations.py::test_addition -v

2. 运行测试类中的单个方法

# 运行测试类中的特定方法pytest test_math_operations.py::TestCalculator::test_power# 简写形式pytest test_math_operations.py::TestCalculator.test_power

3. 使用相对导入路径

如果测试文件在子目录中:

# 假设文件在 tests/ 目录下pytest tests/test_math_operations.py::test_addition# 或使用相对路径pytest ./tests/test_math_operations.py::test_addition

高级选择器方法

4. 使用 -k 参数进行关键字匹配

# 运行名称包含 "addition" 的测试pytest -k addition# 运行名称包含 "add" 或 "sub" 的测试pytest -k"add or sub"# 运行名称包含 "TestCalculator" 的测试类pytest -k TestCalculator# 排除特定测试pytest -k"not division"

5. 使用节点 ID

pytest 为每个测试用例分配了唯一的节点 ID:

# 先查看所有测试用例的节点IDpytest --collect-only# 输出示例:# <Module test_math_operations.py># <Function test_addition># <Function test_subtraction># <Class TestCalculator># <Function test_power># <Function test_square_root># 使用节点ID运行特定测试pytest test_math_operations.py::test_addition

调试相关的命令行选项

6. 使用 --pdb 在失败时进入调试器

# 当测试失败时自动进入 pdb 调试器pytest test_math_operations.py::test_addition --pdb# 只针对特定失败类型进入调试器pytest --pdb --tb=short test_math_operations.py::test_addition

7. 使用 --trace 立即进入调试器

# 在测试开始时立即进入调试器pytest test_math_operations.py::test_addition --trace

8. 使用 -x 在第一次失败时停止

# 第一个测试失败后就停止pytest test_math_operations.py::test_addition -x

9. 使用 --lf 仅运行上次失败的测试

# 仅运行上次失败的测试用例pytest --lf# 结合特定测试文件pytest test_math_operations.py::test_addition --lf

输出控制选项

10. 控制详细程度

# 详细输出pytest test_math_operations.py::test_addition -v# 极简输出pytest test_math_operations.py::test_addition -q# 显示打印语句输出pytest test_math_operations.py::test_addition -s# 显示详细追溯信息pytest test_math_operations.py::test_addition --tb=long# 不显示追溯信息pytest test_math_operations.py::test_addition --tb=no

11. 性能分析

# 显示最慢的N个测试pytest test_math_operations.py::test_addition --durations=5

实际调试示例

场景1:调试失败测试

假设我们有一个失败的测试:

deftest_failing_addition():"""故意失败的测试"""result=1+2print(f"计算结果:{result}")assertresult==4# 这里会失败

调试命令:

# 运行并进入调试器pytest test_math_operations.py::test_failing_addition --pdb -s# 运行结果:# 测试失败,自动进入 pdb 调试器# 可以检查变量:result 的值是 3

场景2:使用断点调试

在代码中添加断点:

importpdbdeftest_with_breakpoint():"""使用断点的测试"""x=10y=20pdb.set_trace()# 手动断点result=x+yassertresult==30

运行命令:

pytest test_math_operations.py::test_with_breakpoint -s

综合实战:完整的调试工作流

步骤1:创建测试问题

# test_debug_example.pydefcalculate_complex(a,b,c):"""复杂计算函数"""result=(a*b)+(b**c)-(a/b)returnround(result,2)deftest_complex_calculation():"""测试复杂计算"""# 这里可能有逻辑错误result=calculate_complex(10,2,3)print(f"计算结果:{result}")# 预期结果应该是 14,但实际是 18assertresult==14

步骤2:逐层调试

# 1. 首先运行测试查看失败信息pytest test_debug_example.py::test_complex_calculation -v# 2. 添加详细输出pytest test_debug_example.py::test_complex_calculation -s# 3. 使用 pdb 调试pytest test_debug_example.py::test_complex_calculation --pdb -s# 4. 修改后重新运行pytest test_debug_example.py::test_complex_calculation --lf -v

最佳实践和建议

1. 使用 pytest.ini 配置文件

创建pytest.ini文件保存常用配置:

[pytest] addopts = -v --tb=short testpaths = tests python_files = test_*.py python_classes = Test* python_functions = test_*

2. 创建自定义命令别名

~/.bashrc~/.zshrc中添加:

# pytest 调试别名aliasptd="pytest --pdb -v"aliaspts="pytest -v -s"aliasptf="pytest --lf -v"

3. 使用 VS Code 或 PyCharm 集成

虽然本文重点在命令行,但 IDE 集成可以提供更好的调试体验:

# VS Code 启动调试配置{"name":"Python: Debug Test","type":"python","request":"test","args":["test_math_operations.py::test_addition"]}

常见问题解答

Q1:如何调试参数化测试?

# 参数化测试示例@pytest.mark.parametrize("a,b,expected",[(1,2,3),(3,4,7)])def test_parametrized(a, b, expected): assert a + b==expected# 调试特定参数组合pytest test_file.py::test_parametrized[1-2-3]

Q2:如何调试夹具(fixture)问题?

# 使用 --setup-show 查看夹具执行流程pytest test_file.py::test_function --setup-show

Q3:如何调试异步测试?

# 对于异步测试使用 -v 和 -spytest test_async.py::test_async_function -v -s

总结

pytest 提供了丰富的命令行选项来调试单个测试用例:

  1. 基础选择:直接使用::语法指定测试路径
  2. 智能过滤:使用-k进行关键字匹配
  3. 调试集成:使用--pdb--trace进入调试器
  4. 输出控制:使用-v-s--tb控制输出格式
  5. 高效重试:使用--lf仅重试失败测试

通过掌握这些技巧,你可以大大提高测试调试的效率。记住,良好的测试习惯是从小处着手,逐步深入调试,而不是一次性运行整个测试套件。

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/2/22 3:05:24

谁懂啊!这些专业论文 AI 写作软件,拯救我的毕业论文

作为一名应届毕业生&#xff0c;最近的生活被毕业论文按在地上反复摩擦&#xff0c;谁懂这种焦虑啊&#xff01;熬了好几个大夜&#xff0c;选题改了八遍&#xff0c;框架被导师打回五次&#xff0c;好不容易憋出初稿&#xff0c;查重率直接飙到 40%&#xff0c;对着满屏的红色…

作者头像 李华
网站建设 2026/2/24 12:08:40

mirror_fold.py_utils_0207curso

import osimport randomimport timefrom typing import Dict, Optional, Tupleimport numpy as np# 后视镜折叠场景配置&#xff08;请按你的4种分辨率填写&#xff09;# key: (width, height) value: (x1, y1, x2, y2) 车辆黑色区域在原图上的像素坐标MIRROR_FOLD_CAR_BOXES:…

作者头像 李华
网站建设 2026/2/26 7:17:54

2026年博士论文去AIGC痕迹:10%以下达标攻略

2026年博士论文去AIGC痕迹&#xff1a;10%以下达标攻略 博士论文AI率要求最严格&#xff1a;10%以下&#xff0c;部分985高校甚至要求5%以下。 我一个博士师兄&#xff0c;论文AI率12%&#xff0c;本来以为稳了&#xff0c;结果学校要求10%以下&#xff0c;只差2个点被打回来…

作者头像 李华
网站建设 2026/2/28 1:52:57

2026年检测平台升级后去AIGC痕迹:最新应对方案

2026年检测平台升级后去AIGC痕迹&#xff1a;最新应对方案 2026年开始&#xff0c;知网、维普、万方都在升级AIGC检测算法。 之前能过的论文&#xff0c;现在重新测可能就不行了。我一个学弟的论文&#xff0c;去年12月测12%&#xff0c;今年1月重测变成32%。 先说结论&#…

作者头像 李华
网站建设 2026/2/25 2:33:03

2026年免费去AIGC痕迹工具有哪些?实测对比告诉你

2026年免费去AIGC痕迹工具有哪些&#xff1f;实测对比告诉你 白嫖心理谁都有&#xff0c;我也一样。 论文AI率55%&#xff0c;第一反应就是找免费工具。在网上搜了一圈&#xff0c;试了好几个免费的&#xff0c;结果效果都不理想。 最后还是老老实实花了几十块钱用付费工具&…

作者头像 李华
网站建设 2026/2/28 4:06:26

2026年期刊投稿去AIGC痕迹:核心期刊这样过审

2026年期刊投稿去AIGC痕迹&#xff1a;核心期刊这样过审 投核心期刊&#xff0c;现在多了一道AIGC检测关。 我一个同事辛辛苦苦写了一篇论文投C刊&#xff0c;初审就被拒了。编辑部反馈&#xff1a;AI生成内容过多。他用AI辅助写的综述部分被检测出来了。 先说结论&#xff1…

作者头像 李华