TASK-007 Add isolated manual testing adapter
This commit is contained in:
@@ -9,3 +9,48 @@ python3 scripts/create_snapshot.py
|
||||
The script writes a timestamped ZIP into `docs/snapshots/`. It includes the application source, `AGENTS.md`, `docs/`, and `scripts/`, including safe untracked files. It omits Git metadata, task worktrees, dependency directories, local environment files, local databases, shared files, caches, generated builds, prior snapshots, symlinks, and common key/credential files. The root `.gitignore` ignores `docs/snapshots/` and `.worktrees/`.
|
||||
|
||||
Inspect the ZIP contents before uploading it if you have added new local data or sensitive file types to the project.
|
||||
|
||||
## Manual task testing (`testtask`)
|
||||
|
||||
From the primary project root, run:
|
||||
|
||||
```sh
|
||||
./scripts/testtask.sh 002
|
||||
```
|
||||
|
||||
Supply the three-digit task number.
|
||||
The adapter locates a unique checked-out `task/TASK-002-*` branch, captures its
|
||||
current tracked changes and permitted untracked files, then starts an isolated
|
||||
copy at http://127.0.0.1:5503 with API at 127.0.0.1:5502. Both ports must be free.
|
||||
The candidate must support `FOLDERSHARE_DATABASE_URI` (provided by TASK-002).
|
||||
|
||||
Prerequisites: installed `roborto-testtask`, Firefox/display, existing Python API
|
||||
venv and frontend node_modules in the primary worktree, and Node >=18. No packages
|
||||
are installed automatically. Python defaults to primary `api/.venv/bin/python`;
|
||||
set `FOLDERSHARE_TEST_PYTHON` to override. Node uses PATH, otherwise the latest
|
||||
installed nvm version; set `FOLDERSHARE_TEST_NODE` to choose explicitly. Dependencies
|
||||
are reused; this verifies the local environment, not a clean dependency install.
|
||||
|
||||
Choose Firefox at the prompt. The launcher prints fresh disposable credentials:
|
||||
`captain` (admin), `friend` (assigned `/friends`), `unassigned`, and `disabled`
|
||||
(which must fail login). Each run has a new shared test password. Only a generated
|
||||
sample file is available; live media/databases/environment files are excluded.
|
||||
|
||||
Snapshots live below the adapter checkout's ignored `.test-worktrees/`. Source
|
||||
hashes are verified before startup and again before readiness; rerun after any
|
||||
candidate edit. Do not develop in a snapshot. A running session is not refreshed
|
||||
in place. Ctrl-C stops the owned processes and removes that session's snapshot,
|
||||
database, credentials and cache. Foreign/existing snapshots are never replaced;
|
||||
after an abrupt machine/launcher failure, inspect ownership and remaining
|
||||
processes before manually clearing a leftover snapshot. Do not run broad cleanup.
|
||||
|
||||
Test credentials have initial access tokens so existing login rendering can be
|
||||
exercised; this is test fixture setup, not a fix to application token issuance.
|
||||
Secure downloads are tracked in TASK-004.
|
||||
|
||||
Adapter checks:
|
||||
|
||||
```sh
|
||||
python3 -m unittest discover -s scripts/tests -v
|
||||
bash -n scripts/testtask.sh .roborto/testtask-hook .roborto/testtask.conf
|
||||
```
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
"""Safety checks: python3 -m unittest discover -s scripts/tests -v."""
|
||||
import importlib.util
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
os.environ.update(ROBORTO_PROJECT_ROOT=str(ROOT), ROBORTO_RUN_DIR='/tmp/testtask-unit-run', ROBORTO_TASK_ID='002', ROBORTO_WORKTREE=str(ROOT / '.test-worktrees/task-002'))
|
||||
spec = importlib.util.spec_from_file_location('adapter', ROOT / 'scripts/testtask_adapter.py')
|
||||
adapter = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(adapter)
|
||||
|
||||
|
||||
class AdapterTests(unittest.TestCase):
|
||||
def test_snapshot_excludes_local_data_and_links(self):
|
||||
with tempfile.TemporaryDirectory() as temporary:
|
||||
root = Path(temporary)
|
||||
subprocess.run(['git', 'init', '-q', str(root)], check=True)
|
||||
for name in ['api/source.py', 'api/new_test.py', 'api/.env', 'api/accounts.sqlite', 'api/share/movie.mp4', 'react/node_modules/package/code.js', 'docs/snapshots/old.zip', 'api/id_rsa', '.roborto/testtask.conf']:
|
||||
path = root / name
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text('fixture')
|
||||
(root / 'api/link.py').symlink_to(root / 'api/source.py')
|
||||
subprocess.run(['git', '-C', str(root), 'add', 'api/source.py'], check=True)
|
||||
(root / 'api/source.py').write_text('unstaged change')
|
||||
files = adapter.safe_files(root)
|
||||
self.assertEqual(set(files), {'api/source.py', 'api/new_test.py', '.roborto/testtask.conf'})
|
||||
(root / 'api/new_test.py').write_text('updated')
|
||||
self.assertNotEqual(files, adapter.safe_files(root))
|
||||
|
||||
def test_cleanup_preserves_foreign_snapshot(self):
|
||||
with tempfile.TemporaryDirectory() as temporary:
|
||||
root = Path(temporary)
|
||||
snapshot = root / '.test-worktrees/task-002'
|
||||
snapshot.mkdir(parents=True)
|
||||
marker = snapshot / adapter.MARKER
|
||||
marker.write_text('/other/session')
|
||||
with patch.object(adapter, 'ROOT', root), patch.object(adapter, 'SNAPSHOT', snapshot):
|
||||
adapter.cleanup()
|
||||
self.assertTrue(snapshot.exists())
|
||||
marker.write_text(str(adapter.RUN))
|
||||
adapter.cleanup()
|
||||
adapter.cleanup()
|
||||
self.assertFalse(snapshot.exists())
|
||||
|
||||
def test_cleanup_rejects_unexpected_path(self):
|
||||
with patch.object(adapter, 'SNAPSHOT', Path('/tmp/unowned')):
|
||||
with self.assertRaises(RuntimeError):
|
||||
adapter.cleanup()
|
||||
|
||||
def test_existing_snapshot_is_never_replaced(self):
|
||||
with tempfile.TemporaryDirectory() as temporary:
|
||||
root = Path(temporary)
|
||||
snapshot = root / '.test-worktrees/task-002'
|
||||
snapshot.mkdir(parents=True)
|
||||
with patch.object(adapter, 'ROOT', root), patch.object(adapter, 'SNAPSHOT', snapshot):
|
||||
with self.assertRaisesRegex(RuntimeError, 'already exists'):
|
||||
adapter.validate()
|
||||
|
||||
def test_malformed_task_rejected(self):
|
||||
with patch.object(adapter, 'TASK', '../002'):
|
||||
with self.assertRaises(RuntimeError):
|
||||
adapter.validate()
|
||||
|
||||
def test_task_discovery(self):
|
||||
output = b'worktree /tmp/TASK-002\0HEAD abc\0branch refs/heads/task/TASK-002-authorization\0\0'
|
||||
with patch.object(adapter.subprocess, 'check_output', return_value=output):
|
||||
self.assertEqual(adapter.source(), Path('/tmp/TASK-002'))
|
||||
with patch.object(adapter, 'TASK', '999'):
|
||||
with self.assertRaisesRegex(RuntimeError, 'found 0'):
|
||||
adapter.source()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
Executable
+5
@@ -0,0 +1,5 @@
|
||||
#!/usr/bin/env bash
|
||||
set -Eeuo pipefail
|
||||
cd "$(dirname "${BASH_SOURCE[0]}")/.."
|
||||
command -v roborto-testtask >/dev/null || { echo 'Install roborto-testtask first.' >&2; exit 127; }
|
||||
exec roborto-testtask "$@"
|
||||
@@ -0,0 +1,203 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Local testtask hook: exact safe source copy, isolated state, foreground servers."""
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import secrets
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
ROOT = Path(os.environ['ROBORTO_PROJECT_ROOT']).resolve()
|
||||
RUN = Path(os.environ['ROBORTO_RUN_DIR']).resolve()
|
||||
TASK = os.environ['ROBORTO_TASK_ID']
|
||||
SNAPSHOT = Path(os.environ['ROBORTO_WORKTREE'])
|
||||
COMMON = Path(subprocess.check_output(['git', '-C', str(ROOT), 'rev-parse', '--path-format=absolute', '--git-common-dir'], text=True).strip())
|
||||
SHARED = COMMON.parent
|
||||
MARKER = '.testtask-owner'
|
||||
EXCLUDED_DIRS = {'.git', '.worktrees', '.test-worktrees', '.venv', 'venv', 'node_modules', 'share', 'instance', '__pycache__', '.pytest_cache', 'dist', 'dist-ssr', 'build', 'coverage', 'snapshots', 'logs'}
|
||||
SUFFIXES = ('.pyc', '.pyo', '.log', '.zip', '.db', '.sqlite', '.sqlite3', '.pem', '.key', '.p12', '.pfx')
|
||||
|
||||
|
||||
def fail(message):
|
||||
raise RuntimeError(message)
|
||||
|
||||
|
||||
def source():
|
||||
entries = subprocess.check_output(['git', '-C', str(ROOT), 'worktree', 'list', '--porcelain', '-z']).decode().split('\0')
|
||||
found, path = [], None
|
||||
for entry in entries:
|
||||
if entry.startswith('worktree '):
|
||||
path = Path(entry[9:])
|
||||
if entry.startswith('branch refs/heads/') and re.fullmatch(r'(?:task/TASK-' + TASK + r'-[\w-]+)', entry[18:]):
|
||||
found.append(path)
|
||||
if len(found) != 1:
|
||||
fail(f'Expected exactly one checked-out task/TASK-{TASK}-* branch; found {len(found)}')
|
||||
return found[0]
|
||||
|
||||
|
||||
def safe_files(src):
|
||||
names = subprocess.check_output(['git', '-C', str(src), 'ls-files', '-z', '--cached', '--others', '--exclude-standard']).split(b'\0')
|
||||
result = {}
|
||||
for raw in names:
|
||||
if not raw:
|
||||
continue
|
||||
relative = Path(os.fsdecode(raw))
|
||||
path = src / relative
|
||||
if any(part in EXCLUDED_DIRS for part in relative.parts):
|
||||
continue
|
||||
if any(part.startswith('.') and part not in {'.gitignore', '.roborto'} for part in relative.parts):
|
||||
continue
|
||||
if relative.name.lower().startswith(('credentials', 'id_rsa', 'id_ed25519')) or relative.name.lower().endswith(SUFFIXES):
|
||||
continue
|
||||
if any(parent.is_symlink() for parent in [path, *path.parents]) or not path.is_file():
|
||||
continue
|
||||
result[relative.as_posix()] = hashlib.sha256(path.read_bytes()).hexdigest()
|
||||
return result
|
||||
|
||||
|
||||
def dependencies():
|
||||
node = os.environ.get('FOLDERSHARE_TEST_NODE') or shutil.which('node')
|
||||
if not node:
|
||||
candidates = list((Path.home() / '.nvm/versions/node').glob('v*/bin/node'))
|
||||
candidates.sort(key=lambda p: tuple(int(n) for n in p.parents[1].name[1:].split('.')))
|
||||
node = str(candidates[-1]) if candidates else None
|
||||
vite = SHARED / 'react/node_modules/vite/bin/vite.js'
|
||||
if not node or not Path(node).is_file() or not vite.is_file():
|
||||
fail('Need Node >=18 and existing react/node_modules; install dependencies separately')
|
||||
version = subprocess.check_output([node, '-p', 'process.versions.node'], text=True)
|
||||
if int(version.split('.')[0]) < 18:
|
||||
fail('Node >=18 required; set FOLDERSHARE_TEST_NODE')
|
||||
return node, vite
|
||||
|
||||
|
||||
def validate():
|
||||
if not re.fullmatch(r'\d{3}', TASK):
|
||||
fail('Task ID must contain three digits')
|
||||
expected = ROOT / '.test-worktrees' / ('task-' + TASK)
|
||||
if SNAPSHOT != expected or SNAPSHOT.parent.is_symlink() or SNAPSHOT.is_symlink():
|
||||
fail('Unexpected or symlinked snapshot path')
|
||||
if SNAPSHOT.exists():
|
||||
fail('Snapshot already exists; preserve it and stop its owning session first')
|
||||
src = source()
|
||||
# Older application settings must never silently fall back to a local DB.
|
||||
if 'FOLDERSHARE_DATABASE_URI' not in (src / 'api/settings.py').read_text():
|
||||
fail('Candidate lacks isolated database configuration (TASK-002 prerequisite)')
|
||||
dependencies()
|
||||
import flask, flask_sqlalchemy, flask_httpauth, flask_migrate, sqlalchemy_serializer # noqa: F401
|
||||
print(f'Validated source {src}', file=sys.stderr)
|
||||
|
||||
|
||||
def prepare():
|
||||
validate()
|
||||
src = source()
|
||||
manifest = safe_files(src)
|
||||
SNAPSHOT.parent.mkdir(exist_ok=True)
|
||||
SNAPSHOT.mkdir(mode=0o700)
|
||||
(SNAPSHOT / MARKER).write_text(str(RUN))
|
||||
for name in manifest:
|
||||
dest = SNAPSHOT / name
|
||||
dest.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copy2(src / name, dest)
|
||||
copied = {name: hashlib.sha256((SNAPSHOT / name).read_bytes()).hexdigest() for name in manifest}
|
||||
if copied != manifest or safe_files(src) != manifest:
|
||||
fail('Source changed during snapshot creation; rerun with a stable candidate')
|
||||
(RUN / 'manifest.json').write_text(json.dumps({'source': str(src), 'files': manifest}, indent=2))
|
||||
(SNAPSHOT / 'react/node_modules').symlink_to(SHARED / 'react/node_modules', target_is_directory=True)
|
||||
(SNAPSHOT / 'react/testtask.vite.config.mjs').write_text('''import base from './vite.config.js';
|
||||
export default {...base, cacheDir: process.env.FOLDERSHARE_TEST_CACHE,
|
||||
server: {...base.server, host: '127.0.0.1', port: 5503, strictPort: true,
|
||||
proxy: {'/api': 'http://127.0.0.1:5502'}}};
|
||||
''')
|
||||
media = RUN / 'media'
|
||||
(media / 'friends').mkdir(parents=True)
|
||||
(media / 'friends/sample.txt').write_text('Disposable test media only.\n')
|
||||
(RUN / 'password').write_text(secrets.token_urlsafe(18))
|
||||
print(f'Snapshot verified: {len(manifest)} source files from {src}', file=sys.stderr)
|
||||
|
||||
|
||||
def start_backend():
|
||||
env = os.environ.copy()
|
||||
env.update(FOLDERSHARE_DATABASE_URI='sqlite:///' + str(RUN / 'accounts.sqlite'), ROOT_PATH=str(RUN / 'media'), PYTHON_DOTENV_DISABLED='1', DEBUG='False', SQLALCHEMY_ECHO='False', PYTHONPATH=str(SNAPSHOT / 'api'))
|
||||
bootstrap = '''from pathlib import Path
|
||||
from settings import app, db
|
||||
from models.user import User
|
||||
import os
|
||||
assert app.config['SQLALCHEMY_DATABASE_URI'] == os.environ['FOLDERSHARE_DATABASE_URI'], 'Unsafe database configuration'
|
||||
with app.app_context():
|
||||
db.create_all()
|
||||
for name, admin, root in [('captain', True, None), ('friend', False, '/friends'), ('unassigned', False, None), ('disabled', False, '/friends')]:
|
||||
user = User(username=name, is_admin=admin, root=root, login_disabled=name == 'disabled')
|
||||
user.set_password(Path(os.environ['ROBORTO_RUN_DIR'], 'password').read_text())
|
||||
db.session.add(user)
|
||||
user.get_token()
|
||||
db.session.commit()
|
||||
import api
|
||||
app.run(host='127.0.0.1', port=5502, debug=False, use_reloader=False)
|
||||
'''
|
||||
os.chdir(SNAPSHOT / 'api')
|
||||
os.execve(sys.executable, [sys.executable, '-c', bootstrap], env)
|
||||
|
||||
|
||||
def start_frontend():
|
||||
node, vite = dependencies()
|
||||
env = os.environ.copy()
|
||||
env['FOLDERSHARE_TEST_CACHE'] = str(RUN / 'vite-cache')
|
||||
os.chdir(SNAPSHOT / 'react')
|
||||
os.execve(node, [node, str(vite), '--config', 'testtask.vite.config.mjs'], env)
|
||||
|
||||
|
||||
def credentials():
|
||||
# Real HTTP checks, in addition to engine port checks.
|
||||
from urllib.request import Request, urlopen
|
||||
from urllib.error import HTTPError
|
||||
for base in ['http://127.0.0.1:5502', 'http://127.0.0.1:5503']:
|
||||
try:
|
||||
urlopen(base + '/api/file/root', timeout=5)
|
||||
fail('Protected API unexpectedly allowed an anonymous request')
|
||||
except HTTPError as error:
|
||||
if error.code != 401:
|
||||
raise
|
||||
password = (RUN / 'password').read_text()
|
||||
for name in ['captain', 'friend', 'unassigned', 'disabled']:
|
||||
basic = base64.b64encode(f'{name}:{password}'.encode()).decode()
|
||||
request = Request('http://127.0.0.1:5503/api/auth/token', method='POST', headers={'Authorization': 'Basic ' + basic})
|
||||
try:
|
||||
with urlopen(request, timeout=5) as response:
|
||||
data = json.load(response)
|
||||
if name == 'disabled' or not data.get('token'):
|
||||
fail('Disposable login fixture failed')
|
||||
except HTTPError as error:
|
||||
if name != 'disabled' or error.code != 401:
|
||||
raise
|
||||
manifest = json.loads((RUN / 'manifest.json').read_text())
|
||||
if safe_files(Path(manifest['source'])) != manifest['files']:
|
||||
fail('Candidate changed since snapshot creation; stop and rerun before testing')
|
||||
with urlopen('http://127.0.0.1:5503', timeout=5) as response:
|
||||
if response.status != 200:
|
||||
fail('Frontend HTTP check failed')
|
||||
print('HTTP readiness passed. Disposable accounts: captain (admin), friend, unassigned, disabled.')
|
||||
print('Shared session password:', (RUN / 'password').read_text())
|
||||
print('Candidate snapshot:', SNAPSHOT)
|
||||
print('Source must remain unchanged while testing; Ctrl-C stops servers and removes this snapshot.')
|
||||
|
||||
|
||||
def cleanup():
|
||||
expected = ROOT / '.test-worktrees' / ('task-' + TASK)
|
||||
if SNAPSHOT != expected or SNAPSHOT.parent.is_symlink():
|
||||
fail('Refusing cleanup outside the owned snapshot path')
|
||||
marker = SNAPSHOT / MARKER
|
||||
if not SNAPSHOT.is_symlink() and marker.is_file() and marker.read_text() == str(RUN):
|
||||
shutil.rmtree(SNAPSHOT)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
actions = {'validate': validate, 'prepare': prepare, 'start-backend': start_backend, 'start-frontend': start_frontend, 'credentials': credentials, 'cleanup': cleanup}
|
||||
actions[sys.argv[1]]()
|
||||
except Exception as error:
|
||||
print(f'testtask: {error}', file=sys.stderr)
|
||||
sys.exit(1)
|
||||
Reference in New Issue
Block a user