
unittest (built-in):
import unittest
def add(a, b):
return a + b
class TestAdd(unittest.TestCase):
def test_positive(self):
self.assertEqual(add(2, 3), 5)
def test_negative(self):
self.assertEqual(add(-1, -1), -2)
def test_zero(self):
self.assertEqual(add(0, 5), 5)
if __name__ == "__main__":
unittest.main()pytest (install: pip install pytest):
def test_add():
assert add(2, 3) == 5
def test_add_negative():
assert add(-1, -1) == -2Run with: pytest test_file.py or just pytest
Common assertions (unittest):
assertEqual, assertNotEqual, assertTrue, assertFalse, assertIsNone, assertIn, assertRaises
Test-Driven Development (TDD): Write the test FIRST, then write the code to make it pass. Sounds counterintuitive, but catches design problems early.
Reference:
TaskLoco™ — The Sticky Note GOAT