SlideShare a Scribd company logo
Object Oriented Testing
(Unit Testing)
Damian Gordon
Object Oriented Testing
• Unit Testing is concerned with testing small chunks of a
program, for example, testing a single class or a single method.
• Python has a library for unit testing called unittest. It
provides several tools for creating and running unit tests.
Object Oriented Testing
• One of the most important classes in unittest is called
TestCase which provides a set of methods to compare
values, set up tests and clean up after tests are finished.
• To write unit tests, we create a subclass of TestCase and
write individual methods to do the actual testing. Typically we
start all of these methods with the name test.
Object Oriented Testing
• Let’s look at a simple example:
Object Oriented Testing
• Let’s look at a simple example:
import unittest
class CheckNumbers(unittest.TestCase):
def test_int_float(self):
self.assertEqual(1, 1.0)
# END test_int_float
# END CheckNumbers
if __name__ == "__main__":
unittest.main()
# ENDIF
Object Oriented Testing
• Let’s look at a simple example:
import unittest
class CheckNumbers(unittest.TestCase):
def test_int_float(self):
self.assertEqual(1, 1.0)
# END test_int_float
# END CheckNumbers
if __name__ == "__main__":
unittest.main()
# ENDIF
Create a subclass of
the TestCase class
Object Oriented Testing
• Let’s look at a simple example:
import unittest
class CheckNumbers(unittest.TestCase):
def test_int_float(self):
self.assertEqual(1, 1.0)
# END test_int_float
# END CheckNumbers
if __name__ == "__main__":
unittest.main()
# ENDIF
Create a subclass of
the TestCase class
This test checks if the
integer and real
value 1 are equal.
Object Oriented Testing
• Let’s look at a simple example:
import unittest
class CheckNumbers(unittest.TestCase):
def test_int_float(self):
self.assertEqual(1, 1.0)
# END test_int_float
# END CheckNumbers
if __name__ == "__main__":
unittest.main()
# ENDIF
Make sure this is
being run as a script
Create a subclass of
the TestCase class
This test checks if the
integer and real
value 1 are equal.
Object Oriented Testing
• And if we run this, we get:
Object Oriented Testing
• And if we run this, we get:
.
-------------------------------------------------
Ran 1 test in 0.020s
OK
Object Oriented Testing
• And if we run this, we get:
.
-------------------------------------------------
Ran 1 test in 0.020s
OK
Dot means the test has passed
Object Oriented Testing
• Let’s try another example:
Object Oriented Testing
• Let’s try another example:
import unittest
class CheckNumbers(unittest.TestCase):
def test_string_float(self):
self.assertEqual(“1”, 1.0)
# END test_string_float
# END CheckNumbers
if __name__ == "__main__":
unittest.main()
# ENDIF
Object Oriented Testing
• Let’s try another example:
import unittest
class CheckNumbers(unittest.TestCase):
def test_string_float(self):
self.assertEqual(“1”, 1.0)
# END test_string_float
# END CheckNumbers
if __name__ == "__main__":
unittest.main()
# ENDIF
This test checks if the
string and real value
1 are equal.
Object Oriented Testing
• And if we run this, we get:
Object Oriented Testing
• And if we run this, we get:
F
=========================================================
FAIL: test_string_float (__main__.CheckNumbers)
This test checks if the string and real value 1 are equal.
--------------------------------------------------------
Traceback (most recent call last):
File "C:/Users/damian/AppData/Local/Programs/Python/Python35-
32/CheckNumbers-string-float.py", line 9, in test_string_float
self.assertEqual("1", 1.0)
AssertionError: '1' != 1.0
--------------------------------------------------------
Ran 1 test in 0.060s
FAILED (failures=1)
Object Oriented Testing
• And if we run this, we get:
F
=========================================================
FAIL: test_string_float (__main__.CheckNumbers)
This test checks if the string and real value 1 are equal.
--------------------------------------------------------
Traceback (most recent call last):
File "C:/Users/damian/AppData/Local/Programs/Python/Python35-
32/CheckNumbers-string-float.py", line 9, in test_string_float
self.assertEqual("1", 1.0)
AssertionError: '1' != 1.0
--------------------------------------------------------
Ran 1 test in 0.060s
FAILED (failures=1)
“F” means the test has failed
Object Oriented Testing
• Let’s combine the two tests together:
Object Oriented Testing
• Let’s combine the two tests together:
import unittest
class CheckNumbers(unittest.TestCase):
if __name__ == "__main__":
unittest.main()
# ENDIF
def test_int_float(self):
self.assertEqual(1, 1.0)
# END test_int_float
def test_string_float(self):
self.assertEqual(“1”, 1.0)
# END test_string_float
Object Oriented Testing
• And if we run this, we get:
Object Oriented Testing
• And if we run this, we get:
.F
=================================================================
FAIL: test_string_float (__main__.CheckNumbers)
---------------------------=-------------------------------------
Traceback (most recent call last):
File "C:UsersdamianAppDataLocalProgramsPythonPython35-
32CheckNumbers.py", line 10, in test_string_float
self.assertEqual("1", 1.0)
AssertionError: '1' != 1.0
-----------------------------------------------------------------
Ran 2 tests in 0.010s
FAILED (failures=1)
Object Oriented Testing
• And if we run this, we get:
.F
=================================================================
FAIL: test_string_float (__main__.CheckNumbers)
---------------------------=-------------------------------------
Traceback (most recent call last):
File "C:UsersdamianAppDataLocalProgramsPythonPython35-
32CheckNumbers.py", line 10, in test_string_float
self.assertEqual("1", 1.0)
AssertionError: '1' != 1.0
-----------------------------------------------------------------
Ran 2 tests in 0.010s
FAILED (failures=1)
“.F” means the first test passed and the
second test has failed
Assertion Methods
Object Oriented Testing
• A test case typically sets certain variables to known values, runs
one or more methods or processes, and then show that correct
expected results were returned by using TestCase assertion
methods.
• There are a few different assertion methods available to confirm
that specific results have been achieved. We already saw
assertEqual, which will cause a test failure if the two
parameters do not pass an equality check. The inverse,
assertNotEqual, will fail if the two parameters do compare as
equal.
Object Oriented Testing
• The assertTrue and assertFalse methods each accept
a single expression, and fail if the expression does not pass an
IF test. These tests are not checking for the Boolean values
True or False, but instead:
– To pass the assertFalse method the test should return False,
None, 0, or an empty list, dictionary, string, set, or tuple.
– To pass the assertFalse method the test should return True,
non-zero numbers, containers with values in.
Methods Description
assertEqual
assertNotEqual
Accept two comparable objects and ensure the named equality
holds.
assertTrue
assertFalse
Accept a single expression, and fail if the expression does not
pass an IF test.
assertGreater
assertGreaterEqual
assertLess
assertLessEqual
Accept two comparable objects and ensure the named
inequality holds.
asssertIn
assertNotIn
Ensure an element is (or is not) an element in a container
object.
assertIsNone
assertIsNotNone
Ensure an element is (or is not) the exact value None (but not
another false value).
assertSameElements Ensure two container objects have the same elements, ignoring
the order.
assertSequenceEqualassertDictEqual
assertSetEqual
assertListEqual
assertTupleEqual
Ensure two containers have the same elements in the same
order. If there's a failure, show a code diff comparing the two
lists to see where they differ. The last four methods also test the
type of the list.
assertRaises Ensure that a specific function call raises a specific exception.
Object Oriented Testing
• Let’s look at the assertRaises method in a bit more detail.
• This method can be used to ensure a specific function call
raises a specific exception. The test passes if the code inside
the with statement raises the proper exception; otherwise, it
fails.
Object Oriented Testing
• Let’s look at an example:
Object Oriented Testing
• Let’s look at an example:
import unittest
def MyAverage(seq):
return sum(seq) / len(seq)
# END average
Continued 
• Let’s look at an example:
Object Oriented Testing
class TestAverage(unittest.TestCase):
def test_zero(self):
self.assertRaises(ZeroDivisionError, MyAverage, [])
# END test_zero
def test_with_zero(self):
with self.assertRaises(ZeroDivisionError):
MyAverage([])
# END test_with_zero
# END CLASS TestAverage
Continued 
 Continued
