SlideShare a Scribd company logo
1 of 33
Testing in Python
Fariz Darari
fariz@cs.ui.ac.id
Testing vs Debugging
Testing:
Checking whether our program works for a set of inputs.
Debugging:
Finding a bug in our program and fixing it.
Software Tester as a job (1/2)
Software Tester as a job (2/2)
Why testing?
• Because your program is not perfect.
• That is, because you (as a programmer) are not perfect.
• Even a professional programmer sometimes writes a program that
still contains bugs.
• Don't use this as an excuse for you to write a program carelessly!!!
• Testing can detect bugs earlier so your program won't be released
to public with too many noticeable bugs!
• However, your program passing some testing does not mean that
your program is correct in general, it's just that your program is
correct for the given test cases!
• Still, tested code is much better than untested code!
Square area function (oops!)
def square_area(x):
return x**3
Square area function (oops!)
def square_area(x):
return x**3
Let's test this code!
You test the function, manually
>>> square_area(1)
1
So far so good, but...
You test the function, manually
>>> square_area(1)
1
So far so good, but...
>>> square_area(2)
8
The expected output is 4.
So, your program is incorrect when input = 2.
You test the function, manually
>>> square_area(1)
1
So far so good, but...
>>> square_area(2)
8
The expected output is 4.
So, your program is incorrect when input = 2.
Then you fix your function
def square_area(x):
return x**2
And you test again the function, manually
>>> square_area(1)
1
So far so good...
>>> square_area(2)
4
This was previously incorrect. Now we get it correct!
And you test again the function, manually
>>> square_area(1)
1
So far so good...
>>> square_area(2)
4
This was previously incorrect. Now we get it correct!
But what about for other inputs (say when input is negative)?
Systematic ways of testing
•doctest
•unittest
Systematic ways of testing
•doctest
•unittest
doctest
• Comes prepackaged with Python
• Simple, you basically just have to include your test
cases inside your function comment (= docstring)
• from python.org:
The doctest module searches for pieces of text that
look like interactive Python sessions, and then
executes those sessions to verify that they work
exactly as shown.
Square area (oops) with doctest
import doctest
def square_area(x):
"""
compute the area of a square
>>> square_area(1)
1
>>> square_area(2)
4
"""
return x**3
if __name__ == "__main__":
doctest.testmod()
Square area (oops) with doctest
Square area with doctest
import doctest
def square_area(x):
"""
compute the area of a square
>>> square_area(1)
1
>>> square_area(2)
4
"""
return x**2
if __name__ == "__main__":
doctest.testmod()
When there is no error, there is nothing to print!
Square area with doctest
When there is no error, there is nothing to print!
Exercise:
(1) Add a testcase for negative inputs, which should return nothing
(2) Fix the square area function to handle negative inputs
Square area with doctest
import doctest
def square_area(x):
"""
compute the area of a square
>>> square_area(1)
1
>>> square_area(2)
4
>>> square_area(-1)
"""
if x < 0:
return None
return x**2
if __name__ == "__main__":
doctest.testmod()
Square area with doctest
Exercise: Create a program and doctest to
compute the area of a rectangle
import doctest
def rectangle_area(x,y):
"""
compute the area of a rectangle
>>> rectangle_area(1,1)
1
>>> rectangle_area(2,3)
6
>>> rectangle_area(-2,3)
>>> rectangle_area(2,-3)
>>> rectangle_area(100,200)
20000
"""
if x < 0 or y < 0:
return None
return x*y
if __name__ == "__main__":
doctest.testmod()
Exercise: Create a program and doctest to
compute the area of a rectangle
Systematic ways of testing
•doctest
•unittest
unittest
• Comes prepackaged with Python
• More extensive than doctest, you have to write
your own, separate, testing code
• As the name suggests, unit testing tests units or
components of the code. (= imagine that your code is
millions of lines, and you have to test it)
unittest for String methods
import unittest
class TestStringMethods(unittest.TestCase):
def test_upper(self):
self.assertEqual('foo'.upper(), 'FOO')
def test_isupper(self):
self.assertTrue('FOO'.isupper())
self.assertFalse('Foo'.isupper())
def test_split(self):
s = 'hello world'
self.assertEqual(s.split(), ['hello', 'world'])
if __name__ == '__main__':
unittest.main()
Square area (oops) with unittest
def square_area(x):
return x**3
square_oops.py
import unittest
from square_oops import square_area
class TestSquareArea(unittest.TestCase):
def test_negative(self):
self.assertEqual(square_area(-1), None)
def test_positive(self):
self.assertEqual(square_area(1),1)
self.assertEqual(square_area(2),4)
self.assertEqual(square_area(5),25)
def test_positive_large(self):
self.assertEqual(square_area(40),1600)
self.assertEqual(square_area(400),160000)
if __name__ == '__main__':
unittest.main() square_oops_test.py (please copy & paste)
Square area with unittest
def square_area(x):
if x < 0: return None
return x**2
square.py
import unittest
from square import square_area
class TestSquareArea(unittest.TestCase):
def test_negative(self):
self.assertEqual(square_area(-1), None)
def test_positive(self):
self.assertEqual(square_area(1),1)
self.assertEqual(square_area(2),4)
self.assertEqual(square_area(5),25)
def test_positive_large(self):
self.assertEqual(square_area(40),1600)
self.assertEqual(square_area(400),160000)
if __name__ == '__main__':
unittest.main() square_test.py (copy and paste)
Exercise: Create a program and unittest to
compute the area of a rectangle
Rectangle area with unittest
def rectangle_area(x,y):
if x < 0 or y < 0: return None
return x*y
rectangle.py
import unittest
from rectangle import rectangle_area
class TestRectangleArea(unittest.TestCase):
def test_negative(self):
self.assertEqual(rectangle_area(-1,1), None)
self.assertEqual(rectangle_area(1,-1), None)
self.assertEqual(rectangle_area(-1,-1), None)
def test_positive(self):
self.assertEqual(rectangle_area(1,1),1)
self.assertEqual(rectangle_area(2,3),6)
for i in range(100):
self.assertEqual(rectangle_area(i,i+1),i*(i+1))
def test_positive_large(self):
self.assertEqual(rectangle_area(40,40),1600)
self.assertEqual(rectangle_area(40,500),20000)
if __name__ == '__main__':
unittest.main()
rectangle_test.py
(you need to copy and paste the code!)
Test-Driven Development (TDD)
• A method of software development to define tests
before actually starting coding!
• The tests define the desired behavior of the program.
• In this way, you code with the mission to satisfy the
tests!
TDD Stages
1. Before writing any code, write test cases.
2. Run the tests, this would surely fail since there is no
code yet.
3. Make working code as minimum as possible to satisfy
the tests.
4. Run the tests, and check if your code passes. If not, fix
your code until you pass.
5. Now, time to refactor (= clean or optimize) your code,
make sure the refactored code passes the tests.
6. Repeat 1-5 for other program features.

