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.
Python code
23 linesimport 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
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
- Use `patch("builtins.input", ...)` to mock user input in CLI shutdown prompts
- 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
More from Production deployment patterns
- Auto Rollback on Error Rate Exceeded in Python medium
- Automate Semantic Versioning with Conventional Commits in Python medium
- Design a Data Helper for Beginners in Python easy
- Docker healthcheck CMD mock in Python easy
- Generate a Mock Artifact Version Tag in Python easy
- Generate a docker-compose.yml with mock services in Python easy
Keep learning
Related tutorials and quizzes for this topic.