• Let’s look at an example:
Object Oriented Testing
class TestAverage(unittest.TestCase):
def test_zero(self):
self.assertRaises(ZeroDivisionError, MyAverage, [])
# END test_zero
def test_with_zero(self):
with self.assertRaises(ZeroDivisionError):
MyAverage([])
# END test_with_zero
# END CLASS TestAverage
Continued 
 Continued
We can test if a call to
MyAverage gives an error is
a blank list is passed in
• Let’s look at an example:
Object Oriented Testing
class TestAverage(unittest.TestCase):
def test_zero(self):
self.assertRaises(ZeroDivisionError, MyAverage, [])
# END test_zero
def test_with_zero(self):
with self.assertRaises(ZeroDivisionError):
MyAverage([])
# END test_with_zero
# END CLASS TestAverage
Continued 
 Continued
We can test if a call to
MyAverage gives an error is
a blank list is passed in
The same test, but calling the
method directly, which will
return a divide-by-zero error,
so we need to use the with
statement to tidy up.
Object Oriented Testing
• Let’s look at an example:
if __name__ == "__main__":
unittest.main()
# ENDIF
 Continued
Object Oriented Testing
• Now let’s look at a more detailed example.
• Let’s look at a program, and it’s test program:
Stats.py Stats-test.py
class StatsList class TestValidInputs
def mean
def median
def mode
def test_mean
def test_median
def test_mode
Object Oriented Testing
• Here’s stats.py:
from collections import defaultdict
class StatsList(list):
def mean(self):
return sum(self) / len(self)
# END mean
Continued 
• Here’s stats.py:
Object Oriented Testing
Continued 
 Continued
def median(self):
if len(self) % 2:
return self[int(len(self) / 2)]
else:
idx = int(len(self) / 2)
return (self[idx] + self[idx-1]) / 2
# ENDIF
# END median
• Here’s stats.py:
Object Oriented Testing
 Continued