More Related Content

What's hot

Introduction to advanced python
Introduction to advanced pythonIntroduction to advanced python
Introduction to advanced pythonCharles-Axel Dein
 
Learn 90% of Python in 90 Minutes
Learn 90% of Python in 90 MinutesLearn 90% of Python in 90 Minutes
Learn 90% of Python in 90 MinutesMatt Harrison
 
Python programming Workshop SITTTR - Kalamassery
Python programming Workshop SITTTR - KalamasseryPython programming Workshop SITTTR - Kalamassery
Python programming Workshop SITTTR - KalamasserySHAMJITH KM
 
Python quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung FuPython quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung Fuclimatewarrior
 
4 b file-io-if-then-else
4 b file-io-if-then-else4 b file-io-if-then-else
4 b file-io-if-then-elseMalik Alig
 
Basic Python Programming: Part 01 and Part 02
Basic Python Programming: Part 01 and Part 02Basic Python Programming: Part 01 and Part 02
Basic Python Programming: Part 01 and Part 02Fariz Darari
 
Python for Security Professionals
Python for Security ProfessionalsPython for Security Professionals
Python for Security ProfessionalsAditya Shankar
 
Introduction to Python - Training for Kids
Introduction to Python - Training for KidsIntroduction to Python - Training for Kids
Introduction to Python - Training for KidsAimee Maree Forsstrom
 
