Using Python unittest in IPython or Jupyter

Configuration for running unittest in IPython or Jupyter is different than running unittest from command line.

When you run following code from IPython or Jupyter

if __name__ == '__main__':
unittest.main()

will result in following error:

E
======================================================================
ERROR: C:\Users\XXXX\AppData\Roaming\jupyter\runtime\kernel-4b12e789-a050-4567-a8a1-7361d4a1745f (unittest.loader._FailedTest)
----------------------------------------------------------------------
AttributeError: module '__main__' has no attribute 'C:\Users\XXXX\AppData\Roaming\jupyter\runtime\kernel-4b12e789-a050-4567-a8a1-7361d4a1745f'
----------------------------------------------------------------------
Ran 1 test in 0.001s
FAILED (errors=1)
An exception has occurred, use %tb to see the full traceback.
SystemExit: True

d:\development\lib\site-packages\IPython\core\interactiveshell.py:2855: UserWarning: To exit: use 'exit', 'quit', or Ctrl-D.
warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1)

The reason is that unittest.main looks at sys.argv and first parameter is what started IPython or Jupyter, therefore the error about kernel connection file not being a valid attribute. Passing explicit list to unittest.main will prevent IPython and Jupyter look at sys.argv. Passing exit=Fals will prevent unittest.main to shutdown the kernell process

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