Python Unittest Module Overview
Python Unittest Module Overview
CS100/CS101 – Python
Outline
●
Python’s unittest module
●
Building test cases for functions and classes
Testing
●
Code should work as it’s supposed to in
response to all the input types
●
Python’s unittest module
Testing a Function
name_function.py
name_function.py
def
def get_formatted_name(first,
get_formatted_name(first, last):
last):
"""Generate
"""Generate aa neatly
neatly formatted
formatted full
full name."""
name."""
full_name
full_name == f"{first}
f"{first} {last}"
{last}"
return
return full_name.title()
full_name.title()
Testing a Function
def
def get_formatted_name(first,
get_formatted_name(first, last):
last):
"""Generate
"""Generate aa neatly
neatly formatted
formatted full
full name."""
name."""
full_name
full_name == f"{first}
f"{first} {last}"
{last}"
return
return full_name.title()
full_name.title()
from [Link]
from name_function
name_function import
import get_formatted_name
get_formatted_name [Link]
print("Enter
print("Enter 'q'
'q' at
at any
any time
time to
to quit.")
quit.")
while
while True:
True:
first
first == input("\nPlease
input("\nPlease give
give me
me aa first
first name:
name: ")
")
if
if first
first ==
== 'q':
'q':
break
break
last
last == input("Please
input("Please give
give me
me aa last
last name:
name: ")
")
if
if last
last ==
== 'q':
'q':
break
break
formatted_name
formatted_name == get_formatted_name(first,
get_formatted_name(first, last)
last)
print(f"\tNeatly
print(f"\tNeatly formatted
formatted name:
name: {formatted_name}.")
{formatted_name}.")
Unit Tests, Test Cases
●
unittest - Python standard library provides
●
Unit Tests, Test Cases
●
unittest - Python standard library provides
●
Unit test verifies that one specific aspect of a
function’s behavior is correct
●
Unit Tests, Test Cases
●
unittest - Python standard library provides
●
Unit test verifies that one specific aspect of a
function’s behavior is correct
●
Test case: Collection of unit tests
– tests within the full range of situations
Unit Tests, Test Cases
●
unittest - Python standard library provides
●
Unit test verifies that one specific aspect of a function’s
behavior is correct
●
Test case: Collection of unit tests
– tests within the full range of situations
●
Full coverage: full range of unit tests covering all the
possible ways a function can be used
A Passing Test
import
import unittest
unittest
from
from name_function
name_function import
import get_formatted_name
get_formatted_name
A Passing Test
import
import unittest
unittest
from
from name_function
name_function import
import get_formatted_name
get_formatted_name
import
importunittest
unittestand
andthe
thefunction
functionwe
wewant
wanttoto
test,
test,get_formatted_name()
get_formatted_name()
A Passing Test
import
import unittest
unittest
from
from name_function
name_function import
import get_formatted_name
get_formatted_name
class
class NamesTestCase([Link]):
NamesTestCase([Link]):
"""Tests
"""Tests for
for 'name_function.py'."""
'name_function.py'."""
A Passing Test
import
import unittest
unittest
from
from name_function
name_function import
import get_formatted_name
get_formatted_name
class
class NamesTestCase([Link]):
NamesTestCase([Link]):
"""Tests
"""Tests for
for 'name_function.py'."""
'name_function.py'."""
NamesTestCase
NamesTestCasewill
willcontain
containaaseries
seriesofofunit
unittests
testsfor
for
get_formatted_name()
get_formatted_name()
Class
Classmust
mustinherit
inheritfrom
fromthe
theclass
[Link]
[Link]
A Passing Test
import
import unittest
unittest
from
from name_function
name_function import
import get_formatted_name
get_formatted_name
class
class NamesTestCase([Link]):
NamesTestCase([Link]):
"""Tests
"""Tests for
for 'name_function.py'."""
'name_function.py'."""
def
def test_first_last_name(self):
test_first_last_name(self):
A Passing Test
import
import unittest
unittest
from
from name_function
name_function import
import get_formatted_name
get_formatted_name
class
class NamesTestCase([Link]):
NamesTestCase([Link]):
"""Tests
"""Tests for
for 'name_function.py'."""
'name_function.py'."""
def
def test_first_last_name(self):
test_first_last_name(self):
One
Onemethod
methodtests
testsone
oneaspect
aspectofofget_formatted_name()
get_formatted_name()
test_first_last_name()
test_first_last_name()checks
checksififthe
thefull
fullname
nameisiscreated
created
correctly when first and last names are supplied
correctly when first and last names are supplied
Any
Anymethod
methodthat
thatstarts
startswith
withtest_
test_will
willbe
berun
runautomatically
automatically
A Passing Test
import
import unittest
unittest
from
from name_function
name_function import
import get_formatted_name
get_formatted_name
class
class NamesTestCase([Link]):
NamesTestCase([Link]):
"""Tests
"""Tests for
for 'name_function.py'."""
'name_function.py'."""
def
def test_first_last_name(self):
test_first_last_name(self):
"""Do
"""Do names
names like
like 'Janis
'Janis Joplin'
Joplin' work?"""
work?"""
formatted_name
formatted_name == get_formatted_name('janis',
get_formatted_name('janis', 'joplin')
'joplin')
[Link](formatted_name,
[Link](formatted_name, 'Janis
'Janis Joplin')
Joplin')
A Passing Test
import
import unittest
unittest
from
from name_function
name_function import
import get_formatted_name
get_formatted_name
class
class NamesTestCase([Link]):
NamesTestCase([Link]):
"""Tests
"""Tests for
for 'name_function.py'."""
'name_function.py'."""
def
def test_first_last_name(self):
test_first_last_name(self):
"""Do
"""Do names
names like
like 'Janis
'Janis Joplin'
Joplin' work?"""
work?"""
formatted_name
formatted_name == get_formatted_name('janis',
get_formatted_name('janis', 'joplin')
'joplin')
[Link](formatted_name,
[Link](formatted_name, 'Janis
'Janis Joplin')
Joplin')
Assert
Assertmethods
methodsverify
verifythat
thatresult
resultmatches
matchesthe
the
expected value.
expected value.
A Passing Test
import
import unittest
unittest
from
from name_function
name_function import
import get_formatted_name
get_formatted_name
class
class NamesTestCase([Link]):
NamesTestCase([Link]):
"""Tests
"""Tests for
for 'name_function.py'."""
'name_function.py'."""
def
def test_first_last_name(self):
test_first_last_name(self):
"""Do
"""Do names
names like
like 'Janis
'Janis Joplin'
Joplin' work?"""
work?"""
formatted_name
formatted_name == get_formatted_name('janis',
get_formatted_name('janis', 'joplin')
'joplin')
[Link](formatted_name,
[Link](formatted_name, 'Janis
'Janis Joplin')
Joplin')
if
if __name__
__name__ ==
== '__main__':
'__main__':
[Link]()
[Link]()
A Passing Test
import
import unittest
unittest
from
from name_function
name_function import
import get_formatted_name
get_formatted_name
class
class NamesTestCase([Link]):
NamesTestCase([Link]):
"""Tests
"""Tests for
for 'name_function.py'."""
'name_function.py'."""
def
def test_first_last_name(self):
test_first_last_name(self):
"""Do
"""Do names
names like
like 'Janis
'Janis Joplin'
Joplin' work?"""
work?"""
formatted_name
formatted_name == get_formatted_name('janis',
get_formatted_name('janis', 'joplin')
'joplin')
[Link](formatted_name,
[Link](formatted_name, 'Janis
'Janis Joplin')
Joplin')
if 22options:
options:run
runthis
thisfile
filedirectly;
directly;testing
if __name__
__name__ ==
== '__main__':
'__main__': testing
[Link]() frameworks
frameworks import this test file andrun
import this test file and run
[Link]()
__name__
__name__== ==‘__main__’
‘__main__’isisTrue
Truewhen
whenthis
thisfile
fileisis
run
rundirectly
directly
A Passing Test
import unittest
import unittest
from name_function import get_formatted_name
from name_function import get_formatted_name
class NamesTestCase([Link]):
class NamesTestCase([Link]):
"""Tests for 'name_function.py'."""
"""Tests for 'name_function.py'."""
def test_first_last_name(self):
def test_first_last_name(self):
"""Do names like 'Janis Joplin' work?"""
"""Do names like 'Janis Joplin' work?"""
formatted_name = get_formatted_name('janis', 'joplin')
formatted_name = get_formatted_name('janis', 'joplin')
[Link](formatted_name, 'Janis Joplin')
[Link](formatted_name, 'Janis Joplin')
if __name__ == '__main__':
if __name__ == '__main__':
[Link]()
[Link]()
.
.
----------------------------------------------------------------------
----------------------------------------------------------------------
Ran 1 test in 0.000s
Ran 1 test in 0.000s
OK
OK
Modified Method
def
def get_formatted_name(first,
get_formatted_name(first, middle,
middle, last):
last):
"""Generate
"""Generate aa neatly
neatly formatted
formatted full
full name."""
name."""
full_name
full_name == f"{first}
f"{first} {middle}
{middle} {last}"
{last}"
return
return full_name.title()
full_name.title()
Modified Method
def
def get_formatted_name(first,
get_formatted_name(first, middle,
middle, last):
last):
"""Generate
"""Generate aa neatly
neatly formatted
formatted full
full name."""
name."""
full_name
full_name == f"{first}
f"{first} {middle}
{middle} {last}"
{last}"
return
return full_name.title()
full_name.title()
EE
======================================================================
======================================================================
ERROR:
ERROR: test_first_last_name
test_first_last_name (__main__.NamesTestCase)
(__main__.NamesTestCase)
----------------------------------------------------------------------
----------------------------------------------------------------------
Traceback
Traceback (most
(most recent
recent call
call last):
last):
File
File "test_name_function.py", line
"test_name_function.py", line 8,
8, in
in test_first_last_name
test_first_last_name
formatted_name
formatted_name == get_formatted_name('janis',
get_formatted_name('janis', 'joplin')
'joplin')
TypeError:
TypeError: get_formatted_name() missing 1 required positional
get_formatted_name() missing 1 required positional argument:
argument: 'last'
'last'
----------------------------------------------------------------------
----------------------------------------------------------------------
Ran
Ran 11 test
test in
in 0.000s
0.000s
FAILED
FAILED (errors=1)
(errors=1)
Modified Method to Pass the Test Case
def
def get_formatted_name(first,
get_formatted_name(first, last,
last, middle=''):
middle=''):
"""Generate
"""Generate aa neatly
neatly formatted
formatted full
full name."""
name."""
if
if middle:
middle:
full_name
full_name == f"{first}
f"{first} {middle}
{middle} {last}"
{last}"
else:
else:
full_name
full_name == f"{first}
f"{first} {last}"
{last}"
return
return full_name.title()
full_name.title()
Middle Name Test Case
--
-- same
same as
as before
before --
--
class NamesTestCase([Link]):
class NamesTestCase([Link]):
"""Tests
"""Tests for
for 'name_function.py'."""
'name_function.py'."""
def
def test_first_last_name(self):
test_first_last_name(self):
--
-- same as
same as before
before --
--
def
def test_first_last_middle_name(self):
test_first_last_middle_name(self):
"""Do
"""Do names
names like
like 'Wolfgang
'Wolfgang Amadeus
Amadeus Mozart'
Mozart' work?"""
work?"""
formatted_name
formatted_name == get_formatted_name('wolfgang',
get_formatted_name('wolfgang', 'mozart',
'mozart', 'amadeus')
'amadeus')
[Link](formatted_name, 'Wolfgang Amadeus Mozart')
[Link](formatted_name, 'Wolfgang Amadeus Mozart')
if
if __name__
__name__ ==
== '__main__':
'__main__':
[Link]()
[Link]()
class
class AnonymousSurvey:
AnonymousSurvey:
"""Collect
"""Collect anonymous
anonymous answers
answers to
to aa survey
survey question."""
question."""
Testing a Class
def
def __init__(self,
__init__(self, question):
question):
"""Store
"""Store aa question,
question, and
and prepare
prepare to
to store
store responses."""
responses."""
[Link]
[Link] == question
question
[Link]
[Link] = []
= []
def
def show_question(self):
show_question(self):
"""Show
"""Show the
the survey
survey question."""
question."""
print([Link])
print([Link])
def
def store_response(self,
store_response(self, new_response):
new_response):
"""Store
"""Store aa single
single response
response to
to the
the survey."""
survey."""
[Link](new_response)
[Link](new_response)
def
def show_results(self):
show_results(self):
"""Show
"""Show all
all the
the responses
responses that
that have
have been
been given."""
given."""
print("Survey
print("Survey results:")
results:")
for
for response
response in
in [Link]:
[Link]:
print(f"-
print(f"- {response}")
{response}")
Executing a Class
from
from survey
survey import
import AnonymousSurvey
AnonymousSurvey
## Define
Define aa question,
question, and
and make
make aa survey.
survey.
question
question == "What
"What language
language did
did you
you first
first learn
learn to
to speak?"
speak?"
my_survey
my_survey == AnonymousSurvey(question)
AnonymousSurvey(question)
## Show
Show the
the question,
question, and
and store
store responses
responses to
to the
the question.
question.
my_survey.show_question()
my_survey.show_question()
print("Enter
print("Enter 'q'
'q' at
at any
any time
time to
to quit.\n")
quit.\n")
while True:
while True:
response
response == input("Language:
input("Language: ")
")
if
if response
response ==
== 'q':
'q':
break
break
my_survey.store_response(response)
my_survey.store_response(response)
## Show
Show the
the survey
survey results.
results.
print("\nThank
print("\nThank you to
you to everyone
everyone who
who participated
participated in
in the
the survey!")
survey!")
my_survey.show_results()
my_survey.show_results()
Testing AnonymousSurvey
import
import unittest
unittest
from
from survey
survey import
import AnonymousSurvey
AnonymousSurvey
class
class TestAnonymousSurvey([Link]):
TestAnonymousSurvey([Link]):
"""Tests
"""Tests for
for the
the class
class AnonymousSurvey"""
AnonymousSurvey"""
Testing AnonymousSurvey
import
import unittest
unittest
from
from survey
survey import
import AnonymousSurvey
AnonymousSurvey
class
class TestAnonymousSurvey([Link]):
TestAnonymousSurvey([Link]):
"""Tests
"""Tests for
for the
the class
class AnonymousSurvey"""
AnonymousSurvey"""
def
def test_store_single_response(self):
test_store_single_response(self):
"""Test
"""Test that
that aa single
single response
response is
is stored
stored properly."""
properly."""
Testing AnonymousSurvey
import
import unittest
unittest
from
from survey
survey import
import AnonymousSurvey
AnonymousSurvey
class
class TestAnonymousSurvey([Link]):
TestAnonymousSurvey([Link]):
"""Tests
"""Tests for
for the
the class
class AnonymousSurvey"""
AnonymousSurvey"""
def
def test_store_single_response(self):
test_store_single_response(self):
"""Test
"""Test that
that aa single
single response
response is
is stored
stored properly."""
properly."""
question
question == "What
"What language
language did
did you
you first
first learn
learn to
to speak?"
speak?"
my_survey = AnonymousSurvey(question)
my_survey = AnonymousSurvey(question)
my_survey.store_response('English')
my_survey.store_response('English')
[Link]('English',
[Link]('English', my_survey.responses)
my_survey.responses)
Testing AnonymousSurvey
import
import unittest
unittest test_survey.py
test_survey.py
from
from survey
survey import
import AnonymousSurvey
AnonymousSurvey
class
class TestAnonymousSurvey([Link]):
TestAnonymousSurvey([Link]):
"""Tests
"""Tests for
for the
the class
class AnonymousSurvey"""
AnonymousSurvey"""
def
def test_store_single_response(self):
test_store_single_response(self):
"""Test
"""Test that
that aa single
single response
response is
is stored
stored properly."""
properly."""
question
question == "What
"What language
language did
did you
you first
first learn
learn to
to speak?"
speak?"
my_survey = AnonymousSurvey(question)
my_survey = AnonymousSurvey(question)
my_survey.store_response('English')
my_survey.store_response('English')
[Link]('English',
[Link]('English', my_survey.responses)
my_survey.responses)
if
if __name__
__name__ ==
== '__main__':
'__main__':
[Link]()
[Link]()
--
-- same
same as
as before
before --
--
Testing AnonymousSurvey
class
class TestAnonymousSurvey([Link]):
TestAnonymousSurvey([Link]):
"""Tests
"""Tests for
for the
the class
class AnonymousSurvey"""
AnonymousSurvey"""
def
def test_store_single_response(self):
test_store_single_response(self):
--
-- same as
same as before
before --
--
def
def test_store_three_responses(self):
test_store_three_responses(self):
"""Test
"""Test that
that three
three individual
individual responses
responses are
are stored
stored properly."""
properly."""
question
question == "What
"What language
language did
did you
you first
first learn
learn to
to speak?"
speak?"
my_survey = AnonymousSurvey(question)
my_survey = AnonymousSurvey(question)
responses
responses == ['English',
['English', 'Spanish',
'Spanish', 'Mandarin']
'Mandarin']
for response in responses:
for response in responses:
my_survey.store_response(response)
my_survey.store_response(response)
for
for response
response in
in responses:
responses:
[Link](response,
[Link](response, my_survey.responses)
my_survey.responses)
if
if __name__
__name__ ==
== '__main__':
'__main__': test_survey.py
test_survey.py
[Link]()
[Link]()
Repeated Instantiation
--
-- same
same as
as before
before --
--
def
def test_store_single_response(self):
test_store_single_response(self):
--
--
my_survey
my_survey == AnonymousSurvey(question)
AnonymousSurvey(question)
--
--
def
def test_store_three_responses(self):
test_store_three_responses(self):
--
--
my_survey
my_survey == AnonymousSurvey(question)
AnonymousSurvey(question)
--
--
--
-- same
same as
as before
before --
--
setUp()
Method
import
import unittest
unittest
from
from survey
survey import
import AnonymousSurvey
AnonymousSurvey
class
class TestAnonymousSurvey([Link]):
TestAnonymousSurvey([Link]):
"""Tests
"""Tests for
for the
the class
class AnonymousSurvey."""
AnonymousSurvey."""
def
def setUp(self):
setUp(self):
...
...
setUp()
Method
import
import unittest
unittest
from
from survey
survey import
import AnonymousSurvey
AnonymousSurvey
class
class TestAnonymousSurvey([Link]):
TestAnonymousSurvey([Link]):
"""Tests
"""Tests for
for the
the class
class AnonymousSurvey."""
AnonymousSurvey."""
def
def setUp(self):
setUp(self):
"""Create
"""Create aa survey
survey and
and aa set
set of
of responses
responses for
for use
use in
in all
all test
test methods.
methods. """
"""
question
question == "What
"What language
language did
did you
you first
first learn
learn to
to speak?"
speak?"
self.my_survey
self.my_survey == AnonymousSurvey(question)
AnonymousSurvey(question)
[Link]
[Link] == ['English',
['English', 'Spanish',
'Spanish', 'Mandarin']
'Mandarin']
setUp()
import
import unittest
unittest Method
from
from survey
survey import
import AnonymousSurvey
AnonymousSurvey
class
class TestAnonymousSurvey([Link]):
TestAnonymousSurvey([Link]):
"""Tests
"""Tests for
for the
the class
class AnonymousSurvey."""
AnonymousSurvey."""
def
def setUp(self):
setUp(self):
"""Create
"""Create aa survey
survey and
and aa set
set of
of responses
responses for
for use
use in
in all
all test
test methods.
methods. """
"""
question
question == "What
"What language
language did
did you
you first
first learn
learn to
to speak?"
speak?"
self.my_survey = AnonymousSurvey(question)
self.my_survey = AnonymousSurvey(question)
[Link]
[Link] == ['English',
['English', 'Spanish',
'Spanish', 'Mandarin']
'Mandarin']
def
def test_store_single_response(self):
test_store_single_response(self):
"""Test
"""Test that
that aa single
single response
response is
is stored
stored properly."""
properly."""
self.my_survey.store_response([Link][0])
self.my_survey.store_response([Link][0])
[Link]([Link][0],
[Link]([Link][0], self.my_survey.responses)
self.my_survey.responses)
setUp()
-- same as before --
-- same as before --
class TestAnonymousSurvey([Link]):
class TestAnonymousSurvey([Link]):
Method
"""Tests for the class AnonymousSurvey."""
"""Tests for the class AnonymousSurvey."""
def setUp(self):
def setUp(self):
"""Create a survey and a set of responses for use in all test methods. """
"""Create a survey and a set of responses for use in all test methods. """
question = "What language did you first learn to speak?"
question = "What language did you first learn to speak?"
self.my_survey = AnonymousSurvey(question)
self.my_survey = AnonymousSurvey(question)
[Link] = ['English', 'Spanish', 'Mandarin']
[Link] = ['English', 'Spanish', 'Mandarin']
def test_store_single_response(self):
def test_store_single_response(self):
-- same as before --
-- same as before --
def test_store_three_responses(self):
def test_store_three_responses(self):
"""Test that three individual responses are stored properly."""
"""Test that three individual responses are stored properly."""
for response in [Link]:
for response in [Link]:
self.my_survey.store_response(response)
self.my_survey.store_response(response)
for response in [Link]:
for response in [Link]:
[Link](response, self.my_survey.responses)
[Link](response, self.my_survey.responses)
import unittest
setUp()
import unittest
from survey import AnonymousSurvey
from survey import AnonymousSurvey
class TestAnonymousSurvey([Link]):
Method
class TestAnonymousSurvey([Link]):
"""Tests for the class AnonymousSurvey."""
"""Tests for the class AnonymousSurvey."""
def setUp(self):
def setUp(self):
"""Create a survey and a set of responses for use in all test methods. """
"""Create a survey and a set of responses for use in all test methods. """
question = "What language did you first learn to speak?"
question = "What language did you first learn to speak?"
self.my_survey = AnonymousSurvey(question)
self.my_survey = AnonymousSurvey(question)
[Link] = ['English', 'Spanish', 'Mandarin']
[Link] = ['English', 'Spanish', 'Mandarin']
def test_store_single_response(self):
def test_store_single_response(self):
"""Test that a single response is stored properly."""
"""Test that a single response is stored properly."""
self.my_survey.store_response([Link][0])
self.my_survey.store_response([Link][0])
[Link]([Link][0], self.my_survey.responses)
[Link]([Link][0], self.my_survey.responses)
def test_store_three_responses(self):
def test_store_three_responses(self):
"""Test that three individual responses are stored properly."""
"""Test that three individual responses are stored properly."""
for response in [Link]:
for response in [Link]:
self.my_survey.store_response(response)
self.my_survey.store_response(response)
for response in [Link]:
for response in [Link]:
[Link](response, self.my_survey.responses)
[Link](response, self.my_survey.responses)
if __name__ == '__main__':
if __name__ == '__main__':
[Link]()
[Link]()
Summary
●
Python’s unittest module
●
Building test cases for functions and classes