Movatterモバイル変換


[0]ホーム

URL:


Fariz Darari, profile picture
Uploaded byFariz Darari
PPTX, PDF577 views

Testing in Python: doctest and unittest

The document discusses testing in Python. It defines testing vs debugging, and explains why testing is important even for professional programmers. It introduces doctest and unittest as systematic ways to test Python code. Doctest allows embedding tests in docstrings, while unittest involves writing separate test files. The document also covers test-driven development, which involves writing tests before coding to define desired behavior.

Embed presentation

Downloaded 15 times
Testing in PythonFariz Dararifariz@cs.ui.ac.id
Testing vs DebuggingTesting: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 thatstill 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 releasedto public with too many noticeable bugs!• However, your program passing some testing does not mean thatyour program is correct in general, it's just that your program iscorrect 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**3Let's test this code!
You test the function, manually>>> square_area(1)1So far so good, but...
You test the function, manually>>> square_area(1)1So far so good, but...>>> square_area(2)8The expected output is 4.So, your program is incorrect when input = 2.
You test the function, manually>>> square_area(1)1So far so good, but...>>> square_area(2)8The expected output is 4.So, your program is incorrect when input = 2.
Then you fix your functiondef square_area(x):return x**2
And you test again the function, manually>>> square_area(1)1So far so good...>>> square_area(2)4This was previously incorrect. Now we get it correct!
And you test again the function, manually>>> square_area(1)1So far so good...>>> square_area(2)4This 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 testcases inside your function comment (= docstring)• from python.org:The doctest module searches for pieces of text thatlook like interactive Python sessions, and thenexecutes those sessions to verify that they workexactly as shown.
Square area (oops) with doctestimport doctestdef square_area(x):"""compute the area of a square>>> square_area(1)1>>> square_area(2)4"""return x**3if __name__ == "__main__":doctest.testmod()
Square area (oops) with doctest
Square area with doctestimport doctestdef square_area(x):"""compute the area of a square>>> square_area(1)1>>> square_area(2)4"""return x**2if __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 inputsSquare area with doctest
import doctestdef square_area(x):"""compute the area of a square>>> square_area(1)1>>> square_area(2)4>>> square_area(-1)"""if x < 0:return Nonereturn x**2if __name__ == "__main__":doctest.testmod()Square area with doctest
Exercise: Create a program and doctest tocompute the area of a rectangle
import doctestdef 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 Nonereturn x*yif __name__ == "__main__":doctest.testmod()Exercise: Create a program and doctest tocompute the area of a rectangle
Systematic ways of testing•doctest•unittest
unittest• Comes prepackaged with Python• More extensive than doctest, you have to writeyour own, separate, testing code• As the name suggests, unit testing tests units orcomponents of the code. (= imagine that your code ismillions of lines, and you have to test it)
unittest for String methodsimport unittestclass 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 unittestdef square_area(x):return x**3square_oops.pyimport unittestfrom square_oops import square_areaclass 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)def test_positive_large(self):self.assertEqual(square_area(40),1600)if __name__ == '__main__':unittest.main()square_oops_test.py
Square area with unittestdef square_area(x):if x < 0: return Nonereturn x**2square.pyimport unittestfrom square import square_areaclass 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)def test_positive_large(self):self.assertEqual(square_area(40),1600)if __name__ == '__main__':unittest.main()square_test.py
Exercise: Create a program and unittest tocompute the area of a rectangle
Rectangle area with unittestdef rectangle_area(x,y):if x < 0 or y < 0: return Nonereturn x*yrectangle.pyimport unittestfrom rectangle import rectangle_areaclass 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)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 testsbefore actually starting coding!• The tests define the desired behavior of the program.• In this way, you code with the mission to satisfy thetests!
TDD Stages1. Before writing any code, write test cases.2. Run the tests, this would surely fail since there is nocode yet.3. Make working code as minimum as possible to satisfythe tests.4. Run the tests, and check if your code passes. If not, fixyour code until you pass.5. Now, time to refactor (= clean) your code, make sure therefactored code passes the tests.6. Repeat 1-5 for other program features.

Recommended

PPTX
Python basics
PPTX
Programming in Python
PDF
Python
PPTX
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
PDF
Python Basics
PDF
python codes
PPTX
Python in 30 minutes!
PDF
Python basic
PPTX
Python programming
PDF
Introduction to advanced python
PDF
Learn 90% of Python in 90 Minutes
ODP
PPTX
06.Loops
PDF
Python programming Workshop SITTTR - Kalamassery
ODP
Python quickstart for programmers: Python Kung Fu
ODP
Python course Day 1
PDF
PPT
4 b file-io-if-then-else
PPTX
Basic Python Programming: Part 01 and Part 02
PPTX
Python for Security Professionals
ODP
Introduction to Python - Training for Kids
PDF
Python Tutorial
PDF
4. python functions
 
