SlideShare a Scribd company logo
unittest
in five minutes



Ray Toal   2011-10-22
How to unit test

• Not manually, that's for sure
• You write code that exercises your code
• Perform assertions that record
  o that you get the results you expect for various inputs
  o that exceptions are raised when they should be
• Pay attention to edge cases
Test-driven development
• Write some tests (yes, first)
• Run them
  o They will fail because the code isn't written yet. That
    is supposed to happen. Good news is you will know
    the tests run.
• Write some code
• Now run the tests again
• Work until the tests pass
• Iterate!
Unit testing in Python

• The module unittest is already there
• Docs
• Python 2.7
• Python 3
• Also see
• The unit testing chapter from Dive Into
     Python
•   Are there alternatives to unittest? See what
    they say on StackOverflow
A first example

• Let's write a function to interleave two lists
• It will be okay if one list is longer than the
    other
•   Before we start writing the code, we should
    know what the function should produce for all
    types of inputs:
     interleave([], []) ☞ []
     interleave([1,5,3], ["hello"]) ☞
     [1,"hello",5,3]
     interleave([True], [[], 8]) ☞ [True, [],
     8]
Write the test first(interleavetest.py)

from interleave import interleave
import unittest


class TestGettingStartedFunctions(unittest.TestCase):
 def test_interleave(self):
       cases = [
           ([], [], []),
           ([1, 4, 6], [], [1, 4, 6]),
           ([], [2, 3], [2, 3]),
           ([1], [9], [1, 9]),
           ([8, 8, 3, 9], [1], [8, 1, 8, 3, 9]),
           ([2], [7, 8, 9], [2, 7, 8, 9]),
       ]
       for a, b, expected in cases:
           self.assertEqual(interleave(a, b), expected)
Write a stub (interleave.py)

def interleave(a, b):
    return None
Run the test

$ python interleavetest.py
F
======================================================================
FAIL: test_interleave (__main__.TestGettingStartedFunctions)
----------------------------------------------------------------------
Traceback (most recent call last):
    File "interleavetest.py", line 15, in test_interleave
     self.assertEqual(interleave(a, b), expected)
AssertionError: None != []


----------------------------------------------------------------------
Ran 1 test in 0.000s


FAILED (failures=1)
Now write the code
def interleave(a, b):
   """Return the interleaving of two sequences as a list."""
   return [y for x in izip_longest(a, b) for y in x if y is not None]
Test again

$ python interleavetest.py
E
======================================================================
ERROR: test_interleave (__main__.TestGettingStartedFunctions)
----------------------------------------------------------------------
Traceback (most recent call last):
    File "interleavetest.py", line 15, in test_interleave
      self.assertEqual(interleave(a, b), expected)
    File "/Users/raytoal/scratch/interleave.py", line 3, in interleave
      return [y for x in izip_longest(a, b) for y in x if y is not None]
NameError: global name 'izip_longest' is not defined


----------------------------------------------------------------------
Ran 1 test in 0.000s


FAILED (errors=1)
Fix the code
from itertools import izip_longest


def interleave(a, b):
   """Return the interleaving of two sequences as a list."""
   return [y for x in izip_longest(a, b) for y in x if y is not None]
Rerun the test
$ python interleavetest.py
.
-------------------------------------------------------------
Ran 1 test in 0.000s


OK
kthx

More Related Content

What's hot (20)

PDF
Python testing using mock and pytest
Suraj Deshmukh
 
ODT
Testing in-python-and-pytest-framework
Arulalan T
 
PPTX
Python Programming Essentials - M39 - Unit Testing
P3 InfoTech Solutions Pvt. Ltd.
 
ODP
Testes pythonicos com pytest
viniciusban
 
ODP
Automated testing in Python and beyond
dn
 
PDF
Effective testing with pytest
Hector Canto
 
PPT
20111018 boost and gtest
Will Shen
 
PPT
Google C++ Testing Framework in Visual Studio 2008
Andrea Francia
 
PDF
Py.test
soasme
 
PPTX
Unit Testing in PHP
Radu Murzea
 
PPTX
Unit Testng with PHP Unit - A Step by Step Training
Ram Awadh Prasad, PMP
 