def mode(self):
freqs = defaultdict(int)
for item in self:
freqs[item] += 1
mode_freq = max(freqs.values())
modes = []
for item, value in freqs.items():
if value == mode_freq:
modes.append(item)
# ENDIF
# ENDFOR
return modes
# END mode
Object Oriented Testing
• We are going to test this program by creating a new file with
our testing code in it.
• So we’ll import unittest, and use the TestCase class
from it, to create a setUp method to do initialization for each
test.
• The setUp method accepts no arguments, and allows us to do
arbitrary setup before each test is run.
Object Oriented Testing
• Here’s stats-test.py:
from stats import StatsList
import unittest
class TestValidInputs(unittest.TestCase):
def setUp(self):
self.stats = StatsList([1,2,2,3,3,4])
# END setUp
Continued 
Object Oriented Testing
• Here’s stats-test.py:
from stats import StatsList
import unittest
class TestValidInputs(unittest.TestCase):
def setUp(self):
self.stats = StatsList([1,2,2,3,3,4])
# END setUp
Continued 
Import the program we’ve just
created, and it’s main class.
Object Oriented Testing
• Here’s stats-test.py:
from stats import StatsList
import unittest
class TestValidInputs(unittest.TestCase):
def setUp(self):
self.stats = StatsList([1,2,2,3,3,4])
# END setUp
Continued 
Import the program we’ve just
created, and it’s main class.
Import unittest.
Object Oriented Testing
• Here’s stats-test.py:
from stats import StatsList
import unittest
class TestValidInputs(unittest.TestCase):
def setUp(self):
self.stats = StatsList([1,2,2,3,3,4])
# END setUp
Continued 
Import the program we’ve just
created, and it’s main class.
Import unittest.
Create the setup method, to
set up values to be tested.
• Here’s stats-test.py:
Object Oriented Testing
Continued 
 Continued
def test_mean(self):
self.assertEqual(self.stats.mean(), 2.5)
# END test_mean
• Here’s stats-test.py:
Object Oriented Testing
Continued 
 Continued
def test_median(self):
self.assertEqual(self.stats.median(), 2.5)
self.stats.append(4)
self.assertEqual(self.stats.median(), 3)
# END test_median
• Here’s stats-test.py:
Object Oriented Testing
 Continued
def test_mode(self):
self.assertEqual(self.stats.mode(), [2,3])
self.stats.remove(2)
self.assertEqual(self.stats.mode(), [3])
# END test_mode
Object Oriented Testing
• And if we run this, we get:
Object Oriented Testing
• And if we run this, we get:
...
----------------------------------------------------------
Ran 3 tests in 0.050s
OK
Object Oriented Testing
• And if we run this, we get:
...
----------------------------------------------------------
Ran 3 tests in 0.050s
OK
“…” means all three tests have passed
Object Oriented Testing
• The setUp method is never explicitly called inside any of the
three test_* methods, the test suite does the call.
• Also note that test_median alters the list, by adding a “4”
to it, yet when test_mode is called, the list has returned to
the values specified in setUp. This shows that setUp is called
individually before each test, to ensure the test class starts
with a clean slate. Tests can be executed in any order, and the
results of one test should not depend on any other tests.
Object Oriented Testing
• TestCase also offers a no-argument tearDown method, which
can be used for cleaning up after each and every test on the class
has run.
• This is useful, for example, if we are testing code that does file I/O,
our tests may create new files as a side effect of testing; the
tearDown method can remove these files and ensure the system
is in the same state it was before the tests ran.
• Test cases should never have side effects.
etc.

More Related Content

What's hot (20)

PPT
SQL select statement and functions
Vikas Gupta
 
PPTX
Database Management - Lecture 2 - SQL select, insert, update and delete
Al-Mamun Sarkar
 
PDF
SQL Queries - DDL Commands
ShubhamBauddh
 
PPT
Looping statements in Java
Jin Castor
 
PPTX
Triggers
Pooja Dixit
 
PDF
Class and Objects in Java
Spotle.ai
 
PPTX
Java – lexical issues
Pradeep Kumar TS
 
PPT
Dbms relational model
Chirag vasava
 
PPTX
Advance oops concepts
Sangharsh agarwal
 
PPTX
Java swing
Apurbo Datta
 
PDF
Sql tutorial
Rumman Ansari
 
PPTX
IoT Levels and Deployment Templates
Prakash Honnur
 
PPTX
SQL Basics
Hammad Rasheed
 
PPTX
Chapter 1 introduction to sql server
baabtra.com - No. 1 supplier of quality freshers
 
PDF
Evolution of Cloud Computing
NephoScale
 
PDF
SE18_Lec 10_ UML Behaviour and Interaction Diagrams
Amr E. Mohamed
 
PPTX
Namespaces in C#
yogita kachve
 
PPTX
Inheritance in java
RahulAnanda1
 
PPTX
Java database connectivity with MySql
Dhyey Dattani
 
PPTX
Packages in PL/SQL
Pooja Dixit
 
SQL select statement and functions
Vikas Gupta
 
Database Management - Lecture 2 - SQL select, insert, update and delete
Al-Mamun Sarkar
 
SQL Queries - DDL Commands
ShubhamBauddh
 
Looping statements in Java
Jin Castor
 
Triggers
Pooja Dixit
 
Class and Objects in Java
Spotle.ai
 
Java – lexical issues
Pradeep Kumar TS
 
Dbms relational model
Chirag vasava
 
Advance oops concepts
Sangharsh agarwal
 
Java swing
Apurbo Datta
 
Sql tutorial
Rumman Ansari
 
IoT Levels and Deployment Templates
Prakash Honnur
 
SQL Basics
Hammad Rasheed
 
Chapter 1 introduction to sql server
baabtra.com - No. 1 supplier of quality freshers
 
Evolution of Cloud Computing
NephoScale
 
