unittest: AttributeError: module '__main__' has no attribute 'C:\...'

Viewed 1695

I am trying to run test in Python. Simplified it looks like this:

#import librarys
import unittest

def methodToTest (df1, df2):
     #do something
     df3 = createDf3()
     return df3

#define test data
df4 = someDf
df5 = anotherDf

class TestMethodToTest(unittest.TestCase):
    def test_m (self):
        result = methodToTest(someDf, anotherDf)
        self.assertEqual(len(result), 2)

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

so I have a method "methodToTest" and and I create some inputs "df4" and "df5". I know that if you put the inputs in the method, the result should be a dataframe with 2 rows. to ensure, that it is running correctly i wanted to write a unittest. But if i try to start the test, the following error massage is displayed:

E
======================================================================
ERROR: C:\...\runtime\kernel-... (unittest.loader._FailedTest)
----------------------------------------------------------------------
AttributeError: module '__main__' has no attribute 'C:\...\jupyter\runtime\kernel-...'

----------------------------------------------------------------------
Ran 1 test in 0.002s

FAILED (errors=1)
An exception has occurred, use %tb to see the full traceback.

SystemExit: True
C:\...\interactiveshell.py:...: UserWarning: To exit: use 'exit', 'quit', or Ctrl-D.
  warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1)

I do not know, why this error occurs and how to avoid it.

1 Answers

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=False will prevent unittest.main to shutdown the kernell process

https://medium.com/@vladbezden/using-python-unittest-in-ipython-or-jupyter-732448724e31

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