from __future__ import annotations import time import unittest from collections.abc import Callable from typing import TypeVar T = TypeVar("T") def retry_with_backoff( operation: Callable[[], T], *, max_attempts: int = 3, initial_delay: float = 0.5, backoff_factor: float = 2.0, retry_on: tuple[type[Exception], ...] = (Exception,), sleep: Callable[[float], None] = time.sleep, ) -> T: """Run an operation, retrying failures with exponential backoff.""" if max_attempts < 1: raise ValueError("max_attempts must be at least 1") if initial_delay < 0: raise ValueError("initial_delay cannot be negative") if backoff_factor < 1: raise ValueError("backoff_factor must be at least 1") delay = initial_delay for attempt in range(1, max_attempts + 1): try: return operation() except retry_on: if attempt == max_attempts: raise sleep(delay) delay *= backoff_factor raise RuntimeError("unreachable") class RetryWithBackoffTests(unittest.TestCase): def test_retries_until_success(self) -> None: attempts = 0 delays: list[float] = [] def flaky_operation() -> str: nonlocal attempts attempts += 1 if attempts < 3: raise OSError("temporary failure") return "success" result = retry_with_backoff( flaky_operation, initial_delay=0.25, sleep=delays.append, ) self.assertEqual(result, "success") self.assertEqual(attempts, 3) self.assertEqual(delays, [0.25, 0.5]) def test_raises_after_max_attempts(self) -> None: attempts = 0 def failing_operation() -> None: nonlocal attempts attempts += 1 raise ValueError("permanent failure") with self.assertRaisesRegex(ValueError, "permanent failure"): retry_with_backoff( failing_operation, max_attempts=2, initial_delay=0, retry_on=(ValueError,), sleep=lambda _: None, ) self.assertEqual(attempts, 2) if __name__ == "__main__": unittest.main()