SlideShare a Scribd company logo
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)
def test_positive_large(self):
self.assertEqual(square_area(40),1600)
if __name__ == '__main__':
unittest.main()
square_oops_test.py
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)
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 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)
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) your code, make sure the
refactored code passes the tests.
6. Repeat 1-5 for other program features.

More Related Content

PPTX
Python basics
NexThoughts Technologies
 
PPTX
Programming in Python
Tiji Thomas
 
PDF
Python
대갑 김
 
PPTX
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
Maulik Borsaniya
 
PDF
Python Basics
tusharpanda88
 
PDF
python codes
tusharpanda88
 
PPTX
Python in 30 minutes!
Fariz Darari
 
PDF
Python basic
Saifuddin Kaijar
 
Programming in Python
Tiji Thomas
 
Python
대갑 김
 
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
Maulik Borsaniya
 
Python Basics
tusharpanda88
 
python codes
tusharpanda88
 
Python in 30 minutes!
Fariz Darari
 
Python basic
Saifuddin Kaijar
 

What's hot (19)

PPTX
Python programming
Ashwin Kumar Ramasamy
 
PDF
Introduction to advanced python
Charles-Axel Dein
 
PDF
Learn 90% of Python in 90 Minutes
Matt Harrison
 
ODP
Day2
Karin Lagesen
 
PPTX
06.Loops
Intro C# Book
 
PDF
Python programming Workshop SITTTR - Kalamassery
SHAMJITH KM
 
ODP
Python quickstart for programmers: Python Kung Fu
climatewarrior
 
ODP
Python course Day 1
Karin Lagesen
 
PDF
Day3
Karin Lagesen
 
PPT
4 b file-io-if-then-else
Malik Alig
 
PPTX
Basic Python Programming: Part 01 and Part 02
Fariz Darari
 
PPTX
Python for Security Professionals
Aditya Shankar
 
ODP
Introduction to Python - Training for Kids
Aimee Maree
 
PDF
Python Tutorial
Eueung Mulyana
 
PDF
4. python functions
in4400
 
PPTX
Python programing
hamzagame
 
PPTX
Python for Beginners(v1)
Panimalar Engineering College
 
PDF
An introduction to Python for absolute beginners
Kálmán "KAMI" Szalai
 
PDF
Functions
Marieswaran Ramasamy
 
Python programming
Ashwin Kumar Ramasamy
 
Introduction to advanced python
Charles-Axel Dein
 
Learn 90% of Python in 90 Minutes
Matt Harrison
 
06.Loops
Intro C# Book
 
Python programming Workshop SITTTR - Kalamassery
SHAMJITH KM
 
Python quickstart for programmers: Python Kung Fu
climatewarrior
 
Python course Day 1
Karin Lagesen
 
4 b file-io-if-then-else
Malik Alig
 
Basic Python Programming: Part 01 and Part 02
Fariz Darari
 
Python for Security Professionals
Aditya Shankar
 
Introduction to Python - Training for Kids
Aimee Maree
 
Python Tutorial
Eueung Mulyana
 
4. python functions
in4400
 
Python programing
hamzagame
 
Python for Beginners(v1)
Panimalar Engineering College
 
An introduction to Python for absolute beginners
Kálmán "KAMI" Szalai
 
Ad

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

PPTX
Testing in Python: doctest and unittest (Updated)
Fariz Darari
 
ODT
Testing in-python-and-pytest-framework
Arulalan T
 
PPTX
2.Python_Unit _Testing_Using_PyUnit_Pytest.pptx
Ganesh Bhosale
 
PPTX
1.Python_Testing_Using_PyUnit_Pytest.pptx
Ganesh Bhosale
 
PDF
Debug - MITX60012016-V005100
Ha Nguyen
 
PPTX
Introduction to unit testing in python
Anirudh
 
PDF
Test and refactoring
Kenneth Ceyer
 
PPTX
unittestinginpythonfor-PYDevelopers.pptx
Ganesh Bhosale
 
PPTX
Coursbjjhuihiuyiyiyuyuiyiuyoilidnes.pptx
kndemo34
 
PDF
MT_01_unittest_python.pdf
Hans Jones
 
PDF
Python Advanced – Building on the foundation
Kevlin Henney
 
PDF
Testing in Django
Kevin Harvey
 
PDF
pytest로 파이썬 코드 테스트하기
Yeongseon Choe
 
PPTX
2.Python_Testing_Using_PyUnit_PyTest.pptx
Ganesh Bhosale
 
PDF
Python testing-frameworks overview
Jachym Cepicky
 
PPTX
Python programming - Everyday(ish) Examples
Ashish Sharma
 
PDF
Debugging 2013- Thomas Ammitzboell-Bach
Mediehuset Ingeniøren Live
 
PPTX
Python: Object-Oriented Testing (Unit Testing)
Damian T. Gordon
 
PPT
Python testing
John(Qiang) Zhang
 
PDF
Writing tests
Jonathan Fine
 
Testing in Python: doctest and unittest (Updated)
Fariz Darari
 
Testing in-python-and-pytest-framework
Arulalan T
 
2.Python_Unit _Testing_Using_PyUnit_Pytest.pptx
Ganesh Bhosale
 
1.Python_Testing_Using_PyUnit_Pytest.pptx
Ganesh Bhosale
 
Debug - MITX60012016-V005100
Ha Nguyen
 
Introduction to unit testing in python
Anirudh
 
Test and refactoring
Kenneth Ceyer
 
