Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to catch unittest exceptions with PyCharm?

The python unittest runner handles all exceptions. I would like to catch them with my debugger.

Is there a way to make my unittest runner re-raise tests exceptions to terminate the process? I want to handle them myself.

Edit: Found a solution.

You can create a unittest.TestSuite and call debug() to run the tests you want to debug - including catching the exceptions with your debugger!

It can be easily done with this pattern:

import unittest

class DebuggableTestCase(unittest.TestCase):
    @classmethod
    def debugTestCase(cls):
        loader = unittest.defaultTestLoader
        testSuite = loader.loadTestsFromTestCase(cls)
        testSuite.debug()

class MyTestCase(DebuggableTestCase):
    def test_function_that_fails(self):
        raise Exception('test')

if __name__ == '__main__':
    MyTestCase.debugTestCase()
like image 450
prgDevelop Avatar asked Dec 29 '12 11:12

prgDevelop


1 Answers

I know this is an old thread, and perhaps some of these things weren't around when the question was asked. But just for posterity...

You can run your unittest tests with py.test as a test runner. You'll get some great features right out of the box. Directly to the point of your question, there are a few good ways to debug with py.test, including with PyCharm.

Specifically to debug on any failure, post-mortem, with PyCharm - what you are asking for - you can install the pytest-pycharm plugin.

pip install pytest-pycharm

(I am working in a virtualenv per-project so this has no downside for me. I recommend you do the same. Otherwise, be aware that you're installing it globally, and this plugin will be active for all projects using this Python interpeter.)

See also:

  • JetBrains PyCharm docs re: Testing Frameworks, which will tell you how to use py.test as your testrunner in PyCharm.
  • Stack Overflow thread: Debugging pytest post mortem exceptions in pycharm/pydev
like image 95
m_floer Avatar answered Sep 18 '22 14:09

m_floer