4. python functions
4. python   functions4. python   functions
4. python functionsin4400
 
Python programing
Python programingPython programing
Python programinghamzagame
 
An introduction to Python for absolute beginners
An introduction to Python for absolute beginnersAn introduction to Python for absolute beginners
An introduction to Python for absolute beginnersKálmán "KAMI" Szalai
 

What's hot (19)

Python programming
Python  programmingPython  programming
Python programming
 
Introduction to advanced python
Introduction to advanced pythonIntroduction to advanced python
Introduction to advanced python
 
Learn 90% of Python in 90 Minutes
Learn 90% of Python in 90 MinutesLearn 90% of Python in 90 Minutes
Learn 90% of Python in 90 Minutes
 
Day2
Day2Day2
Day2
 
06.Loops
06.Loops06.Loops
06.Loops
 
Python programming Workshop SITTTR - Kalamassery
Python programming Workshop SITTTR - KalamasseryPython programming Workshop SITTTR - Kalamassery
Python programming Workshop SITTTR - Kalamassery
 
Python course Day 1
Python course Day 1Python course Day 1
Python course Day 1
 
Python quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung FuPython quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung Fu
 
Day3
Day3Day3
Day3
 
4 b file-io-if-then-else
4 b file-io-if-then-else4 b file-io-if-then-else
4 b file-io-if-then-else
 
Basic Python Programming: Part 01 and Part 02
Basic Python Programming: Part 01 and Part 02Basic Python Programming: Part 01 and Part 02
Basic Python Programming: Part 01 and Part 02
 
Python for Security Professionals
Python for Security ProfessionalsPython for Security Professionals
Python for Security Professionals
 
Introduction to Python - Training for Kids
Introduction to Python - Training for KidsIntroduction to Python - Training for Kids
Introduction to Python - Training for Kids
 
Python Tutorial
Python TutorialPython Tutorial
Python Tutorial
 
4. python functions
4. python   functions4. python   functions
4. python functions
 
Python programing
Python programingPython programing
Python programing
 
Functions
FunctionsFunctions
Functions
 
Python for Beginners(v1)
Python for Beginners(v1)Python for Beginners(v1)
Python for Beginners(v1)
 
An introduction to Python for absolute beginners
An introduction to Python for absolute beginnersAn introduction to Python for absolute beginners
An introduction to Python for absolute beginners
 

Similar to Testing in Python: doctest and unittest (Updated)

Testing in Python: doctest and unittest
Testing in Python: doctest and unittestTesting in Python: doctest and unittest
Testing in Python: doctest and unittestFariz Darari
 
Unit/Integration Testing using Spock
Unit/Integration Testing using SpockUnit/Integration Testing using Spock
Unit/Integration Testing using SpockAnuj Aneja
 
Debug - MITX60012016-V005100
Debug - MITX60012016-V005100Debug - MITX60012016-V005100
Debug - MITX60012016-V005100Ha Nguyen
 
Advances in Unit Testing: Theory and Practice
Advances in Unit Testing: Theory and PracticeAdvances in Unit Testing: Theory and Practice
Advances in Unit Testing: Theory and PracticeTao Xie
 
جلسه پنجم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۱
جلسه پنجم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۱جلسه پنجم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۱
جلسه پنجم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۱Mohammad Reza Kamalifard
 
Grails unit testing
Grails unit testingGrails unit testing
Grails unit testingpleeps
 
Tdd with python unittest for embedded c
Tdd with python unittest for embedded cTdd with python unittest for embedded c
Tdd with python unittest for embedded cBenux Wei
 
Test Driven Development in Python
Test Driven Development in PythonTest Driven Development in Python
Test Driven Development in PythonAnoop Thomas Mathew
 
Software Testing for Data Scientists
Software Testing for Data ScientistsSoftware Testing for Data Scientists
Software Testing for Data ScientistsAjay Ohri
 
