How to Mock a Dependency for Readiness Probe in Python

Use unittest.mock.Mock to simulate a dependency's readiness check response for testing a service's is_ready method without hitting a real connection.

Easy Python 3.8+ Aug 9, 2026 Production deployment patterns 17 views 0 copies

Python code

39 lines
Python 3.8+
import time
import unittest
from unittest.mock import Mock

class Service:
    def __init__(self, dependency):
        self.dependency = dependency

    def is_ready(self):
        try:
            result = self.dependency.check()
            return result == "ready"
        except Exception:
            return False

def main():
    # Real dependency that fails intermittently
    class FailingDependency:
        def check(self):
            time.sleep(0.1)
            raise ConnectionError("Dependency down")

    service = Service(FailingDependency())
    print("Real dependency ready:", service.is_ready())

    # Mocked dependency that always returns "ready"
    mock_dep = Mock()
    mock_dep.check.return_value = "ready"
    service_mocked = Service(mock_dep)
    print("Mocked dependency ready:", service_mocked.is_ready())

    # Mocked dependency that raises an exception
    mock_dep_fail = Mock()
    mock_dep_fail.check.side_effect = TimeoutError("Timeout")
    service_fail = Service(mock_dep_fail)
    print("Failing mock ready:", service_fail.is_ready())

if __name__ == "__main__":
    main()

Output

stdout
Real dependency ready: False
Mocked dependency ready: True
Failing mock ready: False

How it works

The Service class wraps a dependency object with a check() method. is_ready() calls that method, returns True when it returns the string "ready", and catches any exception to return False. Using unittest.mock.Mock, you control the return value with return_value and simulate exceptions via side_effect. This isolates the probe logic from flaky I/O so you can assert readiness behavior deterministically. The real dependency here demonstrates a failure case, while the mocks show both healthy and exceptional paths.

Common mistakes

  • Forgetting to set `return_value`, so the mock returns another Mock and never matches "ready".
  • Using `side_effect` to raise an exception but not expecting `is_ready()` to catch it into False.
  • Mocking the wrong method name (e.g., `check_health` vs `check`) and getting an unexpected call.

Variations

  1. Use `patch` to replace a dependency attribute on a class during a test.
  2. Create a `Mock` with `spec=ActualDependency` to enforce method signatures.

Real-world use cases

  • Unit-testing a Kubernetes-style readiness probe that pings a database before serving traffic.
  • Verifying a service degrades gracefully when a downstream API times out during startup health checks.
  • Simulating a healthy dependency for integration tests that run without external services.

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.