温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

怎么用python pytest调试

发布时间:2026-09-24 06:16:17 来源:亿速云 阅读:84 作者:小樊 栏目:编程语言

下面从基础用法 → 常用调试技巧 → 进阶工具三个层次,系统讲讲怎么用 pytest 调试 Python 代码。


一、最基础的 pytest 使用

1. 安装

pip install pytest

2. 写测试文件

# test_demo.py
def add(a, b):
    return a + b

def test_add():
    assert add(1, 2) == 3

3. 运行测试

pytest

或指定文件:

pytest test_demo.py

二、pytest 调试常用方法(重点)

✅ 1. 查看详细错误信息

pytest -v

或

pytest -vv

✅ 2. 只运行失败的用例(非常实用)

pytest --lf

(last failed)


✅ 3. 在出错时立即停(调试神器)

pytest -x

或失败 N 次停止:

pytest --maxfail=1

✅ 4. 打印 print 内容(重要)

pytest 默认吞掉 print,需要加:

pytest -s

例子:

def test_demo():
    print("debug info")
    assert 1 == 2

运行:

pytest -s

✅ 5. 使用 pdb 断点调试(最常用)

方法一:代码里加断点

def test_demo():
    x = 10
    import pdb; pdb.set_trace()
    assert x == 10

运行:

pytest -s

方法二:pytest 自动进入 pdb

pytest --pdb

失败后自动进入调试器。


✅ 6. 使用 breakpoint()(Python 3.7+)

def test_demo():
    x = 10
    breakpoint()
    assert x == 10

三、pytest 进阶调试技巧

✅ 1. 只运行某个测试函数

pytest test_demo.py::test_add

✅ 2. 按关键字运行

pytest -k "add"

✅ 3. 查看 fixture 调用链

pytest --setup-show

✅ 4. 显示最慢的测试

pytest --durations=3

✅ 5. 使用 logging 调试

import logging

def test_log():
    logging.warning("this is warning")
    assert True

运行:

pytest -o log_cli=true

四、IDE 调试(强烈推荐)

PyCharm

  • 右键测试 → Debug
  • 直接下断点

VS Code

  • 安装 Python 插件
  • 创建 launch.json
  • 选择 pytest 调试

五、常见调试套路总结

场景 推荐方式
看报错 pytest -vv
看 print pytest -s
出错暂停 pytest --pdb
单测调试 breakpoint()
反复失败 pytest --lf
性能问题 --durations

如果你愿意,可以告诉我:

  • 你用的是 PyCharm / VS Code / 命令行
  • 是 单元测试 / 接口测试 / 爬虫 / 异步代码
  • 具体卡在哪一步

我可以给你更针对性的调试方案。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI
助
手