pytest之pdb 调试
pdb 是 Python 标准库的调试模块。在 pytest 中,可以直接使用 --pdb 参数在测试失败时开启调试;
直接使用 --pdb 参数:
import pytest
class TestDemoA:
@pytest.mark.parametrize('data', [1, 2, 3, 4])
def test_A_001(self, data):
# 当 data>2 时会断言失败进入调试模式
if data > 2:
assert 0
if __name__ == '__main__':
pytest.main(['-q', '--pdb'])
断言失败进入pdb
pdb 提示符出现后,便可以使用 pdb 的交互调试功能,查看错误时,有以下常用命令:
p/print expr :输出变量 expr 的值;
pp expr :美化输出 expr 的值;
l/list :列出错误并显示错误之前和之后的5行代码;
l/lsit begin, end :列出错误,并显示指定行号之间的代码;
a/args :打印当前函数的所有参数和变量;
u/up :移动到堆栈的上一层;
d/down :移动到堆栈的下一层;
q/quit :退出当前调试会话(也会退出测试会话);
在控制台与 pdb 进行交互:
# 在控制台进行交互:
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> entering PDB >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
>>>>>>>>>>>>>>>>>> PDB post_mortem (IO-capturing turned off) >>>>>>>>>>>>>>>>>>
> d:\pyprojects\demo\pytestdemo\pytest_hook_demo\test_z.py(21)test_A_001()
-> assert 0
(Pdb) p data
3
(Pdb) pp data
3
(Pdb) l
16
17 @pytest.mark.parametrize('data', [1, 2, 3, 4])
18 def test_A_001(self, data):
19 # 当 data>2 时会断言失败进入调试模式
20 if data > 2:
21 -> assert 0
22
23
24 if __name__ == '__main__':
25 pytest.main(['-q', '--pdb'])
[EOF]
(Pdb) l 1, 100
1 # !/usr/bin/env python
2 # -*- coding:utf-8 -*-
3 # @Time : 2019/11/26 15:21
4 # @Author: ChenXun
5
6 import pytest
7
8
9 class TestDemoA:
10 #
11 # def test_A_001(self):
12 # assert 1
13 #
14 # def test_A_002(self):
15 # pytest.skip('跳过的原因?')
16
17 @pytest.mark.parametrize('data', [1, 2, 3, 4])
18 def test_A_001(self, data):
19 # 当 data>2 时会断言失败进入调试模式
20 if data > 2:
21 -> assert 0
22
23
24 if __name__ == '__main__':
25 pytest.main(['-q', '--pdb'])
[EOF]
(Pdb) a
self = <pytestDemo.pytest_hook_demo.test_Z.TestDemoA object at 0x000001BB7144FDD8>
data = 3
(Pdb) u
> d:\pyprojects\demo\venv\lib\site-packages\_pytest\python.py(170)pytest_pyfunc_call()
-> result = testfunction(**testargs)
(Pdb) u
> d:\pyprojects\demo\venv\lib\site-packages\pluggy\callers.py(187)_multicall()
-> res = hook_impl.function(*args)
(Pdb) d
> d:\pyprojects\demo\venv\lib\site-packages\_pytest\python.py(170)pytest_pyfunc_call()
-> result = testfunction(**testargs)
(Pdb) d
> d:\pyprojects\demo\pytestdemo\pytest_hook_demo\test_z.py(21)test_A_001()
-> assert 0
(Pdb) q
!!!!!!!!!!!!!!!!!! _pytest.outcomes.Exit: Quitting debugger !!!!!!!!!!!!!!!!!!!
=================== 1 failed, 2 passed in 519.70s (0:08:39) ===================
Process finished with exit code 0