๐งช Python Testing with unittest and pytest
Testing your Python code prevents bugs from reaching production. pytest makes writing and running tests fast, readable, and enjoyable.
Write tests FIRST (TDD) or right after โ tests written later are often skipped. Aim for >80% coverage with pytest-cov.
๐ป Code Example:
# โโ Using unittest (built-in) โโโโโโโโโโโโโโโโโโโโ import unittest def calculate_pynfinity_xp(actions: list) -> int: """Calculate total XP for a user's actions.""" XP_MAP = {'login': 10, 'challenge': 30, 'pebble': 100} return sum(XP_MAP.get(action, 0) for action in actions) class TestXPCalculation(unittest.TestCase): def test_single_action(self): self.assertEqual(calculate_pynfinity_xp(['login']), 10) def test_multiple_actions(self): result = calculate_pynfinity_xp(['login', 'challenge', 'pebble']) self.assertEqual(result, 140) # 10 + 30 + 100 def test_unknown_action(self): self.assertEqual(calculate_pynfinity_xp(['unknown']), 0) def test_empty_list(self): self.assertEqual(calculate_pynfinity_xp([]), 0) if __name__ == '__main__': unittest.main() # โโ Using pytest (recommended โ pip install pytest) โโ # Save as test_xp.py and run: pytest test_xp.py -v def test_login_xp(): assert calculate_pynfinity_xp(['login']) == 10 def test_full_day_xp(): actions = ['login', 'challenge', 'pebble', 'pebble'] assert calculate_pynfinity_xp(actions) == 240 # 10+30+100+100 def test_invalid_action_gives_zero(): assert calculate_pynfinity_xp(['invalid', 'bogus']) == 0 # Run: pytest test_xp.py -v --tb=short
| Concept | Key Takeaway |
|---|---|
| assertEqual(a, b) | a == b โ most common assertion |
| assertRaises(Error) | Assert that specific exception is raised |
| pytest.fixture | Reusable test setup functions |
| pytest.mark.parametrize | Run same test with multiple inputs |
| pytest -v -k 'test_login' | Run only tests matching pattern |
Keep exploring and happy coding! ๐