Python: Object-Oriented Testing (Unit Testing)
Python: Object-Oriented Testing (Unit Testing)Python: Object-Oriented Testing (Unit Testing)
Python: Object-Oriented Testing (Unit Testing)Damian T. Gordon
 
JAVASCRIPT TDD(Test driven Development) & Qunit Tutorial
JAVASCRIPT TDD(Test driven Development) & Qunit TutorialJAVASCRIPT TDD(Test driven Development) & Qunit Tutorial
JAVASCRIPT TDD(Test driven Development) & Qunit TutorialAnup Singh
 
Test Driven Development With Python
Test Driven Development With PythonTest Driven Development With Python
Test Driven Development With PythonSiddhi
 

Similar to Testing in Python: doctest and unittest (Updated) (20)

Testing in Python: doctest and unittest
Testing in Python: doctest and unittestTesting in Python: doctest and unittest
Testing in Python: doctest and unittest
 
Python testing
Python  testingPython  testing
Python testing
 
Unit/Integration Testing using Spock
Unit/Integration Testing using SpockUnit/Integration Testing using Spock
Unit/Integration Testing using Spock
 
Debug - MITX60012016-V005100
Debug - MITX60012016-V005100Debug - MITX60012016-V005100
Debug - MITX60012016-V005100
 
Python unit testing
Python unit testingPython unit testing
Python unit testing
 
How to fake_properly
How to fake_properlyHow to fake_properly
How to fake_properly
 
Testing in Django
Testing in DjangoTesting in Django
Testing in Django
 
Advances in Unit Testing: Theory and Practice
Advances in Unit Testing: Theory and PracticeAdvances in Unit Testing: Theory and Practice
Advances in Unit Testing: Theory and Practice
 
جلسه پنجم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۱
جلسه پنجم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۱جلسه پنجم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۱
جلسه پنجم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۱
 
Unit testing - A&BP CC
Unit testing - A&BP CCUnit testing - A&BP CC
Unit testing - A&BP CC
 
Grails unit testing
Grails unit testingGrails unit testing
Grails unit testing
 
Tdd with python unittest for embedded c
Tdd with python unittest for embedded cTdd with python unittest for embedded c
Tdd with python unittest for embedded c
 
Java Tutorial
Java Tutorial Java Tutorial
Java Tutorial
 
Test Driven Development in Python
Test Driven Development in PythonTest Driven Development in Python
Test Driven Development in Python
 
Software Testing for Data Scientists
Software Testing for Data ScientistsSoftware Testing for Data Scientists
Software Testing for Data Scientists
 
Python: Object-Oriented Testing (Unit Testing)
Python: Object-Oriented Testing (Unit Testing)Python: Object-Oriented Testing (Unit Testing)
Python: Object-Oriented Testing (Unit Testing)
 
Mock Introduction
Mock IntroductionMock Introduction
Mock Introduction
 
JAVASCRIPT TDD(Test driven Development) & Qunit Tutorial
JAVASCRIPT TDD(Test driven Development) & Qunit TutorialJAVASCRIPT TDD(Test driven Development) & Qunit Tutorial
JAVASCRIPT TDD(Test driven Development) & Qunit Tutorial
 
Java introduction
Java introductionJava introduction
Java introduction
 
Test Driven Development With Python
Test Driven Development With PythonTest Driven Development With Python
Test Driven Development With Python
 

More from Fariz Darari

Data X Museum - Hari Museum Internasional 2022 - WMID
Data X Museum - Hari Museum Internasional 2022 - WMIDData X Museum - Hari Museum Internasional 2022 - WMID
Data X Museum - Hari Museum Internasional 2022 - WMIDFariz Darari
 
[PUBLIC] quiz-01-midterm-solutions.pdf
[PUBLIC] quiz-01-midterm-solutions.pdf[PUBLIC] quiz-01-midterm-solutions.pdf
[PUBLIC] quiz-01-midterm-solutions.pdfFariz Darari
 
Free AI Kit - Game Theory
Free AI Kit - Game TheoryFree AI Kit - Game Theory
Free AI Kit - Game TheoryFariz Darari
 