PPTX
Python programing
PPTX
Python for Beginners(v1)
PDF
An introduction to Python for absolute beginners
PDF
PPTX
Testing in Python: doctest and unittest (Updated)
ODT
Testing in-python-and-pytest-framework
PPTX
2.Python_Unit _Testing_Using_PyUnit_Pytest.pptx

More Related Content

PPTX
Python basics
PPTX
Programming in Python
PDF
Python
PPTX
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
PDF
Python Basics
PDF
python codes
PPTX
Python in 30 minutes!
PDF
Python basic
Python basics
Programming in Python
Python
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
Python Basics
python codes
Python in 30 minutes!
Python basic

What's hot

PPTX
Python programming
PDF
Introduction to advanced python
PDF
Learn 90% of Python in 90 Minutes
ODP
PPTX
06.Loops
PDF
Python programming Workshop SITTTR - Kalamassery
ODP
Python quickstart for programmers: Python Kung Fu
ODP
Python course Day 1
PDF
PPT
4 b file-io-if-then-else
PPTX
Basic Python Programming: Part 01 and Part 02
PPTX
Python for Security Professionals
ODP
Introduction to Python - Training for Kids
PDF
Python Tutorial
PDF
4. python functions
 
PPTX
Python programing
PPTX
Python for Beginners(v1)
PDF
An introduction to Python for absolute beginners
PDF
Python programming
Introduction to advanced python
Learn 90% of Python in 90 Minutes
06.Loops
Python programming Workshop SITTTR - Kalamassery
Python quickstart for programmers: Python Kung Fu
Python course Day 1
4 b file-io-if-then-else
Basic Python Programming: Part 01 and Part 02
Python for Security Professionals
Introduction to Python - Training for Kids
Python Tutorial
4. python functions
 
Python programing
Python for Beginners(v1)
An introduction to Python for absolute beginners

Similar to Testing in Python: doctest and unittest

PPTX
Testing in Python: doctest and unittest (Updated)
ODT
Testing in-python-and-pytest-framework
PPTX
2.Python_Unit _Testing_Using_PyUnit_Pytest.pptx
PPTX
1.Python_Testing_Using_PyUnit_Pytest.pptx
PDF
Debug - MITX60012016-V005100
PPTX
Introduction to unit testing in python
PDF
Test and refactoring
PPTX
unittestinginpythonfor-PYDevelopers.pptx
PPTX
Coursbjjhuihiuyiyiyuyuiyiuyoilidnes.pptx
PDF
MT_01_unittest_python.pdf
PDF
Python Advanced – Building on the foundation
PDF
Testing in Django
PDF
pytest로 파이썬 코드 테스트하기
PPTX
2.Python_Testing_Using_PyUnit_PyTest.pptx
PDF
Python testing-frameworks overview
PPTX
Python programming - Everyday(ish) Examples
PDF
Debugging 2013- Thomas Ammitzboell-Bach
PPTX
Python: Object-Oriented Testing (Unit Testing)
PPT
Python testing
PDF
Writing tests
Testing in Python: doctest and unittest (Updated)
Testing in-python-and-pytest-framework
2.Python_Unit _Testing_Using_PyUnit_Pytest.pptx
1.Python_Testing_Using_PyUnit_Pytest.pptx
Debug - MITX60012016-V005100
Introduction to unit testing in python
Test and refactoring
unittestinginpythonfor-PYDevelopers.pptx
Coursbjjhuihiuyiyiyuyuiyiuyoilidnes.pptx
MT_01_unittest_python.pdf
Python Advanced – Building on the foundation
Testing in Django
pytest로 파이썬 코드 테스트하기
2.Python_Testing_Using_PyUnit_PyTest.pptx
Python testing-frameworks overview
Python programming - Everyday(ish) Examples
Debugging 2013- Thomas Ammitzboell-Bach
Python: Object-Oriented Testing (Unit Testing)
Python testing
Writing tests

More from Fariz Darari

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

Recently uploaded