SE18_Lec 10_ UML Behaviour and Interaction Diagrams
Amr E. Mohamed
 
Namespaces in C#
yogita kachve
 
Inheritance in java
RahulAnanda1
 
Java database connectivity with MySql
Dhyey Dattani
 
Packages in PL/SQL
Pooja Dixit
 

Viewers also liked (20)

PPTX
Python: Modules and Packages
Damian T. Gordon
 
PPTX
Python: Migrating from Procedural to Object-Oriented Programming
Damian T. Gordon
 
PPT
How to Program
Damian T. Gordon
 
PPTX
Python: Basic Inheritance
Damian T. Gordon
 
PPTX
Python: Object-oriented Testing
Damian T. Gordon
 
PPTX
Python: The Iterator Pattern
Damian T. Gordon
 
PPTX
Python: Multiple Inheritance
Damian T. Gordon
 
PPTX
Python: Common Design Patterns
Damian T. Gordon
 
PPTX
Operating Systems: Virtual Memory
Damian T. Gordon
 
PPTX
Operating Systems: Memory Management
Damian T. Gordon
 
PPT
Testing of Object-Oriented Software
Praveen Penumathsa
 
PPT
Use of Specularities and Motion in the Extraction of Surface Shape
Damian T. Gordon
 
PPTX
The Use of Behavioural Economics to Encourage First-Year Completion and Reten...
Damian T. Gordon
 
PPTX
A Compendium of Creativity Tools
Damian T. Gordon
 
PPT
Concepts from Random Words
Damian T. Gordon
 
PPTX
Creative Commons Sites
Damian T. Gordon
 
PPT
Diagrams of the 2009 Claremont Report
Damian T. Gordon
 
PPTX
The Only Way is Ethics
Damian T. Gordon
 
PPTX
Python: Third-Party Libraries
Damian T. Gordon
 
PPT
Computer Vision: Reflectance Analysis for Image Understanding
Damian T. Gordon
 
Python: Modules and Packages
Damian T. Gordon
 
Python: Migrating from Procedural to Object-Oriented Programming
Damian T. Gordon
 
How to Program
Damian T. Gordon
 
Python: Basic Inheritance
Damian T. Gordon
 
Python: Object-oriented Testing
Damian T. Gordon
 
Python: The Iterator Pattern
Damian T. Gordon
 
Python: Multiple Inheritance
Damian T. Gordon
 
Python: Common Design Patterns
Damian T. Gordon
 
Operating Systems: Virtual Memory
Damian T. Gordon
 
Operating Systems: Memory Management
Damian T. Gordon
 
Testing of Object-Oriented Software
Praveen Penumathsa
 
Use of Specularities and Motion in the Extraction of Surface Shape
Damian T. Gordon
 
The Use of Behavioural Economics to Encourage First-Year Completion and Reten...
Damian T. Gordon
 
A Compendium of Creativity Tools
Damian T. Gordon
 
Concepts from Random Words
Damian T. Gordon
 
Creative Commons Sites
Damian T. Gordon
 
Diagrams of the 2009 Claremont Report
Damian T. Gordon
 
The Only Way is Ethics
Damian T. Gordon
 
Python: Third-Party Libraries
Damian T. Gordon
 
Computer Vision: Reflectance Analysis for Image Understanding
Damian T. Gordon
 
Ad

Similar to Python: Object-Oriented Testing (Unit Testing) (20)

PPTX
2.Python_Testing_Using_PyUnit_PyTest.pptx
Ganesh Bhosale
 
ODP
Python unit testing
Darryl Sherman
 
PPTX
Junit 4.0
pallavikhandekar212
 
PPTX
SE2018_Lec 20_ Test-Driven Development (TDD)
Amr E. Mohamed
 
PPTX
Java Unit Test - JUnit
Aktuğ Urun
 
PPTX
Testing in Python: doctest and unittest
Fariz Darari
 
PPTX
Testing in Python: doctest and unittest (Updated)
Fariz Darari
 
PDF
We Are All Testers Now: The Testing Pyramid and Front-End Development
All Things Open
 
PPTX
Introduction to JUnit
Devvrat Shukla
 
PPTX
TDD Training
Manuela Grindei
 
PPTX
Test in action week 2
Yi-Huan Chan
 
PPTX
Unit Testng with PHP Unit - A Step by Step Training
Ram Awadh Prasad, PMP
 
PDF
SE2_Lec 21_ TDD and Junit
Amr E. Mohamed
 
PPTX
Dreamforce Campfire - Apex Testing Tips and Tricks
Daniel Ballinger
 
PDF
Just Do It! ColdBox Integration Testing
Ortus Solutions, Corp
 
PDF
Test driven development
christoforosnalmpantis
 
PPTX
Unit Testing in Java
Ahmed M. Gomaa
 
PDF
MT_01_unittest_python.pdf
Hans Jones
 
2.Python_Testing_Using_PyUnit_PyTest.pptx
Ganesh Bhosale
 
Python unit testing
Darryl Sherman
 
SE2018_Lec 20_ Test-Driven Development (TDD)
Amr E. Mohamed
 
Java Unit Test - JUnit
Aktuğ Urun
 
Testing in Python: doctest and unittest
Fariz Darari
 
Testing in Python: doctest and unittest (Updated)
Fariz Darari
 
We Are All Testers Now: The Testing Pyramid and Front-End Development
All Things Open
 