PPT
Introduzione al TDD
Andrea Francia
 
PDF
Keep your repo clean
Hector Canto
 
PDF
C++ Unit Test with Google Testing Framework
Humberto Marchezi
 
PPTX
Automated Python Test Frameworks for Hardware Verification and Validation
Barbara Jones
 
PDF
Golang dot-testing-lite
Richárd Kovács
 
PPT
Test Driven Development with PHPUnit
Mindfire Solutions
 
PPT
Phpunit testing
Nikunj Bhatnagar
 
PPT
Selenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalks
Lohika_Odessa_TechTalks
 
Python testing using mock and pytest
Suraj Deshmukh
 
Testing in-python-and-pytest-framework
Arulalan T
 
Python Programming Essentials - M39 - Unit Testing
P3 InfoTech Solutions Pvt. Ltd.
 
Testes pythonicos com pytest
viniciusban
 
Automated testing in Python and beyond
dn
 
Effective testing with pytest
Hector Canto
 
20111018 boost and gtest
Will Shen
 
Google C++ Testing Framework in Visual Studio 2008
Andrea Francia
 
Py.test
soasme
 
Unit Testing in PHP
Radu Murzea
 
Unit Testng with PHP Unit - A Step by Step Training
Ram Awadh Prasad, PMP
 
Introduzione al TDD
Andrea Francia
 
Keep your repo clean
Hector Canto
 
C++ Unit Test with Google Testing Framework
Humberto Marchezi
 
Automated Python Test Frameworks for Hardware Verification and Validation
Barbara Jones
 
Golang dot-testing-lite
Richárd Kovács
 
Test Driven Development with PHPUnit
Mindfire Solutions
 
Phpunit testing
Nikunj Bhatnagar
 
Selenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalks
Lohika_Odessa_TechTalks
 

Viewers also liked (20)

PPTX
Unit Testing with Python
MicroPyramid .
 
PDF
Python Ireland Nov 2010 Talk: Unit Testing
Python Ireland
 
PDF
TDD in Python With Pytest
Eddy Reyes
 
PPTX
2014/07/07 Software Testing - Truong Anh Hoang
Vu Hung Nguyen
 
PDF
Web API Test Automation Using Frisby & Node.js
Ho Chi Minh City Software Testing Club
 
PDF
Common Web UI Problems Transforming Manual to Automation
Ho Chi Minh City Software Testing Club
 
PDF
Security testing-What can we do - Trinh Minh Hien
Ho Chi Minh City Software Testing Club
 
PDF
[HCMC STC Jan 2015] Making IT Count – Agile Test Metrics
Ho Chi Minh City Software Testing Club
 
PDF
[HCMC STC Jan 2015] Practical Experiences In Test Automation
Ho Chi Minh City Software Testing Club
 
PDF
A Novel Approach of Automation Test for Software Monitoring Solution - Tran S...
Ho Chi Minh City Software Testing Club
 
PDF
Deliver Fast, Break Nothing Via Effective Building Developer and Tester Colla...
Ho Chi Minh City Software Testing Club
 
PDF
[HCMC STC Jan 2015] FATS: A Framework For Automated Testing Scenarios
Ho Chi Minh City Software Testing Club
 
PDF
Building an effective mobile testing strategy
Ho Chi Minh City Software Testing Club
 
PDF
Agile Testing - Not Just Tester’s Story _ Dang Thanh Long
Ho Chi Minh City Software Testing Club
 
PDF
The New Agile Testing Quadrants: Bringing Skilled Testers and Developers Toge...
Ho Chi Minh City Software Testing Club
 
PDF
A Universal Automation Framework based on BDD Cucumber and Ruby on Rails - Ph...
Ho Chi Minh City Software Testing Club
 
PDF
Test Design with Action-based Testing Methodology - Ngo Hoang Minh
Ho Chi Minh City Software Testing Club
 
PDF
Analytical Risk-based and Specification-based Testing - Bui Duy Tam
Ho Chi Minh City Software Testing Club
 
PDF
[HCMC STC Jan 2015] Risk-Based Software Testing Approaches
Ho Chi Minh City Software Testing Club
 
