FORGE-F008 Add unified testing toolkit for generated projects
This commit is contained in:
@@ -1,5 +1,7 @@
|
|||||||
# Current state
|
# Current state
|
||||||
|
|
||||||
|
FORGE-F008 is implementation-complete on `codex`, pending Captain acceptance: `toolkits/testing` separates manual Compose environments from automated suites and allowlisted `act` jobs, and the Flask/React generator copies it into new projects. All 29 Forge tests and a generated Compose configuration check pass. Live Docker/`act` execution is blocked by daemon access, and Windows is unverified.
|
||||||
|
|
||||||
FORGE-F014 is Captain-accepted and provides a portable testtask runner and existing-project installer. A target worktree must explicitly configure its test command. A disposable PitchInvader-shaped fixture validated the workflow; PitchInvader itself has not been tested or modified. Windows validation remains pending.
|
FORGE-F014 is Captain-accepted and provides a portable testtask runner and existing-project installer. A target worktree must explicitly configure its test command. A disposable PitchInvader-shaped fixture validated the workflow; PitchInvader itself has not been tested or modified. Windows validation remains pending.
|
||||||
|
|
||||||
FORGE-F001, FORGE-F002, FORGE-F006, and FORGE-F007 were human accepted and are present on `codex`. F003 and F004 candidates are integrated locally with external validation and acceptance pending. The Captain-authorised F004 lifecycle follow-up from `codex-forge-f004-lifecycle` was integrated into `codex` at `727a64e` after combined Forge checks; it extends F002's accepted context contract without reopening F002. FORGE-F011 is a planned visual design quality follow-up to F003; image-to-editable-Penpot reconstruction remains unproven and requires investigation. F006 provides an independent Flask/React template package and generator, with SQLite, PostgreSQL, MySQL, and MariaDB migrations verified in disposable Docker containers. Windows generation remains untested. The original bootstrap repository remains available; no external retirement was performed. Explicit business/personal profile configuration is implemented. `bortstack-context`, `bortstack-contributor`, and `bortstack-design` packages are present; one skill directory remains reserved. The repository `testtask` entry point is provisioned but blocked because Forge has no application runtime or manual-test hook. No cross-template generator or active legacy-skill migration has been implemented. Captain reports successful external validation of local Penpot 2.18 Docker and integrated MCP, but this session has no Penpot connector/browser. JJ's hands-on and Windows workflow has not been tested. Decisions FORGE-001 through FORGE-011 remain accepted. FORGE-008 authorises direct `codex` work generally; Captain explicitly requested isolation for the F004 lifecycle follow-up.
|
FORGE-F001, FORGE-F002, FORGE-F006, and FORGE-F007 were human accepted and are present on `codex`. F003 and F004 candidates are integrated locally with external validation and acceptance pending. The Captain-authorised F004 lifecycle follow-up from `codex-forge-f004-lifecycle` was integrated into `codex` at `727a64e` after combined Forge checks; it extends F002's accepted context contract without reopening F002. FORGE-F011 is a planned visual design quality follow-up to F003; image-to-editable-Penpot reconstruction remains unproven and requires investigation. F006 provides an independent Flask/React template package and generator, with SQLite, PostgreSQL, MySQL, and MariaDB migrations verified in disposable Docker containers. Windows generation remains untested. The original bootstrap repository remains available; no external retirement was performed. Explicit business/personal profile configuration is implemented. `bortstack-context`, `bortstack-contributor`, and `bortstack-design` packages are present; one skill directory remains reserved. The repository `testtask` entry point is provisioned but blocked because Forge has no application runtime or manual-test hook. No cross-template generator or active legacy-skill migration has been implemented. Captain reports successful external validation of local Penpot 2.18 Docker and integrated MCP, but this session has no Penpot connector/browser. JJ's hands-on and Windows workflow has not been tested. Decisions FORGE-001 through FORGE-011 remain accepted. FORGE-008 authorises direct `codex` work generally; Captain explicitly requested isolation for the F004 lifecycle follow-up.
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
# Handoff
|
# Handoff
|
||||||
|
|
||||||
|
FORGE-F008 candidate (2026-11-19): Captain authorised direct `codex` implementation from `b9cc143`. `toolkits/testing` and the Flask/React generator now provide separate manual and automated entry points with shared read-only target selection. Existing PitchInvader, RouletteBuddy, and Roborto Testtask repositories were inspected but not modified. All 29 Forge tests, generated Compose configuration, task ID audit, installer dry-run, Python compilation, and `git diff --check` passed. Fake-runtime fixtures exercised Compose and safe `act`; live startup, real `act`, and local-account provisioning were not run because Docker daemon access was denied. Windows remains untested. Review the scoped commit on `codex`; Captain acceptance is required before F008 is Complete. Do not migrate existing applications as part of this task.
|
||||||
|
|
||||||
FORGE-F014: Captain accepted the isolated candidate on 2026-11-19 and requested merge to `codex`. Branch `codex-forge-f014` at `/tmp/bortstack-forge-f014` is based on `860d6d4`; implementation commit `17660d8`. Portable distribution is under `distribution/testtask`; `scripts/install-testtask.py` installs it without replacing existing files. Each target branch worktree needs `.bortstack/testtask.json` with an explicit command array. The disposable fixture passed; no PitchInvader files were changed. Windows and real PitchInvader validation remain open. Preserve the task worktree after integration.
|
FORGE-F014: Captain accepted the isolated candidate on 2026-11-19 and requested merge to `codex`. Branch `codex-forge-f014` at `/tmp/bortstack-forge-f014` is based on `860d6d4`; implementation commit `17660d8`. Portable distribution is under `distribution/testtask`; `scripts/install-testtask.py` installs it without replacing existing files. Each target branch worktree needs `.bortstack/testtask.json` with an explicit command array. The disposable fixture passed; no PitchInvader files were changed. Windows and real PitchInvader validation remain open. Preserve the task worktree after integration.
|
||||||
|
|
||||||
Current work: Captain authorised and completed integration of the contributor lifecycle follow-up from `codex-forge-f004-lifecycle` (`c2d4561`) into `codex` at merge commit `727a64e`. The source worktree is `/tmp/bortstack-forge-f004-lifecycle`, baseline `934e62c`; the target had advanced to `900bd6c` with FORGE-F011 planning. F002 remains Complete. F004 is integrated locally but still pending JJ's external validation and human acceptance. The original F004 worktree remains preserved.
|
Current work: Captain authorised and completed integration of the contributor lifecycle follow-up from `codex-forge-f004-lifecycle` (`c2d4561`) into `codex` at merge commit `727a64e`. The source worktree is `/tmp/bortstack-forge-f004-lifecycle`, baseline `934e62c`; the target had advanced to `900bd6c` with FORGE-F011 planning. F002 remains Complete. F004 is integrated locally but still pending JJ's external validation and human acceptance. The original F004 worktree remains preserved.
|
||||||
|
|||||||
+5
-1
@@ -78,12 +78,16 @@ Acceptance: both profiles work with separately configured ownership and branding
|
|||||||
Implementation record (2026-11-17): Added a dependency-free flat profile configurator and read/write module, updated the profile contract and context skill, and tested business and personal records in temporary new/existing directories with different owners and brands. The command requires explicit contributor, testing, and deployment values, preserves existing project files, and refuses to overwrite an existing profile. Linux tests passed; Windows command and filesystem behavior have not been exercised on Windows. No real external project was changed. Captain accepted F007 on 2026-11-17.
|
Implementation record (2026-11-17): Added a dependency-free flat profile configurator and read/write module, updated the profile contract and context skill, and tested business and personal records in temporary new/existing directories with different owners and brands. The command requires explicit contributor, testing, and deployment values, preserves existing project files, and refuses to overwrite an existing profile. Linux tests passed; Windows command and filesystem behavior have not been exercised on Windows. No real external project was changed. Captain accepted F007 on 2026-11-17.
|
||||||
|
|
||||||
## FORGE-F008 — Standardise Local Testing and `act`
|
## FORGE-F008 — Standardise Local Testing and `act`
|
||||||
Status: Planned. Priority: Medium. Dependencies: FORGE-F006.
|
Status: Implementation Complete on `codex`; Captain acceptance pending. Priority: Medium. Dependencies: FORGE-F006. Captain explicitly authorised implementation on 2026-11-19 under FORGE-008's direct-`codex` policy; baseline `b9cc143`.
|
||||||
|
|
||||||
Provide simple local test commands, Docker testing where appropriate, optional GitHub Actions-compatible `act`, clear results, separation of test failures from infrastructure failures, safeguards against publishing/deployment, and bounded automated repair. Remote CI must not be required for local verification.
|
Provide simple local test commands, Docker testing where appropriate, optional GitHub Actions-compatible `act`, clear results, separation of test failures from infrastructure failures, safeguards against publishing/deployment, and bounded automated repair. Remote CI must not be required for local verification.
|
||||||
|
|
||||||
Acceptance: validate a generated template locally and demonstrate failure classification and deployment protection.
|
Acceptance: validate a generated template locally and demonstrate failure classification and deployment protection.
|
||||||
|
|
||||||
|
Implementation scope (2026-11-19): One canonical `toolkits/testing` package supplies separate manual `testtask.sh` and automated `testrunner.sh` entry points with shared read-only target resolution. Generated Flask/React projects receive the package, explicit `.bortstack/testing.json`, Docker Compose manual environment settings, a local account provisioner, and unit/integration commands. Existing-project installation and legacy Roborto migration remain outside F008. The older Forge `distribution/testtask` stays in place for its accepted F014 scope; it is not the manual launcher. Local fixtures cover branch/task resolution, worktree paths with spaces, manual Compose lifecycle boundaries, credential selection failure, suite selection/failure, and safe `act` allowlisting. Docker daemon access and Windows validation are pending; do not claim live Compose or GitHub-hosted success. Human acceptance is required before Complete.
|
||||||
|
|
||||||
|
Validation: 29 Forge tests passed, including generated-project inclusion and invocation, branch/task/worktree resolution, isolated Compose fixture lifecycle, credential privacy and selection, suite results, and fake-runtime safe `act`. A generated Flask/React project's `docker compose config --quiet` passed. `context_audit.py`, installer dry-run, Python compilation, and `git diff --check` passed. `act` is installed (`0.2.91`) but the Docker daemon denied access, so live Compose startup, real local Actions execution, and account provisioning remain unverified. Windows is untested. No existing application repository or production resource was changed.
|
||||||
|
|
||||||
## FORGE-F009 — Optional Gitea Integration
|
## FORGE-F009 — Optional Gitea Integration
|
||||||
Status: Planned (deferred). Priority: Deferred. Dependencies: FORGE-F005.
|
Status: Planned (deferred). Priority: Deferred. Dependencies: FORGE-F005.
|
||||||
|
|
||||||
|
|||||||
@@ -3,3 +3,5 @@
|
|||||||
A template descriptor identifies template ID and version, supported project type, configuration variables, generation procedure, dependencies, development commands, validation/test commands, optional capabilities, platform requirements, and initial context behavior. `templates/flask-react/template.json` is the first implemented descriptor; `templates/flask-react/generate.py` is its standalone generation API. F005 will orchestrate selection and project profiles across templates. Generated projects have no Forge runtime dependency.
|
A template descriptor identifies template ID and version, supported project type, configuration variables, generation procedure, dependencies, development commands, validation/test commands, optional capabilities, platform requirements, and initial context behavior. `templates/flask-react/template.json` is the first implemented descriptor; `templates/flask-react/generate.py` is its standalone generation API. F005 will orchestrate selection and project profiles across templates. Generated projects have no Forge runtime dependency.
|
||||||
|
|
||||||
The migration source is the existing `flask-react-auth-base` repository at the commit recorded in the descriptor. It remains external and unchanged. Forge's generator accepts a project name, new destination, and optional `--git-init`; it refuses existing destinations and paths inside Forge. Email and hosting foundations are optional per FORGE-009, with no active GitHub workflow or automatic deployment in generated projects.
|
The migration source is the existing `flask-react-auth-base` repository at the commit recorded in the descriptor. It remains external and unchanged. Forge's generator accepts a project name, new destination, and optional `--git-init`; it refuses existing destinations and paths inside Forge. Email and hosting foundations are optional per FORGE-009, with no active GitHub workflow or automatic deployment in generated projects.
|
||||||
|
|
||||||
|
FORGE-F008 copies the canonical testing toolkit into generated projects. The generated `.bortstack/testing.json` owns Compose manual-development settings, local account provisioning, automated suite commands and optional approved `act` jobs. `testtask.sh` is for manual environments; `testrunner.sh` is for automated suites. The package contract and platform requirements are in `toolkits/testing/README.md`.
|
||||||
|
|||||||
@@ -0,0 +1,22 @@
|
|||||||
|
{
|
||||||
|
"version": 1,
|
||||||
|
"manual": {
|
||||||
|
"kind": "compose",
|
||||||
|
"environment": "development",
|
||||||
|
"file": "docker-compose.yml",
|
||||||
|
"env_file": ".env.example",
|
||||||
|
"project": "__APP_SLUG__",
|
||||||
|
"ports": {"BORTSTACK_API_PORT": 5001, "BORTSTACK_WEB_PORT": 8081},
|
||||||
|
"readiness": ["http://127.0.0.1:5001/api/health/ready", "http://127.0.0.1:8081/"],
|
||||||
|
"urls": ["http://127.0.0.1:8081/"],
|
||||||
|
"authentication": {"required": true, "provision": ["python3", "scripts/provision-test-user.py"]}
|
||||||
|
},
|
||||||
|
"automated": {
|
||||||
|
"default": ["unit"],
|
||||||
|
"suites": {
|
||||||
|
"unit": {"command": ["./scripts/run-unit-tests.sh"], "cwd": "."},
|
||||||
|
"integration": {"command": ["./scripts/run-integration-tests.sh"], "cwd": "."}
|
||||||
|
},
|
||||||
|
"act": []
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -20,6 +20,38 @@ Windows PowerShell: create the virtual environment with `py -3 -m venv api/.venv
|
|||||||
|
|
||||||
## Validation
|
## Validation
|
||||||
|
|
||||||
|
The generated testing toolkit is available without Forge at runtime:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
./scripts/testtask.sh --start # Compose development services and local account
|
||||||
|
./scripts/testtask.sh --status
|
||||||
|
./scripts/testtask.sh --stop # stops only this worktree's Compose project
|
||||||
|
./scripts/testrunner.sh --unit
|
||||||
|
./scripts/testrunner.sh --integration
|
||||||
|
```
|
||||||
|
|
||||||
|
The toolkit uses Git worktree metadata. Generate with `--git-init` or initialise
|
||||||
|
Git locally before using the commands; an initial commit is not required for
|
||||||
|
the current worktree. Explicit branch targets require a local branch ref and
|
||||||
|
an existing checkout.
|
||||||
|
|
||||||
|
Configure a private local test account in `~/.config/bortstack/testing.env`
|
||||||
|
with `BORTSTACK_TEST_EMAIL` and `BORTSTACK_TEST_PASSWORD`, then `chmod 600`
|
||||||
|
that file. `testtask.sh` asks before using it and permits a one-session hidden
|
||||||
|
password override. Non-interactive use requires `--use-default-credentials`.
|
||||||
|
The generated development hook creates a verified account only in this
|
||||||
|
worktree's Compose development database; an existing account is accepted only
|
||||||
|
when its password matches. Compose uses ports 5001 and 8081 by default;
|
||||||
|
adjust `.bortstack/testing.json` if they are occupied. Keep the same file's
|
||||||
|
URLs in sync. The toolkit never removes the persistent SQLite volume.
|
||||||
|
|
||||||
|
`testrunner.sh` requires the documented Python virtual environment and
|
||||||
|
`react/node_modules`; it does not install dependencies. `--act` is unavailable
|
||||||
|
until a reviewed local-safe GitHub workflow/job is explicitly allowlisted in
|
||||||
|
`.bortstack/testing.json`. The optional deployment workflow is not allowlisted.
|
||||||
|
See the generated config and Forge's toolkit README for the schema and Windows
|
||||||
|
requirements.
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
cd api && .venv/bin/pytest
|
cd api && .venv/bin/pytest
|
||||||
cd react && npm run lint && npm test && npm run build
|
cd react && npm run lint && npm test && npm run build
|
||||||
|
|||||||
@@ -0,0 +1,46 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Provision only this generated project's local Compose development account."""
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
project = os.environ.get("BORTSTACK_COMPOSE_PROJECT", "")
|
||||||
|
compose_file = Path(os.environ.get("BORTSTACK_COMPOSE_FILE", ""))
|
||||||
|
secret_file = Path(os.environ.get("BORTSTACK_CREDENTIALS_FILE", ""))
|
||||||
|
if not project.startswith("bortstack-") or not compose_file.is_file() or not secret_file.is_file():
|
||||||
|
raise SystemExit("local Compose project and temporary credentials are required")
|
||||||
|
if os.environ.get("APP_ENV", "development") != "development":
|
||||||
|
raise SystemExit("refusing account provisioning outside development")
|
||||||
|
secret = json.loads(secret_file.read_text(encoding="utf-8"))
|
||||||
|
if not secret.get("BORTSTACK_TEST_EMAIL") or not secret.get("BORTSTACK_TEST_PASSWORD"):
|
||||||
|
raise SystemExit("missing local test credentials")
|
||||||
|
base = ["docker", "compose", "--project-name", project, "--file", str(compose_file)]
|
||||||
|
if subprocess.run(base + ["exec", "-T", "api", "flask", "--app", "api.py", "db", "upgrade"], check=False).returncode:
|
||||||
|
raise SystemExit("local development migration failed")
|
||||||
|
code = '''
|
||||||
|
import json, sys
|
||||||
|
from datetime import datetime
|
||||||
|
from sqlalchemy import func
|
||||||
|
from settings import app, db
|
||||||
|
from models.user import User, normalize_email
|
||||||
|
values = json.load(sys.stdin)
|
||||||
|
email = normalize_email(values["BORTSTACK_TEST_EMAIL"])
|
||||||
|
password = values["BORTSTACK_TEST_PASSWORD"]
|
||||||
|
if len(password) < 8:
|
||||||
|
raise SystemExit("test password must have at least eight characters")
|
||||||
|
with app.app_context():
|
||||||
|
existing = User.query.filter(func.lower(User.email) == email).first()
|
||||||
|
if existing:
|
||||||
|
if not existing.check_password(password) or existing.email_verified_at is None:
|
||||||
|
raise SystemExit("test account exists with different credentials or is unverified; no account was changed")
|
||||||
|
else:
|
||||||
|
user = User(email=email, username="Local Test User", email_verified_at=datetime.utcnow())
|
||||||
|
user.set_password(password)
|
||||||
|
db.session.add(user)
|
||||||
|
db.session.commit()
|
||||||
|
'''
|
||||||
|
result = subprocess.run(base + ["exec", "-T", "api", "python", "-c", code],
|
||||||
|
input=json.dumps(secret), text=True, check=False)
|
||||||
|
sys.exit(result.returncode)
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
set -eu
|
||||||
|
root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||||
|
if [ ! -d "$root/react/node_modules" ]; then
|
||||||
|
echo 'integration tests unavailable: install react/node_modules first' >&2
|
||||||
|
exit 3
|
||||||
|
fi
|
||||||
|
(cd "$root/react" && npm run test:e2e)
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
set -eu
|
||||||
|
root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||||
|
if [ ! -x "$root/api/.venv/bin/python" ] || [ ! -d "$root/react/node_modules" ]; then
|
||||||
|
echo 'unit tests unavailable: install api/.venv and react/node_modules first' >&2
|
||||||
|
exit 3
|
||||||
|
fi
|
||||||
|
(cd "$root/api" && APP_ENV=testing .venv/bin/python -m pytest -c pytest.ini tests)
|
||||||
|
(cd "$root/react" && npm test -- --run)
|
||||||
@@ -8,7 +8,9 @@ from pathlib import Path
|
|||||||
|
|
||||||
|
|
||||||
ROOT = Path(__file__).resolve().parent
|
ROOT = Path(__file__).resolve().parent
|
||||||
|
TOOLKIT = ROOT.parent.parent / "toolkits/testing/scripts"
|
||||||
TOKEN_FILES = (".env.example", "docker-compose.yml", "react/index.html",
|
TOKEN_FILES = (".env.example", "docker-compose.yml", "react/index.html",
|
||||||
|
".bortstack/testing.json",
|
||||||
"react/src/config/site.js", "react/src/components/Logo/Logo.jsx",
|
"react/src/config/site.js", "react/src/components/Logo/Logo.jsx",
|
||||||
"ops/databases/postgres.env.example", "ops/databases/mysql.env.example",
|
"ops/databases/postgres.env.example", "ops/databases/mysql.env.example",
|
||||||
"ops/databases/mariadb.env.example")
|
"ops/databases/mariadb.env.example")
|
||||||
@@ -31,6 +33,8 @@ def generate(name, destination, git_init=False):
|
|||||||
try:
|
try:
|
||||||
shutil.copytree(ROOT / "source", target, symlinks=False, dirs_exist_ok=True)
|
shutil.copytree(ROOT / "source", target, symlinks=False, dirs_exist_ok=True)
|
||||||
shutil.copytree(ROOT / "boilerplate", target, dirs_exist_ok=True)
|
shutil.copytree(ROOT / "boilerplate", target, dirs_exist_ok=True)
|
||||||
|
for tool_name in ("testtask.sh", "testrunner.sh", "target.py", "toolkit.py"):
|
||||||
|
shutil.copy2(TOOLKIT / tool_name, target / "scripts" / tool_name)
|
||||||
values = {"__PROJECT_NAME__": name, "__APP_SLUG__": slug,
|
values = {"__PROJECT_NAME__": name, "__APP_SLUG__": slug,
|
||||||
"__DATABASE_NAME__": slug.replace("-", "_")}
|
"__DATABASE_NAME__": slug.replace("-", "_")}
|
||||||
for relative in TOKEN_FILES:
|
for relative in TOKEN_FILES:
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ services:
|
|||||||
retries: 5
|
retries: 5
|
||||||
start_period: 20s
|
start_period: 20s
|
||||||
ports:
|
ports:
|
||||||
- "127.0.0.1:5001:5000"
|
- "127.0.0.1:${BORTSTACK_API_PORT:-5001}:5000"
|
||||||
networks:
|
networks:
|
||||||
- internal
|
- internal
|
||||||
|
|
||||||
@@ -48,7 +48,7 @@ services:
|
|||||||
retries: 5
|
retries: 5
|
||||||
start_period: 10s
|
start_period: 10s
|
||||||
ports:
|
ports:
|
||||||
- "127.0.0.1:8081:80"
|
- "127.0.0.1:${BORTSTACK_WEB_PORT:-8081}:80"
|
||||||
networks:
|
networks:
|
||||||
- internal
|
- internal
|
||||||
|
|
||||||
|
|||||||
@@ -11,8 +11,8 @@
|
|||||||
"development": ["Python 3.12", "Node.js 22", "npm"],
|
"development": ["Python 3.12", "Node.js 22", "npm"],
|
||||||
"optional": ["Docker Compose", "Chromium/Playwright"]
|
"optional": ["Docker Compose", "Chromium/Playwright"]
|
||||||
},
|
},
|
||||||
"development_commands": ["cd api && flask --app api.py run", "cd react && npm run dev"],
|
"development_commands": ["./scripts/testtask.sh", "./scripts/testtask.sh --status", "./scripts/testtask.sh --stop"],
|
||||||
"validation_commands": ["cd api && pytest", "cd react && npm run lint && npm test && npm run build", "docker compose --env-file .env.example config --quiet"],
|
"validation_commands": ["./scripts/testrunner.sh", "./scripts/testrunner.sh --all", "cd react && npm run lint && npm run build", "docker compose --env-file .env.example config --quiet"],
|
||||||
"database_engines": ["SQLite", "PostgreSQL", "MySQL", "MariaDB"],
|
"database_engines": ["SQLite", "PostgreSQL", "MySQL", "MariaDB"],
|
||||||
"optional_capabilities": ["Resend outbound email", "PostgreSQL/MySQL/MariaDB production persistence", "Docker/nginx hosting", "SWAG integration", "GitHub Actions publishing/deployment"],
|
"optional_capabilities": ["Resend outbound email", "PostgreSQL/MySQL/MariaDB production persistence", "Docker/nginx hosting", "SWAG integration", "GitHub Actions publishing/deployment"],
|
||||||
"initial_context": "Fresh AGENTS.md and five docs records are generated; profile selection is delegated to bortstack-context/F007.",
|
"initial_context": "Fresh AGENTS.md and five docs records are generated; profile selection is delegated to bortstack-context/F007.",
|
||||||
|
|||||||
@@ -24,6 +24,14 @@ class FlaskReactTemplateTests(unittest.TestCase):
|
|||||||
self.assertFalse((project / ".git").exists())
|
self.assertFalse((project / ".git").exists())
|
||||||
self.assertFalse((project / ".github").exists())
|
self.assertFalse((project / ".github").exists())
|
||||||
self.assertFalse((project / ".bortstack/profile.yaml").exists())
|
self.assertFalse((project / ".bortstack/profile.yaml").exists())
|
||||||
|
self.assertTrue((project / "scripts/testtask.sh").is_file())
|
||||||
|
self.assertTrue((project / "scripts/testrunner.sh").is_file())
|
||||||
|
testing = json.loads((project / ".bortstack/testing.json").read_text())
|
||||||
|
self.assertEqual(testing["manual"]["project"], "orion-starter")
|
||||||
|
self.assertEqual(testing["automated"]["default"], ["unit"])
|
||||||
|
self.assertEqual(testing["automated"]["act"], [])
|
||||||
|
help_result = subprocess.run([str(project / "scripts/testrunner.sh"), "--help"], cwd=project, capture_output=True, text=True)
|
||||||
|
self.assertEqual(help_result.returncode, 0, help_result.stderr)
|
||||||
self.assertFalse((project / "scripts/create-project.sh").exists())
|
self.assertFalse((project / "scripts/create-project.sh").exists())
|
||||||
env = (project / ".env.example").read_text()
|
env = (project / ".env.example").read_text()
|
||||||
self.assertIn("APP_SLUG=orion-starter", env)
|
self.assertIn("APP_SLUG=orion-starter", env)
|
||||||
@@ -48,6 +56,10 @@ class FlaskReactTemplateTests(unittest.TestCase):
|
|||||||
command = ["python3", str(GENERATOR), "New App", str(project), "--git-init"]
|
command = ["python3", str(GENERATOR), "New App", str(project), "--git-init"]
|
||||||
self.assertEqual(subprocess.run(command, capture_output=True).returncode, 0)
|
self.assertEqual(subprocess.run(command, capture_output=True).returncode, 0)
|
||||||
self.assertEqual(subprocess.check_output(["git", "-C", str(project), "branch", "--show-current"], text=True).strip(), "main")
|
self.assertEqual(subprocess.check_output(["git", "-C", str(project), "branch", "--show-current"], text=True).strip(), "main")
|
||||||
|
runner = subprocess.run([str(project / "scripts/testrunner.sh")], cwd=project, capture_output=True, text=True)
|
||||||
|
self.assertEqual(runner.returncode, 3)
|
||||||
|
self.assertIn("branch: main", runner.stdout)
|
||||||
|
self.assertIn("infrastructure unavailable", runner.stdout)
|
||||||
marker = project / "local.txt"
|
marker = project / "local.txt"
|
||||||
marker.write_text("preserve")
|
marker.write_text("preserve")
|
||||||
self.assertNotEqual(subprocess.run(command, capture_output=True).returncode, 0)
|
self.assertNotEqual(subprocess.run(command, capture_output=True).returncode, 0)
|
||||||
|
|||||||
@@ -0,0 +1,209 @@
|
|||||||
|
"""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()
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
# Bortstack Testing Toolkit
|
||||||
|
|
||||||
|
This package is copied into generated applications. `scripts/testtask.sh` starts,
|
||||||
|
checks, or stops a **manual development environment**. `scripts/testrunner.sh`
|
||||||
|
runs configured automated suites. Both use `scripts/target.py` to select a Git
|
||||||
|
worktree; neither needs Forge at runtime. This package does not migrate existing
|
||||||
|
Roborto application launchers. Forge's earlier `distribution/testtask` is a
|
||||||
|
separate existing-project automated runner and remains unchanged for its
|
||||||
|
previously accepted scope.
|
||||||
|
|
||||||
|
The project needs a local Git repository. An unborn initial branch works for
|
||||||
|
no-target commands, so a newly generated project can use `--git-init` without
|
||||||
|
making a commit. A generated project created without Git must initialise it
|
||||||
|
before using the toolkit.
|
||||||
|
|
||||||
|
The application owns `.bortstack/testing.json` (see
|
||||||
|
`config/testing.example.json`). A no-argument command uses the current worktree
|
||||||
|
and its checked-out branch. A branch name uses its existing worktree; a task ID
|
||||||
|
uses `docs/TASKS.md` headings and `Branch/worktree: \`name\`` references or a
|
||||||
|
matching branch slug. A branch needs no task record. Missing, ambiguous, and
|
||||||
|
detached targets fail without Git mutation.
|
||||||
|
|
||||||
|
## Manual environments
|
||||||
|
|
||||||
|
`./scripts/testtask.sh [target] [--start|--status|--stop]` starts by default.
|
||||||
|
The current adapter supports Docker Compose. It uses a unique project name
|
||||||
|
derived from the selected worktree and branch, checks declared host ports,
|
||||||
|
starts only that project, verifies configured loopback readiness URLs, and
|
||||||
|
prints configured URLs. `--stop` runs Compose `stop` for that project; it never
|
||||||
|
removes volumes, databases, worktrees, or another project's containers. A
|
||||||
|
running project is reported without restarting it. Define project-specific
|
||||||
|
Compose services, ports, URLs, and optional account provisioning in the
|
||||||
|
application configuration. Do not configure production resources here.
|
||||||
|
|
||||||
|
For authentication, create `~/.config/bortstack/testing.env` with mode 0600:
|
||||||
|
|
||||||
|
```dotenv
|
||||||
|
BORTSTACK_TEST_EMAIL=test@localhost
|
||||||
|
BORTSTACK_TEST_PASSWORD=choose-a-private-local-password
|
||||||
|
```
|
||||||
|
|
||||||
|
`$XDG_CONFIG_HOME/bortstack/testing.env` is also accepted, and
|
||||||
|
`$XDG_CONFIG_HOME/bortstack/<project>/testing.env` can override either value.
|
||||||
|
The parser accepts only these two literal keys; it does not evaluate shell
|
||||||
|
code. The launcher asks before using defaults. Selecting N prompts for a new
|
||||||
|
email and hidden password without saving them. With no terminal, use
|
||||||
|
`--use-default-credentials` explicitly. Required credentials without a
|
||||||
|
configured local provisioning hook fail before startup. A hook receives only
|
||||||
|
the path in `BORTSTACK_CREDENTIALS_FILE` to a temporary mode-0600 JSON file;
|
||||||
|
it must never print or forward the password as a command argument. The generic
|
||||||
|
toolkit cannot promise an account exists until the project hook succeeds.
|
||||||
|
|
||||||
|
## Automated suites
|
||||||
|
|
||||||
|
`./scripts/testrunner.sh [target] [--unit] [--integration] [--act] [--all]` runs
|
||||||
|
the configured default suites when no option is supplied. Explicit suites can
|
||||||
|
be combined. `--all` includes every configured suite and only allowlisted act
|
||||||
|
jobs. Commands are argument arrays and run in the selected worktree. The tool
|
||||||
|
prints each executed suite and exit code; missing configuration or dependencies
|
||||||
|
cannot count as a pass. Exit 2 denotes target errors, 3 configuration or
|
||||||
|
infrastructure unavailability, 4 unsafe/cancelled selection, and test commands
|
||||||
|
retain their own nonzero exit codes.
|
||||||
|
|
||||||
|
`act` needs its executable and a working Docker daemon. Each allowed job must
|
||||||
|
name a local `.github/workflows/` file and job. A conservative content check
|
||||||
|
rejects obvious deployment, publishing, release, push, secret, and production
|
||||||
|
operations even if listed. Review the whole workflow before allowlisting it;
|
||||||
|
static checks cannot prove a workflow harmless. No user credentials or secrets
|
||||||
|
are passed to `act`. An act pass is local evidence, not a GitHub-hosted result.
|
||||||
|
|
||||||
|
Linux requires Python 3, Git, a POSIX shell and Docker Compose for manual
|
||||||
|
Compose environments. Windows contributors can use WSL2 with Git, Python,
|
||||||
|
Docker Desktop's WSL integration, and the project toolchain. Git Bash may work
|
||||||
|
if Docker, Python, and all project commands are available there. Windows has
|
||||||
|
not been exercised in this implementation.
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
{
|
||||||
|
"version": 1,
|
||||||
|
"manual": {
|
||||||
|
"kind": "compose",
|
||||||
|
"environment": "development",
|
||||||
|
"file": "docker-compose.yml",
|
||||||
|
"project": "my-project",
|
||||||
|
"ports": {"APP_PORT": 8081},
|
||||||
|
"readiness": ["http://127.0.0.1:8081/health"],
|
||||||
|
"urls": ["http://127.0.0.1:8081/"],
|
||||||
|
"authentication": {"required": false}
|
||||||
|
},
|
||||||
|
"automated": {
|
||||||
|
"default": ["unit"],
|
||||||
|
"suites": {
|
||||||
|
"unit": {"command": ["make", "test-unit"], "cwd": ".", "timeout_seconds": 600},
|
||||||
|
"integration": {"command": ["make", "test-integration"], "cwd": "."}
|
||||||
|
},
|
||||||
|
"act": [{"workflow": ".github/workflows/local-ci.yml", "job": "unit"}]
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
"""Read-only Git branch, task, and worktree selection shared by both entry points."""
|
||||||
|
import re
|
||||||
|
import subprocess
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
HEADING = re.compile(r"^## ([A-Z][A-Z0-9]*(?:-[A-Z0-9]+)+)\s+[—-]", re.M)
|
||||||
|
LABEL = re.compile(r"(?:Task )?[Bb]ranch(?:/worktree)?:\s*`([^`]+)`")
|
||||||
|
|
||||||
|
|
||||||
|
class TargetError(Exception):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def git(root, *args):
|
||||||
|
result = subprocess.run(["git", "-C", str(root), *args], capture_output=True, text=True)
|
||||||
|
if result.returncode:
|
||||||
|
raise TargetError(result.stderr.strip() or "Git command failed")
|
||||||
|
return result.stdout.strip()
|
||||||
|
|
||||||
|
|
||||||
|
def task_records(root):
|
||||||
|
path = root / "docs/TASKS.md"
|
||||||
|
if not path.is_file():
|
||||||
|
return {}
|
||||||
|
content = path.read_text(encoding="utf-8")
|
||||||
|
headings = list(HEADING.finditer(content))
|
||||||
|
records = {}
|
||||||
|
for i, match in enumerate(headings):
|
||||||
|
end = headings[i + 1].start() if i + 1 < len(headings) else len(content)
|
||||||
|
records.setdefault(match.group(1), []).append(content[match.end():end])
|
||||||
|
return records
|
||||||
|
|
||||||
|
|
||||||
|
def associated(task_id, section, branches):
|
||||||
|
slug = task_id.lower()
|
||||||
|
found = {name for name in branches if re.search(rf"(^|[-/]){re.escape(slug)}($|[-/])", name.lower())}
|
||||||
|
found.update(name for name in LABEL.findall(section) if name in branches)
|
||||||
|
return found
|
||||||
|
|
||||||
|
|
||||||
|
def resolve(script_path, identifier=None):
|
||||||
|
origin = Path.cwd() if identifier is None else script_path.parent
|
||||||
|
root = Path(git(origin, "rev-parse", "--show-toplevel")).resolve()
|
||||||
|
branches = set(git(root, "for-each-ref", "--format=%(refname:short)", "refs/heads").splitlines())
|
||||||
|
records = task_records(root)
|
||||||
|
if identifier is None:
|
||||||
|
result = subprocess.run(["git", "-C", str(origin), "symbolic-ref", "--quiet", "--short", "HEAD"], capture_output=True, text=True)
|
||||||
|
branch = result.stdout.strip()
|
||||||
|
if not branch:
|
||||||
|
raise TargetError("current worktree has detached HEAD; specify a branch or task ID")
|
||||||
|
selected = Path(git(origin, "rev-parse", "--show-toplevel")).resolve()
|
||||||
|
else:
|
||||||
|
task_match = identifier in records
|
||||||
|
branch_match = identifier in branches
|
||||||
|
if task_match and branch_match:
|
||||||
|
raise TargetError(f"ambiguous identifier {identifier}: both task ID and branch; disambiguate in project records")
|
||||||
|
if task_match:
|
||||||
|
if len(records[identifier]) != 1:
|
||||||
|
raise TargetError(f"ambiguous task ID {identifier}: duplicate records")
|
||||||
|
matches = associated(identifier, records[identifier][0], branches)
|
||||||
|
if len(matches) != 1:
|
||||||
|
raise TargetError(f"task {identifier} maps to {len(matches)} branches: {', '.join(sorted(matches))}")
|
||||||
|
branch = next(iter(matches))
|
||||||
|
elif branch_match:
|
||||||
|
branch = identifier
|
||||||
|
else:
|
||||||
|
raise TargetError(f"unknown task ID or local branch: {identifier}")
|
||||||
|
paths = []
|
||||||
|
for block in git(root, "worktree", "list", "--porcelain").split("\n\n"):
|
||||||
|
lines = block.splitlines()
|
||||||
|
if f"branch refs/heads/{branch}" in lines:
|
||||||
|
path = next((Path(line[9:]) for line in lines if line.startswith("worktree ")), None)
|
||||||
|
if path and path.is_dir():
|
||||||
|
paths.append(path.resolve())
|
||||||
|
if len(paths) != 1:
|
||||||
|
raise TargetError(f"branch {branch} has {len(paths)} existing worktrees; require exactly one")
|
||||||
|
selected = paths[0]
|
||||||
|
if identifier is not None and branch not in branches:
|
||||||
|
raise TargetError(f"branch unavailable: {branch}")
|
||||||
|
return root, branch, selected
|
||||||
Executable
+4
@@ -0,0 +1,4 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
set -eu
|
||||||
|
script_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
|
||||||
|
exec python3 "$script_dir/toolkit.py" automated "$@"
|
||||||
Executable
+4
@@ -0,0 +1,4 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
set -eu
|
||||||
|
script_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
|
||||||
|
exec python3 "$script_dir/toolkit.py" manual "$@"
|
||||||
Executable
+342
@@ -0,0 +1,342 @@
|
|||||||
|
#!/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:]))
|
||||||
Reference in New Issue
Block a user