PDF
inSis suite - Laboratory Information Management System
PDF
Oracle AI Database 26ai _ AI-Native Database for Enterprises.pdf
PDF
DSD-INT 2025 Flood Early Warning System for the Trans-African Hydrometeorolog...
PDF
IAAM Meetup #7 chez Onepoint - Construire un Rag-as-a-service en production. ...
PPTX
Future of Software Testing: AI-Powered Open Source Testing Tools
PDF
Smarter Testing Safer Systems Balancing AI and Oversight in Regulated Environ...
PDF
DSD-INT 2025 Delft3D FM Suite 2026.01 2D3D - New features + Improvements - Sp...
PDF
DSD-INT 2025 3D Modeling of Shallow Water Dynamics Using Delft3D FM - Martins
PDF
Presentation Empowerment Technology in ICT
PPTX
AI Clinic Management Tool for Dermatologists Making Skin Care Smarter, Simple...
PPTX
Building a RAG System for Customer Support - L1
PDF
DSD-INT 2025 Building-Aware Flood and Lifeline Scour Modeling with Delft3D FM...
PDF
DSD-INT 2025 Century-Scale Impacts of Sediment-Based Coastal Restoration unde...
PDF
DSD-INT 2025 MeshKernel and D-Grid Editor - Stout
PDF
DevOps Monitoring Tools: The 2025 Guide to Performance & Observability
PDF
DSD-INT 2025 Understanding the Paraguay River Response to Hard Bottom Dredgin...
PDF
Custom MGA Software Development: Better Apporach
PDF
Data Integration with Salesforce Bootcamp
PPTX
Moving Cloud 360:- Busy Software Provider In Delhi NCR
PDF
BCA 1st Semester Fundamentals Solved Question Paper 44121
inSis suite - Laboratory Information Management System
Oracle AI Database 26ai _ AI-Native Database for Enterprises.pdf
DSD-INT 2025 Flood Early Warning System for the Trans-African Hydrometeorolog...
IAAM Meetup #7 chez Onepoint - Construire un Rag-as-a-service en production. ...
Future of Software Testing: AI-Powered Open Source Testing Tools
Smarter Testing Safer Systems Balancing AI and Oversight in Regulated Environ...
DSD-INT 2025 Delft3D FM Suite 2026.01 2D3D - New features + Improvements - Sp...
DSD-INT 2025 3D Modeling of Shallow Water Dynamics Using Delft3D FM - Martins
Presentation Empowerment Technology in ICT
AI Clinic Management Tool for Dermatologists Making Skin Care Smarter, Simple...
Building a RAG System for Customer Support - L1
DSD-INT 2025 Building-Aware Flood and Lifeline Scour Modeling with Delft3D FM...
DSD-INT 2025 Century-Scale Impacts of Sediment-Based Coastal Restoration unde...
DSD-INT 2025 MeshKernel and D-Grid Editor - Stout
DevOps Monitoring Tools: The 2025 Guide to Performance & Observability
DSD-INT 2025 Understanding the Paraguay River Response to Hard Bottom Dredgin...
Custom MGA Software Development: Better Apporach
Data Integration with Salesforce Bootcamp
Moving Cloud 360:- Busy Software Provider In Delhi NCR
BCA 1st Semester Fundamentals Solved Question Paper 44121

