How to Smoke Test a Deployment in Python with unittest.mock
Run a post-deploy smoke test by mocking the deployment status check to verify your health-check logic returns PASS/FAIL.
Python code
20 linesimport unittest
from unittest.mock import Mock, patch
class DeploymentService:
def check_status(self):
return "unknown"
def smoke_test_deploy():
service = DeploymentService()
with patch.object(service, "check_status", return_value="healthy") as mock_check:
status = service.check_status()
if status == "healthy":
print("PASS: deployment is healthy")
return True
else:
print("FAIL: deployment is not healthy")
return False
if __name__ == "__main__":
smoke_test_deploy()
Output
PASS: deployment is healthy
True
How it works
The patch.object context manager temporarily replaces check_status with a mock that returns "healthy", letting you test the smoke-test logic without hitting a real service. The mock is automatically restored after the with block, so the original behavior remains intact. Because the function returns a boolean and prints a status line, calling it behaves like a minimal CI/CD health gate. The pattern is valuable when you want to verify the control flow of your verification script before pointing it at a real deployment.
Common mistakes
- Forgetting that `patch.object` only lasts inside the `with` block — the mock is removed right after.
- Testing the mock itself by asserting on `mock_check` instead of on the function's return value.
- Hardcoding the mock return value so the failure path is never exercised in tests.
Variations
- Use `@patch('__main__.DeploymentService.check_status')` as a decorator on the test function instead of a context manager.
- Mock `requests.get` inside an HTTP-based health check with a fake response to simulate a real endpoint.
Real-world use cases
- Validating a CI/CD pipeline's smoke-test script by stubbing the health endpoint before deployment.
- Verifying rollback logic in a production environment by asserting the health check fails gracefully.
- Testing alerting hooks that fire when a post-deploy status check returns anything other than healthy.
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.