Skip to content

Python automation scripts ​

Encyclopedia home · Search machine-readable catalog

CF-076 ​

Dependency-free fixture health service

Copy to health.py.

python
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

class Health(BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path != "/healthz":
            self.send_error(404)
            return
        payload = b'{"status":"ok"}'
        self.send_response(200)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(payload)))
        self.end_headers()
        self.wfile.write(payload)

if __name__ == "__main__":
    ThreadingHTTPServer(("0.0.0.0", 8000), Health).serve_forever()

Verification. Use only as an isolated fixture service. Assert health and 404 behavior.

Validation runtime-tested. Official reference

CF-077 ​

Parse release manifest

Copy to scripts/manifest.py.

python
import json, re, sys
from pathlib import Path

manifest = json.loads(Path(sys.argv[1]).read_text())
if not re.fullmatch(r"[0-9a-f]{40}", manifest.get("source_commit", "")):
    raise SystemExit("Invalid source commit")
print(manifest["source_commit"])

Verification. Pass a JSON manifest. Empty or malformed commits should fail.

Validation syntax-validated. Official reference

CF-078 ​

Build a line-delimited evidence record

Copy to scripts/evidence.py.

python
import json, os
from datetime import datetime, timezone

print(json.dumps({"commit": os.environ["GITHUB_SHA"], "utc": datetime.now(timezone.utc).isoformat()}))

Verification. Supply GITHUB_SHA and append output to a per-run evidence file.

Validation syntax-validated. Official reference

CF-079 ​

Calculate p95 latency

Copy to scripts/p95.py.

python
import math, sys

values = sorted(float(line) for line in sys.stdin if line.strip())
if not values or not all(math.isfinite(x) and x >= 0 for x in values):
    raise SystemExit("Invalid or missing samples")
print(values[math.ceil(0.95 * len(values)) - 1])

Verification. Input is one nonnegative latency per line. Method is nearest rank and units follow input.

Validation syntax-validated. Official reference

CF-080 ​

Verify JSON health payload

Copy to scripts/probe.py.

python
import json, sys
from urllib.request import urlopen

with urlopen(sys.argv[1], timeout=5) as response:
    if json.load(response).get("status") != "ok":
        raise SystemExit("Unhealthy payload")

Verification. Pass an approved local fixture URL. Network or parse failures fail closed.

Validation syntax-validated. Official reference

CF-081 ​

Compare benchmark thresholds

Copy to scripts/compare.py.

python
import json, sys
from pathlib import Path

base, candidate = (json.loads(Path(path).read_text()) for path in sys.argv[1:3])
if base["p99_ttft_ms"] <= 0 or candidate["p99_ttft_ms"] > base["p99_ttft_ms"] * 1.15:
    raise SystemExit("Latency threshold failed")
print("latency gate passed")

Verification. Verify test cases on both sides of 15 percent tolerance.

Validation syntax-validated. Official reference

CF-082 ​

Generate safe service names

Copy to scripts/changed-services.py.

python
import re, sys

services = set()
for path in sys.stdin:
    parts = path.rstrip("\n").split("/")
    if len(parts) >= 3 and parts[0] == "services" and re.fullmatch(r"[a-z][a-z0-9-]+", parts[1]):
        services.add(parts[1])
print("\n".join(sorted(services)))

Verification. Pass changed file paths. Treat root/global changes separately.

Validation syntax-validated. Official reference

CF-083 ​

Compare two artifact hashes

Copy to scripts/same-file.py.

python
import hashlib, sys

def digest(path):
    with open(path, "rb") as artifact:
        return hashlib.file_digest(artifact, "sha256").hexdigest()

if digest(sys.argv[1]) != digest(sys.argv[2]):
    raise SystemExit("Artifacts differ")

Verification. Requires Python 3.11 or later. Use a changed byte to prove rejection.

Validation syntax-validated. Official reference

CF-084 ​

Summarize JUnit suite counts

Copy to scripts/test-report.py.

python
import sys
from xml.etree.ElementTree import parse

root = parse(sys.argv[1]).getroot()
suites = [root] if root.tag == "testsuite" else root.findall("testsuite")
tests = sum(int(suite.attrib.get("tests", 0)) for suite in suites)
failures = sum(int(suite.attrib.get("failures", 0)) for suite in suites)
print(f"{tests} tests, {failures} failures")
raise SystemExit(0 if tests and failures == 0 else 1)

Verification. Parse a bounded trusted test report, and check the producer's exit status separately for errors.

Validation syntax-validated. Official reference

CF-085 ​

Build test failure fixture CLI

Copy to scripts/fixture.py.

python
import argparse

parser = argparse.ArgumentParser()
parser.add_argument("--fail", action="store_true")
args = parser.parse_args()
if args.fail:
    raise SystemExit("intentional test failure")
print("fixture passed")

Verification. Use to test CI gates with the same reviewed command in pass and fail modes.

Validation syntax-validated. Official reference