Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ipdb with python unittest module

Is there any convenient way to get an ipdb debugger on an exception, when running tests with python's unittest module?

It's convenient to debug python code using ipython --pdb my_script.py. However, when I use the unittest module, with

class MyTestCase(unittest.TestCase):
    def runTest(self):
        x = 0
        y = 3/x

unittest catches the exception and exits.

like image 728
John Avatar asked Jul 26 '15 18:07

John


2 Answers

nose now has an ipdb plugin. You can install it via:

pip install ipdbplugin

Then test your program by,

nosetests --ipdb <test_file>
like image 155
Bily Avatar answered Nov 11 '22 11:11

Bily


I find it helpful to run the tests first and see if any error occurs. This helps get a holistic view of the error. For example are there more than one test that are failing, and which one should be looked at first.

After analysing that, this is my approach to test/debug cycle. In your test:

def test_foo_is_bar(self):
    import ipdb
    ipdb.set_trace()
    self.assertEqual('foo', 'bar')

Now run the test with:

nosetests -s tests/test_example.py

-s flag will help your to get into input mode instead of getting the exception from nose.

Sidenote: I have shortcut set to paste import ipdb as pdb; pdb.set_trace() in IntelliJ(PyCharm) settings, so that I can insert this one line to stop wherever I want in my code.

like image 2
Shubham Chaudhary Avatar answered Nov 11 '22 10:11

Shubham Chaudhary