0

I'm just learning about python and unittests in particular.

I'm trying to follow the following simple example where the function being tested is:

def get_formatted_name(first, last):
    """Generate a neatly formatted name"""
    full_name = first + ' ' + last
    return full_name.title()

and the test code is:

import unittest
from name_function import get_formatted_name


class NamesTestCase(unittest.TestCase):
    """Tests for 'name_function.py'"""

    def test_first_last_name(self):
        """Do names liike 'Janis Joplin' work """
        formatted_name = get_formatted_name('janis', 'joplin')
        self.assertEqual(formatted_name, 'Janis Joplin')

unittest.main()

According to the example this should run fine and report that the test ran successfully.

However I get the following errors:

EE
======================================================================
ERROR: test_name_function (unittest.loader._FailedTest)
----------------------------------------------------------------------
AttributeError: module '__main__' has no attribute 'test_name_function'

======================================================================
ERROR: true (unittest.loader._FailedTest)
----------------------------------------------------------------------
AttributeError: module '__main__' has no attribute 'true'

----------------------------------------------------------------------
Ran 2 tests in 0.000s

FAILED (errors=2)

Process finished with exit code 1

Unfortunately I have no idea what is going wrong!

1
  • I faced same issue Everything is OK when i run the script in terminal but when i run it in the PyCharm i faced same issue. So i think it may have something to do with Pycharm Commented Mar 28, 2018 at 5:15

1 Answer 1

2

As per the documentation you would need to add the following code. That way it'll run as the main module rather than anything else. You can see the example here.

if __name__ == '__main__':
    unittest.main()
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you that is completely missing from the example I am following but works when I add it.
As a follow up can I ask why the if name == 'main': is necessary? I've seen the answer here: stackoverflow.com/questions/419163/what-does-if-name-main-do but am still unclear why it is necessary here? Surely as I am running the testcode directly then it is already the main function? Indeed this is why the code in the if statement is triggered? So it doesn't seem to change anything?
That's actually a great question. However, I'm sorry to say that I'm unable to answer that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.