| 1 | import importlib.util |
| 2 | import json |
| 3 | import os |
| 4 | from pathlib import Path |
| 5 | import tempfile |
| 6 | import sys |
| 7 | import unittest |
| 8 | from unittest.mock import patch |
| 9 | |
| 10 | sys.dont_write_bytecode = True |
| 11 | |
| 12 | spec = importlib.util.spec_from_file_location('staging', Path(__file__).with_name('staging-thin.py')) |
| 13 | staging = importlib.util.module_from_spec(spec) |
| 14 | spec.loader.exec_module(staging) |
| 15 | |
| 16 | |
| 17 | class SuiteTest(unittest.TestCase): |
| 18 | def test_fresh_runs_and_green_record(self): |
| 19 | with tempfile.TemporaryDirectory(dir=os.environ.get('TMPDIR', str(Path.home() / '.cache'))) as folder: |
| 20 | root = Path(folder) |
| 21 | suite_root = root / 'suite' |
| 22 | (suite_root / 'config').mkdir(parents=True) |
| 23 | bindings = suite_root / 'config/bindings.json' |
| 24 | original = json.dumps([{'local_id': 'claude-a', 'person_id': 'old.invalid'}, |
| 25 | {'local_id': 'codex-app', 'person_id': 'old.invalid'}]) |
| 26 | bindings.write_text(original) |
| 27 | service = suite_root / 'service.env' |
| 28 | original_service = 'EQUIPO_TOOL_PROXY_PATH="/installed/equipo-tool-proxy"\nEQUIPO_RUNNER_STATE_DIR="/existing/state"\n' |
| 29 | service.write_text(original_service) |
| 30 | addresses, runs, cleaned, records, enrolled, retired = [], [], [], [], [], [] |
| 31 | fail = False |
| 32 | report_mode = "valid" |
| 33 | |
| 34 | def mail(address, path): |
| 35 | staging.private(path, 'cookie') |
| 36 | return 'cookie' |
| 37 | |
| 38 | def setup(cookie, **extra): |
| 39 | if 'EQUIPO_STAGING_ADD_OWNER' in extra: |
| 40 | addresses.append(extra['EQUIPO_STAGING_ADD_OWNER']) |
| 41 | if 'EQUIPO_STAGING_TOKEN_FILE' in extra: |
| 42 | staging.private(Path(extra['EQUIPO_STAGING_TOKEN_FILE']), 'fresh-token') |
| 43 | if 'EQUIPO_STAGING_REMOVE_SUITE' in extra: |
| 44 | # Retired by the owner, after its tasks were cleaned up. |
| 45 | self.assertEqual(cookie, 'cookie') |
| 46 | self.assertEqual(cleaned[-1], extra['EQUIPO_STAGING_REMOVE_SUITE']) |
| 47 | retired.append(extra['EQUIPO_STAGING_REMOVE_SUITE']) |
| 48 | |
| 49 | def run(args, **kwargs): |
| 50 | if 'is-active' in args: |
| 51 | return 'active\n' |
| 52 | if '^TestStaging$' in args: |
| 53 | env = kwargs['env'] |
| 54 | runs.append(env) |
| 55 | self.assertEqual(kwargs['log'].parent, root / 'suite-logs') |
| 56 | self.assertIn(env['EQUIPO_STAGING_RUN_ID'], kwargs['log'].name) |
| 57 | self.assertEqual(env['EQUIPO_STAGING_TOKEN'], 'fresh-token') |
| 58 | self.assertGreaterEqual(int(env['EQUIPO_STAGING_TURN_LIMIT']), 25) |
| 59 | running = staging.read_env(service) |
| 60 | self.assertTrue(all(b['person_id'] == addresses[-1] for b in json.loads(Path(running['EQUIPO_ACCOUNT_BINDINGS_PATH']).read_text()))) |
| 61 | state = Path(running['EQUIPO_RUNNER_STATE_DIR']) |
| 62 | self.assertEqual((state / 'person').read_text(), addresses[-1]) |
| 63 | self.assertEqual(running['EQUIPO_RUNNER_CREATE_REPOS'], '0') |
| 64 | if fail: |
| 65 | raise RuntimeError('scenario failed') |
| 66 | if report_mode != 'missing': |
| 67 | Path(env['EQUIPO_HEADLESS_REPORT']).write_text('{}' if report_mode == 'valid' else 'broken') |
| 68 | return '' |
| 69 | |
| 70 | def enrol(release, env, cookie): |
| 71 | enrolled.append(addresses[-1]) |
| 72 | self.assertEqual(cookie.read_text(), 'cookie') |
| 73 | self.assertEqual(release, Path('/installed')) |
| 74 | state = Path(env['EQUIPO_RUNNER_STATE_DIR']) |
| 75 | self.assertEqual(list(state.iterdir()), []) |
| 76 | self.assertNotEqual(str(state), '/existing/state') |
| 77 | (state / 'person').write_text(addresses[-1]) |
| 78 | |
| 79 | with patch.multiple(staging, ROOT=root, SUITE_ROOT=suite_root), \ |
| 80 | patch.object(staging, 'mail_signin', side_effect=mail), \ |
| 81 | patch.object(staging, 'setup_test', side_effect=setup), \ |
| 82 | patch.object(staging, 'claude_a', return_value={'person_id': 'owner@example.com'}), \ |
| 83 | patch.object(staging, 'run', side_effect=run), \ |
| 84 | patch.object(staging, 'enrol', side_effect=enrol), \ |
| 85 | patch.object(staging, 'cleanup_suite', side_effect=lambda token, person: cleaned.append(person)), \ |
| 86 | patch.object(staging, 'record_running', side_effect=lambda: records.append(True)), \ |
| 87 | patch.dict(os.environ, {}, clear=False): |
| 88 | os.environ.pop('EQUIPO_STAGING_TURN_LIMIT', None) |
| 89 | os.environ['TMPDIR'] = str(root) |
| 90 | staging.suite() |
| 91 | staging.suite('2_project') |
| 92 | fail = True |
| 93 | with self.assertRaisesRegex(RuntimeError, 'scenario failed'): |
| 94 | staging.suite() |
| 95 | fail = False |
| 96 | report_mode = 'missing' |
| 97 | with self.assertRaises(FileNotFoundError): |
| 98 | staging.suite() |
| 99 | report_mode = 'broken' |
| 100 | with self.assertRaises(json.JSONDecodeError): |
| 101 | staging.suite() |
| 102 | self.assertEqual(len(set(addresses)), 5) |
| 103 | self.assertTrue(all(a.startswith('suite-') and a.endswith('@equipo-staging.invalid') for a in addresses)) |
| 104 | self.assertEqual(enrolled, addresses) |
| 105 | self.assertEqual(cleaned, addresses) |
| 106 | # Every run's person, and with it the runner it enrolled, is |
| 107 | # removed at the end, a failed run's too (2026-11-28: 32 suite |
| 108 | # runners were left enrolled on staging). |
| 109 | self.assertEqual(retired, addresses) |
| 110 | self.assertEqual(len(records), 1) |
| 111 | self.assertEqual(bindings.read_text(), original) |
| 112 | self.assertEqual(service.read_text(), original_service) |
| 113 | self.assertEqual(len({e['EQUIPO_STAGING_RUN_ID'] for e in runs}), 5) |
| 114 | self.assertFalse(list(root.glob('equipo-suite-*'))) |
| 115 | |
| 116 | def test_cleanup_only_this_person_and_continues_after_failure(self): |
| 117 | person = 'suite-run@equipo-staging.invalid' |
| 118 | tasks = [dict(id='ours-1', creator=person, stage='noted'), |
| 119 | dict(id='human', creator='owner@example.com', stage='in_progress'), |
| 120 | dict(id='old', creator='suite-old@equipo-staging.invalid', stage='noted'), |
| 121 | dict(id='ours-done', creator=person, stage='done'), |
| 122 | dict(id='ours-2', creator=person, stage='in_progress')] |
| 123 | requests = [] |
| 124 | from io import BytesIO |
| 125 | |
| 126 | def respond(req, **kwargs): |
| 127 | requests.append(req) |
| 128 | if req.full_url.endswith('/tasks'): |
| 129 | return BytesIO(json.dumps({'items': tasks}).encode()) |
| 130 | if 'ours-1' in req.full_url: |
| 131 | raise OSError('temporary failure') |
| 132 | return BytesIO(b'{}') |
| 133 | |
| 134 | def settle(seconds): |
| 135 | # The runner confirms termination a little later. |
| 136 | tasks[-1]['stage'] = 'cancelled' |
| 137 | |
| 138 | with patch.object(staging.urllib.request, 'urlopen', side_effect=respond), \ |
| 139 | patch.object(staging.time, 'sleep', side_effect=settle): |
| 140 | staging.cleanup_suite('test-token', person) |
| 141 | self.assertEqual([r.method for r in requests], ['GET', 'POST', 'POST', 'GET', 'GET']) |
| 142 | self.assertEqual([r.full_url.rsplit('/', 2)[-2] for r in requests[1:3]], ['ours-1', 'ours-2']) |
| 143 | self.assertTrue(all(r.get_header('Authorization') == 'Bearer test-token' for r in requests)) |
| 144 | |
| 145 | def test_cleanup_waits_for_running_steps_to_stop(self): |
| 146 | # A cancel only finishes once the runner confirms; stopping the |
| 147 | # suite runner first strands the step and blocks every release. |
| 148 | person = 'suite-run@equipo-staging.invalid' |
| 149 | tasks = [dict(id='ours', creator=person, stage='in_progress')] |
| 150 | from io import BytesIO |
| 151 | clock = [0.0] |
| 152 | |
| 153 | def respond(req, **kwargs): |
| 154 | if req.full_url.endswith('/tasks'): |
| 155 | return BytesIO(json.dumps({'items': tasks}).encode()) |
| 156 | return BytesIO(b'{}') |
| 157 | |
| 158 | def sleep(seconds): |
| 159 | clock[0] += seconds |
| 160 | |
| 161 | with patch.object(staging.urllib.request, 'urlopen', side_effect=respond), \ |
| 162 | patch.object(staging.time, 'sleep', side_effect=sleep), \ |
| 163 | patch.object(staging.time, 'monotonic', side_effect=lambda: clock[0]): |
| 164 | staging.cleanup_suite('test-token', person) |
| 165 | self.assertGreaterEqual(clock[0], staging.CANCEL_WAIT) |
| 166 | |
| 167 | def test_retire_failure_does_not_hide_the_run(self): |
| 168 | # A removal that fails is said, and the run's own outcome stands. |
| 169 | def setup(cookie, **extra): |
| 170 | raise RuntimeError('HTTP 500') |
| 171 | |
| 172 | with tempfile.TemporaryDirectory(dir=os.environ.get('TMPDIR', str(Path.home() / '.cache'))) as folder, \ |
| 173 | patch.object(staging, 'mail_signin', return_value='cookie'), \ |
| 174 | patch.object(staging, 'claude_a', return_value={'person_id': 'owner@example.com'}), \ |
| 175 | patch.object(staging, 'setup_test', side_effect=setup), \ |
| 176 | patch('builtins.print') as said: |
| 177 | staging.retire_suite('suite-run@equipo-staging.invalid', Path(folder) / 'owner-cookie') |
| 178 | self.assertIn('suite retire', said.call_args[0][0]) |
| 179 | with self.assertRaises(ValueError): |
| 180 | staging.retire_suite('owner@example.com', Path('/nowhere')) |
| 181 | |
| 182 | def test_stale_suite_runners_are_retired_counting_only(self): |
| 183 | # The one-off cleanup: suite people whose runners are still |
| 184 | # enrolled, read from staging's database copy, are removed by the |
| 185 | # owner in one pass; only counts are printed, never an address. |
| 186 | counts = iter(['count=32\n', 'count=0\n']) |
| 187 | sql, removed = [], [] |
| 188 | |
| 189 | def carlos(verb, *args, quiet=False): |
| 190 | sql.append(args[-1]) |
| 191 | if "group_concat" in args[-1]: |
| 192 | return "header\npersons=suite-a@equipo-staging.invalid,suite-b@equipo-staging.invalid,owner@example.com\n" |
| 193 | return next(counts) |
| 194 | |
| 195 | def setup(cookie, **extra): |
| 196 | removed.append(extra['EQUIPO_STAGING_REMOVE_SUITE']) |
| 197 | |
| 198 | with tempfile.TemporaryDirectory(dir=os.environ.get('TMPDIR', str(Path.home() / '.cache'))) as folder, \ |
| 199 | patch.object(staging, 'ROOT', Path(folder)), \ |
| 200 | patch.object(staging, 'carlos', side_effect=carlos), \ |
| 201 | patch.object(staging, 'mail_signin', return_value='cookie'), \ |
| 202 | patch.object(staging, 'claude_a', return_value={'person_id': 'owner@example.com'}), \ |
| 203 | patch.object(staging, 'setup_test', side_effect=setup), \ |
| 204 | patch.object(staging.time, 'sleep'), \ |
| 205 | patch('builtins.print') as said: |
| 206 | staging.cleanup_suite_runners() |
| 207 | self.assertEqual(removed, ['suite-a@equipo-staging.invalid,suite-b@equipo-staging.invalid']) |
| 208 | self.assertTrue(all("LIKE 'suite-%@equipo-staging.invalid'" in q and 'revoked_at IS NULL' in q for q in sql)) |
| 209 | out = ' '.join(str(c.args[0]) for c in said.call_args_list) |
| 210 | self.assertNotIn('@', out) |
| 211 | self.assertIn('32', out) |
| 212 | self.assertIn('2', out) |
| 213 | self.assertIn('0', out) |
| 214 | |
| 215 | def test_in_flight_ignores_suite_people(self): |
| 216 | seen = [] |
| 217 | |
| 218 | def carlos(verb, *args, quiet=False): |
| 219 | seen.append(args[-1]) |
| 220 | return '0/0\n' |
| 221 | |
| 222 | with patch.object(staging, 'carlos', side_effect=carlos): |
| 223 | self.assertEqual(staging.in_flight(), (0, 0)) |
| 224 | self.assertIn("task_id NOT IN (SELECT id FROM chat_tasks WHERE creator LIKE 'suite-%@equipo-staging.invalid')", seen[0]) |
| 225 | |
| 226 | def test_signin_ignores_links_logged_before_it_began(self): |
| 227 | origin = staging.ORIGIN |
| 228 | old = origin + '/auth/verify?t=old' |
| 229 | new = origin + '/auth/verify?t=new' |
| 230 | other = origin + '/auth/verify?t=other' |
| 231 | logs = '\n'.join(['NOT SENT to a@example.com: ' + old, |
| 232 | 'NOT SENT to b@example.com: ' + other, |
| 233 | 'NOT SENT to a@example.com: ' + new]) |
| 234 | before = set(staging.signin_links(logs.split('\n')[0], 'a@example.com', set())) |
| 235 | self.assertEqual(staging.signin_links(logs, 'a@example.com', before), [new]) |
| 236 | self.assertEqual(staging.signin_links(logs.split('\n')[0], 'a@example.com', before), []) |
| 237 | |
| 238 | |
| 239 | # What go test -v prints when a staging scenario fails: the failure lines, |
| 240 | # then far more than 2000 characters of passing chatter and timing logs. |
| 241 | FAILED_RUN = '''=== RUN TestStaging |
| 242 | === RUN TestStaging/7_stream_resume |
| 243 | scenarios_test.go:530: model turns used: 1 (total 3) |
| 244 | === RUN TestStaging/8_instance_restart |
| 245 | scenarios_test.go:380: restart: carlos restart failed: exit status 1 |
| 246 | second line of the same message |
| 247 | scenarios_test.go:385: sign-in https://x.invalid/auth/verify?token=abc kept |
| 248 | panic.go:694: model turns used: 1 (total 4) |
| 249 | === NAME TestStaging |
| 250 | scenarios_test.go:536: model turns used: 4 |
| 251 | ''' + ''.join(f' scenarios_test.go:540: timing {i}: {{"first_token": "1.2s", "turn": "3.4s"}}\n' for i in range(200)) + '''--- FAIL: TestStaging (300.00s) |
| 252 | --- PASS: TestStaging/7_stream_resume (12.00s) |
| 253 | --- FAIL: TestStaging/8_instance_restart (240.00s) |
| 254 | FAIL |
| 255 | FAIL\tequipo/internal/headless\t300.123s |
| 256 | FAIL |
| 257 | ''' |
| 258 | |
| 259 | |
| 260 | class FailureOutputTest(unittest.TestCase): |
| 261 | def test_failed_scenario_keeps_its_message_and_the_full_log(self): |
| 262 | with scratch() as folder: |
| 263 | root = Path(folder) |
| 264 | log = root / 'suite-logs' / 'run.log' |
| 265 | fake = root / 'fake.txt' |
| 266 | fake.write_text(FAILED_RUN) |
| 267 | with self.assertRaises(RuntimeError) as caught: |
| 268 | staging.run([sys.executable, '-c', 'import sys; sys.stdout.write(open(sys.argv[1]).read()); sys.exit(1)', str(fake)], log=log) |
| 269 | message = str(caught.exception) |
| 270 | self.assertIn('--- FAIL: TestStaging/8_instance_restart (240.00s)', message) |
| 271 | self.assertIn('carlos restart failed: exit status 1', message) |
| 272 | self.assertIn('second line of the same message', message) |
| 273 | self.assertIn('scenarios_test.go:385', message) |
| 274 | # The failed scenario comes before its parent's chatter. |
| 275 | self.assertLess(message.index('--- FAIL: TestStaging/8_instance_restart'), message.index('--- FAIL: TestStaging (')) |
| 276 | self.assertNotIn('7_stream_resume', message) |
| 277 | self.assertIn(str(log), message) |
| 278 | self.assertNotIn('token=abc', message) |
| 279 | # The log is the whole output, redacted, private. |
| 280 | self.assertEqual(log.stat().st_mode & 0o777, 0o600) |
| 281 | text = log.read_text() |
| 282 | self.assertIn('timing 199', text) |
| 283 | self.assertIn('7_stream_resume', text) |
| 284 | self.assertNotIn('token=abc', text) |
| 285 | |
| 286 | def test_a_long_failure_keeps_its_last_lines(self): |
| 287 | lines = ['=== RUN TestStaging/cancel'] + [f' scenarios_test.go:416: line {i:05d} ' + 'x' * 80 for i in range(1000)] + ['--- FAIL: TestStaging/cancel (60.50s)'] |
| 288 | summary = staging.failures('\n'.join(lines) + '\n') |
| 289 | self.assertIn('line 00999', summary) |
| 290 | self.assertNotIn('line 00000', summary) |
| 291 | self.assertLess(len(summary), 3 * staging.FAILURE_TAIL) |
| 292 | |
| 293 | def test_a_panic_or_timeout_is_kept(self): |
| 294 | out = '=== RUN TestStaging/cancel\npanic: test timed out after 90m0s\n\trunning tests:\n\t\tTestStaging/cancel (1h29m)\n' |
| 295 | self.assertIn('panic: test timed out after 90m0s', staging.failures(out)) |
| 296 | self.assertIn('TestStaging/cancel (1h29m)', staging.failures(out)) |
| 297 | |
| 298 | def test_success_writes_the_log_too(self): |
| 299 | with scratch() as folder: |
| 300 | log = Path(folder) / 'suite-logs' / 'ok.log' |
| 301 | staging.run([sys.executable, '-c', 'print("--- PASS: TestStaging (1.00s)")'], log=log, quiet=True) |
| 302 | self.assertIn('--- PASS', log.read_text()) |
| 303 | |
| 304 | |
| 305 | def scratch(): |
| 306 | return tempfile.TemporaryDirectory(dir=os.environ.get('TMPDIR', str(Path.home() / '.cache'))) |
| 307 | |
| 308 | |
| 309 | class ReleaseTest(unittest.TestCase): |
| 310 | """What the staging runner is installed with.""" |
| 311 | |
| 312 | def release(self, repo, sha): |
| 313 | built = repo / 'releases' / f'equipo-runner-linux-amd64-{sha}' |
| 314 | built.mkdir(parents=True) |
| 315 | for name in ('equipo-runner', 'equipo-tool-proxy', 'gitleaks'): |
| 316 | (built / name).write_bytes(name.encode() + b' bytes') |
| 317 | (built / name).chmod(0o700) |
| 318 | made = {k: staging.sha256(built / n) for k, n in (('runner', 'equipo-runner'), ('tool_proxy', 'equipo-tool-proxy'), ('gitleaks', 'gitleaks'))} |
| 319 | (repo / 'releases' / f'equipo-linux-arm64-{sha}.manifest.json').write_text(json.dumps({'sha256': made})) |
| 320 | return built |
| 321 | |
| 322 | def test_build_installs_the_preview_scanner_beside_the_runner(self): |
| 323 | # The runner looks for gitleaks next to its own executable; without |
| 324 | # it every preview fails with preview_scanner. |
| 325 | with scratch() as folder: |
| 326 | repo, root = Path(folder) / 'repo', Path(folder) / 'root' |
| 327 | built = self.release(repo, 'abc1234') |
| 328 | prod = Path(folder) / 'prod.env' |
| 329 | prod.write_text('EQUIPO_CLAUDE_PATH="/bin/claude"\n') |
| 330 | with patch.multiple(staging, REPO=repo, ROOT=root, PROD_ENV=prod), \ |
| 331 | patch.object(staging, 'head', return_value='abc1234'), \ |
| 332 | patch.object(staging, 'run', return_value=''): |
| 333 | staging.build() |
| 334 | scanner = root / 'releases/abc1234/gitleaks' |
| 335 | self.assertEqual(scanner.read_bytes(), (built / 'gitleaks').read_bytes()) |
| 336 | self.assertTrue(os.access(scanner, os.X_OK)) |
| 337 | |
| 338 | def test_build_installs_the_renderer_beside_the_runner(self): |
| 339 | # The published renderer is downloaded in full and held to the |
| 340 | # release (publish-renderer.sh check), after provenance and before |
| 341 | # anything is installed; the staged runner unpacks that download |
| 342 | # beside itself (install-renderer); verify-installed then checks |
| 343 | # the tree and renders the fixture page with it. |
| 344 | with scratch() as folder: |
| 345 | repo, root = Path(folder) / 'repo', Path(folder) / 'root' |
| 346 | built = self.release(repo, 'abc1234') |
| 347 | prod = Path(folder) / 'prod.env' |
| 348 | prod.write_text('EQUIPO_CLAUDE_PATH="/bin/claude"\n') |
| 349 | with patch.multiple(staging, REPO=repo, ROOT=root, PROD_ENV=prod), \ |
| 350 | patch.object(staging, 'head', return_value='abc1234'), \ |
| 351 | patch.object(staging, 'run', return_value='') as run: |
| 352 | staging.build() |
| 353 | calls = [c.args[0] for c in run.call_args_list] |
| 354 | published = root / 'releases/abc1234/published-renderer' |
| 355 | check = ['scripts/publish-renderer.sh', 'check', str(built), str(published)] |
| 356 | install = [str(root / 'releases/abc1234/equipo-runner'), 'install-renderer', str(published / 'renderer.tar.gz')] |
| 357 | self.assertIn(check, calls) |
| 358 | self.assertIn(install, calls) |
| 359 | # After the provenance check, which holds the runner to the |
| 360 | # release, and the published asset's check. |
| 361 | verify = ['python3', 'scripts/staged-artifacts.py', 'verify', 'abc1234'] |
| 362 | self.assertLess(calls.index(verify), calls.index(check)) |
| 363 | self.assertLess(calls.index(check), calls.index(install)) |
| 364 | |
| 365 | def test_provenance_holds_the_scanner_to_the_release(self): |
| 366 | with scratch() as folder: |
| 367 | repo, root = Path(folder) / 'repo', Path(folder) / 'root' |
| 368 | built = self.release(repo, 'abc1234') |
| 369 | installed = root / 'releases/abc1234' |
| 370 | installed.mkdir(parents=True) |
| 371 | for name in ('equipo-runner', 'equipo-tool-proxy', 'gitleaks'): |
| 372 | (installed / name).write_bytes((built / name).read_bytes()) |
| 373 | with patch.multiple(staging, REPO=repo, ROOT=root), patch.object(staging, 'run', return_value=''): |
| 374 | self.assertIn('gitleaks', staging.provenance('abc1234')) |
| 375 | (installed / 'gitleaks').write_bytes(b'another scanner') |
| 376 | with self.assertRaisesRegex(RuntimeError, 'gitleaks'): |
| 377 | staging.provenance('abc1234') |
| 378 | (installed / 'gitleaks').unlink() |
| 379 | with self.assertRaisesRegex(RuntimeError, 'gitleaks'): |
| 380 | staging.provenance('abc1234') |
| 381 | |
| 382 | |
| 383 | class CredentialTest(unittest.TestCase): |
| 384 | """The owner's runner merges into repositories it creates for jobs.""" |
| 385 | |
| 386 | API, GIT = 'agent-bearer-not-for-print', 'agent-pat-not-for-print' |
| 387 | |
| 388 | def production(self, folder, repositories): |
| 389 | path = Path(folder) / 'prod/amadan.json' |
| 390 | staging.private(path, json.dumps({'agent': 'equipo-docs-t1~paul@example.com', 'repositories': repositories})) |
| 391 | prod = Path(folder) / 'prod/service.env' |
| 392 | prod.write_text(f'EQUIPO_AMADAN_CREDENTIAL_PATH="{path}"\nEQUIPO_GIT_PATH="/usr/bin/git"\n') |
| 393 | return path, prod |
| 394 | |
| 395 | def test_owner_runner_gets_an_agent_wide_credential_and_production_keeps_its_own(self): |
| 396 | with scratch() as folder: |
| 397 | shared = {'api': self.API, 'git': self.GIT} |
| 398 | source, prod = self.production(folder, {'amadan.net/oficina/equipo': shared, 'amadan.net/oficina/docs': shared}) |
| 399 | before = source.read_bytes() |
| 400 | root, home = Path(folder) / 'root', Path(folder) / 'home' |
| 401 | release = Path(folder) / 'release' |
| 402 | release.mkdir() |
| 403 | for r in (root, root / 'suite'): |
| 404 | (r / 'state').mkdir(parents=True) |
| 405 | (r / 'state/credentials.json').write_text('{}') |
| 406 | out = [] |
| 407 | with patch.multiple(staging, ROOT=root, SUITE_ROOT=root / 'suite', PROD_ENV=prod), \ |
| 408 | patch.object(staging.Path, 'home', return_value=home), \ |
| 409 | patch.object(staging, 'run', return_value=''), \ |
| 410 | patch.object(staging, 'instance_id', return_value='INSTANCE'), \ |
| 411 | patch.object(staging, 'claude_a', return_value={'local_id': 'claude-a'}), \ |
| 412 | patch.object(staging, 'added_in_app', return_value=[]), \ |
| 413 | patch.object(staging, 'sha256', return_value='digest'), \ |
| 414 | patch('builtins.print', side_effect=lambda *a, **k: out.append(' '.join(map(str, a)))): |
| 415 | staging.install('abc1234', release, root, staging.UNIT, 'owner@example.com', root / 'cookie', create=True) |
| 416 | staging.install('abc1234', release, root / 'suite', staging.SUITE_UNIT, staging.SUITE, root / 'suite/cookie', create=False) |
| 417 | owner = Path(staging.read_env(root / 'service.env')['EQUIPO_AMADAN_CREDENTIAL_PATH']) |
| 418 | self.assertEqual(owner, root / 'amadan.json') |
| 419 | self.assertEqual(owner.stat().st_mode & 0o777, 0o600) |
| 420 | self.assertEqual(json.loads(owner.read_text()), |
| 421 | {'agent': 'equipo-docs-t1~paul@example.com', 'api': self.API, 'git': self.GIT}) |
| 422 | self.assertEqual(staging.read_env(root / 'suite/service.env')['EQUIPO_AMADAN_CREDENTIAL_PATH'], str(source)) |
| 423 | self.assertEqual(source.read_bytes(), before) |
| 424 | self.assertFalse(any(self.API in line or self.GIT in line for line in out)) |
| 425 | |
| 426 | def test_refuses_without_one_bearer_and_one_git_pat(self): |
| 427 | for name, repositories in (('two bearers', {'amadan.net/a/b': {'api': 'one', 'git': 'pat'}, 'amadan.net/a/c': {'api': 'two', 'git': 'pat'}}), |
| 428 | ('legacy, no git', {'amadan.net/a/b': 'bearer-only'}), |
| 429 | ('empty', {})): |
| 430 | with self.subTest(name), scratch() as folder: |
| 431 | source, _ = self.production(folder, repositories) |
| 432 | root = Path(folder) / 'root' |
| 433 | with patch.object(staging, 'ROOT', root): |
| 434 | with self.assertRaisesRegex(RuntimeError, 'agent bearer'): |
| 435 | staging.agent_credential(source) |
| 436 | self.assertFalse((root / 'amadan.json').exists()) |
| 437 | |
| 438 | def test_keeps_an_agent_wide_entry_production_already_has(self): |
| 439 | with scratch() as folder: |
| 440 | source = Path(folder) / 'amadan.json' |
| 441 | staging.private(source, json.dumps({'agent': 'a~p@example.com', 'api': self.API, 'git': self.GIT, |
| 442 | 'repositories': {'amadan.net/a/b': {'api': 'old', 'git': 'old'}}})) |
| 443 | root = Path(folder) / 'root' |
| 444 | with patch.object(staging, 'ROOT', root): |
| 445 | written = staging.agent_credential(source) |
| 446 | self.assertEqual(json.loads(written.read_text()), {'agent': 'a~p@example.com', 'api': self.API, 'git': self.GIT}) |
| 447 | |
| 448 | |
| 449 | if __name__ == '__main__': |
| 450 | unittest.main() |
| 451 | |