如何在运行pytest测试时随意执行ipdb.set_trace()

man*_*anu 89 pytest

我正在为我的测试套件使用pytest.虽然在复杂的组件间测试中捕获错误,但我想放在import ipdb; ipdb.set_trace()我的代码中间以允许我调试它.

但是,由于pytest陷阱sys.stdin/sys.stdout ipdb失败.如何在使用pytest进行测试时使用ipdb.

我没有兴趣在失败后跳转到pdb或ipdb,但是在代码中的任何地方放置中断并且能够在发生故障之前在那里调试它.

pet*_*hka 137

由于py.test捕获输出而引发错误.

你应该运行py.test with -soption(关闭捕获输出).例如:

py.test -s my_test.py
Run Code Online (Sandbox Code Playgroud)

  • 如果想在Django中执行此操作,请将`addopts = -s`添加到`pytest.ini`文件中. (10认同)

lou*_*ton 32

遗憾的是,不再支持pytest-ipdb.

解决方案是运行 pytest my_test.py --pdb --pdbcls=IPython.terminal.debugger:Pdb

从help命令:

pytest -h
  --pdb                 start the interactive Python debugger on errors.
  --pdbcls=modulename:classname
                        start a custom interactive Python debugger on errors.
                        For example:
                        --pdbcls=IPython.terminal.debugger:TerminalPdb
Run Code Online (Sandbox Code Playgroud)

区别在于TerminalPdb似乎抛出错误,但Pdb没有(Ipython docs).

  • `TerminalPdb` 再次工作,并且是首选解决方案,因为它将为您提供选项卡补全。 (3认同)

joa*_*oar 24

安装pytest-ipdb插件然后使用

pytest.set_trace()
Run Code Online (Sandbox Code Playgroud)

  • 请注意,不再维护`pytest-ipdb`,建议[`pdbpp`](https://pypi.python.org/pypi/pdbpp/)作为替代方案.但是,pytest本身也支持[pytest.set_trace()`快捷方式](http://doc.pytest.org/en/latest/usage.html?highlight=set_trace#setting-a-breakpoint-aka-set-跟踪)和[自3.0](http://doc.pytest.org/en/latest/changelog.html#id7),允许传递自定义调试器类,如`--pdbcls = IPython.core.debugger:Pdb `. (21认同)

sor*_*rin 9

截至2019 年 11 月,应修复此问题:

pip install ipdb gnureadline ptpython

export PYTEST_ADDOPTS='--pdb --pdbcls=IPython.terminal.debugger:Pdb'
Run Code Online (Sandbox Code Playgroud)