class TestAnonymousSurvey(unittest.TestCase): """Tests for the class AnonymouseSurvey""" # The method setUp() does two things: def setUp(self): """Create a survey and a set of responses for use in all test methods""" question = "What language did you first learn to speak?" # It creates a survey instance and, self.mySurvey = AnonymousSurvey(question) # it creates a list of responses self.responses = ["English", "Spanish", "Mandarin"] # The above are prefixed by 'self', so they can be used anywhere in the class. def testStoreSingleResponse(self): """Test that a single response is stored properly.""" # We take the response in the first spot of our list above and save it to our response list in our class AnonymousSurvey self.mySurvey.storeResponse(self.responses[0]) # We then check if spot 1 in the list above is save in our list in our class self.assertIn(self.responses[0], self.mySurvey.responses) def testStoreThreeResponses(self): """Test that a single response is stored properly.""" # Looping over our list above to save it to our class for response in self.responses: self.mySurvey.storeResponse(response) # looping over our list above again to test each one against the saved list in our class for response in self.responses: self.assertIn(response, self.mySurvey.responses)
from survey import AnonymousSurvey # Define a question, and make a survey question = "What language did you first learn to speak?" mySurvey = AnonymousSurvey(question) # Show the question, and store responses to the question mySurvey.showQuestion() print("Enter 'q' at any time to quit.\n") while True: response = input("Language: ") if response == "q": break mySurvey.storeResponse(response) # Show the survey results print("\nThank you to everyone who participated in the survey!") mySurvey.showResults() # This class works for a simple anonymous survey. But let’s say we want to # improve AnonymousSurvey and the module it’s in, survey. We could allow each # user to enter more than one response. We could write a method to list only # unique responses and to report how many times each response was given. # We could write another class to manage nonanonymous surveys. # Implementing such changes would risk affecting the current behavior # of the class AnonymousSurvey. For example, it’s possible that while trying to # allow each user to enter multiple responses, we could accidentally change # how single responses are handled. To ensure we don’t break existing behavior # as we develop this module, we can write tests for the class.