Three pytest tests plus an exit code can decide whether to roll back, provided exit code 5 doesn't slip past the gate.
Key Takeaways
- Smoke tests only check a few critical paths, such as startup, database connection, and authentication, and finish within 2 minutes.
- Declare command-line options in conftest.py, and the same test suite can run in any customer environment.
- The deployment script must treat all non-zero exit codes as failures, including exit code 5 (no tests collected).
In ArgoCD, you can attach smoke tests to a PostSync hook so they run automatically as soon as deployment completes. One detail is often overlooked: when tests fail, the sync is marked as failed, but the new resources remain in the cluster. The tool only notifies you; whether to roll back is still your decision.
For a Forward Deployed Engineer (FDE), this is daily work. You install the product into the customer's infrastructure, using the customer's own network, database, and login system, and the pipeline shows green. The Google SRE Workbook explicitly points out that some release failures only surface once real traffic starts hitting the service. The customer environment is exactly where these failures appear.
This article shows how to write a smoke test suite with pytest. The tests run in any customer environment with a single command-line option and return an exit code that the deployment script uses to decide whether to keep the version or roll back.
What to do and what you need
Consider a hypothetical example: you've just deployed a document search service to the customer's infrastructure. The service has three endpoints, also fictional for illustration:
/health
indicates the process has started,
/ready
only returns 200 when it can connect to the database,
/api/search
requires a token. In real work, replace these with the endpoints your product actually exposes.
You need Python 3, pytest, the URL of the environment to check, and a test token stored in an environment variable. The code below uses the standard library
urllib
, so nothing extra needs to be installed. This is a minimal version, enough to grasp the method, but not production-ready.
smoke/ pytest.ini conftest.py test_smoke.py
Step 1: Only check what would bring the whole system down
A smoke test is a quick check of whether core functionality works, telling you early whether the fundamentals of the deployment are running properly. Limit the scope to critical paths, such as startup, database connection, and authentication. Edge cases and individual minor features don't belong here.
The whole test suite should have a time budget of under 2 minutes. The example above has three tests with a 5-second timeout per request. The worst case is all four requests hanging until timeout, about 20 seconds, still well within the limit. If the test suite starts ballooning to several minutes, you've put regression tests in the wrong place.
Step 2: Register markers so pytest catches typos for you
pytest recommends registering custom markers in the config file, such as
smoke
:
# pytest.ini
[pytest]
markers =
smoke: 部署后对关键路径的快速检查Verification: run
pytest --markers
and find the
smoke
line in the list. When running tests, always add
--strict-markers
. With this flag enabled, any unregistered marker applied via the
@pytest.mark...
decorator raises an error. A misspelled
@pytest.mark.smok
gets caught immediately, instead of silently ensuring that test is never selected.
Step 3: One test suite for all customer environments
Don't hardcode URLs. The pytest documentation explains how to add command-line options in
conftest.py
via
pytest_addoption
and pass the value to tests through a fixture:
# conftest.py
import pytest
def pytest_addoption(parser):
parser.addoption("--target-url", action="store", default=None,
help="待检查环境的基础 URL")
@pytest.fixture
def target_url(request):
url = request.config.getoption("--target-url")
if not url:
pytest.fail("缺少 --target-url")
return url.rstrip("/")Verification: run
pytest --help
and find
--target-url
。
Step 4: Write three tests for the three critical paths
# test_smoke.py
import os
import urllib.error
import urllib.request
import pytest
TIMEOUT = 5 # 秒
def get_status(url, token=None):
req = urllib.request.Request(url)
if token:
req.add_header("Authorization", f"Bearer {token}") # 假定的认证方式
try:
with urllib.request.urlopen(req, timeout=TIMEOUT) as resp:
return resp.status
except urllib.error.HTTPError as err:
return err.code
@pytest.mark.smoke
def test_service_started(target_url):
assert get_status(f"{target_url}/health") == 200
@pytest.mark.smoke
def test_database_reachable(target_url):
assert get_status(f"{target_url}/ready") == 200
@pytest.mark.smoke
def test_auth_rejects_then_accepts(target_url):
assert get_status(f"{target_url}/api/search?q=test") == 401
token = os.environ["SMOKE_TOKEN"]
assert get_status(f"{target_url}/api/search?q=test", token) == 200The third test checks both directions at once. Being accessible without a token is a security vulnerability, not a success. If the test only checks "returns 200 with a token," it would still pass even if the authentication layer were completely disabled.
Step 5: Use the exit code to decide keep or roll back
What the deployment script needs to read is pytest's exit code. 0 means all tests passed; 1 means tests were collected and run but some failed; 5 means no tests were collected, and that's exactly where the trap lies.
pytest -m smoke --strict-markers --target-url "$TARGET_URL" -q rc=$? if [ "$rc" -ne 0 ]; then echo "冒烟测试失败(退出码 $rc),请考虑回滚" exit 1 fi
Suppose you mistype
-m smoek
on the command line.
--strict-markers
only catches typos in decorators, not in
-m
expressions, so pytest selects no tests and returns exit code 5. If the script only checks
rc -eq 1
, the deployment passes the gate without a single test running. So the correct condition is
-ne 0
。
Three ways smoke tests can fool you
The first is the exit code 5 trap described above. The second is letting the test suite balloon to ten minutes: people in a hurry will skip it, and that's precisely when it's needed most.
The value of smoke tests lies in speed: the moment a test fails, you know something is wrong and can roll back before users notice.
The third is assuming the system will handle it for you. As the ArgoCD example at the start showed, a failed PostSync hook doesn't remove the new resources. Before pressing deploy, write out the rollback procedure, and at minimum designate one person with the authority to make the call.
What this skill looks like at the customer site
Google SRE defines a canary release as a partial, time-limited deployment of a change, with the change evaluated at the same time. Smoke tests are a simplified version of that evaluation step, and in your first week at a customer site, before you have traffic splitting and monitoring dashboards, they're often the only viable option.
The first thing to do in week one is ask the customer for a test account dedicated to smoke testing, so that
SMOKE_TOKEN
doesn't have to borrow a real person's token.
This test suite is also a communication tool. When the customer asks "Is it installed?", you can answer with three green results and an exit code, instead of "It should be fine."
In interviews or on your resume, be specific: which paths the smoke tests check, at which stage of the pipeline they run, and what failures they've caught. Descriptions like this show that you can verify the product is actually running, not just deployed.
A green pipeline means the code has been delivered. Whether the product is actually running on the customer's infrastructure, only those three pytest tests can answer.
Was this article helpful?
Thanks for your feedback!