Unit testing with unittest
A unit test checks one small piece of behavior automatically and reports pass or fail. A suite of fast, repeatable tests tells you quickly when a change breaks something. Tests also serve as executable documentation: they show how a function is expected to behave, including in unusual cases.
Python
import io
import unittest
def apply_discount(price_cents, percent):
if not 0 <= percent <= 100:
raise ValueError("percent must be between 0 and 100")
return price_cents * (100 - percent) // 100
class DiscountTests(unittest.TestCase):
def test_typical_discount(self):
self.assertEqual(apply_discount(8000, 25), 6000)
def test_zero_discount_keeps_price(self):
self.assertEqual(apply_discount(1999, 0), 1999)
def test_invalid_percent_is_rejected(self):
with self.assertRaises(ValueError):
apply_discount(1000, 120)
suite = unittest.defaultTestLoader.loadTestsFromTestCase(DiscountTests)
result = unittest.TextTestRunner(stream=io.StringIO()).run(suite)
print(result.testsRun, result.wasSuccessful())