How to Mock a Slow Startup Probe for Fast Testing in Python

This code shows how to replace a slow startup probe's initialization with a mock to make tests run fast and reliably.

Easy Python 3.9+ Aug 9, 2026 Production deployment patterns 15 views 0 copies

Python code

32 lines
Python 3.9+
import time
from unittest.mock import Mock, patch


class StartupProbe:
    def __init__(self, init_time):
        self.init_time = init_time
        self.ready = False

    def initialize(self):
        time.sleep(self.init_time)
        self.ready = True
        return self.ready


def run_startup_probe(probe):
    start = time.perf_counter()
    result = probe.initialize()
    elapsed = time.perf_counter() - start
    return result, elapsed


if __name__ == "__main__":
    slow_probe = StartupProbe(init_time=3)
    fast_probe = StartupProbe(init_time=0.01)

    real_result, real_elapsed = run_startup_probe(fast_probe)
    print(f"Real: ready={real_result}, elapsed={real_elapsed:.3f}s")

    with patch.object(StartupProbe, "initialize", return_value=True):
        mock_result, mock_elapsed = run_startup_probe(slow_probe)
        print(f"Mocked: ready={mock_result}, elapsed={mock_elapsed:.3f}s (probe skipped)")

Output

stdout
Real: ready=True, elapsed=0.010s
Mocked: ready=True, elapsed=0.000s (probe skipped)

How it works

The patch.object context manager temporarily replaces StartupProbe.initialize with a mock that returns True immediately. This avoids the time.sleep call in the real method, so run_startup_probe completes almost instantly. The mock records the call, allowing you to assert that the probe was invoked during the test. This pattern is essential for unit testing code that depends on slow external resources like network calls or disk I/O. By patching the slow parts, you isolate the logic under test from timing issues and flakiness.

Common mistakes

  • Patching the wrong object: ensure you patch where the method is looked up (the class), not an instance attribute.
  • Forgetting to restore the original after the test (the context manager handles this automatically).
  • Patching only the `time.sleep` but not the `initialize` method may still leave side effects unmocked.

Variations

  1. Use `unittest.mock.patch('module.ClassName.method')` with a string target to patch without needing to import the class.
  2. Use `create_autospec` to mock the probe and its methods automatically for stronger type checking.

Real-world use cases

  • Testing HTTP health-check handlers that call a startup probe without waiting for a real server during CI.
  • Simulating a slow probe in integration tests to verify timeout logic without actually delaying.
  • Mocking external service initialization in unit tests to keep the test suite fast and deterministic.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Production deployment patterns

Related tutorials and quizzes for this topic.