Neural Networks and Deep Learning: An Intro
Neural Networks and Deep Learning: An IntroNeural Networks and Deep Learning: An Intro
Neural Networks and Deep Learning: An IntroFariz Darari
 
NLP guest lecture: How to get text to confess what knowledge it has
NLP guest lecture: How to get text to confess what knowledge it hasNLP guest lecture: How to get text to confess what knowledge it has
NLP guest lecture: How to get text to confess what knowledge it hasFariz Darari
 
Supply and Demand - AI Talents
Supply and Demand - AI TalentsSupply and Demand - AI Talents
Supply and Demand - AI TalentsFariz Darari
 
AI in education done properly
AI in education done properlyAI in education done properly
AI in education done properlyFariz Darari
 
Artificial Neural Networks: Pointers
Artificial Neural Networks: PointersArtificial Neural Networks: Pointers
Artificial Neural Networks: PointersFariz Darari
 
Open Tridharma at ICACSIS 2019
Open Tridharma at ICACSIS 2019Open Tridharma at ICACSIS 2019
Open Tridharma at ICACSIS 2019Fariz Darari
 
Defense Slides of Avicenna Wisesa - PROWD
Defense Slides of Avicenna Wisesa - PROWDDefense Slides of Avicenna Wisesa - PROWD
Defense Slides of Avicenna Wisesa - PROWDFariz Darari
 
Seminar Laporan Aktualisasi - Tridharma Terbuka - Fariz Darari
Seminar Laporan Aktualisasi - Tridharma Terbuka - Fariz DarariSeminar Laporan Aktualisasi - Tridharma Terbuka - Fariz Darari
Seminar Laporan Aktualisasi - Tridharma Terbuka - Fariz DarariFariz Darari
 
Foundations of Programming - Java OOP
Foundations of Programming - Java OOPFoundations of Programming - Java OOP
Foundations of Programming - Java OOPFariz Darari
 
Recursion in Python
Recursion in PythonRecursion in Python
Recursion in PythonFariz Darari
 
[ISWC 2013] Completeness statements about RDF data sources and their use for ...
[ISWC 2013] Completeness statements about RDF data sources and their use for ...[ISWC 2013] Completeness statements about RDF data sources and their use for ...
[ISWC 2013] Completeness statements about RDF data sources and their use for ...Fariz Darari
 
Dissertation Defense - Managing and Consuming Completeness Information for RD...
Dissertation Defense - Managing and Consuming Completeness Information for RD...Dissertation Defense - Managing and Consuming Completeness Information for RD...
Dissertation Defense - Managing and Consuming Completeness Information for RD...Fariz Darari
 
Research Writing - 2018.07.18
Research Writing - 2018.07.18Research Writing - 2018.07.18
Research Writing - 2018.07.18Fariz Darari
 
KOI - Knowledge Of Incidents - SemEval 2018
KOI - Knowledge Of Incidents - SemEval 2018KOI - Knowledge Of Incidents - SemEval 2018
KOI - Knowledge Of Incidents - SemEval 2018Fariz Darari
 
Comparing Index Structures for Completeness Reasoning
Comparing Index Structures for Completeness ReasoningComparing Index Structures for Completeness Reasoning
Comparing Index Structures for Completeness ReasoningFariz Darari
 
Research Writing - Universitas Indonesia
Research Writing - Universitas IndonesiaResearch Writing - Universitas Indonesia
Research Writing - Universitas IndonesiaFariz Darari
 
Otsuka Talk in Dec 2017
Otsuka Talk in Dec 2017Otsuka Talk in Dec 2017
Otsuka Talk in Dec 2017Fariz Darari
 

More from Fariz Darari (20)

Data X Museum - Hari Museum Internasional 2022 - WMID
Data X Museum - Hari Museum Internasional 2022 - WMIDData X Museum - Hari Museum Internasional 2022 - WMID
Data X Museum - Hari Museum Internasional 2022 - WMID
 
