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.

Medium Python 3.9+ Aug 9, 2026 Production deployment patterns 13 views 0 copies

Python code

20 lines
Python 3.9+
import 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

stdout
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

  1. Use `@patch('__main__.DeploymentService.check_status')` as a decorator on the test function instead of a context manager.
  2. 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

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.