Some jobs are much easier with a package from PyPI: requests and httpx for HTTP, tenacity for retries, pyyaml and python-dotenv for configuration, click or typer and rich for command-line tools, jinja2 for templates, paramiko and fabric for SSH, boto3, kubernetes, docker, and hvac for clouds, clusters, and Vault, and prometheus_client and psutil for metrics. This lesson grows a deployment checker from a script into a tool with those packages, and shows the two ways it breaks: an unpinned dependency that changes overnight, and an HTTP call with no timeout.
Difficulty: Intermediate · Know this first: Lesson 29, Lesson 42
By the end of this lesson you can work at four levels:
This page teaches it with a plain-language analogy, an animated diagram with normal and failure scenarios, a simulator, a quiz, basic, intermediate, advanced, and master checks, the expert detail ("Go deeper"), a production incident, a hands-on lab with commands and their output, and a production design exercise.
This bar adds up minutes for the deployment check in CI. It is a worked example, not a measurement. The pin and HTTP hops are where it breaks.
Pick how requirements.txt names a dependency, and what the dependency released last night.
Unpinned: CI installed the new major version and the checker broke
Three questions. No score is saved anywhere — this is just you against the material.
Working with packages grows in four levels: installing them properly, using them safely, building tools with them, and managing them across a team.
At the basic level packages go into a virtual environment.
python3 -m venv .venv, . .venv/bin/activate, pip install NAME.pip show, pip list, pip freeze > requirements.txt.pyyaml and yaml, python-dotenv and dotenv.Where it breaks: sudo pip install into the system Python, which the operating system also uses.
Try it: Basic
pip install python-dotenv worked, but import python_dotenv fails. Why?
Now do it: For three packages you use, write down the install and import names.
At the intermediate level every call is bounded and every input is parsed safely.
requests, httpx, paramiko, and SDK clients; raise_for_status().tenacity).yaml.safe_load; jinja2 with StrictUndefined; known_hosts enforced for SSH.Try it: Intermediate
A retry decorator retries every exception five times. What is wrong?
Now do it: Restrict one retry policy to temporary errors.
At the advanced level packages become a proper tool.
click or typer CLI with tests through CliRunner; exit codes CI understands.kubernetes and boto3 clients with least-privilege credentials.prometheus_client; packaging with pyproject.toml and an entry point.Try it: Advanced
How do you test a click command without running a subprocess?
Now do it: Add a CliRunner test for the --help output and one failing case.
At the master level dependencies are a managed supply chain.
pip-audit in CI; a bot for update pull requests; licences checked.Trade-off: strict pins and mirrors make builds repeatable and slow down taking fixes; a weekly update bot with tests balances both.
Try it: Master
A vulnerability is announced in a library your tools pin. How do you find every affected tool?
Now do it: Run pip-audit on one repository and fix what it finds.
The deployment checker's core: pinned packages, bounded calls, retries only for temporary failures, a real CLI, and metrics.
# requirements.txt pins every package with == (from pip freeze), or use a lock file with hashes
import sys
import click, requests, yaml
from prometheus_client import CollectorRegistry, Counter, Histogram, push_to_gateway
from tenacity import retry, retry_if_exception, stop_after_attempt, wait_exponential_jitter
def temporary(e):
if isinstance(e, (requests.ConnectionError, requests.Timeout)):
return True
return isinstance(e, requests.HTTPError) and e.response.status_code in (429, 502, 503, 504)
@retry(retry=retry_if_exception(temporary), stop=stop_after_attempt(4), wait=wait_exponential_jitter(1, 10), reraise=True)
def check(session, url):
r = session.get(url, timeout=(3, 10)) # never without a timeout
r.raise_for_status()
return r.json()
@click.command()
@click.option("--env", required=True, type=click.Choice(["staging", "prod"]))
@click.option("--targets", default="targets.yaml", type=click.Path(exists=True))
def main(env, targets):
reg = CollectorRegistry()
failures = Counter("deploy_check_failures_total", "Failed checks", registry=reg)
duration = Histogram("deploy_check_duration_seconds", "Check duration", registry=reg)
urls = yaml.safe_load(open(targets, encoding="utf-8"))[env]
failed = 0
with requests.Session() as s, duration.time():
for url in urls:
try:
check(s, url)
click.echo(f"ok {url}")
except Exception as e:
failures.inc()
failed += 1
click.echo(f"FAILED {url}: {e}", err=True)
push_to_gateway("pushgateway.monitoring:9091", job="deploy-check", registry=reg)
sys.exit(1 if failed else 0)
if __name__ == "__main__":
main()
This is a composite of a failure pattern that keeps repeating; the details are illustrative. A dependency upgraded itself overnight.
Every tool uses a lock file with hashes, a bot proposes updates weekly with the test suite as the gate, and CI fails if any requirement is unpinned.
One small program per package, each run offline: a local test server stands in for real APIs, so every output is real and repeatable. Each example is a whole program: save it under the name in its first line, run it with python3, and you should see exactly the output below it.
Before you start: These examples need requests httpx tenacity pyyaml python-dotenv jinja2 click rich psutil prometheus_client kubernetes paramiko: make a virtual environment and install them with python3 -m venv .venv && . .venv/bin/activate && pip install requests httpx tenacity pyyaml python-dotenv jinja2 click rich psutil prometheus_client kubernetes paramiko. Versions differ in small ways, so a number in the last decimal place may not match yours.
In everyday terms
A package has two names, like a shop and the brand on the box: the name you ask pip for, and the name you import. importlib.metadata reads the label to tell you which box a module came out of.
importlib.metadata.packages_distributions() maps each importable name to the package that installed it, so you can find the install name of anything already installed. Third-party packages answer the same questions once installed; their names on PyPI can differ from the name you import (pip install scikit-learn, then import sklearn). The lesson Finding the Right Command, Library and Method covers this in full.
# find_it.py
import importlib.metadata as md
import dotenv, jinja2, requests, yaml # installed with pip in this lesson's virtual environment
dists = md.packages_distributions()
for name in ["yaml", "dotenv", "jinja2", "requests", "urllib3", "PIL"]:
print(f"import {name:<9} comes from: {sorted(set(dists.get(name, ['(not installed)'])))}")
$ python3 find_it.py import yaml comes from: ['PyYAML'] import dotenv comes from: ['python-dotenv'] import jinja2 comes from: ['Jinja2'] import requests comes from: ['requests'] import urllib3 comes from: ['urllib3'] import PIL comes from: ['(not installed)']
Always pass timeout=(connect, read); raise_for_status() turns 4xx and 5xx into exceptions.
# example_01.py
import json, threading
from http.server import BaseHTTPRequestHandler, HTTPServer
import requests
class API(BaseHTTPRequestHandler):
def do_GET(self):
if self.path == "/health":
body = json.dumps({"status": "ok", "version": "1.4.2"}).encode()
self.send_response(200); self.send_header("Content-Type", "application/json"); self.end_headers()
self.wfile.write(body)
else:
self.send_response(404); self.end_headers()
def log_message(self, *args):
pass
server = HTTPServer(("127.0.0.1", 0), API)
threading.Thread(target=server.serve_forever, daemon=True).start()
base = f"http://127.0.0.1:{server.server_port}"
r = requests.get(f"{base}/health", timeout=(3, 10))
print(r.status_code, r.headers["Content-Type"], r.json())
try:
requests.get(f"{base}/missing", timeout=(3, 10)).raise_for_status()
except requests.HTTPError as e:
print("HTTPError:", e.response.status_code)
server.shutdown()
$ python3 example_01.py
200 application/json {'status': 'ok', 'version': '1.4.2'}
HTTPError: 404
A Session with Retry retries 503s by itself; here the server fails twice, then answers.
# example_02.py
import threading
from http.server import BaseHTTPRequestHandler, HTTPServer
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
calls = 0
class Flaky(BaseHTTPRequestHandler):
def do_GET(self):
global calls
calls += 1
self.send_response(503 if calls < 3 else 200); self.end_headers()
self.wfile.write(b"" if calls < 3 else b"ready")
def log_message(self, *args):
pass
server = HTTPServer(("127.0.0.1", 0), Flaky)
threading.Thread(target=server.serve_forever, daemon=True).start()
with requests.Session() as s:
s.mount("http://", HTTPAdapter(max_retries=Retry(total=3, status_forcelist=[503], backoff_factor=0)))
r = s.get(f"http://127.0.0.1:{server.server_port}/", timeout=(3, 10))
print(r.status_code, r.text, "after", calls, "calls")
server.shutdown()
$ python3 example_02.py 200 ready after 3 calls
A server that accepts the connection and answers too slowly raises ReadTimeout instead of hanging your job.
# example_03.py
import threading, time
from http.server import BaseHTTPRequestHandler, HTTPServer
import requests
class Slow(BaseHTTPRequestHandler):
def do_GET(self):
time.sleep(2)
self.send_response(200); self.end_headers()
def log_message(self, *args):
pass
server = HTTPServer(("127.0.0.1", 0), Slow)
threading.Thread(target=server.serve_forever, daemon=True).start()
start = time.monotonic()
try:
requests.get(f"http://127.0.0.1:{server.server_port}/", timeout=(3, 0.5))
except requests.Timeout as e:
print(type(e).__name__, "after about", round(time.monotonic() - start, 1), "seconds")
$ python3 example_03.py ReadTimeout after about 0.5 seconds
httpx has a 5-second timeout unless you set another. A mock transport stands in for the server.
# example_04.py
import httpx
def api(request):
return httpx.Response(200, json={"path": request.url.path, "replicas": 3})
print(httpx.Client().timeout)
with httpx.Client(base_url="https://api.example.com", transport=httpx.MockTransport(api), timeout=10) as client:
r = client.get("/deployments/checkout")
print(r.status_code, r.json())
$ python3 example_04.py
Timeout(timeout=5.0)
200 {'path': '/deployments/checkout', 'replicas': 3}
Retry only the errors that can go away, a fixed number of times; then give up with the last error.
# example_05.py
from tenacity import RetryError, retry, retry_if_exception_type, stop_after_attempt, wait_none
attempts = []
@retry(stop=stop_after_attempt(3), wait=wait_none(), retry=retry_if_exception_type(ConnectionError))
def connect():
attempts.append(1)
if len(attempts) < 3:
raise ConnectionError("refused")
return "connected"
print(connect(), "after", len(attempts), "attempts")
@retry(stop=stop_after_attempt(2), wait=wait_none())
def never():
raise TimeoutError("no answer")
try:
never()
except RetryError as e:
print("gave up:", type(e.last_attempt.exception()).__name__, "after", e.last_attempt.attempt_number, "attempts")
$ python3 example_05.py connected after 3 attempts gave up: TimeoutError after 2 attempts
safe_load builds plain data only. yaml.load without a loader is refused by current versions.
# example_06.py
import yaml
text = """\
kind: Deployment
metadata: {name: checkout}
spec: {replicas: 3}
---
kind: Service
metadata: {name: checkout}
"""
docs = list(yaml.safe_load_all(text))
print([d["kind"] for d in docs], docs[0]["spec"]["replicas"])
print(yaml.safe_dump({"targets": ["web-1", "web-2"], "timeout": 10}, sort_keys=False).strip())
try:
yaml.load(text)
except TypeError as e:
print("TypeError:", str(e)[:60])
$ python3 example_06.py ['Deployment', 'Service'] 3 targets: - web-1 - web-2 timeout: 10 TypeError: load() missing 1 required positional argument: 'Loader'
For local runs, a .env file fills the environment; variables already set win unless you pass override=True.
# example_07.py import io, os from dotenv import dotenv_values, load_dotenv env_text = "API_URL=https://api.example.com\nTIMEOUT=10\n# a comment\nDEBUG=false\n" print(dict(dotenv_values(stream=io.StringIO(env_text)))) os.environ["TIMEOUT"] = "30" load_dotenv(stream=io.StringIO(env_text)) print(os.environ["API_URL"], os.environ["TIMEOUT"])
$ python3 example_07.py
{'API_URL': 'https://api.example.com', 'TIMEOUT': '10', 'DEBUG': 'false'}
https://api.example.com 30
StrictUndefined turns a missing variable into an error instead of an empty line in a config file.
# example_08.py
from jinja2 import Environment, StrictUndefined, UndefinedError
env = Environment(undefined=StrictUndefined, trim_blocks=True, lstrip_blocks=True)
tpl = env.from_string("""\
upstream {{ name }} {
{% for host in hosts %}
server {{ host }}:{{ port }};
{% endfor %}
}""")
print(tpl.render(name="checkout", hosts=["10.0.0.11", "10.0.0.12"], port=8080))
try:
tpl.render(name="checkout", hosts=["10.0.0.11"])
except UndefinedError as e:
print("UndefinedError:", e)
$ python3 example_08.py
upstream checkout {
server 10.0.0.11:8080;
server 10.0.0.12:8080;
}
UndefinedError: 'port' is undefined
Options become arguments to your function; CliRunner runs the command in-process to test it.
# example_09.py
import click
from click.testing import CliRunner
@click.command()
@click.option("--env", required=True, type=click.Choice(["staging", "prod"]))
@click.option("--replicas", default=2, show_default=True, type=int)
def deploy(env, replicas):
"""Check a deployment."""
click.echo(f"checking {env} with {replicas} replicas")
if replicas < 1:
raise click.UsageError("need at least one replica")
runner = CliRunner()
for args in (["--env", "prod", "--replicas", "3"], ["--env", "dev"], ["--env", "staging", "--replicas", "0"]):
r = runner.invoke(deploy, args)
print(r.exit_code, r.output.strip().splitlines()[-1])
$ python3 example_09.py 0 checking prod with 3 replicas 2 Error: Invalid value for '--env': 'dev' is not one of 'staging', 'prod'. 2 Error: need at least one replica
rich prints tables and colours in a terminal, and plain text when the output goes to a file or a CI log.
# example_10.py
import io
from rich.console import Console
from rich.table import Table
table = Table(title="Deployments")
for col in ("name", "ready", "image"):
table.add_column(col)
table.add_row("checkout", "3/3", "checkout:1.4.2")
table.add_row("payments", "1/2", "payments:2.0.0")
out = io.StringIO()
Console(file=out, width=60, color_system=None).print(table)
print(out.getvalue().rstrip())
$ python3 example_10.py
Deployments
┏━━━━━━━━━━┳━━━━━━━┳━━━━━━━━━━━━━━━━┓
┃ name ┃ ready ┃ image ┃
┡━━━━━━━━━━╇━━━━━━━╇━━━━━━━━━━━━━━━━┩
│ checkout │ 3/3 │ checkout:1.4.2 │
│ payments │ 1/2 │ payments:2.0.0 │
└──────────┴───────┴────────────────┘
CPU, memory, disks, and processes, the same way on Linux, macOS, and Windows.
# example_11.py
import psutil
print("CPUs:", psutil.cpu_count() >= 1)
mem = psutil.virtual_memory()
print("memory fields:", list(mem._fields)[:4], "| total > 0:", mem.total > 0)
print("this process:", psutil.Process().name())
print("root disk percent is a number:", isinstance(psutil.disk_usage("/").percent, float))
$ python3 example_11.py CPUs: True memory fields: ['total', 'available', 'percent', 'used'] | total > 0: True this process: python3 root disk percent is a number: True
Counters, gauges, and histograms in a registry, written in the Prometheus text format.
# example_12.py
from prometheus_client import CollectorRegistry, Counter, Gauge, Histogram, disable_created_metrics, generate_latest
disable_created_metrics()
reg = CollectorRegistry()
checks = Counter("deploy_checks_total", "Checks run", ["result"], registry=reg)
replicas = Gauge("deploy_ready_replicas", "Ready replicas", ["deployment"], registry=reg)
duration = Histogram("deploy_check_seconds", "Check duration", buckets=[0.5, 1, 5], registry=reg)
checks.labels("ok").inc(11); checks.labels("failed").inc()
replicas.labels("checkout").set(3)
duration.observe(0.7)
for line in generate_latest(reg).decode().splitlines():
if not line.startswith("#") and ("bucket" not in line or 'le="1.0"' in line):
print(line)
$ python3 example_12.py
deploy_checks_total{result="ok"} 11.0
deploy_checks_total{result="failed"} 1.0
deploy_ready_replicas{deployment="checkout"} 3.0
deploy_check_seconds_bucket{le="1.0"} 1.0
deploy_check_seconds_count 1.0
deploy_check_seconds_sum 0.7
The client's model classes build exactly the YAML you would apply; sanitize_for_serialization shows it.
# example_13.py
import json
from kubernetes import client
container = client.V1Container(name="checkout", image="registry.example.com/checkout:1.4.2",
resources=client.V1ResourceRequirements(requests={"cpu": "250m", "memory": "256Mi"}))
dep = client.V1Deployment(
api_version="apps/v1", kind="Deployment", metadata=client.V1ObjectMeta(name="checkout"),
spec=client.V1DeploymentSpec(replicas=3, selector=client.V1LabelSelector(match_labels={"app": "checkout"}),
template=client.V1PodTemplateSpec(metadata=client.V1ObjectMeta(labels={"app": "checkout"}),
spec=client.V1PodSpec(containers=[container]))))
body = client.ApiClient().sanitize_for_serialization(dep)
print(json.dumps(body["spec"]["template"]["spec"]["containers"][0], sort_keys=True))
print("apply with: client.AppsV1Api().create_namespaced_deployment('shop', body)")
$ python3 example_13.py
{"image": "registry.example.com/checkout:1.4.2", "name": "checkout", "resources": {"requests": {"cpu": "250m", "memory": "256Mi"}}}
apply with: client.AppsV1Api().create_namespaced_deployment('shop', body)
paramiko is SSH in Python. Generate keys, and never auto-accept unknown host keys in automation.
# example_14.py
import paramiko
key = paramiko.RSAKey.generate(2048)
print(key.get_name(), key.get_bits(), "bits")
ssh = paramiko.SSHClient()
ssh.load_system_host_keys()
ssh.set_missing_host_key_policy(paramiko.RejectPolicy())
print("unknown hosts are rejected:", isinstance(ssh._policy, paramiko.RejectPolicy))
print("connect with: ssh.connect('web-01', username='deploy', key_filename='~/.ssh/id_ed25519', timeout=10)")
$ python3 example_14.py
ssh-rsa 2048 bits
unknown hosts are rejected: True
connect with: ssh.connect('web-01', username='deploy', key_filename='~/.ssh/id_ed25519', timeout=10)
Write each one from scratch before you open the solution. The output under each solution is what it really prints.
Start a local server that answers /version with JSON, call it with requests and a timeout, and print the status code and the version.
# task_1.py
import json, threading
from http.server import BaseHTTPRequestHandler, HTTPServer
import requests
class H(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200); self.send_header("Content-Type", "application/json"); self.end_headers()
self.wfile.write(json.dumps({"version": "2.1.0"}).encode())
def log_message(self, *args):
pass
server = HTTPServer(("127.0.0.1", 0), H)
threading.Thread(target=server.serve_forever, daemon=True).start()
r = requests.get(f"http://127.0.0.1:{server.server_port}/version", timeout=(3, 10))
print(r.status_code, r.json()["version"])
server.shutdown()$ python3 task_1.py 200 2.1.0
Render a jinja2 template that lists three hosts, one per line, as - host.
# task_2.py
from jinja2 import Environment, StrictUndefined
tpl = Environment(undefined=StrictUndefined).from_string("{% for h in hosts %}- {{ h }}\n{% endfor %}")
print(tpl.render(hosts=["web-1", "web-2", "db-1"]).rstrip())$ python3 task_2.py - web-1 - web-2 - db-1
Parse a YAML string with two documents using safe_load_all and print each document's kind.
# task_3.py import yaml text = "kind: ConfigMap\n---\nkind: Secret\n" print([d["kind"] for d in yaml.safe_load_all(text)])
$ python3 task_3.py ['ConfigMap', 'Secret']
Use tenacity to retry a function that fails twice and succeeds on the third try, printing the attempt number each time.
# task_4.py
from tenacity import retry, stop_after_attempt, wait_none
n = 0
@retry(stop=stop_after_attempt(5), wait=wait_none())
def job():
global n
n += 1
print("attempt", n)
if n < 3:
raise RuntimeError("not yet")
return "done"
print(job())$ python3 task_4.py attempt 1 attempt 2 attempt 3 done
You need Python 3 on Linux, macOS, or WSL on Windows (run wsl --install in PowerShell once); check with python3 --version. The terminal is only for setting Python up and running it and its tools: the Python itself goes in .py files, in part 2 and in "Python, example by example" above.
Type each one, read what it prints, and compare it with the note above it.
Make a folder for this lesson with its own virtual environment, and install what the lesson needs into it. Every command after this runs inside it; deactivate leaves it, and source .venv/bin/activate brings it back.
mkdir -p ~/labs/python-packages-for-devops && cd ~/labs/python-packages-for-devops python3 -m venv .venv || echo "No venv module: on Debian or Ubuntu run sudo apt install -y python3-venv and try again" source .venv/bin/activate && python --version pip install requests httpx tenacity pyyaml python-dotenv jinja2 click rich
See what is installed, and pin it.
pip list --format=freeze | grep -iE "^(requests|httpx|tenacity|pyyaml|click|rich)==" pip freeze > requirements.txt && wc -l requirements.txt
Install names and import names differ: ask pip which files a package put in place.
pip show -f pyyaml | grep -E "^Name|yaml/__init__" pip show -f python-dotenv | grep -E "^Name|dotenv/__init__"
Check what a package needs, and what needs it, before you add or remove it.
pip show requests | grep -E "^(Requires|Required-by)"
Audit the pinned packages for known vulnerabilities.
pip install -q pip-audit && pip-audit -r requirements.txt
A timeout in action: call an address that never answers, and see the error after 2 seconds instead of waiting forever.
python -c "import requests; requests.get('http://10.255.255.1', timeout=2)" 2>&1 | tail -n 1deps_lint.pyThis program checks automation code for the two failures in this lesson, using only the standard library: requirements that are not pinned, and HTTP calls without a timeout, plus yaml.load without a safe loader. Save it as deps_lint.py in the lesson folder, then run it.
# deps_lint.py
import re
requirements = """\
requests==2.32.5
kubernetes
pyyaml>=6
click~=8.3
tenacity==9.1.2 --hash=sha256:abc123
"""
code = '''\
r = requests.get(url)
r = requests.get(url, timeout=(3, 10))
s.post(api, json=body)
data = yaml.load(open("targets.yaml"))
data = yaml.safe_load(open("targets.yaml"))
'''
for line in requirements.splitlines():
name = re.split(r"[=<>~ ]", line, maxsplit=1)[0]
if "==" in line:
kind = "pinned" + (" with hash" if "--hash" in line else "")
elif "~=" in line:
kind = "compatible releases only (minor updates arrive by themselves)"
elif re.search(r"[<>]", line):
kind = "RANGE: any future release can arrive"
else:
kind = "UNPINNED: whatever was released last"
print(f"{name:<11} {kind}")
for n, line in enumerate(code.splitlines(), 1):
if re.search(r"\b(requests|s|session|client)\.(get|post|put|delete|patch)\(", line) and "timeout" not in line:
print(f"line {n}: HTTP call without a timeout -> {line.strip()}")
if re.search(r"\byaml\.load\(", line) and "Loader" not in line:
print(f"line {n}: yaml.load without a safe loader -> use yaml.safe_load")
Run it, and you should see this output:
$ python3 deps_lint.py requests pinned kubernetes UNPINNED: whatever was released last pyyaml RANGE: any future release can arrive click compatible releases only (minor updates arrive by themselves) tenacity pinned with hash line 1: HTTP call without a timeout -> r = requests.get(url) line 3: HTTP call without a timeout -> s.post(api, json=body) line 4: yaml.load without a safe loader -> use yaml.safe_load
A program you keep needs a test, so you know at once when a change alters what it does. This one uses unittest, which comes with Python: it runs deps_lint.py and checks that it exits cleanly and prints exactly the output above. Save it as test_deps_lint.py next to the program.
# test_deps_lint.py: checks that deps_lint.py still prints exactly what this lesson shows.
# Run it with: python3 -m unittest -v test_deps_lint
import subprocess
import sys
import unittest
from pathlib import Path
HERE = Path(__file__).resolve().parent
EXPECTED = r"""
requests pinned
kubernetes UNPINNED: whatever was released last
pyyaml RANGE: any future release can arrive
click compatible releases only (minor updates arrive by themselves)
tenacity pinned with hash
line 1: HTTP call without a timeout -> r = requests.get(url)
line 3: HTTP call without a timeout -> s.post(api, json=body)
line 4: yaml.load without a safe loader -> use yaml.safe_load
""".strip("\n")
class TestDepsLint(unittest.TestCase):
def run_program(self):
return subprocess.run([sys.executable, str(HERE / "deps_lint.py")], cwd=HERE,
capture_output=True, text=True, timeout=60)
def test_exits_cleanly(self):
result = self.run_program()
self.assertEqual(result.returncode, 0, result.stderr)
def test_prints_the_expected_output(self):
result = self.run_program()
self.assertEqual(result.stdout.rstrip(), EXPECTED)
if __name__ == "__main__":
unittest.main()
Run it: you should see both tests end in ok, then OK. Then change one value in the program, run it again, and read how the failure shows you the difference. pytest runs the same file unchanged, if you prefer it.
python3 -m unittest -v test_deps_lint
New to a feature used above? These W3Schools pages explain each one from zero, with examples you can run in the browser.
grep, wc, tail, mkdir, echo, cd, Pipes, Redirection, If...Else.Build a CLI that checks every Kubernetes Deployment in a namespace: rollout finished, all replicas ready, image tag matches the release manifest, and reports to Prometheus.
Which packages do you need, and how are they pinned? How does the tool authenticate inside and outside a cluster? What timeouts and retries apply to each call? What exit codes and metrics does it produce?
Say 60 Deployments, a 2-minute budget, and a CI job that must fail on any mismatch.
kubernetes (load_incluster_config, falling back to load_kube_config), pyyaml for the manifest, click for the CLI, rich for a table when interactive, prometheus_client pushing to a Pushgateway; a lock file with hashes; request timeouts on the Kubernetes client; tenacity on 429 and 5xx only; exit 1 on any mismatch, 2 on errors reaching the API.
The official client is complete and heavy; calling the API with requests and a service-account token is lighter and leaves you to handle auth and paging. A lock file is repeatable and needs an update process.
Each row is one way this system went wrong in the diagram's scenarios. The hop number is where to look first.
| Scenario | Where | Effect | What goes wrong |
|---|---|---|---|
| Unpinned dependency | Hop 2: Pin | Breaks | requirements.txt says "kubernetes" with no version. A new major version renamed a method the checker calls; CI installs it at 07:00 and every deployment check fails with AttributeError. |
| No timeout | Hop 3: HTTP | Breaks | requests.get(health_url) has no timeout. A load balancer in a bad state accepts the TCP connection and never sends a response; the check waits until the CI job limit kills it three hours later, holding the deploy lock all the time. |
The official documentation and standards behind this lesson. Versions and defaults change; when a command or field here differs from them, trust the official page.
Last updated . Next review due by November 2027. Found something out of date? Tell me.