下面从入门到进阶,系统讲一下如何用 pytest 进行调试(不只是“运行测试”,而是“定位问题”)。
pytest test_sample.py
pytest -x # 遇到第一个失败就停
pytest --lf # 只运行上次失败的
pytest --ff # 先跑失败的
pytest -v
pytest -vv
pytest -l # 显示局部变量
pytest --tb=long
pytest --tb=short
pytest --tb=line
推荐调试时用:
pytest -l --tb=long
def test_demo():
x = 1
print("x =", x)
assert x == 2
运行:
pytest -s
pytest --pdb
pytest -x --pdb
def test_demo():
x = 10
import pdb; pdb.set_trace()
assert x == 20
常用 pdb 命令:
n # 下一步
s # 进入函数
c # 继续
p x # 打印变量
l # 查看代码
q # 退出
pip install ipdb
import ipdb
ipdb.set_trace()
def test_demo():
x = 5
breakpoint()
assert x == 6
launch.jsonpytest示例 launch.json:
{
"name": "pytest",
"type": "python",
"request": "launch",
"module": "pytest",
"args": ["-s"]
}
pytest --setup-show
@pytest.fixture
def data():
x = 1
breakpoint()
return x
| 问题 | 命令 |
|---|---|
| 测试不运行 | pytest --collect-only |
| 想看变量 | pytest -l |
| 想进调试器 | pytest --pdb |
| 只看失败 | pytest --lf |
| fixture 错 | pytest --setup-show |
pytest -x -l --tb=long --pdb
或本地开发:
pytest -s --pdb
如果你愿意,可以告诉我:
我可以给你更具体的调试方案。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。