๐งช Pytest Testing
Pytest is a framework that makes building simple and scalable tests easy.
Mastering this concept will significantly boost your Python data science skills!
๐ป Code Example:
import pytest from unittest.mock import patch, MagicMock # โโ Code under test โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ class PynfinityXP: XP_MAP = {"login": 10, "challenge": 30, "pebble": 100, "referral": 50} def __init__(self): self._total = 0 self._history = [] def award(self, action: str) -> int: pts = self.XP_MAP.get(action, 0) self._total += pts self._history.append((action, pts)) return pts @property def total(self) -> int: return self._total @property def level(self) -> str: if self._total >= 500: return "Expert" if self._total >= 200: return "Intermediate" return "Beginner" # โโ Fixtures โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ @pytest.fixture def xp(): return PynfinityXP() @pytest.fixture def loaded_xp(xp): """XP instance with some actions already done.""" xp.award("login"); xp.award("challenge"); xp.award("pebble") return xp # โโ Tests โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ def test_login_gives_10_xp(xp): assert xp.award("login") == 10 def test_unknown_action_gives_zero(xp): assert xp.award("nonexistent") == 0 @pytest.mark.parametrize("action,expected", [ ("login", 10), ("challenge", 30), ("pebble", 100), ("referral", 50), ("unknown", 0), ]) def test_all_actions(xp, action, expected): assert xp.award(action) == expected def test_total_accumulates(xp): xp.award("login") xp.award("challenge") assert xp.total == 40 def test_level_progression(loaded_xp): # loaded_xp = 10 + 30 + 100 = 140 โ Beginner assert loaded_xp.level == "Beginner" loaded_xp.award("pebble") # +100 โ 240 โ Intermediate assert loaded_xp.level == "Intermediate" def test_mock_external_service(xp): """Test that notification is called on expert level.""" with patch("builtins.print") as mock_print: for _ in range(6): xp.award("pebble") # 600 XP โ Expert assert xp.level == "Expert" # Run: pytest test_xp.py -v --tb=short
Keep exploring and happy coding! ๐ป