PDF
Introduction to Back End Automation Testing - Nguyen Vu Hoang, Hoang Phi
Ho Chi Minh City Software Testing Club
 
Unit Testing with Python
MicroPyramid .
 
Python Ireland Nov 2010 Talk: Unit Testing
Python Ireland
 
TDD in Python With Pytest
Eddy Reyes
 
2014/07/07 Software Testing - Truong Anh Hoang
Vu Hung Nguyen
 
Web API Test Automation Using Frisby & Node.js
Ho Chi Minh City Software Testing Club
 
Common Web UI Problems Transforming Manual to Automation
Ho Chi Minh City Software Testing Club
 
Security testing-What can we do - Trinh Minh Hien
Ho Chi Minh City Software Testing Club
 
[HCMC STC Jan 2015] Making IT Count – Agile Test Metrics
Ho Chi Minh City Software Testing Club
 
[HCMC STC Jan 2015] Practical Experiences In Test Automation
Ho Chi Minh City Software Testing Club
 
A Novel Approach of Automation Test for Software Monitoring Solution - Tran S...
Ho Chi Minh City Software Testing Club
 
Deliver Fast, Break Nothing Via Effective Building Developer and Tester Colla...
Ho Chi Minh City Software Testing Club
 
[HCMC STC Jan 2015] FATS: A Framework For Automated Testing Scenarios
Ho Chi Minh City Software Testing Club
 
Building an effective mobile testing strategy
Ho Chi Minh City Software Testing Club
 
Agile Testing - Not Just Tester’s Story _ Dang Thanh Long
Ho Chi Minh City Software Testing Club
 
The New Agile Testing Quadrants: Bringing Skilled Testers and Developers Toge...
Ho Chi Minh City Software Testing Club
 
A Universal Automation Framework based on BDD Cucumber and Ruby on Rails - Ph...
Ho Chi Minh City Software Testing Club
 
Test Design with Action-based Testing Methodology - Ngo Hoang Minh
Ho Chi Minh City Software Testing Club
 
Analytical Risk-based and Specification-based Testing - Bui Duy Tam
Ho Chi Minh City Software Testing Club
 
[HCMC STC Jan 2015] Risk-Based Software Testing Approaches
Ho Chi Minh City Software Testing Club
 
Introduction to Back End Automation Testing - Nguyen Vu Hoang, Hoang Phi
Ho Chi Minh City Software Testing Club
 
Ad

Similar to unittest in 5 minutes (20)

PPTX
White Box Testing on a Python Function.pptx
GevitaChinnaiah
 
PDF
New and improved: Coming changes to the unittest module
PyCon Italia
 
PDF
Writing tests
Jonathan Fine
 
PPTX
2.Python_Testing_Using_PyUnit_PyTest.pptx
Ganesh Bhosale
 
PDF
Functional python
Jesué Junior
 
ODP
Python unit testing
Darryl Sherman
 
PDF
LecccccccccccccProgrammingLecture-09.pdf
AmirMohamedNabilSale
 
PDF
Python testing-frameworks overview
Jachym Cepicky
 
PPTX
Coursbjjhuihiuyiyiyuyuiyiuyoilidnes.pptx
kndemo34
 
PDF
Writing dumb tests
Luke Lee
 
PDF
PresentationqwertyuiopasdfghUnittest.pdf
kndemo34
 
DOCX
NPTEL QUIZ.docx
GEETHAR59
 
PDF
Python Programming Module 3 (2).pdf
Thanmayee S
 
ODP
Day2
Karin Lagesen
 
PDF
Python for High School Programmers
Siva Arunachalam
 
PPTX
Python Workshop - Learn Python the Hard Way
Utkarsh Sengar
 
PDF
Functions and modules in python
Karin Lagesen
 
PDF
Debug - MITX60012016-V005100
Ha Nguyen
 
PDF
2 Python Basics II meeting 2 tunghai university pdf
Anggi Andriyadi
 
PDF
pyton Notes9
Amba Research
 
White Box Testing on a Python Function.pptx
GevitaChinnaiah
 