Introduction to JUnit
Devvrat Shukla
 
TDD Training
Manuela Grindei
 
Test in action week 2
Yi-Huan Chan
 
Unit Testng with PHP Unit - A Step by Step Training
Ram Awadh Prasad, PMP
 
SE2_Lec 21_ TDD and Junit
Amr E. Mohamed
 
Dreamforce Campfire - Apex Testing Tips and Tricks
Daniel Ballinger
 
Just Do It! ColdBox Integration Testing
Ortus Solutions, Corp
 
Test driven development
christoforosnalmpantis
 
Unit Testing in Java
Ahmed M. Gomaa
 
MT_01_unittest_python.pdf
Hans Jones
 
Ad

More from Damian T. Gordon (20)

PPTX
Introduction to Prompts and Prompt Engineering
Damian T. Gordon
 
PPTX
Introduction to Vibe Coding and Vibe Engineering
Damian T. Gordon
 
PPTX
TRIZ: Theory of Inventive Problem Solving
Damian T. Gordon
 
PPTX
Some Ethical Considerations of AI and GenAI
Damian T. Gordon
 
PPTX
Some Common Errors that Generative AI Produces
Damian T. Gordon
 
PPTX
The Use of Data and Datasets in Data Science
Damian T. Gordon
 
PPTX
A History of Different Versions of Microsoft Windows
Damian T. Gordon
 
PPTX
Writing an Abstract: A Question-based Approach
Damian T. Gordon
 
PPTX
Using GenAI for Universal Design for Learning
Damian T. Gordon
 
DOC
A CheckSheet for Inclusive Software Design
Damian T. Gordon
 
PPTX
A History of Versions of the Apple MacOS
Damian T. Gordon
 
PPTX
68 Ways that Data Science and AI can help address the UN Sustainability Goals
Damian T. Gordon
 
PPTX
Copyright and Creative Commons Considerations
Damian T. Gordon
 
PPTX
Exam Preparation: Some Ideas and Suggestions
Damian T. Gordon
 
PPTX
Studying and Notetaking: Some Suggestions
Damian T. Gordon
 
PPTX
The Growth Mindset: Explanations and Activities
Damian T. Gordon
 
PPTX
Hyperparameter Tuning in Neural Networks
Damian T. Gordon
 
PPTX
Early 20th Century Modern Art: Movements and Artists
Damian T. Gordon
 
PPTX
An Introduction to Generative Artificial Intelligence
Damian T. Gordon
 
PPTX
An Introduction to Green Computing with a fun quiz.
Damian T. Gordon
 
Introduction to Prompts and Prompt Engineering
Damian T. Gordon
 
Introduction to Vibe Coding and Vibe Engineering
Damian T. Gordon
 
TRIZ: Theory of Inventive Problem Solving
Damian T. Gordon
 
Some Ethical Considerations of AI and GenAI
Damian T. Gordon
 
Some Common Errors that Generative AI Produces
Damian T. Gordon
 
The Use of Data and Datasets in Data Science
Damian T. Gordon
 
A History of Different Versions of Microsoft Windows
Damian T. Gordon
 
Writing an Abstract: A Question-based Approach
Damian T. Gordon
 
Using GenAI for Universal Design for Learning
Damian T. Gordon
 
A CheckSheet for Inclusive Software Design
Damian T. Gordon
 
A History of Versions of the Apple MacOS
Damian T. Gordon
 
68 Ways that Data Science and AI can help address the UN Sustainability Goals
Damian T. Gordon
 
Copyright and Creative Commons Considerations
Damian T. Gordon
 
Exam Preparation: Some Ideas and Suggestions
Damian T. Gordon
 
Studying and Notetaking: Some Suggestions
Damian T. Gordon
 
The Growth Mindset: Explanations and Activities
Damian T. Gordon
 
Hyperparameter Tuning in Neural Networks
Damian T. Gordon
 
Early 20th Century Modern Art: Movements and Artists
Damian T. Gordon
 
An Introduction to Generative Artificial Intelligence
Damian T. Gordon
 
An Introduction to Green Computing with a fun quiz.
Damian T. Gordon
 

Recently uploaded (20)

