Files
bortstack-forge/tests/test_testing_toolkit.py
T

210 lines
12 KiB
Python

"""Disposable repository checks for the generated testing toolkit."""
import json
import importlib.util
import argparse
import os
import shutil
import subprocess
import sys
import tempfile
import unittest
from pathlib import Path
from unittest.mock import patch
SOURCE = Path(__file__).resolve().parents[1] / "toolkits/testing/scripts"
def run(*args, cwd=None, env=None):
return subprocess.run(args, cwd=cwd, env=env, capture_output=True, text=True)
class ToolkitTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory(prefix="testing toolkit ")
self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name) / "repo with spaces"
self.root.mkdir()
(self.root / "scripts").mkdir()
(self.root / "docs").mkdir()
(self.root / ".bortstack").mkdir()
for name in ("testtask.sh", "testrunner.sh", "toolkit.py", "target.py"):
shutil.copy2(SOURCE / name, self.root / "scripts" / name)
(self.root / "docs/TASKS.md").write_text("## PI-042 — Current\nBranch/worktree: `feature/homepage`\n\n## TASK-001 — Legacy\nBranch/worktree: `feature-legacy`\n")
(self.root / ".bortstack/testing.json").write_text(json.dumps({
"version": 1,
"manual": {"kind": "compose", "environment": "development", "file": "compose.yml", "project": "fixture", "ports": {"TEST_PORT": 59991}, "urls": ["http://127.0.0.1:59991/"]},
"automated": {"default": ["unit"], "suites": {
"unit": {"command": ["python3", "scripts/check.py", "unit"]},
"integration": {"command": ["python3", "scripts/check.py", "integration"]}}, "act": []}}))
(self.root / "compose.yml").write_text("services: {}\n")
(self.root / "scripts/check.py").write_text("import pathlib, sys\npathlib.Path('ran-' + sys.argv[1]).write_text(pathlib.Path.cwd().name)\nsys.exit(int(pathlib.Path('failure').read_text()) if pathlib.Path('failure').exists() else 0)\n")
run("git", "init", "-q", str(self.root))
run("git", "add", ".", cwd=self.root)
run("git", "-c", "user.name=Test", "-c", "user.email=test@example.org", "commit", "-qm", "base", cwd=self.root)
run("git", "branch", "codex", cwd=self.root)
run("git", "branch", "feature/homepage", cwd=self.root)
run("git", "branch", "feature-legacy", cwd=self.root)
def runner(self, *args, cwd=None, env=None):
return run(str(self.root / "scripts/testrunner.sh"), *args, cwd=cwd or self.root, env=env)
def test_default_branch_task_ids_and_failures(self):
result = self.runner()
self.assertEqual(result.returncode, 0, result.stderr)
self.assertIn("branch: " + run("git", "branch", "--show-current", cwd=self.root).stdout.strip(), result.stdout)
self.assertTrue((self.root / "ran-unit").exists())
self.assertIn("0 existing worktrees", self.runner("PI-042").stderr)
tree = Path(self.temp.name) / "task tree"
run("git", "worktree", "add", "-q", str(tree), "feature/homepage", cwd=self.root)
result = self.runner("PI-042", "--unit", "--integration")
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual((tree / "ran-unit").read_text(), tree.name)
self.assertEqual((tree / "ran-integration").read_text(), tree.name)
self.assertEqual(self.runner("feature/homepage", "--all").returncode, 0)
self.assertEqual(self.runner("unknown").returncode, 2)
self.assertEqual(self.runner("--act").returncode, 4)
(tree / "failure").write_text("7")
result = self.runner("PI-042", "--unit")
self.assertEqual(result.returncode, 7)
self.assertIn("test failure", result.stdout)
legacy = Path(self.temp.name) / "legacy"
run("git", "worktree", "add", "-q", str(legacy), "feature-legacy", cwd=self.root)
self.assertEqual(self.runner("TASK-001").returncode, 0)
def test_no_target_uses_invoking_worktree_and_detached_fails(self):
tree = Path(self.temp.name) / "codex tree"
run("git", "worktree", "add", "-q", str(tree), "codex", cwd=self.root)
result = self.runner(cwd=tree)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertIn("branch: codex", result.stdout)
self.assertEqual(self.runner("codex").returncode, 0)
detached = Path(self.temp.name) / "detached"
run("git", "worktree", "add", "-q", "--detach", str(detached), cwd=self.root)
self.assertIn("detached HEAD", self.runner(cwd=detached).stderr)
run("git", "branch", "PI-042", cwd=self.root)
self.assertIn("ambiguous identifier", self.runner("PI-042").stderr)
def test_configuration_and_act_safety(self):
config = self.root / ".bortstack/testing.json"
value = json.loads(config.read_text())
value["automated"]["act"] = [{"workflow": ".github/workflows/ci.yml", "job": "unit"}]
config.write_text(json.dumps(value))
workflow = self.root / ".github/workflows/ci.yml"
workflow.parent.mkdir(parents=True)
workflow.write_text("name: CI\non: push\njobs:\n unit:\n runs-on: ubuntu-latest\n steps:\n - run: git push origin main\n")
result = self.runner("--act")
self.assertEqual(result.returncode, 4)
self.assertIn("unsafe", result.stderr)
workflow.write_text("name: Local CI\non: push\njobs:\n unit:\n runs-on: ubuntu-latest\n steps:\n - run: echo safe\n")
bin_dir = Path(self.temp.name) / "bin"
bin_dir.mkdir()
for name, content in {
"docker": "#!/bin/sh\nexit 0\n",
"act": "#!/bin/sh\nprintf '%s\\n' \"$*\" >\"$ACT_LOG\"\nexit 0\n",
}.items():
path = bin_dir / name
path.write_text(content)
path.chmod(0o755)
env = os.environ.copy()
env["PATH"] = str(bin_dir) + os.pathsep + env["PATH"]
env["ACT_LOG"] = str(Path(self.temp.name) / "act.log")
result = self.runner("--act", env=env)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertIn("--job unit", Path(env["ACT_LOG"]).read_text())
self.assertEqual(self.runner("--all", env=env).returncode, 0)
config.write_text("not json")
self.assertIn("invalid configuration", self.runner().stderr)
config.unlink()
self.assertIn("testing unavailable", self.runner().stderr)
def test_manual_port_and_credentials(self):
bin_dir = Path(self.temp.name) / "bin"
bin_dir.mkdir()
docker = bin_dir / "docker"
docker.write_text("#!/bin/sh\ncase \"$*\" in *'info'*) exit 0;; *'ps -q'*) [ \"${DOCKER_ACTIVE:-0}\" = 1 ] && echo container; exit 0;; *'up --detach --build'*) echo up >>\"$DOCKER_LOG\";; *'stop'*) echo stop >>\"$DOCKER_LOG\";; esac\n")
docker.chmod(0o755)
env = os.environ.copy()
env["PATH"] = str(bin_dir) + os.pathsep + env["PATH"]
env["DOCKER_LOG"] = str(Path(self.temp.name) / "docker.log")
result = run(str(self.root / "scripts/testtask.sh"), "--start", cwd=self.root, env=env)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertIn("url: http://127.0.0.1:59991/", result.stdout)
self.assertIn("up", Path(env["DOCKER_LOG"]).read_text())
auth = json.loads((self.root / ".bortstack/testing.json").read_text())
auth["manual"]["authentication"] = {"required": True, "provision": ["python3", "scripts/check.py", "unit"]}
(self.root / ".bortstack/testing.json").write_text(json.dumps(auth))
result = run(str(self.root / "scripts/testtask.sh"), "--start", cwd=self.root, env=env)
self.assertEqual(result.returncode, 4)
self.assertIn("selection", result.stderr)
config_dir = Path(self.temp.name) / "private config" / "bortstack"
config_dir.mkdir(parents=True)
secret = config_dir / "testing.env"
secret.write_text("BORTSTACK_TEST_EMAIL=test@localhost\nBORTSTACK_TEST_PASSWORD=private-local-password\n")
secret.chmod(0o600)
env["XDG_CONFIG_HOME"] = str(config_dir.parent)
result = run(str(self.root / "scripts/testtask.sh"), "--use-default-credentials", cwd=self.root, env=env)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertNotIn("private-local-password", result.stdout + result.stderr)
secret.chmod(0o644)
result = run(str(self.root / "scripts/testtask.sh"), "--use-default-credentials", cwd=self.root, env=env)
self.assertEqual(result.returncode, 4)
self.assertIn("user-only", result.stderr)
env["DOCKER_ACTIVE"] = "1"
status = run(str(self.root / "scripts/testtask.sh"), "--status", cwd=self.root, env=env)
self.assertIn("status: running", status.stdout)
self.assertEqual(run(str(self.root / "scripts/testtask.sh"), "--stop", cwd=self.root, env=env).returncode, 0)
self.assertIn("stop", Path(env["DOCKER_LOG"]).read_text())
def test_interactive_custom_credentials_are_ephemeral(self):
sys.path.insert(0, str(SOURCE))
self.addCleanup(lambda: sys.path.remove(str(SOURCE)))
spec = importlib.util.spec_from_file_location("forge_toolkit_test", SOURCE / "toolkit.py")
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
private = Path(self.temp.name) / "config"
private.mkdir()
with patch.dict(os.environ, {"XDG_CONFIG_HOME": str(private)}), \
patch.object(sys.stdin, "isatty", return_value=True), \
patch("builtins.input", return_value="custom@localhost"), \
patch.object(module.getpass, "getpass", return_value="hidden-custom"):
chosen = module.credentials("fixture", False)
self.assertEqual(chosen["BORTSTACK_TEST_PASSWORD"], "hidden-custom")
self.assertFalse((private / "bortstack/testing.env").exists())
default = private / "bortstack/testing.env"
default.parent.mkdir()
default.write_text("BORTSTACK_TEST_EMAIL=default@localhost\nBORTSTACK_TEST_PASSWORD=default-private\n")
default.chmod(0o600)
with patch.dict(os.environ, {"XDG_CONFIG_HOME": str(private)}), \
patch.object(sys.stdin, "isatty", return_value=True), \
patch("builtins.input", return_value=""):
self.assertEqual(module.credentials("fixture", False)["BORTSTACK_TEST_EMAIL"], "default@localhost")
with patch.dict(os.environ, {"XDG_CONFIG_HOME": str(private)}), \
patch.object(sys.stdin, "isatty", return_value=True), \
patch("builtins.input", side_effect=["n", ""]):
with self.assertRaises(module.ToolkitError):
module.credentials("fixture", False)
def test_port_conflict_does_not_start_compose(self):
sys.path.insert(0, str(SOURCE))
self.addCleanup(lambda: sys.path.remove(str(SOURCE)))
spec = importlib.util.spec_from_file_location("forge_toolkit_port_test", SOURCE / "toolkit.py")
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
bin_dir = Path(self.temp.name) / "bin-port"
bin_dir.mkdir()
docker = bin_dir / "docker"
log = Path(self.temp.name) / "docker-port.log"
docker.write_text("#!/bin/sh\nprintf '%s\\n' \"$*\" >>\"$DOCKER_LOG\"\nexit 0\n")
docker.chmod(0o755)
env = {"PATH": str(bin_dir) + os.pathsep + os.environ["PATH"], "DOCKER_LOG": str(log)}
config = json.loads((self.root / ".bortstack/testing.json").read_text())
with patch.dict(os.environ, env), patch.object(module, "port_open", return_value=True):
with self.assertRaises(module.ToolkitError) as error:
module.manual("manual", self.root, "main", config, argparse.Namespace(action="start", use_default_credentials=False))
self.assertEqual(error.exception.code, 4)
self.assertNotIn("up --detach", log.read_text())
if __name__ == "__main__":
unittest.main()