Post

Python Crash Course 11 - Testing

I’m YouKoutaku. These codes are from the book python_Crash_Course, 2nd edition. I learned python and took these notes for this book.

11. Testing code

11.1 Test function

1
2
3
4
5
# name_function.py: A simple function to return a formatted name.
def get_formatted_name(first, last):
    """ Generate a neatly formatted full name. """
    full_name = f"{first} {last}"
    return full_name.title()
1
2
3
4
5
6
7
8
9
10
11
12
# name.py: A program that uses the get_formatted_name() function.
#from name_function import get_formatted_name
print("Enter 'q' at any time to quit.")
while True:
    first = input("\nPlease give me a first name: ")
    if first == 'q':
        break
    last = input("Please give me a last name: ")
    if last == 'q':
        break
    formatted_name = get_formatted_name(first, last)
    print(f"\tNeatly formatted name: {formatted_name}.")
1
Enter 'q' at any time to quit.
  • unittest is a module in Python’s standard library that provides tools for testing your code.
  • unittest.TestCase is a class that provides a set of testing tools.
  • self.assertEqual() is a method that verifies that a result you received matches the result you expected to receive.
1
2
3
4
5
6
7
8
9
10
11
12
13
# Test the function
import unittest
#from name_function import get_formatted_name

class NamesTestCase(unittest.TestCase):
    """ test name_function.py """
    def test_first_last_name(self):
        """ Do names like 'Janis Joplin' work? """
        formatted_name = get_formatted_name('janis', 'joplin')
        self.assertEqual(formatted_name, 'Janis Joplin')

if __name__ == '__main__':
    unittest.main()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# Add more tests
# Test the function
import unittest
#from name_function import get_formatted_name

class NamesTestCase(unittest.TestCase):
    """ test name_function.py """
    def test_first_last_name(self):
        """ Do names like 'Janis Joplin' work? """
        formatted_name = get_formatted_name('janis', 'joplin')
        self.assertEqual(formatted_name, 'Janis Joplin')
    def test_first_middle_last_name(self):
        """ Do names like 'Wolfgang Amadeus Mozart' work? """
        formatted_name = get_formatted_name('wolfgang', 'mozart', 'amadeus')
        self.assertEqual(formatted_name, 'Wolfgang Amadeus Mozart')

if __name__ == '__main__':
    unittest.main()

11.2 Test class

There are methods in unittest.TestCase.

MethodChecks that
assertEqual(a, b)a == b
assertNotEqual(a, b)a != b
assertTrue(x)bool(x) is True
assertFalse(x)bool(x) is False
assertIs(a, b)a is b
assertIsNot(a, b)a is not b
assertIsNone(x)x is None
assertIsNotNone(x)x is not None
assertIn(a, b)a in b
assertNotIn(a, b)a not in b
assertIsInstance(a, b)isinstance(a, b)
assertNotIsInstance(a, b)not isinstance(a, b)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# Survey.py: A class to represent a survey.
class AnonymousSurvey:  
    """ collect anonymous answers to a survey question."""
    def __init__(self, question):
        """ store a question, and prepare to store responses."""
        self.question = question
        self.responses = []
    def show_question(self):
        """ show the survey question."""
        print(self.question)
    def store_response(self, new_response):
        """ store a single response to the survey"""
        self.responses.append(new_response)
    def show_results(self):
        """ show all the responses that have been given."""
        print("Survey results:")
        for response in self.responses:
            print(f"- {response}")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# from survey import AnonymousSurvey

question = "What language did you first learn to speak?"
my_survey = AnonymousSurvey(question)
# Show the question and store responses to the question.
my_survey.show_question()
print("Enter 'q' at any time to quit.\n")
while True:
    response = input("Language: ")
    if response == 'q':
        break
    my_survey.store_response(response)

# Show the survey results.
print("\nThank you to everyone who participated in the survey!")
my_survey.show_results()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# test_survey.py: A test class for the AnonymousSurvey class.
import unittest 
#from survey import AnonymousSurvey

class TestAnonymousSurvey(unittest.TestCase):
    """ tests for the class AnonymousSurvey"""
    def test_store_single_response(self):
        """ check that a single response is stored properly."""
        question = "What language did you first learn to speak?"
        my_survey = AnonymousSurvey(question)
        my_survey.store_response('English')
        self.assertIn('English', my_survey.responses)
# assertIn() method: check if a value is in a list

if __name__ == '__main__': unittest.main()

setup(self)

  1. Create a object
  2. Create a list of answers
  3. To Make sure they can be used everywhere in class
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import unittest
#from survey import AnonymousSurvey

class TestAnonymousSurvey(unittest.TestCase):
    """ tests for the class AnonymousSurvey"""
    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?"
        self.my_survey = AnonymousSurvey(question)
        self.responses = ['English', 'Spanish', 'Mandarin']
    def test_store_single_response(self):
        """ check that a single response is stored properly."""
        self.my_survey.store_response(self.responses[0])
        self.assertIn(self.responses[0], self.my_survey.responses)
    def test_store_three_responses(self):
        """ check that three responses are stored properly."""
        for response in self.responses:
            self.my_survey.store_response(response)
        for response in self.responses:
            self.assertIn(response, self.my_survey.responses)

if __name__ == '__main__': unittest.main()
This post is licensed under CC BY 4.0 by the author.