PDF
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
PDF
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - GLOBAL SUCCESS - CẢ NĂM - NĂM 2024 (VOCABULARY, ...
Nguyen Thanh Tu Collection
 
PDF
Dimensions of Societal Planning in Commonism
StefanMz
 
PDF
DIGESTION OF CARBOHYDRATES,PROTEINS,LIPIDS
raviralanaresh2
 
PDF
Lesson 2 - WATER,pH, BUFFERS, AND ACID-BASE.pdf
marvinnbustamante1
 
PPTX
grade 5 lesson ENGLISH 5_Q1_PPT_WEEK3.pptx
SireQuinn
 
PDF
The dynastic history of the Chahmana.pdf
PrachiSontakke5
 
PPTX
Views on Education of Indian Thinkers Mahatma Gandhi.pptx
ShrutiMahanta1
 
PPTX
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
PDF
CEREBRAL PALSY: NURSING MANAGEMENT .pdf
PRADEEP ABOTHU
 
PDF
LAW OF CONTRACT (5 YEAR LLB & UNITARY LLB )- MODULE - 1.& 2 - LEARN THROUGH P...
APARNA T SHAIL KUMAR
 
PPTX
2025 Winter SWAYAM NPTEL & A Student.pptx
Utsav Yagnik
 
PDF
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
PPTX
HYDROCEPHALUS: NURSING MANAGEMENT .pptx
PRADEEP ABOTHU
 
PPTX
Stereochemistry-Optical Isomerism in organic compoundsptx
Tarannum Nadaf-Mansuri
 
PPTX
Soil and agriculture microbiology .pptx
Keerthana Ramesh
 
PPTX
STAFF DEVELOPMENT AND WELFARE: MANAGEMENT
PRADEEP ABOTHU
 
PPTX
ASRB NET 2023 PREVIOUS YEAR QUESTION PAPER GENETICS AND PLANT BREEDING BY SAT...
Krashi Coaching
 
PPTX
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
PDF
CONCURSO DE POESIA “POETUFAS – PASSOS SUAVES PELO VERSO.pdf
Colégio Santa Teresinha
 
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - GLOBAL SUCCESS - CẢ NĂM - NĂM 2024 (VOCABULARY, ...
Nguyen Thanh Tu Collection
 
Dimensions of Societal Planning in Commonism
StefanMz
 
DIGESTION OF CARBOHYDRATES,PROTEINS,LIPIDS
raviralanaresh2
 
Lesson 2 - WATER,pH, BUFFERS, AND ACID-BASE.pdf
marvinnbustamante1
 
grade 5 lesson ENGLISH 5_Q1_PPT_WEEK3.pptx
SireQuinn
 
The dynastic history of the Chahmana.pdf
PrachiSontakke5
 
Views on Education of Indian Thinkers Mahatma Gandhi.pptx
ShrutiMahanta1
 
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
CEREBRAL PALSY: NURSING MANAGEMENT .pdf
PRADEEP ABOTHU
 
LAW OF CONTRACT (5 YEAR LLB & UNITARY LLB )- MODULE - 1.& 2 - LEARN THROUGH P...
APARNA T SHAIL KUMAR
 
2025 Winter SWAYAM NPTEL & A Student.pptx
Utsav Yagnik
 
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
HYDROCEPHALUS: NURSING MANAGEMENT .pptx
PRADEEP ABOTHU
 
Stereochemistry-Optical Isomerism in organic compoundsptx
Tarannum Nadaf-Mansuri
 
Soil and agriculture microbiology .pptx
Keerthana Ramesh
 
STAFF DEVELOPMENT AND WELFARE: MANAGEMENT
PRADEEP ABOTHU
 
ASRB NET 2023 PREVIOUS YEAR QUESTION PAPER GENETICS AND PLANT BREEDING BY SAT...
Krashi Coaching
 
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
CONCURSO DE POESIA “POETUFAS – PASSOS SUAVES PELO VERSO.pdf
Colégio Santa Teresinha
 

Python: Object-Oriented Testing (Unit Testing)

  • 1. Object Oriented Testing (Unit Testing) Damian Gordon
  • 2. Object Oriented Testing • Unit Testing is concerned with testing small chunks of a program, for example, testing a single class or a single method. • Python has a library for unit testing called unittest. It provides several tools for creating and running unit tests.
  • 3. Object Oriented Testing • One of the most important classes in unittest is called TestCase which provides a set of methods to compare values, set up tests and clean up after tests are finished. • To write unit tests, we create a subclass of TestCase and write individual methods to do the actual testing. Typically we start all of these methods with the name test.
  • 4. Object Oriented Testing • Let’s look at a simple example:
  • 5. Object Oriented Testing • Let’s look at a simple example: import unittest class CheckNumbers(unittest.TestCase): def test_int_float(self): self.assertEqual(1, 1.0) # END test_int_float # END CheckNumbers if __name__ == "__main__": unittest.main() # ENDIF
  • 6. Object Oriented Testing • Let’s look at a simple example: import unittest class CheckNumbers(unittest.TestCase): def test_int_float(self): self.assertEqual(1, 1.0) # END test_int_float # END CheckNumbers if __name__ == "__main__": unittest.main() # ENDIF Create a subclass of the TestCase class
  • 7. Object Oriented Testing • Let’s look at a simple example: import unittest class CheckNumbers(unittest.TestCase): def test_int_float(self): self.assertEqual(1, 1.0) # END test_int_float # END CheckNumbers if __name__ == "__main__": unittest.main() # ENDIF Create a subclass of the TestCase class This test checks if the integer and real value 1 are equal.
  • 8. Object Oriented Testing • Let’s look at a simple example: import unittest class CheckNumbers(unittest.TestCase): def test_int_float(self): self.assertEqual(1, 1.0) # END test_int_float # END CheckNumbers if __name__ == "__main__": unittest.main() # ENDIF Make sure this is being run as a script Create a subclass of the TestCase class This test checks if the integer and real value 1 are equal.
  • 9. Object Oriented Testing • And if we run this, we get:
  • 10. Object Oriented Testing • And if we run this, we get: . ------------------------------------------------- Ran 1 test in 0.020s OK
  • 11. Object Oriented Testing • And if we run this, we get: . ------------------------------------------------- Ran 1 test in 0.020s OK Dot means the test has passed
  • 12. Object Oriented Testing • Let’s try another example:
  • 13. Object Oriented Testing • Let’s try another example: import unittest class CheckNumbers(unittest.TestCase): def test_string_float(self): self.assertEqual(“1”, 1.0) # END test_string_float # END CheckNumbers if __name__ == "__main__": unittest.main() # ENDIF
  • 14. Object Oriented Testing • Let’s try another example: import unittest class CheckNumbers(unittest.TestCase): def test_string_float(self): self.assertEqual(“1”, 1.0) # END test_string_float # END CheckNumbers if __name__ == "__main__": unittest.main() # ENDIF This test checks if the string and real value 1 are equal.
  • 15. Object Oriented Testing • And if we run this, we get:
  • 16. Object Oriented Testing • And if we run this, we get: F ========================================================= FAIL: test_string_float (__main__.CheckNumbers) This test checks if the string and real value 1 are equal. -------------------------------------------------------- Traceback (most recent call last): File "C:/Users/damian/AppData/Local/Programs/Python/Python35- 32/CheckNumbers-string-float.py", line 9, in test_string_float self.assertEqual("1", 1.0) AssertionError: '1' != 1.0 -------------------------------------------------------- Ran 1 test in 0.060s FAILED (failures=1)
  • 17. Object Oriented Testing • And if we run this, we get: F ========================================================= FAIL: test_string_float (__main__.CheckNumbers) This test checks if the string and real value 1 are equal. -------------------------------------------------------- Traceback (most recent call last): File "C:/Users/damian/AppData/Local/Programs/Python/Python35- 32/CheckNumbers-string-float.py", line 9, in test_string_float self.assertEqual("1", 1.0) AssertionError: '1' != 1.0 -------------------------------------------------------- Ran 1 test in 0.060s FAILED (failures=1) “F” means the test has failed
  • 18. Object Oriented Testing • Let’s combine the two tests together:
  • 19. Object Oriented Testing • Let’s combine the two tests together: import unittest class CheckNumbers(unittest.TestCase): if __name__ == "__main__": unittest.main() # ENDIF def test_int_float(self): self.assertEqual(1, 1.0) # END test_int_float def test_string_float(self): self.assertEqual(“1”, 1.0) # END test_string_float
  • 20. Object Oriented Testing • And if we run this, we get:
  • 21. Object Oriented Testing • And if we run this, we get: .F ================================================================= FAIL: test_string_float (__main__.CheckNumbers) ---------------------------=------------------------------------- Traceback (most recent call last): File "C:UsersdamianAppDataLocalProgramsPythonPython35- 32CheckNumbers.py", line 10, in test_string_float self.assertEqual("1", 1.0) AssertionError: '1' != 1.0 ----------------------------------------------------------------- Ran 2 tests in 0.010s FAILED (failures=1)
  • 22. Object Oriented Testing • And if we run this, we get: .F ================================================================= FAIL: test_string_float (__main__.CheckNumbers) ---------------------------=------------------------------------- Traceback (most recent call last): File "C:UsersdamianAppDataLocalProgramsPythonPython35- 32CheckNumbers.py", line 10, in test_string_float self.assertEqual("1", 1.0) AssertionError: '1' != 1.0 ----------------------------------------------------------------- Ran 2 tests in 0.010s FAILED (failures=1) “.F” means the first test passed and the second test has failed
  • 24. Object Oriented Testing • A test case typically sets certain variables to known values, runs one or more methods or processes, and then show that correct expected results were returned by using TestCase assertion methods. • There are a few different assertion methods available to confirm that specific results have been achieved. We already saw assertEqual, which will cause a test failure if the two parameters do not pass an equality check. The inverse, assertNotEqual, will fail if the two parameters do compare as equal.
  • 25. Object Oriented Testing • The assertTrue and assertFalse methods each accept a single expression, and fail if the expression does not pass an IF test. These tests are not checking for the Boolean values True or False, but instead: – To pass the assertFalse method the test should return False, None, 0, or an empty list, dictionary, string, set, or tuple. – To pass the assertFalse method the test should return True, non-zero numbers, containers with values in.
  • 26. Methods Description assertEqual assertNotEqual Accept two comparable objects and ensure the named equality holds. assertTrue assertFalse Accept a single expression, and fail if the expression does not pass an IF test. assertGreater assertGreaterEqual assertLess assertLessEqual Accept two comparable objects and ensure the named inequality holds. asssertIn assertNotIn Ensure an element is (or is not) an element in a container object. assertIsNone assertIsNotNone Ensure an element is (or is not) the exact value None (but not another false value). assertSameElements Ensure two container objects have the same elements, ignoring the order. assertSequenceEqualassertDictEqual assertSetEqual assertListEqual assertTupleEqual Ensure two containers have the same elements in the same order. If there's a failure, show a code diff comparing the two lists to see where they differ. The last four methods also test the type of the list. assertRaises Ensure that a specific function call raises a specific exception.
  • 27. Object Oriented Testing • Let’s look at the assertRaises method in a bit more detail. • This method can be used to ensure a specific function call raises a specific exception. The test passes if the code inside the with statement raises the proper exception; otherwise, it fails.
  • 28. Object Oriented Testing • Let’s look at an example:
  • 29. Object Oriented Testing • Let’s look at an example: import unittest def MyAverage(seq): return sum(seq) / len(seq) # END average Continued 
  • 30. • Let’s look at an example: Object Oriented Testing class TestAverage(unittest.TestCase): def test_zero(self): self.assertRaises(ZeroDivisionError, MyAverage, []) # END test_zero def test_with_zero(self): with self.assertRaises(ZeroDivisionError): MyAverage([]) # END test_with_zero # END CLASS TestAverage Continued   Continued
  • 31. • Let’s look at an example: Object Oriented Testing class TestAverage(unittest.TestCase): def test_zero(self): self.assertRaises(ZeroDivisionError, MyAverage, []) # END test_zero def test_with_zero(self): with self.assertRaises(ZeroDivisionError): MyAverage([]) # END test_with_zero # END CLASS TestAverage Continued   Continued We can test if a call to MyAverage gives an error is a blank list is passed in
  • 32. • Let’s look at an example: Object Oriented Testing class TestAverage(unittest.TestCase): def test_zero(self): self.assertRaises(ZeroDivisionError, MyAverage, []) # END test_zero def test_with_zero(self): with self.assertRaises(ZeroDivisionError): MyAverage([]) # END test_with_zero # END CLASS TestAverage Continued   Continued We can test if a call to MyAverage gives an error is a blank list is passed in The same test, but calling the method directly, which will return a divide-by-zero error, so we need to use the with statement to tidy up.
  • 33. Object Oriented Testing • Let’s look at an example: if __name__ == "__main__": unittest.main() # ENDIF  Continued
  • 34. Object Oriented Testing • Now let’s look at a more detailed example. • Let’s look at a program, and it’s test program: Stats.py Stats-test.py class StatsList class TestValidInputs def mean def median def mode def test_mean def test_median def test_mode
  • 35. Object Oriented Testing • Here’s stats.py: from collections import defaultdict class StatsList(list): def mean(self): return sum(self) / len(self) # END mean Continued 
  • 36. • Here’s stats.py: Object Oriented Testing Continued   Continued def median(self): if len(self) % 2: return self[int(len(self) / 2)] else: idx = int(len(self) / 2) return (self[idx] + self[idx-1]) / 2 # ENDIF # END median
  • 37. • Here’s stats.py: Object Oriented Testing  Continued def mode(self): freqs = defaultdict(int) for item in self: freqs[item] += 1 mode_freq = max(freqs.values()) modes = [] for item, value in freqs.items(): if value == mode_freq: modes.append(item) # ENDIF # ENDFOR return modes # END mode
  • 38. Object Oriented Testing • We are going to test this program by creating a new file with our testing code in it. • So we’ll import unittest, and use the TestCase class from it, to create a setUp method to do initialization for each test. • The setUp method accepts no arguments, and allows us to do arbitrary setup before each test is run.
  • 39. Object Oriented Testing • Here’s stats-test.py: from stats import StatsList import unittest class TestValidInputs(unittest.TestCase): def setUp(self): self.stats = StatsList([1,2,2,3,3,4]) # END setUp Continued 
  • 40. Object Oriented Testing • Here’s stats-test.py: from stats import StatsList import unittest class TestValidInputs(unittest.TestCase): def setUp(self): self.stats = StatsList([1,2,2,3,3,4]) # END setUp Continued  Import the program we’ve just created, and it’s main class.
  • 41. Object Oriented Testing • Here’s stats-test.py: from stats import StatsList import unittest class TestValidInputs(unittest.TestCase): def setUp(self): self.stats = StatsList([1,2,2,3,3,4]) # END setUp Continued  Import the program we’ve just created, and it’s main class. Import unittest.
  • 42. Object Oriented Testing • Here’s stats-test.py: from stats import StatsList import unittest class TestValidInputs(unittest.TestCase): def setUp(self): self.stats = StatsList([1,2,2,3,3,4]) # END setUp Continued  Import the program we’ve just created, and it’s main class. Import unittest. Create the setup method, to set up values to be tested.
  • 43. • Here’s stats-test.py: Object Oriented Testing Continued   Continued def test_mean(self): self.assertEqual(self.stats.mean(), 2.5) # END test_mean
  • 44. • Here’s stats-test.py: Object Oriented Testing Continued   Continued def test_median(self): self.assertEqual(self.stats.median(), 2.5) self.stats.append(4) self.assertEqual(self.stats.median(), 3) # END test_median
  • 45. • Here’s stats-test.py: Object Oriented Testing  Continued def test_mode(self): self.assertEqual(self.stats.mode(), [2,3]) self.stats.remove(2) self.assertEqual(self.stats.mode(), [3]) # END test_mode
  • 46. Object Oriented Testing • And if we run this, we get:
  • 47. Object Oriented Testing • And if we run this, we get: ... ---------------------------------------------------------- Ran 3 tests in 0.050s OK
  • 48. Object Oriented Testing • And if we run this, we get: ... ---------------------------------------------------------- Ran 3 tests in 0.050s OK “…” means all three tests have passed
  • 49. Object Oriented Testing • The setUp method is never explicitly called inside any of the three test_* methods, the test suite does the call. • Also note that test_median alters the list, by adding a “4” to it, yet when test_mode is called, the list has returned to the values specified in setUp. This shows that setUp is called individually before each test, to ensure the test class starts with a clean slate. Tests can be executed in any order, and the results of one test should not depend on any other tests.
  • 50. Object Oriented Testing • TestCase also offers a no-argument tearDown method, which can be used for cleaning up after each and every test on the class has run. • This is useful, for example, if we are testing code that does file I/O, our tests may create new files as a side effect of testing; the tearDown method can remove these files and ensure the system is in the same state it was before the tests ran. • Test cases should never have side effects.
  • 51. etc.