Part 11 / Topic 7 of 12
unittest and doctest (standard library)
Python ships with its own testing tools, no install needed. You will see unittest in older projects.
pytest can run unittest tests too, so you can switch gradually.
| pytest | unittest | |
|---|---|---|
| Install | pip install pytest |
built in |
| Test shape | plain function def test_…(): |
method in a class that inherits unittest.TestCase (Part 9) |
| Check | assert a == b |
self.assertEqual(a, b) |
| Errors | with pytest.raises(ValueError): |
with self.assertRaises(ValueError): |
| Run | python -m pytest |
python -m unittest |
import unittest
from shop import apply_discount
class TestApplyDiscount(unittest.TestCase):
def test_ten_percent(self):
self.assertEqual(apply_discount(1000, 10), 900)
def test_bad_percent(self):
with self.assertRaises(ValueError):
apply_discount(1000, 120)
doctest runs the examples written in a docstring (the >>> lines) and checks the output below them. Good for small examples that also act as documentation.
import doctest
def rupees_to_paise(rupees):
"""
>>> rupees_to_paise(12.5)
1250
"""
return round(rupees * 100)
print(doctest.testmod()) # TestResults(failed=0, attempted=1)
Demo of both: 04_unittest_and_doctest.py.
Done here? The practice set for Part 11 — 7 exercises with solutions — is on the part page.