New and improved: Coming changes to the unittest module
PyCon Italia
 
Writing tests
Jonathan Fine
 
2.Python_Testing_Using_PyUnit_PyTest.pptx
Ganesh Bhosale
 
Functional python
Jesué Junior
 
Python unit testing
Darryl Sherman
 
LecccccccccccccProgrammingLecture-09.pdf
AmirMohamedNabilSale
 
Python testing-frameworks overview
Jachym Cepicky
 
Coursbjjhuihiuyiyiyuyuiyiuyoilidnes.pptx
kndemo34
 
Writing dumb tests
Luke Lee
 
PresentationqwertyuiopasdfghUnittest.pdf
kndemo34
 
NPTEL QUIZ.docx
GEETHAR59
 
Python Programming Module 3 (2).pdf
Thanmayee S
 
Python for High School Programmers
Siva Arunachalam
 
Python Workshop - Learn Python the Hard Way
Utkarsh Sengar
 
Functions and modules in python
Karin Lagesen
 
Debug - MITX60012016-V005100
Ha Nguyen
 
2 Python Basics II meeting 2 tunghai university pdf
Anggi Andriyadi
 
pyton Notes9
Amba Research
 
Ad

More from Ray Toal (7)

PPTX
Git workshop
Ray Toal
 
PPTX
Learning and Modern Programming Languages
Ray Toal
 
PPTX
Java best practices
Ray Toal
 
ODP
Convention-Based Syntactic Descriptions
Ray Toal
 
PPT
An Annotation Framework for Statically-Typed Syntax Trees
Ray Toal
 
PPT
Economics of Open Source Software
Ray Toal
 
PPTX
Modeling Patterns for JavaScript Browser-Based Games
Ray Toal
 
Git workshop
Ray Toal
 
Learning and Modern Programming Languages
Ray Toal
 
Java best practices
Ray Toal
 
Convention-Based Syntactic Descriptions
Ray Toal
 
An Annotation Framework for Statically-Typed Syntax Trees
Ray Toal
 
Economics of Open Source Software
Ray Toal
 
Modeling Patterns for JavaScript Browser-Based Games
Ray Toal
 

Recently uploaded (20)

PDF
Bharatiya Antariksh Hackathon 2025 Idea Submission PPT.pdf
ghjghvhjgc
 
PDF
“Squinting Vision Pipelines: Detecting and Correcting Errors in Vision Models...
Edge AI and Vision Alliance
 
PDF
NASA A Researcher’s Guide to International Space Station : Earth Observations
Dr. PANKAJ DHUSSA
 
PDF
“Computer Vision at Sea: Automated Fish Tracking for Sustainable Fishing,” a ...
Edge AI and Vision Alliance
 
PPTX
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
PDF
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
PDF
99 Bottles of Trust on the Wall — Operational Principles for Trust in Cyber C...
treyka
 
PPTX
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
PDF
UPDF - AI PDF Editor & Converter Key Features
DealFuel
 
PDF
UiPath DevConnect 2025: Agentic Automation Community User Group Meeting
DianaGray10
 
PPTX
Talbott's brief History of Computers for CollabDays Hamburg 2025
Talbott Crowell
 
PPTX
Manual Testing for Accessibility Enhancement
Julia Undeutsch
 
PDF
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
PDF
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PDF
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
PDF
ICONIQ State of AI Report 2025 - The Builder's Playbook
Razin Mustafiz
 
PDF
Software Development Company Keene Systems, Inc (1).pdf
Custom Software Development Company | Keene Systems, Inc.
 
PDF
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
PPTX
Agentforce World Tour Toronto '25 - MCP with MuleSoft
Alexandra N. Martinez
 
PPTX
CapCut Pro PC Crack Latest Version Free Free
josanj305
 
Bharatiya Antariksh Hackathon 2025 Idea Submission PPT.pdf
ghjghvhjgc
 
“Squinting Vision Pipelines: Detecting and Correcting Errors in Vision Models...
Edge AI and Vision Alliance
 
NASA A Researcher’s Guide to International Space Station : Earth Observations
Dr. PANKAJ DHUSSA
 
