unittest.main() not working within main()

I am learning unittest on class and encounter a problem that unittest.main() can not run within main function:

Here is the class AnonymousSurvey which collects anonymous answers to a survey question.

import unittest

class AnonymousSurvey:
    """Collect anonymous answers to a survey question."""

    def __init__(self, question):
        self.question = question
        self.responses = []

    def show_question(self):
        print(question)

    def store_response(self, new_response):
        self.responses.append(new_response) 

    def show_results(self):
        print("Survey results:")
        for response in self.responses: 
            print("- " + response)

The unittest is encapsulated in a main() function.

def main():

    class TestAnonymousSurvey(unittest.TestCase):
        """Test that a single response is stored properly"""

        def test_store_single_response(self):
            question = "What language did you first learn to speak?"
            my_survey = AnonymousSurvey(question)
            my_survey.store_response("English")

            self.assertIn("English", my_survey.responses)

    unittest.main()



if __name__ == "__main__":
    main()

It report ran0 tests

In [64]: !python survey.py                                                                                        

----------------------------------------------------------------------
Ran 0 tests in 0.000s

OK

How could I get it working within a main() area?

1 answer

  • answered 2018-11-08 06:35 Modelmat

    As unittest's basic example, you would just place the unittest.main() into the if __name__ == "__main__": if statement, leaving the unittest class outside. Hence, your unittest code should become:

    class TestAnonymousSurvey(unittest.TestCase):
        """Test that a single response is stored properly"""
    
        def test_store_single_response(self):
            question = "What language did you first learn to speak?"
            my_survey = AnonymousSurvey(question)
            my_survey.store_response("English")
    
            self.assertIn("English", my_survey.responses)
    
    if __name__ == "__main__":
        unittest.main()