Bazman
Bazman

Reputation: 2150

Unittest example not working

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!

Upvotes: 0

Views: 1882

Answers (1)

Jonathan
Jonathan

Reputation: 8890

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()

Upvotes: 2

Related Questions