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 -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
PDF
Python basic
PDF
Python Basics
PPTX
Python in 30 minutes!
PPTX
Programming in Python
PDF
python codes
PPTX
Python basics
PDF
Python
PDF
Learn 90% of Python in 90 Minutes
PPTX
Python programming
PPTX
Python programing
ODP
Introduction to Python - Training for Kids
PDF
An introduction to Python for absolute beginners
PPTX
Basic Python Programming: Part 01 and Part 02
PPTX
06.Loops
PPTX
Python for Beginners(v1)
PDF
Python programming Workshop SITTTR - Kalamassery
ODP
PDF
Introduction to advanced python
PPTX
Python for Security Professionals
PDF
Python Tutorial
ODP
Python quickstart for programmers: Python Kung Fu
ODP
Python course Day 1
PPT
4 b file-io-if-then-else
PDF
4. python functions
 
PDF
PDF
PPTX
Python: Object-Oriented Testing (Unit Testing)
PPT
Python testing
PDF
Debug - MITX60012016-V005100

More Related Content

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

What's hot

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

Similar to Testing in Python: doctest and unittest

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

More from Fariz Darari

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

Recently uploaded

PPT
Presentation on TCL/TK scripting language
PDF
IAAM Meetup #7 chez Onepoint - Construire un Rag-as-a-service en production. ...
PPTX
Presentation on AWS Cloud RDS Deep dive
PDF
Breaking the Vulnerability Management Cycle with Anchore and Echo
PDF
DSD-INT 2025 Delft3D FM Suite 2026.01 2D3D - New features + Improvements - Sp...
PDF
Bring AI and build AI agents into your Jakarta EE Apps with LangChain4J-CDI
PPTX
Understanding-ROM-RAM-Cache-and-Buffer-Memory.pptx.pptx
PDF
How Device, OS, and Network Variability Affects App Experience - And How to T...
PDF
Fundamental of Information Systems introduction.pdf
PPTX
Zotero Software Demonstration. Biomedical Perspective
PDF
Custom Software Development Presentation.pdf
PDF
Data Integration with Salesforce Bootcamp
PDF
SCORM Cloud: The 5 categories of content distribution
PDF
Presentation Empowerment Technology in ICT
PPTX
Boost Productivity the Smart Way with AI Automation Solutions
PDF
DSD-INT 2025 Understanding the Paraguay River Response to Hard Bottom Dredgin...
PDF
DSD-INT 2025 Coupling SFINCS to a flood risk model to evaluate the effects of...
PDF
DSD-INT 2025 Century-Scale Impacts of Sediment-Based Coastal Restoration unde...
PDF
DSD-INT 2025 Building-Aware Flood and Lifeline Scour Modeling with Delft3D FM...
PDF
DSD-INT 2025 The Sinterklaas Storm in the Southwest of the Netherlands - Wope...
Presentation on TCL/TK scripting language
IAAM Meetup #7 chez Onepoint - Construire un Rag-as-a-service en production. ...
Presentation on AWS Cloud RDS Deep dive
Breaking the Vulnerability Management Cycle with Anchore and Echo
DSD-INT 2025 Delft3D FM Suite 2026.01 2D3D - New features + Improvements - Sp...
Bring AI and build AI agents into your Jakarta EE Apps with LangChain4J-CDI
Understanding-ROM-RAM-Cache-and-Buffer-Memory.pptx.pptx
How Device, OS, and Network Variability Affects App Experience - And How to T...
Fundamental of Information Systems introduction.pdf
Zotero Software Demonstration. Biomedical Perspective
Custom Software Development Presentation.pdf
Data Integration with Salesforce Bootcamp
SCORM Cloud: The 5 categories of content distribution
Presentation Empowerment Technology in ICT
Boost Productivity the Smart Way with AI Automation Solutions
DSD-INT 2025 Understanding the Paraguay River Response to Hard Bottom Dredgin...
DSD-INT 2025 Coupling SFINCS to a flood risk model to evaluate the effects of...
DSD-INT 2025 Century-Scale Impacts of Sediment-Based Coastal Restoration unde...
DSD-INT 2025 Building-Aware Flood and Lifeline Scour Modeling with Delft3D FM...
DSD-INT 2025 The Sinterklaas Storm in the Southwest of the Netherlands - Wope...

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