How to Mock time.sleep in a Python PreStop Hook

This code simulates a Kubernetes PreStop hook that delays shutdown, then mocks time.sleep to verify the hook logic without real delay.

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

Python code

23 lines
Python 3.9+
import subprocess
import sys
import time
from unittest.mock import patch

def pre_stop_hook():
    """Simulate a Kubernetes PreStop hook that sleeps before shutdown."""
    print("PreStop hook started: delaying shutdown")
    time.sleep(3)
    print("PreStop hook completed: ready to shutdown")

if __name__ == "__main__":
    # Mock time.sleep to demonstrate the hook without actual delay
    with patch("__main__.time.sleep") as mock_sleep:
        pre_stop_hook()
        mock_sleep.assert_called_once_with(3)
        print("Mock verified: sleep called with 3 seconds")
    
    # Show real timing demonstration
    start = time.time()
    pre_stop_hook()
    elapsed = time.time() - start
    print(f"Actual execution took {elapsed:.2f} seconds")

Output

stdout
PreStop hook started: delaying shutdown
PreStop hook completed: ready to shutdown
Mock verified: sleep called with 3 seconds
PreStop hook started: delaying shutdown
PreStop hook completed: ready to shutdown
Actual execution took 3.00 seconds

How it works

The pre_stop_hook function uses time.sleep(3) to simulate an async wait before container termination. By wrapping the call in patch, we replace sleep with a mock, so the function runs instantly and we can assert it was called with the expected argument. This pattern lets you test shutdown logic in CI without blocking for actual delays. The second call runs the real sleep to demonstrate the timing difference.

Common mistakes

  • Patching `time.sleep` instead of `__main__.time.sleep` when the function is in the same module
  • Forgetting to assert the call arguments, so the mock never validates the sleep duration
  • Mocking the wrong sleep reference (e.g., a local import) and the patch having no effect

Variations

  1. Use `patch("builtins.input", ...)` to mock user input in CLI shutdown prompts
  2. Mock `time.sleep` with `side_effect` to simulate a real delay or raise an exception for error-handling tests

Real-world use cases

  • Unit-testing Kubernetes PreStop hooks without slowing down CI pipelines.
  • Verifying graceful shutdown logic in container entrypoint scripts before deployment.
  • Mocking sleep calls in batch jobs to speed up test suites that probe retry intervals.

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.