[PUBLIC] quiz-01-midterm-solutions.pdf
[PUBLIC] quiz-01-midterm-solutions.pdf[PUBLIC] quiz-01-midterm-solutions.pdf
[PUBLIC] quiz-01-midterm-solutions.pdf
 
Free AI Kit - Game Theory
Free AI Kit - Game TheoryFree AI Kit - Game Theory
Free AI Kit - Game Theory
 
Neural Networks and Deep Learning: An Intro
Neural Networks and Deep Learning: An IntroNeural Networks and Deep Learning: An Intro
Neural Networks and Deep Learning: An Intro
 
NLP guest lecture: How to get text to confess what knowledge it has
NLP guest lecture: How to get text to confess what knowledge it hasNLP guest lecture: How to get text to confess what knowledge it has
NLP guest lecture: How to get text to confess what knowledge it has
 
Supply and Demand - AI Talents
Supply and Demand - AI TalentsSupply and Demand - AI Talents
Supply and Demand - AI Talents
 
AI in education done properly
AI in education done properlyAI in education done properly
AI in education done properly
 
Artificial Neural Networks: Pointers
Artificial Neural Networks: PointersArtificial Neural Networks: Pointers
Artificial Neural Networks: Pointers
 
Open Tridharma at ICACSIS 2019
Open Tridharma at ICACSIS 2019Open Tridharma at ICACSIS 2019
Open Tridharma at ICACSIS 2019
 
Defense Slides of Avicenna Wisesa - PROWD
Defense Slides of Avicenna Wisesa - PROWDDefense Slides of Avicenna Wisesa - PROWD
Defense Slides of Avicenna Wisesa - PROWD
 
Seminar Laporan Aktualisasi - Tridharma Terbuka - Fariz Darari
Seminar Laporan Aktualisasi - Tridharma Terbuka - Fariz DarariSeminar Laporan Aktualisasi - Tridharma Terbuka - Fariz Darari
Seminar Laporan Aktualisasi - Tridharma Terbuka - Fariz Darari
 
Foundations of Programming - Java OOP
Foundations of Programming - Java OOPFoundations of Programming - Java OOP
Foundations of Programming - Java OOP
 
Recursion in Python
Recursion in PythonRecursion in Python
Recursion in Python
 
[ISWC 2013] Completeness statements about RDF data sources and their use for ...
[ISWC 2013] Completeness statements about RDF data sources and their use for ...[ISWC 2013] Completeness statements about RDF data sources and their use for ...
[ISWC 2013] Completeness statements about RDF data sources and their use for ...
 
Dissertation Defense - Managing and Consuming Completeness Information for RD...
Dissertation Defense - Managing and Consuming Completeness Information for RD...Dissertation Defense - Managing and Consuming Completeness Information for RD...
Dissertation Defense - Managing and Consuming Completeness Information for RD...
 
Research Writing - 2018.07.18
Research Writing - 2018.07.18Research Writing - 2018.07.18
Research Writing - 2018.07.18
 
KOI - Knowledge Of Incidents - SemEval 2018
KOI - Knowledge Of Incidents - SemEval 2018KOI - Knowledge Of Incidents - SemEval 2018
KOI - Knowledge Of Incidents - SemEval 2018
 
Comparing Index Structures for Completeness Reasoning
Comparing Index Structures for Completeness ReasoningComparing Index Structures for Completeness Reasoning
Comparing Index Structures for Completeness Reasoning
 
Research Writing - Universitas Indonesia
Research Writing - Universitas IndonesiaResearch Writing - Universitas Indonesia
Research Writing - Universitas Indonesia
 
Otsuka Talk in Dec 2017
Otsuka Talk in Dec 2017Otsuka Talk in Dec 2017
Otsuka Talk in Dec 2017
 

Recently uploaded

Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningVitsRangannavar
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...aditisharan08
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsMehedi Hasan Shohan
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 

Recently uploaded (20)

Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learning
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software Solutions
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 

