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!

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Bazman
  • 2,058
  • 9
  • 45
  • 65
  • 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 – Qingwei. tech Mar 28 '18 at 05:15

1 Answers1

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()
Jonathan
  • 8,453
  • 9
  • 51
  • 74
  • Thank you that is completely missing from the example I am following but works when I add it. – Bazman May 20 '17 at 17:15
  • As a follow up can I ask why the if __name__ == '__main__': is necessary? I've seen the answer here: http://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? – Bazman May 20 '17 at 17:37
  • 1
    That's actually a great question. However, I'm sorry to say that I'm unable to answer that. – Jonathan May 20 '17 at 17:48