129

I'm using pytest for my test suite. While catching bugs in complex inter-components test, I would like to place import ipdb; ipdb.set_trace() in the middle of my code to allow me to debug it.

However, since pytest traps sys.stdin/sys.stdout ipdb fails. How can I use ipdb while testing with pytest.

I'm not interested in jumping to pdb or ipdb after a failure, but to place breaks anywhere in the code and be able to debug it there before the failure occurs.

louis_guitton
  • 5,105
  • 1
  • 31
  • 33
manu
  • 3,544
  • 5
  • 28
  • 50

5 Answers5

188

The error is raised because pytest captures output by default.

You can run pytest with -s option (turn off capture output). For example:

py.test -s my_test.py

and then in my_test.py:

import ipdb;
ipdb.set_trace()
anon01
  • 10,618
  • 8
  • 35
  • 58
petRUShka
  • 9,812
  • 12
  • 61
  • 95
68

pytest-ipdb is unfortunately not supported anymore.

The solution is to run pytest my_test.py --pdb --pdbcls=IPython.terminal.debugger:Pdb

From the help command:

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

The difference is just that TerminalPdb seems to throw erros, but Pdb not (Ipython docs).

ivan_pozdeev
  • 33,874
  • 19
  • 107
  • 152
louis_guitton
  • 5,105
  • 1
  • 31
  • 33
7

As of 2019-11 here is what should fix it:

pip install ipdb gnureadline ptpython

export PYTEST_ADDOPTS='--pdb --pdbcls=IPython.terminal.debugger:Pdb'
sorin
  • 161,544
  • 178
  • 535
  • 806
  • 1
    if you install `prompt-toolkit` version `2.0.10` then ipdb will work fine again, because it breaks due to recent update of this package to 3.0.0 – Pawel Barcik Nov 28 '19 at 09:56
3

This is what I use

py.test tests/ --pdbcls=IPython.core.debugger:Pdb -s

avoliva
  • 3,181
  • 5
  • 23
  • 37
0

You may want to give pdbpp a try. I've had more success with it, compared to ipdb when used with pytest. See my answer here: https://stackoverflow.com/a/69320311/2896799.

Apteryx
  • 5,822
  • 3
  • 16
  • 18