“Computer Vision at Sea: Automated Fish Tracking for Sustainable Fishing,” a ...
Edge AI and Vision Alliance
 
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
99 Bottles of Trust on the Wall — Operational Principles for Trust in Cyber C...
treyka
 
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
UPDF - AI PDF Editor & Converter Key Features
DealFuel
 
UiPath DevConnect 2025: Agentic Automation Community User Group Meeting
DianaGray10
 
Talbott's brief History of Computers for CollabDays Hamburg 2025
Talbott Crowell
 
Manual Testing for Accessibility Enhancement
Julia Undeutsch
 
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
ICONIQ State of AI Report 2025 - The Builder's Playbook
Razin Mustafiz
 
Software Development Company Keene Systems, Inc (1).pdf
Custom Software Development Company | Keene Systems, Inc.
 
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
Agentforce World Tour Toronto '25 - MCP with MuleSoft
Alexandra N. Martinez
 
CapCut Pro PC Crack Latest Version Free Free
josanj305
 

unittest in 5 minutes

  • 2. How to unit test • Not manually, that's for sure • You write code that exercises your code • Perform assertions that record o that you get the results you expect for various inputs o that exceptions are raised when they should be • Pay attention to edge cases
  • 3. Test-driven development • Write some tests (yes, first) • Run them o They will fail because the code isn't written yet. That is supposed to happen. Good news is you will know the tests run. • Write some code • Now run the tests again • Work until the tests pass • Iterate!
  • 4. Unit testing in Python • The module unittest is already there • Docs • Python 2.7 • Python 3 • Also see • The unit testing chapter from Dive Into Python • Are there alternatives to unittest? See what they say on StackOverflow
  • 5. A first example • Let's write a function to interleave two lists • It will be okay if one list is longer than the other • Before we start writing the code, we should know what the function should produce for all types of inputs: interleave([], []) ☞ [] interleave([1,5,3], ["hello"]) ☞ [1,"hello",5,3] interleave([True], [[], 8]) ☞ [True, [], 8]
  • 6. Write the test first(interleavetest.py) from interleave import interleave import unittest class TestGettingStartedFunctions(unittest.TestCase): def test_interleave(self): cases = [ ([], [], []), ([1, 4, 6], [], [1, 4, 6]), ([], [2, 3], [2, 3]), ([1], [9], [1, 9]), ([8, 8, 3, 9], [1], [8, 1, 8, 3, 9]), ([2], [7, 8, 9], [2, 7, 8, 9]), ] for a, b, expected in cases: self.assertEqual(interleave(a, b), expected)
  • 7. Write a stub (interleave.py) def interleave(a, b): return None
  • 8. Run the test $ python interleavetest.py F ====================================================================== FAIL: test_interleave (__main__.TestGettingStartedFunctions) ---------------------------------------------------------------------- Traceback (most recent call last): File "interleavetest.py", line 15, in test_interleave self.assertEqual(interleave(a, b), expected) AssertionError: None != [] ---------------------------------------------------------------------- Ran 1 test in 0.000s FAILED (failures=1)
  • 9. Now write the code def interleave(a, b): """Return the interleaving of two sequences as a list.""" return [y for x in izip_longest(a, b) for y in x if y is not None]
  • 10. Test again $ python interleavetest.py E ====================================================================== ERROR: test_interleave (__main__.TestGettingStartedFunctions) ---------------------------------------------------------------------- Traceback (most recent call last): File "interleavetest.py", line 15, in test_interleave self.assertEqual(interleave(a, b), expected) File "/Users/raytoal/scratch/interleave.py", line 3, in interleave return [y for x in izip_longest(a, b) for y in x if y is not None] NameError: global name 'izip_longest' is not defined ---------------------------------------------------------------------- Ran 1 test in 0.000s FAILED (errors=1)
  • 11. Fix the code from itertools import izip_longest def interleave(a, b): """Return the interleaving of two sequences as a list.""" return [y for x in izip_longest(a, b) for y in x if y is not None]
  • 12. Rerun the test $ python interleavetest.py . ------------------------------------------------------------- Ran 1 test in 0.000s OK
  • 13. kthx