#!/usr/bin/env python3 """Framework-neutral manual environments and automated test execution.""" import argparse import getpass import hashlib import json import os import re import shutil import socket import stat import subprocess import sys import tempfile import time import urllib.error import urllib.request from pathlib import Path from target import TargetError, resolve class ToolkitError(Exception): def __init__(self, message, code=3, category="configuration"): super().__init__(message) self.code = code self.category = category def config_for(tree): path = tree / ".bortstack/testing.json" if not path.is_file(): raise ToolkitError(f"testing unavailable: missing {path}") try: data = json.loads(path.read_text(encoding="utf-8")) except (OSError, json.JSONDecodeError) as exc: raise ToolkitError(f"invalid configuration {path}: {exc}") from exc if not isinstance(data, dict) or data.get("version") != 1: raise ToolkitError(f"invalid configuration {path}: expected version 1") return data def command(value, label): if not isinstance(value, list) or not value or any(not isinstance(x, str) or not x for x in value): raise ToolkitError(f"{label} must be a nonempty argument array") return value def local_path(tree, value): if not isinstance(value, str) or not value: raise ToolkitError("configured path must be a nonempty string") path = (tree / value).resolve() if not path.is_relative_to(tree.resolve()): raise ToolkitError(f"configured path leaves selected worktree: {value}", 4, "unsafe") return path def run(cmd, cwd, env=None, timeout=None): try: return subprocess.run(cmd, cwd=cwd, env=env, timeout=timeout, check=False).returncode except (OSError, subprocess.TimeoutExpired) as exc: raise ToolkitError(f"infrastructure unavailable for {cmd[0]}: {exc}", 3, "infrastructure") from exc def read_credential_file(path): if not path.is_file(): return {} if os.name == "posix" and stat.S_IMODE(path.stat().st_mode) & 0o077: raise ToolkitError(f"credential file must be user-only (chmod 600): {path}", 4, "unsafe") values = {} for line in path.read_text(encoding="utf-8").splitlines(): if not line.strip() or line.lstrip().startswith("#"): continue match = re.fullmatch(r"(BORTSTACK_TEST_EMAIL|BORTSTACK_TEST_PASSWORD)=([^\r\n]*)", line) if not match: raise ToolkitError(f"invalid credential entry in {path}") values[match.group(1)] = match.group(2) return values def credentials(project, use_defaults): if not isinstance(project, str) or not re.fullmatch(r"[a-zA-Z0-9][a-zA-Z0-9_-]*", project): raise ToolkitError("manual project name must be a simple identifier") base = Path(os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config")) / "bortstack" values = read_credential_file(base / "testing.env") values.update(read_credential_file(base / project / "testing.env")) complete = bool(values.get("BORTSTACK_TEST_EMAIL") and values.get("BORTSTACK_TEST_PASSWORD")) if use_defaults: if not complete: raise ToolkitError("configured test credentials are missing", 3) return values if not sys.stdin.isatty(): raise ToolkitError("authentication requires interactive selection or --use-default-credentials", 4, "cancelled") if complete: print(f"Local test account: {values['BORTSTACK_TEST_EMAIL']} / [configured]") answer = input("Use configured credentials? [Y/n] ").strip().lower() if answer in ("", "y", "yes"): return values if answer not in ("n", "no"): raise ToolkitError("credential selection cancelled", 4, "cancelled") email = input("Local test email (blank to cancel): ").strip() if not email: raise ToolkitError("credential selection cancelled", 4, "cancelled") password = getpass.getpass("Local test password: ") if not password: raise ToolkitError("credential selection cancelled", 4, "cancelled") return {"BORTSTACK_TEST_EMAIL": email, "BORTSTACK_TEST_PASSWORD": password} def port_open(port): try: with socket.socket() as sock: sock.settimeout(0.2) return sock.connect_ex(("127.0.0.1", int(port))) == 0 except PermissionError: # Some restricted Linux development environments block socket creation. for table in (Path("/proc/net/tcp"), Path("/proc/net/tcp6")): if table.is_file(): for line in table.read_text().splitlines()[1:]: fields = line.split() if len(fields) > 3 and fields[3] == "0A" and int(fields[1].split(":")[1], 16) == int(port): return True return False def compose_command(manual, tree, branch): file = local_path(tree, manual.get("file", "docker-compose.yml")) if not file.is_file(): raise ToolkitError(f"missing Compose file: {file}") slug = re.sub(r"[^a-z0-9]+", "-", tree.name.lower()).strip("-") or "app" suffix = hashlib.sha256(f"{tree.resolve()}:{branch}".encode()).hexdigest()[:8] project = f"bortstack-{slug[:24]}-{suffix}" return ["docker", "compose", "--project-name", project, "--file", str(file)] def manual(mode, tree, branch, config, args): data = config.get("manual") if not isinstance(data, dict): raise ToolkitError("manual environment is unconfigured") if data.get("environment") != "development": raise ToolkitError("manual environment must explicitly be development", 4, "unsafe") if data.get("kind") != "compose": raise ToolkitError("manual kind must be compose; project adapters own other runtimes") if not shutil.which("docker") or run(["docker", "info", "--format", "{{.ServerVersion}}"], tree) != 0: raise ToolkitError("Docker daemon is unavailable", 3, "infrastructure") base = compose_command(data, tree, branch) ports = data.get("ports", {}) if not isinstance(ports, dict) or any(not isinstance(key, str) or not re.fullmatch(r"[A-Z][A-Z0-9_]*", key) or not isinstance(value, int) or value < 1 or value > 65535 for key, value in ports.items()): raise ToolkitError("manual ports must map environment names to valid port numbers") attempts = data.get("readiness_attempts", 30) if not isinstance(attempts, int) or not 1 <= attempts <= 300: raise ToolkitError("readiness_attempts must be an integer from 1 to 300") env = os.environ.copy() if not isinstance(data.get("readiness", []), list) or not isinstance(data.get("urls", []), list): raise ToolkitError("manual readiness and urls must be arrays") for url in data.get("readiness", []): if not isinstance(url, str) or not url.startswith("http://127.0.0.1:"): raise ToolkitError("readiness URLs must use local loopback HTTP", 4, "unsafe") for url in data.get("urls", []): if not isinstance(url, str) or not url.startswith("http://127.0.0.1:"): raise ToolkitError("display URLs must use local loopback HTTP", 4, "unsafe") env.update({key: str(value) for key, value in ports.items()}) if data.get("env_file"): env["APP_ENV_FILE"] = str(local_path(tree, data["env_file"])) env["BORTSTACK_COMPOSE_PROJECT"] = base[3] env["BORTSTACK_COMPOSE_FILE"] = base[5] running = subprocess.run(base + ["ps", "-q"], cwd=tree, env=env, capture_output=True, text=True) if running.returncode: raise ToolkitError("could not inspect selected Compose environment", 3, "infrastructure") active = bool(running.stdout.strip()) if args.action == "status": print("status: running" if active else "status: stopped") return 0 if args.action == "stop": if not active: print("status: already stopped") return 0 code = run(base + ["stop"], tree, env) print(f"status: {'stopped' if code == 0 else 'stop failed'}") return code if active: print("status: already running") for url in data.get("urls", []): print(f"url: {url}") return 0 occupied = [value for value in ports.values() if port_open(value)] if occupied: raise ToolkitError(f"ports already occupied: {', '.join(map(str, occupied))}; no other environment was stopped", 4, "unsafe") auth = data.get("authentication", {}) if not isinstance(auth, dict): raise ToolkitError("authentication configuration must be an object") selected = None if auth.get("required"): if not auth.get("provision"): raise ToolkitError("authentication provisioning is unavailable; configure a local hook before startup") selected = credentials(data.get("project", tree.name), args.use_default_credentials) code = run(base + ["up", "--detach", "--build"], tree, env) if code: print("status: startup failed; inspect selected Compose project", file=sys.stderr) return code for url in data.get("readiness", []): for _ in range(attempts): try: urllib.request.urlopen(url, timeout=1).close() break except (urllib.error.URLError, TimeoutError): time.sleep(1) else: raise ToolkitError(f"service not ready: {url}", 3, "infrastructure") if selected: provision = command(auth["provision"], "authentication provision") with tempfile.TemporaryDirectory(prefix="bortstack-credentials-") as temp: secret = Path(temp) / "credentials.json" secret.write_text(json.dumps(selected), encoding="utf-8") secret.chmod(0o600) hook_env = env.copy() hook_env["BORTSTACK_CREDENTIALS_FILE"] = str(secret) code = run(provision, tree, hook_env) if code: raise ToolkitError(f"local account provisioning failed (exit {code})", code, "infrastructure") print(f"local test account: {selected['BORTSTACK_TEST_EMAIL']} (password hidden)") for url in data.get("urls", []): print(f"url: {url}") print("status: running; use testtask.sh --status or --stop for this worktree") return 0 def suites(config, flags): automation = config.get("automated") if not isinstance(automation, dict): raise ToolkitError("automated suites are unconfigured") configured = automation.get("suites", {}) if not isinstance(configured, dict): raise ToolkitError("automated.suites must be an object") chosen = [] if flags.all: chosen = list(configured) if automation.get("act"): chosen.append("act") elif flags.unit or flags.integration or flags.act: chosen = [name for name in ("unit", "integration", "act") if getattr(flags, name)] else: chosen = automation.get("default", []) if not isinstance(chosen, list) or not chosen: raise ToolkitError("no default or selected test suites configured") return automation, configured, list(dict.fromkeys(chosen)) def run_act(tree, entry): if not isinstance(entry, dict) or not isinstance(entry.get("workflow"), str) or not isinstance(entry.get("job"), str): raise ToolkitError("act allowlist entries need workflow and job") workflow = local_path(tree, entry["workflow"]) if not workflow.is_file() or not workflow.is_relative_to(tree / ".github/workflows"): raise ToolkitError(f"act workflow is missing or outside .github/workflows: {workflow}", 4, "unsafe") content = workflow.read_text(encoding="utf-8") if re.search(r"(?im)^\s*(deploy|publish|release|push|production|staging):|\b(secrets\.|docker\s+push|git\s+push|gh\s+release|npm\s+publish)\b", content): raise ToolkitError(f"act workflow has unsafe operations: {workflow.name}", 4, "unsafe") if not shutil.which("act"): raise ToolkitError("act executable is unavailable", 3, "infrastructure") if not shutil.which("docker") or run(["docker", "info", "--format", "{{.ServerVersion}}"], tree) != 0: raise ToolkitError("Docker runtime is unavailable for act", 3, "infrastructure") cmd = ["act", "--workflows", str(workflow), "--job", entry["job"], "--eventpath", os.devnull] print(f"command: act --workflows {workflow} --job {entry['job']} [no secrets]", flush=True) return run(cmd, tree) def automated(tree, config, flags): automation, configured, chosen = suites(config, flags) print(f"suites: {', '.join(chosen)}", flush=True) results = [] for name in chosen: if name == "act": entries = automation.get("act", []) if not isinstance(entries, list) or not entries: raise ToolkitError("act suite has no approved workflows", 4, "unsafe") for entry in entries: code = run_act(tree, entry) results.append((f"act:{entry['job']}", code, classify(code))) else: suite = configured.get(name) if not isinstance(suite, dict): raise ToolkitError(f"requested suite {name} is unconfigured") cmd = command(suite.get("command"), f"suite {name}") cwd = local_path(tree, suite.get("cwd", ".")) if not cwd.is_dir(): raise ToolkitError(f"suite {name} working directory is missing: {cwd}") timeout = suite.get("timeout_seconds") if timeout is not None and (not isinstance(timeout, int) or not 1 <= timeout <= 86400): raise ToolkitError(f"suite {name} timeout_seconds must be 1 to 86400") print(f"command ({name}): {cmd!r} in {cwd}", flush=True) code = run(cmd, cwd, timeout=timeout) results.append((name, code, classify(code))) print(f"result: {results[-1][0]} {results[-1][2]} (exit {results[-1][1]})", flush=True) final = next((code for _, code, _ in results if code), 0) print(f"total: {len(results)} executed, {'passed' if final == 0 else 'failed'}; exit {final}") return final def classify(code): if code == 0: return "passed" if code == 3 or code == 127: return "infrastructure unavailable" if code == 4: return "unsafe or disallowed" if code in (130, 143): return "cancelled" return "test failure" def main(argv): mode = argv.pop(0) parser = argparse.ArgumentParser(prog=f"{mode} testing") parser.add_argument("target", nargs="?") if mode == "manual": group = parser.add_mutually_exclusive_group() group.add_argument("--start", dest="action", action="store_const", const="start") group.add_argument("--status", dest="action", action="store_const", const="status") group.add_argument("--stop", dest="action", action="store_const", const="stop") parser.add_argument("--use-default-credentials", action="store_true") else: for name in ("unit", "integration", "act", "all"): parser.add_argument(f"--{name}", action="store_true") args = parser.parse_args(argv) try: root, branch, tree = resolve(Path(__file__).resolve(), args.target) print(f"repository: {root}\nbranch: {branch}\nworktree: {tree}", flush=True) config = config_for(tree) return manual(mode, tree, branch, config, args) if mode == "manual" else automated(tree, config, args) except (KeyboardInterrupt, EOFError): print("testing: cancelled", file=sys.stderr) return 130 except TargetError as exc: print(f"testing: target error: {exc}", file=sys.stderr) return 2 except ToolkitError as exc: print(f"testing: {exc.category}: {exc}; exit {exc.code}", file=sys.stderr) return exc.code if __name__ == "__main__": raise SystemExit(main(sys.argv[1:]))