python3 for unit test: AttributeError: module '__main__' has no attribute "kernel…"

Question:

I am practicing the unittest for python and it always directed to a JSON file:

Unittest code

import unittest
from name_function import get_formatted_name
class NamesTestCase(unittest.TestCase):

    def test_first_last_name(self):
        formatted_name=get_formatted_name("allen","park")
        self.assertEqual(formatted_name,"Allen Park")

unittest.main()

ERROR

/Users/xxx/Library/Jupyter/runtime/kernel-0eacd257-bf93-4c0f-843c-2e8a96377a17
(unittest.loader._FailedTest)

AttributeError: module '__main__' has no attribute
'/Users/xxx/Library/Jupyter/runtime/kernel-0eacd257-bf93-4c0f-843c-2e8a96377a17'

The traceback is:

    SystemExit                                Traceback (most recent call last)
    <ipython-input-1-15fe4fc5728d> in <module>()
         20         self.assertIn(response,my_survey.responses)
         21 
    ---> 22 unittest.main()

    /anaconda3/lib/python3.6/unittest/main.py in __init__(self, module, defaultTest, argv, testRunner, testLoader, exit, verbosity, failfast, catchbreak, buffer, warnings, tb_locals)
         93         self.progName = os.path.basename(argv[0])
         94         self.parseArgs(argv)
    ---> 95         self.runTests()
         96 
         97     def usageExit(self, msg=None):

    /anaconda3/lib/python3.6/unittest/main.py in runTests(self)
        256         self.result = testRunner.run(self.test)
        257         if self.exit:
    --> 258             sys.exit(not self.result.wasSuccessful())
        259 
        260 main = TestProgram

    SystemExit: True

How do I fix this?

Asked By: J.W.Liu

||

Answers:

Have a look at “https://medium.com/@vladbezden/using-python-unittest-in-ipython-or-jupyter-732448724e31

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

using following:

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

It worked, but was failing before due to a mirror typo. I replaced:

self.asertEqual

with:

self.assertEqual
Answered By: PengfeiCui

The highest-voted answer should work. Just remember to check if other parts of the code are right. Especially pay attention to this line:

self.assertEqual(formatted_name, ‘Janis Joplin’)

Be careful about the spelling and input the right compared string, which is supposed to be a capitalized, properly spaced full name. The corresponding premise is that in the name_function.py, the return is full_name.title()

Answered By: Yunwei Cao
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.