How do you run unit tests in Python in the REPL?

Viewed 656

I'm trying to develop unit tests in Python using unittest from the Standard Library, and I want to try things out in the REPL. If I have the following code loaded

import unittest

class TestTrivial(unittest.TestCase):
    def test_trivial(self):
        self.assertEqual(1 + 1, 2)
        self.assertFalse(2 + 2 == 5)

Then I can evaluate the following in the REPL:

unittest.main()

That spits out:

Ran 1 test in 0.000s

OK

Process Python finished

The problem is it killed the REPL. How do I run it without quitting the REPL?

1 Answers

Pass exit=False as an argument:

unittest.main(exit=False)

unittest.main isn't actually a function; it's just another name for unittest.main.TestProgram, whose __init__ method ultimately calls a runTests method, which ends with these lines:

    if self.exit:
        sys.exit(not self.result.wasSuccessful())

Setting self.exit to False prevents sys.exit from being called.

This is documented (see the end of the section), but not easily found.

Related