unittestinginpythonfor-PYDevelopers.pptx
Ganesh Bhosale
 
Coursbjjhuihiuyiyiyuyuiyiuyoilidnes.pptx
kndemo34
 
MT_01_unittest_python.pdf
Hans Jones
 
Python Advanced – Building on the foundation
Kevlin Henney
 
Testing in Django
Kevin Harvey
 
pytest로 파이썬 코드 테스트하기
Yeongseon Choe
 
2.Python_Testing_Using_PyUnit_PyTest.pptx
Ganesh Bhosale
 
Python testing-frameworks overview
Jachym Cepicky
 
Python programming - Everyday(ish) Examples
Ashish Sharma
 
Debugging 2013- Thomas Ammitzboell-Bach
Mediehuset Ingeniøren Live
 
Python: Object-Oriented Testing (Unit Testing)
Damian T. Gordon
 
Python testing
John(Qiang) Zhang
 
Writing tests
Jonathan Fine
 
Ad

More from Fariz Darari (20)

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

Recently uploaded (20)

PPTX
EU POPs Limits & Digital Product Passports Compliance Strategy 2025.pptx
Certivo Inc
 
PDF
What to consider before purchasing Microsoft 365 Business Premium_PDF.pdf
Q-Advise
 
PDF
Key Features to Look for in Arizona App Development Services
Net-Craft.com
 
PPTX
TestNG for Java Testing and Automation testing
ssuser0213cb
 
DOCX
The Future of Smart Factories Why Embedded Analytics Leads the Way
Varsha Nayak
 
PDF
Protecting the Digital World Cyber Securit
dnthakkar16
 
PDF
Become an Agentblazer Champion Challenge Kickoff
Dele Amefo
 
PDF
ShowUs: Pharo Stream Deck (ESUG 2025, Gdansk)
ESUG
 
PPTX
Visualising Data with Scatterplots in IBM SPSS Statistics.pptx
Version 1 Analytics
 
PPTX
AIRLINE PRICE API | FLIGHT API COST |
philipnathen82
 
PDF
Exploring AI Agents in Process Industries
amoreira6
 
PPTX
Services offered by Dynamic Solutions in Pakistan
DaniyaalAdeemShibli1
 
PPTX
Maximizing Revenue with Marketo Measure: A Deep Dive into Multi-Touch Attribu...
bbedford2
 
PDF
IEEE-CS Tech Predictions, SWEBOK and Quantum Software: Towards Q-SWEBOK
Hironori Washizaki
 
PDF
The Role of Automation and AI in EHS Management for Data Centers.pdf
TECH EHS Solution
 
PPTX
oapresentation.pptx
mehatdhavalrajubhai
 
PDF
Why Use Open Source Reporting Tools for Business Intelligence.pdf
Varsha Nayak
 
PDF
Teaching Reproducibility and Embracing Variability: From Floating-Point Exper...
University of Rennes, INSA Rennes, Inria/IRISA, CNRS
 
PPT
Order to Cash Lifecycle Overview R12 .ppt
nbvreddy229
 
PPTX
AI-Ready Handoff: Auto-Summaries & Draft Emails from MQL to Slack in One Flow
bbedford2
 
EU POPs Limits & Digital Product Passports Compliance Strategy 2025.pptx
Certivo Inc
 
What to consider before purchasing Microsoft 365 Business Premium_PDF.pdf
Q-Advise
 
Key Features to Look for in Arizona App Development Services
Net-Craft.com
 
TestNG for Java Testing and Automation testing
ssuser0213cb
 
The Future of Smart Factories Why Embedded Analytics Leads the Way
Varsha Nayak
 
Protecting the Digital World Cyber Securit
dnthakkar16
 
Become an Agentblazer Champion Challenge Kickoff
Dele Amefo
 
ShowUs: Pharo Stream Deck (ESUG 2025, Gdansk)
ESUG
 
Visualising Data with Scatterplots in IBM SPSS Statistics.pptx
Version 1 Analytics
 
AIRLINE PRICE API | FLIGHT API COST |
philipnathen82
 
Exploring AI Agents in Process Industries
amoreira6
 
Services offered by Dynamic Solutions in Pakistan
DaniyaalAdeemShibli1
 
Maximizing Revenue with Marketo Measure: A Deep Dive into Multi-Touch Attribu...
bbedford2
 
IEEE-CS Tech Predictions, SWEBOK and Quantum Software: Towards Q-SWEBOK
Hironori Washizaki
 
The Role of Automation and AI in EHS Management for Data Centers.pdf
TECH EHS Solution
 
oapresentation.pptx
mehatdhavalrajubhai
 
Why Use Open Source Reporting Tools for Business Intelligence.pdf
Varsha Nayak
 
Teaching Reproducibility and Embracing Variability: From Floating-Point Exper...
University of Rennes, INSA Rennes, Inria/IRISA, CNRS
 
Order to Cash Lifecycle Overview R12 .ppt
nbvreddy229
 
AI-Ready Handoff: Auto-Summaries & Draft Emails from MQL to Slack in One Flow
bbedford2
 

Testing in Python: doctest and unittest

  • 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) def test_positive_large(self): self.assertEqual(square_area(40),1600) if __name__ == '__main__': unittest.main() square_oops_test.py
  • 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) def test_positive_large(self): self.assertEqual(square_area(40),1600) if __name__ == '__main__': unittest.main() square_test.py
  • 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) 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) your code, make sure the refactored 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_icon https://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.eu Run: 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