← All advanced lessons

Advanced Python / A04

Testing Your Code

Unit tests, test cases, assertions, failures, and testing functions and classes.

Advanced Python - 4. testing Your Code

4. testing Your Code

4.1 testing a Function

4.1.1 Creating Something to Test

4.1.2 Unit Tests and Test Cases

4.1.3 A Failing Test

4.1.4 Adding a New Test

4.2 testing a Class

4.2.1 More “assert” methods

4.2.2 A Class to Test

4.2.3 testing the Class

4.3 Conclusion

Chapter 4 Assignments

A4.1

4. Testing Your Code

4.1 testing a Function

4.1.1 Creating Something to Test

def get_formatted_name(first, last):

full_name = first + ‘ ‘ + last

return full_name.title() # Capitalizes the first letter

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(“\tNeatly formatted name: “ + formatted_name + ‘.’)

OUTPUT:

Enter ‘q’ at any time to quit.

Please give me a first name: janis

Please give me a last name: joplin

Neatly formatted name: Janis Joplin

Please give me a first name: bob

Please give me a last name: dylan

Neatly formatted name: Bob Dylan

Please give me a first name: q

4.1.2 Unit Tests and Test Cases

import unittest

from name_function import get_formatted_name

class NamesTestCase(unittest.TestCase):

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

unittest.main()

self.assertEqual(formatted_name, ‘Janis Joplin’)

says, “Compare the value in formatted_name to the string ‘Janis Joplin’. If they are equal

as expected, fine. But if they don’t match, let me know!”

.

—-------------------------------------------------------

Ran 1 test in 0.000s

OK

4.1.3 A Failing Test

def get_formatted_name(first, middle, last):

full_name = first + ‘ ‘ + middle + ‘ ‘ + last

return full_name.title()

1- E

=========================================

2- ERROR: test_first_last_name (main.NamesTestCase)

—---------------------------------------------------------------------

3- Traceback (most recent call last):

File “test_name_function.py”, line 8, in test_first_last_name

formatted_name = get_formatted_name(‘janis’, ‘joplin’)

TypeError: get_formatted_name() missing 1 required positional argument: ‘last’

—--------------------------------------------------------------------

4- Ran 1 test in 0.000s

5- FAILED (errors=1)

1- The single E tells us one unit test in the test case resulted in an error

2- Tells us that the particular unit test test_first_last_name is what failed in

NamesTestCase.

3- The typical Python error explaining what the error was. In this case, it was that

the function was looking for three arguments but only got two.

4- One unit test was run

5- The overall test case failed and one error occurred.

def get_formatted_name(first, last, middle = ‘’):

if middle: # When there is a middle, this is True

full_name = first + ‘ ‘ + middle + ‘ ‘ + last

else: # When no middle is given

full_name = first + ‘ ‘ + last

return full_name.title()

  • If we run the test_name_function.py test again, the program works for the ‘Janis Joplin’ test. The result is:

.

—-------------------------------------------------------

Ran 1 test in 0.000s

OK

4.1.4 Adding a New Test

import unittest

from name_function import get_formatted_name

class NamesTestCase(unittest.TestCase):

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_last_middle_name(self):

‘’’ Do names like ‘Wolfgang Amadeus Mozart’ work?’’’

formatted_name = get_formatted_name(

‘wolfgang’, ‘mozart’, ‘amadeus’)

self.assertEqual(formatted_name, ‘Wolfgang Amadeus Mozart’)

unittest.main()

.

—-------------------------------------------------------

Ran 2 tests in 0.000s

OK

4.2 testing a Class

4.2.1 More “assert” methods

self.assertEqual(formatted_name, ‘Janis Joplin’)

Method Use

assertEqual(a, b) Verify that a == b

assertNotEqual(a, b) Verify that a != b

assertTrue(x) Verify that x is True

assertFalse(x) Verify that x is False

assertIn(item, list) Verify that item is in list

assertNotIn(item, list) Verify that item is not in list

4.2.2 A Class to Test

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('- ' + response)

from survey import AnonymousSurvey

# Define a question, make a survey

question = "What language did you first learn to speak?"

my_survey = AnonymousSurvey(questions)

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

What language did you first learn to speak?

Enter ‘q’ at any time to quit.

Language: English

Language: Spanish

Language: English

Language: Mandarin

Language: q

Thank you to everyone who participated in the survey!

Survey results:

-English

-Spanish

-English

-Mandarin

4.2.3 testing the Class

import unittest

from survey import AnonymousSurvey

class TestAnonymousSurvey(unittest.TestCase):

""" Test for the class AnonymousSurvey """

def test_store_single_response(self):

""" Test 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)

unittest.main()

.

—----------------------------------------------

Ran 1 test in 0.0001s

OK

def test_store_three_responses(self):

""" Test that three individual responses are stored properly """

question = "What language did you first learn to speak?"

my_survey = AnonymousSurvey(question)

responses = ['English', 'Spanish', 'Mandarin']

for response in responses:

my_survey.store_response(response)

for response in responses:

self.assertIn(response, my_survey.responses)

..

—--------------------------------

Ran 2 tests in 0.000s

OK

import unittest

from survey import AnonymousSurvey

class TestAnonymousSurvey(unittest.TestCase):

""" Test 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 = AnonymouseSurvey(question)

self.responses = ['English', 'Spanish', 'Mandarin']

def test_store_single_response(self):

""" Test 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):

""" Test that three individual responses are stored properly """

for response in responses:

self.my_survey.store_response(response)

for response in self.responses:

self.assertIn(response, self.my_survey.responses)

unittest.main()

4.3 Conclusion

Chapter 4 Assignments

A4.1 City, Country

A4.2 Population

A4.3 Employee

(more potential ASSIGNMENTS)