How to Write a Fast Smoke Test for a Critical Path in Python
A quick smoke test that validates the /health critical path executes fast enough, raising errors on wrong paths or slow responses.
Python code
16 linesimport time
def smoke_test(path):
if path != "/health":
raise ValueError("Critical path expected /health")
start = time.perf_counter()
# Simulate the critical health check work
time.sleep(0.01)
elapsed = time.perf_counter() - start
if elapsed > 0.05:
raise RuntimeError("Health check too slow")
return {"status": "ok", "path": path, "elapsed_ms": round(elapsed * 1000, 2)}
if __name__ == "__main__":
result = smoke_test("/health")
print(result)
Output
{'status': 'ok', 'path': '/health', 'elapsed_ms': 10.0}
How it works
time.perf_counter() measures elapsed time with the highest available resolution, ideal for micro-benchmarks. The function validates the expected path upfront with an explicit ValueError, separating input errors from performance issues. A hard time.sleep(0.01) simulates real work, while the 0.05-second threshold catches regressions. Returning a dict makes the result easy to assert on in a test framework. Running smoke_test in __main__ provides a manual CLI hook for quick verification.
Common mistakes
- Using `time.time()` instead of `time.perf_counter()` for sub-millisecond timing
- Raising generic `Exception` instead of specific types like `ValueError` and `RuntimeError`
- Sleeping for too long in the test, masking real performance issues
- Forgetting to check the return value when the function is used in CI
Variations
- Use pytest with `@pytest.mark.parametrize` to test multiple paths and thresholds
- Replace `time.sleep` with a mock to avoid actual delays in unit tests
Real-world use cases
- CI pipelines that verify a service's health endpoint responds within a strict SLA before deploying.
- Startup scripts that confirm a critical database connection or worker thread initializes quickly.
- Canary releases that run a fast path check on the new instance before shifting traffic.
Sponsored
More from Testing & modern typing
- Capture stdout and stderr with pytest capsys easy
- Characterization Test for Legacy Python Code medium
- Dataclass with Type Hints Fields in Python easy
- Dependency Injection in Python for Testability easy
- Design Data Helpers with Python TypedDict and Literal easy
- Fix and Test a Regression Bug in Python with Unit Tests easy
Keep learning
Related tutorials and quizzes for this topic.