Testing in Python: doctest and unittest (Updated)

  • 1. Testing in Python Fariz Darari fariz@cs.ui.ac.id
  • 2. Testing vs Debugging Testing: Checking whether our program works for a set of inputs. Debugging: Finding a bug in our program and fixing it.
  • 3. Software Tester as a job (1/2)
  • 4. Software Tester as a job (2/2)
  • 5. Why testing? • Because your program is not perfect. • That is, because you (as a programmer) are not perfect. • Even a professional programmer sometimes writes a program that still contains bugs. • Don't use this as an excuse for you to write a program carelessly!!! • Testing can detect bugs earlier so your program won't be released to public with too many noticeable bugs! • However, your program passing some testing does not mean that your program is correct in general, it's just that your program is correct for the given test cases! • Still, tested code is much better than untested code!
  • 6. Square area function (oops!) def square_area(x): return x**3
  • 7. Square area function (oops!) def square_area(x): return x**3 Let's test this code!
  • 8. You test the function, manually >>> square_area(1) 1 So far so good, but...
  • 9. You test the function, manually >>> square_area(1) 1 So far so good, but... >>> square_area(2) 8 The expected output is 4. So, your program is incorrect when input = 2.
  • 10. You test the function, manually >>> square_area(1) 1 So far so good, but... >>> square_area(2) 8 The expected output is 4. So, your program is incorrect when input = 2.
  • 11. Then you fix your function def square_area(x): return x**2
  • 12. And you test again the function, manually >>> square_area(1) 1 So far so good... >>> square_area(2) 4 This was previously incorrect. Now we get it correct!
  • 13. And you test again the function, manually >>> square_area(1) 1 So far so good... >>> square_area(2) 4 This was previously incorrect. Now we get it correct! But what about for other inputs (say when input is negative)?
  • 14. Systematic ways of testing •doctest •unittest
  • 15. Systematic ways of testing •doctest •unittest
  • 16. doctest • Comes prepackaged with Python • Simple, you basically just have to include your test cases inside your function comment (= docstring) • from python.org: The doctest module searches for pieces of text that look like interactive Python sessions, and then executes those sessions to verify that they work exactly as shown.
  • 17. Square area (oops) with doctest import doctest def square_area(x): """ compute the area of a square >>> square_area(1) 1 >>> square_area(2) 4 """ return x**3 if __name__ == "__main__": doctest.testmod()
  • 18. Square area (oops) with doctest
  • 19. Square area with doctest import doctest def square_area(x): """ compute the area of a square >>> square_area(1) 1 >>> square_area(2) 4 """ return x**2 if __name__ == "__main__": doctest.testmod()
  • 20. When there is no error, there is nothing to print! Square area with doctest
  • 21. When there is no error, there is nothing to print! Exercise: (1) Add a testcase for negative inputs, which should return nothing (2) Fix the square area function to handle negative inputs Square area with doctest
  • 22. import doctest def square_area(x): """ compute the area of a square >>> square_area(1) 1 >>> square_area(2) 4 >>> square_area(-1) """ if x < 0: return None return x**2 if __name__ == "__main__": doctest.testmod() Square area with doctest
  • 23. Exercise: Create a program and doctest to compute the area of a rectangle
  • 24. import doctest def rectangle_area(x,y): """ compute the area of a rectangle >>> rectangle_area(1,1) 1 >>> rectangle_area(2,3) 6 >>> rectangle_area(-2,3) >>> rectangle_area(2,-3) >>> rectangle_area(100,200) 20000 """ if x < 0 or y < 0: return None return x*y if __name__ == "__main__": doctest.testmod() Exercise: Create a program and doctest to compute the area of a rectangle
  • 25. Systematic ways of testing •doctest •unittest
  • 26. unittest • Comes prepackaged with Python • More extensive than doctest, you have to write your own, separate, testing code • As the name suggests, unit testing tests units or components of the code. (= imagine that your code is millions of lines, and you have to test it)
  • 27. unittest for String methods import unittest class TestStringMethods(unittest.TestCase): def test_upper(self): self.assertEqual('foo'.upper(), 'FOO') def test_isupper(self): self.assertTrue('FOO'.isupper()) self.assertFalse('Foo'.isupper()) def test_split(self): s = 'hello world' self.assertEqual(s.split(), ['hello', 'world']) if __name__ == '__main__': unittest.main()
  • 28. Square area (oops) with unittest def square_area(x): return x**3 square_oops.py import unittest from square_oops import square_area class TestSquareArea(unittest.TestCase): def test_negative(self): self.assertEqual(square_area(-1), None) def test_positive(self): self.assertEqual(square_area(1),1) self.assertEqual(square_area(2),4) self.assertEqual(square_area(5),25) def test_positive_large(self): self.assertEqual(square_area(40),1600) self.assertEqual(square_area(400),160000) if __name__ == '__main__': unittest.main() square_oops_test.py (please copy & paste)
  • 29. Square area with unittest def square_area(x): if x < 0: return None return x**2 square.py import unittest from square import square_area class TestSquareArea(unittest.TestCase): def test_negative(self): self.assertEqual(square_area(-1), None) def test_positive(self): self.assertEqual(square_area(1),1) self.assertEqual(square_area(2),4) self.assertEqual(square_area(5),25) def test_positive_large(self): self.assertEqual(square_area(40),1600) self.assertEqual(square_area(400),160000) if __name__ == '__main__': unittest.main() square_test.py (copy and paste)
  • 30. Exercise: Create a program and unittest to compute the area of a rectangle
  • 31. Rectangle area with unittest def rectangle_area(x,y): if x < 0 or y < 0: return None return x*y rectangle.py import unittest from rectangle import rectangle_area class TestRectangleArea(unittest.TestCase): def test_negative(self): self.assertEqual(rectangle_area(-1,1), None) self.assertEqual(rectangle_area(1,-1), None) self.assertEqual(rectangle_area(-1,-1), None) def test_positive(self): self.assertEqual(rectangle_area(1,1),1) self.assertEqual(rectangle_area(2,3),6) for i in range(100): self.assertEqual(rectangle_area(i,i+1),i*(i+1)) def test_positive_large(self): self.assertEqual(rectangle_area(40,40),1600) self.assertEqual(rectangle_area(40,500),20000) if __name__ == '__main__': unittest.main() rectangle_test.py (you need to copy and paste the code!)
  • 32. Test-Driven Development (TDD) • A method of software development to define tests before actually starting coding! • The tests define the desired behavior of the program. • In this way, you code with the mission to satisfy the tests!
  • 33. TDD Stages 1. Before writing any code, write test cases. 2. Run the tests, this would surely fail since there is no code yet. 3. Make working code as minimum as possible to satisfy the tests. 4. Run the tests, and check if your code passes. If not, fix your code until you pass. 5. Now, time to refactor (= clean or optimize) your code, make sure the refactored code passes the tests. 6. Repeat 1-5 for other program features.

