Unable to run unittest's main function in ipython/jupyter notebook

前端 未结 3 1645
终归单人心
终归单人心 2021-02-02 16:17

I am giving an example which throws an error in ipython/jupyter notebook, but runs fine as an individual script.

import unittest

class Samples(unittest.TestCase         


        
相关标签:
3条回答
  • 2021-02-02 16:40

    We can try TestLoader to load test cases from TestCaseClass

    and attach those testcases to TextTestRunner then run it.

    import unittest
    suite = unittest.TestLoader().loadTestsFromTestCase(Samples)
    runner = unittest.TextTestRunner(verbosity=2)
    runner.run(suite)
    
    0 讨论(0)
  • 2021-02-02 16:55

    unittest.main looks at sys.argv by default, which is what started IPython, hence the error about the kernel connection file not being a valid attribute. You can pass an explicit list to main to avoid looking up sys.argv.

    In the notebook, you will also want to include exit=False to prevent unittest.main from trying to shutdown the kernel process:

    unittest.main(argv=['first-arg-is-ignored'], exit=False)
    

    You can pass further arguments in the argv list, e.g.

    unittest.main(argv=['ignored', '-v'], exit=False)
    
    0 讨论(0)
  • 2021-02-02 16:56

    @Hari Baskar 's answer can be made generic by defining a decorator:

    def run_test(tcls):
        """
        Runs unit tests from a test class
        :param tcls: A class, derived from unittest.TestCase
        """
        suite = unittest.TestLoader().loadTestsFromTestCase(tcls)
        runner = unittest.TextTestRunner(verbosity=2)
        runner.run(suite)
    

    Run the test by applying the @run_test decorator to the class to be tested:

    @run_test
    class Samples(unittest.TestCase):
        def testToPow(self):
            pow3 = 3**3
            # use the tools the unittest module gives you...
            self.assertEqual(pow3, 27)
    
    0 讨论(0)
提交回复
热议问题