Testing in Python: doctest and unittest

  • 1.
    Testing in PythonFarizDararifariz@cs.ui.ac.id
  • 2.
    Testing vs DebuggingTesting:Checkingwhether our program works for a set of inputs.Debugging:Finding a bug in our program and fixing it.
  • 3.
  • 4.
  • 5.
    Why testing?• Becauseyour program is not perfect.• That is, because you (as a programmer) are not perfect.• Even a professional programmer sometimes writes a program thatstill 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 releasedto public with too many noticeable bugs!• However, your program passing some testing does not mean thatyour program is correct in general, it's just that your program iscorrect 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**3Let's test this code!
  • 8.
    You test thefunction, manually>>> square_area(1)1So far so good, but...
  • 9.
    You test thefunction, manually>>> square_area(1)1So far so good, but...>>> square_area(2)8The expected output is 4.So, your program is incorrect when input = 2.
  • 10.
    You test thefunction, manually>>> square_area(1)1So far so good, but...>>> square_area(2)8The expected output is 4.So, your program is incorrect when input = 2.
  • 11.
    Then you fixyour functiondef square_area(x):return x**2
  • 12.
    And you testagain the function, manually>>> square_area(1)1So far so good...>>> square_area(2)4This was previously incorrect. Now we get it correct!
  • 13.
    And you testagain the function, manually>>> square_area(1)1So far so good...>>> square_area(2)4This was previously incorrect. Now we get it correct!But what about for other inputs (say when input is negative)?
  • 14.
    Systematic ways oftesting•doctest•unittest
  • 15.
    Systematic ways oftesting•doctest•unittest
  • 16.
    doctest• Comes prepackagedwith Python• Simple, you basically just have to include your testcases inside your function comment (= docstring)• from python.org:The doctest module searches for pieces of text thatlook like interactive Python sessions, and thenexecutes those sessions to verify that they workexactly as shown.
  • 17.
    Square area (oops)with doctestimport doctestdef square_area(x):"""compute the area of a square>>> square_area(1)1>>> square_area(2)4"""return x**3if __name__ == "__main__":doctest.testmod()
  • 18.
    Square area (oops)with doctest
  • 19.
    Square area withdoctestimport doctestdef square_area(x):"""compute the area of a square>>> square_area(1)1>>> square_area(2)4"""return x**2if __name__ == "__main__":doctest.testmod()
  • 20.
    When there isno error, there is nothing to print!Square area with doctest
  • 21.
    When there isno 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 inputsSquare area with doctest
  • 22.
    import doctestdef square_area(x):"""computethe area of a square>>> square_area(1)1>>> square_area(2)4>>> square_area(-1)"""if x < 0:return Nonereturn x**2if __name__ == "__main__":doctest.testmod()Square area with doctest
  • 23.
    Exercise: Create aprogram and doctest tocompute the area of a rectangle
  • 24.
    import doctestdef rectangle_area(x,y):"""computethe 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 Nonereturn x*yif __name__ == "__main__":doctest.testmod()Exercise: Create a program and doctest tocompute the area of a rectangle
  • 25.
    Systematic ways oftesting•doctest•unittest
  • 26.
    unittest• Comes prepackagedwith Python• More extensive than doctest, you have to writeyour own, separate, testing code• As the name suggests, unit testing tests units orcomponents of the code. (= imagine that your code ismillions of lines, and you have to test it)
  • 27.
    unittest for Stringmethodsimport unittestclass 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 unittestdef square_area(x):return x**3square_oops.pyimport unittestfrom square_oops import square_areaclass 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)def test_positive_large(self):self.assertEqual(square_area(40),1600)if __name__ == '__main__':unittest.main()square_oops_test.py
  • 29.
    Square area withunittestdef square_area(x):if x < 0: return Nonereturn x**2square.pyimport unittestfrom square import square_areaclass 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)def test_positive_large(self):self.assertEqual(square_area(40),1600)if __name__ == '__main__':unittest.main()square_test.py
  • 30.
    Exercise: Create aprogram and unittest tocompute the area of a rectangle
  • 31.
    Rectangle area withunittestdef rectangle_area(x,y):if x < 0 or y < 0: return Nonereturn x*yrectangle.pyimport unittestfrom rectangle import rectangle_areaclass 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)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 testsbefore actually starting coding!• The tests define the desired behavior of the program.• In this way, you code with the mission to satisfy thetests!
  • 33.
    TDD Stages1. Beforewriting any code, write test cases.2. Run the tests, this would surely fail since there is nocode yet.3. Make working code as minimum as possible to satisfythe tests.4. Run the tests, and check if your code passes. If not, fixyour code until you pass.5. Now, time to refactor (= clean) your code, make sure therefactored code passes the tests.6. Repeat 1-5 for other program features.

Editor's Notes

  • #2 https://www.iconfinder.com/icons/1790658/checklist_checkmark_clipboard_document_list_tracklist_iconhttps://www.python.org/static/community_logos/python-powered-w-200x80.png
  • #3 https://www.pexels.com/photo/nature-insect-ladybug-bug-35805/
  • #4 https://www.indeed.com/viewjob?jk=8ebb09795a250983&tk=1ctrskjj9b91h803&from=serp&vjs=3
  • #5 https://www.indeed.com/viewjob?jk=8ebb09795a250983&tk=1ctrskjj9b91h803&from=serp&vjs=3
  • #14 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)!
  • #15 https://www.pexels.com/photo/red-and-yellow-hatchback-axa-crash-tests-163016/
  • #16 https://www.pexels.com/photo/red-and-yellow-hatchback-axa-crash-tests-163016/
  • #17 Source: python-course.euRun:python –m doctest –v filename.py
  • #26 https://www.pexels.com/photo/red-and-yellow-hatchback-axa-crash-tests-163016/
  • #27 https://www.python-course.eu/python3_tests.php
  • #33 https://www.python-course.eu/python3_tests.php
  • #34 https://medium.com/koding-kala-weekend/tdd-the-series-part-1-apa-itu-test-driven-development-tdd-ff92c95c945f

[8]ページ先頭

©2009-2025 Movatter.jp