Editor's Notes

  1. https://www.iconfinder.com/icons/1790658/checklist_checkmark_clipboard_document_list_tracklist_icon https://www.python.org/static/community_logos/python-powered-w-200x80.png
  2. https://www.pexels.com/photo/nature-insect-ladybug-bug-35805/
  3. https://www.indeed.com/viewjob?jk=8ebb09795a250983&tk=1ctrskjj9b91h803&from=serp&vjs=3
  4. https://www.indeed.com/viewjob?jk=8ebb09795a250983&tk=1ctrskjj9b91h803&from=serp&vjs=3
  5. Show that your code works in an odd way for negative input. Ideally, the code should reject the negative input (by returning None, or raising ValueError)!
  6. https://www.pexels.com/photo/red-and-yellow-hatchback-axa-crash-tests-163016/
  7. https://www.pexels.com/photo/red-and-yellow-hatchback-axa-crash-tests-163016/
  8. Source: python-course.eu Run: python –m doctest –v filename.py
  9. https://www.pexels.com/photo/red-and-yellow-hatchback-axa-crash-tests-163016/
  10. https://www.python-course.eu/python3_tests.php
  11. https://www.python-course.eu/python3_tests.php
  12. https://medium.com/koding-kala-weekend/tdd-the-series-part-1-apa-itu-test-driven-development-tdd-ff92c95c945f