下面从基础用法 → 常用调试技巧 → 进阶工具三个层次,系统讲讲怎么用 pytest 调试 Python 代码。
pip install pytest
# test_demo.py
def add(a, b):
return a + b
def test_add():
assert add(1, 2) == 3
pytest
或指定文件:
pytest test_demo.py
pytest -v
或
pytest -vv
pytest --lf
(last failed)
pytest -x
或失败 N 次停止:
pytest --maxfail=1
pytest 默认吞掉 print,需要加:
pytest -s
例子:
def test_demo():
print("debug info")
assert 1 == 2
运行:
pytest -s
def test_demo():
x = 10
import pdb; pdb.set_trace()
assert x == 10
运行:
pytest -s
pytest --pdb
失败后自动进入调试器。
def test_demo():
x = 10
breakpoint()
assert x == 10
pytest test_demo.py::test_add
pytest -k "add"
pytest --setup-show
pytest --durations=3
import logging
def test_log():
logging.warning("this is warning")
assert True
运行:
pytest -o log_cli=true
launch.json| 场景 | 推荐方式 |
|---|---|
| 看报错 | pytest -vv |
| 看 print | pytest -s |
| 出错暂停 | pytest --pdb |
| 单测调试 | breakpoint() |
| 反复失败 | pytest --lf |
| 性能问题 | --durations |
如果你愿意,可以告诉我:
我可以给你更针对性的调试方案。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。