Search code examples
pythonunit-testingjupyter-notebookpython-unittest

Is there a way to test only a subset of unittests in a jupyter notebook?


I followed the unittest example in this answere here: https://stackoverflow.com/a/48405555/8790507

I have two test classes in two cells, so something like:

First cell:

class TestSuite1(unittest.TestCase):
    def test_in_suite1(self):
        pass:

Second cell:

class TestSuite2(unittest.TestCase):
    def test_in_suite2(self):
        pass:

Third cell:

unittest.main(argv=[''], verbosity=2, exit=False)

Now my problem is, that the last cell runs all tests in both test suites. I would like to split the third cell into two, one which tests suite 1, and another that tests suite 2.

What do I need to put in argv to achieve this?

Edit: Following a suggestion, I tried unittest.main(argv=['TestSuite2'], verbosity=2, exit=False) to only run suite 2, but as the screenshot below shows, TestSuite2 only has a single test in it, but it's still running the 10 tests in TestSuite1.

enter image description here


Solution

  • TL, DR; we can manually load the testSuite and run it in a cell.

    loader = unittest.TestLoader()
    suite = loader.loadTestsFromTestCase(TestSuite1)
    runner = unittest.TextTestRunner(verbosity=2)
    runner.run(suite)
    

    proof_in_screenshot

    Interesting Point: If you have TestSuite1 and TestSuite2 and you already ran them before. Now, even if you comment out TestSuite2 and rerun them by unittest.main(argv=[''], verbosity=2, exit=False), Jupyter Notebook will still run two testSuites unless you restart the kernel.

    The reason is that maintains the same Python process, so previously executed test classes remain in memory. We can manually load the suite and run single testSuite.