GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Kuiper, cosmos and drawing engines / cosmic / tools/explore

Test Extras and 1 more file

A test in the explore folder of Cosmic that checks Extras. It sets up (`setUp`) and runs extras (`run_extras`).

524 lines of Python from cosmic, in 2 files. Topic: Kuiper, cosmos and drawing engines. Section 1140 of 2044.

Cut 2026-12-06T03:07:51+00:00. A copy for reading; the repository at the stated commit is the source.

In the State lines below, domain stage, users and canonical status are rule-based first approximations from code and path evidence (rules explore-agent-rules-v1), not observed facts: the rules.

In this section

  1. Test Extras test · cosmic / tools/explore/test_extras.py lines 1–316
  2. Test Ship test · cosmic / tools/explore/test_ship.py lines 1–208

Test Extras

A test in the explore folder of Cosmic that checks Extras. It sets up (`setUp`) and runs extras (`run_extras`).

testcosmic / tools/explore/test_extras.py · lines 1–316 of 316 · Entry point · pattern tearDown (shared by 38 files)

What it does
It tests its inputs. Defines 25 functions or classes, including ex, ExtrasTest, setUp, tearDown, run_extras. Uses libraries json, os, shutil, sys, tempfile. Side effects: changes the web page (DOM); reads or writes files; starts processes.
Inputs & outputs
In: JSON file data.json; JSON file jobs.json; JSON file build_graph.json; JSON file extras.json; JSON file board.json; JSON file identity.json; JSON file graph.json; JSON file keys.json. Out: JSON file identity.json; JSON file r.json; JSON file a.json; JSON file b.json; SVG drawing.
Downstream impact
It is itself an entry point (test); no other file was found loading it.
What it achieves
Tests for `extras.py`. It writes `../index.html`. It accepts `--graph`, `--out` and `--secret-key`.
Why it matters
Guards the behaviour of Extras.
Application
cosmic · tools/explore · test
Uses
Extras (import), json, os, shutil, sys, tempfile, textwrap, unittest, argparse
Used by
none found
Produces
ex, ExtrasTest
Defines here
ex, ExtrasTest, setUp, tearDown, run_extras, hub, test_missing_and_failing_extras_are_skipped, test_strict_exit_code, test_timeout_is_a_skip, test_hub_lists_only_existing_extras, test_builtin_cards_when_present, test_sitemap_llms_robots, test_link_index_opt_in_and_idempotent, test_step_overrides, test_data_only_extra_has_no_card, test_required_flag_missing_is_pending, test_post_processors, test_lab_graph_path, test_slim_kuiper_keeps_shape, test_audit_mass_flags_code_bodies, test_copy_step_and_optional_paths, test_loop_defined_flags_get_overrides, test_phases_late_extra_runs_after_pre_post, test_parse_flags, test_paths_made_relative
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
cosmic@51bebf892d63a617408bc5e25b270b9f893e9c03 tools/explore/test_extras.py:1-316 · blob 574d82599d62d8e9918183c37c654fe88a3767ff · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, process · domain stage: unknown · users: none · canonical: unknown
"""Tests for extras.py. Run: python -m unittest tools/explore/test_extras.py

Fake generators in a temporary search root stand in for the team's extras, so nothing real is run.
"""
import json
import os
import shutil
import sys
import tempfile
import textwrap
import unittest

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import extras as E  # noqa: E402

OK_GEN = textwrap.dedent('''
    import argparse, os
    ap = argparse.ArgumentParser()
    ap.add_argument('--graph', required=True)
    ap.add_argument('--out', default='/nonexistent')
    a = ap.parse_args()
    os.makedirs(a.out, exist_ok=True)
    assert os.path.isfile(a.graph)
    open(os.path.join(a.out, 'index.html'), 'w').write('<title>Good</title><a href="../index.html">home</a>')
    open(os.path.join(a.out, 'page2.html'), 'w').write('<title>Two</title>')
    open(os.path.join(a.out, 'data.json'), 'w').write('{"schema": "x"}')
''')
FAIL_GEN = textwrap.dedent('''
    import argparse, os, sys
    ap = argparse.ArgumentParser(); ap.add_argument('--out'); a = ap.parse_args()
    os.makedirs(a.out, exist_ok=True)
    open(os.path.join(a.out, 'index.html'), 'w').write('partial')
    sys.exit('boom: generator crashed')
''')
EMPTY_GEN = 'import argparse; ap = argparse.ArgumentParser(); ap.add_argument("--out"); ap.parse_args()\n'
SLOW_GEN = 'import time, argparse; ap = argparse.ArgumentParser(); ap.add_argument("--out"); ap.parse_args(); time.sleep(30)\n'
NEEDS_GEN = 'import argparse; ap = argparse.ArgumentParser(); ap.add_argument("--secret-key", required=True); ap.parse_args()\n'
FILE_OUT_GEN = textwrap.dedent('''
    import argparse, json, os
    ap = argparse.ArgumentParser(); ap.add_argument('--out'); ap.add_argument('--games', type=int); a = ap.parse_args()
    assert a.games is None
    json.dump({"ok": 1}, open(a.out, 'w'))
''')
DATA_GEN = textwrap.dedent('''
    import argparse, json, os
    ap = argparse.ArgumentParser(); ap.add_argument('--out'); a = ap.parse_args()
    json.dump({"schema": "d"}, open(os.path.join(a.out, 'identity.json'), 'w'))
    os.makedirs(os.path.join(a.out, 'stage', 'x')); open(os.path.join(a.out, 'stage', 'x', 'scratch.mjs'), 'w').write('')
    open(os.path.join(a.out, 'jobs.json'), 'w').write('[]')
''')
POST_OK = textwrap.dedent('''
    import argparse, pathlib
    ap = argparse.ArgumentParser(); ap.add_argument('--site', required=True); a = ap.parse_args()
    p = pathlib.Path(a.site, 'more.html'); s = p.read_text()
    if 'data-ec-theme' not in s:
        p.write_text(s.replace('</head>', '<script data-ec-theme="play"></script></head>'))
''')
POST_BAD = 'import sys; sys.exit("theme broke")\n'
PAGE_GEN = textwrap.dedent('''
    import argparse, os
    ap = argparse.ArgumentParser(); ap.add_argument('--board'); ap.add_argument('--out'); a = ap.parse_args()
    assert os.path.isfile(a.board), a.board
    open(os.path.join(a.out, 'index.html'), 'w').write('<title>Board</title>')
''')


def ex(slug, *files, **kw):
    return {'slug': slug, 'title': slug.title(), 'owner': 't', 'desc': 'The %s experience.' % slug,
            'steps': kw.get('steps') or [{'files': [f]} for f in files]}


class ExtrasTest(unittest.TestCase):
    def setUp(self):
        self.tmp = tempfile.mkdtemp()
        self.root = os.path.join(self.tmp, 'gens')
        self.site = os.path.join(self.tmp, 'explore-code')
        os.makedirs(self.root)
        os.makedirs(self.site)
        with open(os.path.join(self.site, 'build_graph.json'), 'w') as fh:
            json.dump({'schema': 'explore-build-graph-v1', 'cut': '2026-12-05T13:33:26+00:00',
                       'base': 'https://example.org/explore-code/'}, fh)
        with open(os.path.join(self.site, 'index.html'), 'w') as fh:
            fh.write('<html><body><nav><a href="search.html">Search</a></nav></body></html>')
        with open(os.path.join(self.site, 'llms.txt'), 'w') as fh:
            fh.write('# Explore Code\n')
        with open(os.path.join(self.site, 'robots-sitemaps.txt'), 'w') as fh:
            fh.write('Sitemap: https://example.org/explore-code/sitemap.xml\n')
        for name, src in [('good/gen.py', OK_GEN), ('bad/gen.py', FAIL_GEN), ('empty/gen.py', EMPTY_GEN),
                          ('slow/gen.py', SLOW_GEN), ('needs/gen.py', NEEDS_GEN), ('chess/board.py', FILE_OUT_GEN),
                          ('chess/page.py', PAGE_GEN), ('data/gen.py', DATA_GEN), ('theme/inject.py', POST_OK),
                          ('theme/bad.py', POST_BAD)]:
            p = os.path.join(self.root, name)
            os.makedirs(os.path.dirname(p), exist_ok=True)
            with open(p, 'w') as fh:
                fh.write(src)

    def tearDown(self):
        shutil.rmtree(self.tmp, ignore_errors=True)

    def run_extras(self, extras, *args, posts=()):
        rc = E.main(['--site', self.site] + list(args), extras=extras, roots=[self.root], posts=list(posts))
        with open(os.path.join(self.site, 'extras.json')) as fh:
            return rc, {r['slug']: r for r in json.load(fh)['extras']}

    def hub(self):
        with open(os.path.join(self.site, 'more.html')) as fh:
            return fh.read()

    def test_missing_and_failing_extras_are_skipped(self):
        rc, rec = self.run_extras([ex('good', 'good/gen.py'), ex('bad', 'bad/gen.py'), ex('gone', 'gone/gen.py'),
                                   ex('empty', 'empty/gen.py'), ex('needs', 'needs/gen.py')])
        self.assertEqual(rc, 0)
        self.assertEqual(rec['good']['status'], 'ok')
        self.assertEqual(rec['bad']['status'], 'failed')
        self.assertIn('boom', rec['bad']['reason'])
        self.assertEqual(rec['gone']['status'], 'pending')
        self.assertEqual(rec['empty']['status'], 'failed')
        self.assertEqual(rec['needs']['status'], 'failed')
        self.assertIn('--secret-key', rec['needs']['reason'])
        # partial output of a failed extra is discarded; staging is cleaned
        self.assertFalse(os.path.exists(os.path.join(self.site, 'bad')))
        self.assertFalse(os.path.exists(os.path.join(self.site, '.extras-staging')))
        self.assertTrue(os.path.isfile(os.path.join(self.site, 'good', 'index.html')))

    def test_strict_exit_code(self):
        rc, _ = self.run_extras([ex('bad', 'bad/gen.py')], '--strict')
        self.assertEqual(rc, 1)
        rc, _ = self.run_extras([ex('gone', 'gone/gen.py')], '--strict')
        self.assertEqual(rc, 0)  # a pending (not yet written) extra is not a failure

    def test_timeout_is_a_skip(self):
        _, rec = self.run_extras([ex('slow', 'slow/gen.py')], '--timeout', '2')
        self.assertEqual(rec['slow']['status'], 'failed')
        self.assertIn('timed out', rec['slow']['reason'])

    def test_hub_lists_only_existing_extras(self):
        self.run_extras([ex('good', 'good/gen.py'), ex('bad', 'bad/gen.py'), ex('gone', 'gone/gen.py')])
        h = self.hub()
        self.assertIn('href="good/index.html"', h)
        self.assertIn('The good experience.', h)
        self.assertNotIn('bad/', h)
        self.assertNotIn('gone/', h)
        self.assertNotIn('visual/index.html', h)  # built-in card only when the page exists
        self.assertEqual(h.count('class="card"'), 1)
        self.assertIn('<svg', h)  # every card has a picture
        self.assertIn('width=device-width', h)

    def test_builtin_cards_when_present(self):
        os.makedirs(os.path.join(self.site, 'visual'))
        open(os.path.join(self.site, 'visual', 'index.html'), 'w').write('x')
        self.run_extras([])
        h = self.hub()
        self.assertIn('href="visual/index.html"', h)
        self.assertNotIn('href="search.html" aria-label', h)

    def test_sitemap_llms_robots(self):
        self.run_extras([ex('good', 'good/gen.py'), ex('bad', 'bad/gen.py')])
        sm = open(os.path.join(self.site, 'sitemap-extras.xml')).read()
        self.assertIn('<loc>https://example.org/explore-code/more.html</loc>', sm)
        self.assertIn('<loc>https://example.org/explore-code/good/page2.html</loc>', sm)
        self.assertNotIn('/bad/', sm)
        ll = open(os.path.join(self.site, 'llms-extras.txt')).read()
        self.assertIn('https://example.org/explore-code/good/index.html', ll)
        self.assertIn('https://example.org/explore-code/good/data.json', ll)
        self.run_extras([ex('good', 'good/gen.py')])  # second run: robots line not duplicated
        rs = open(os.path.join(self.site, 'robots-sitemaps.txt')).read()
        self.assertEqual(rs.count('sitemap-extras.xml'), 1)

    def test_link_index_opt_in_and_idempotent(self):
        self.run_extras([ex('good', 'good/gen.py')])
        self.assertNotIn('more.html', open(os.path.join(self.site, 'index.html')).read())
        for _ in range(2):
            self.run_extras([ex('good', 'good/gen.py')], '--link-index')
        idx = open(os.path.join(self.site, 'index.html')).read()
        self.assertEqual(idx.count('href="more.html"'), 1)
        self.assertEqual(open(os.path.join(self.site, 'llms.txt')).read().count('llms-extras.txt'), 1)

    def test_step_overrides(self):
        steps = [{'files': ['chess/board.py'], 'args': {'--out': '{out}/board.json', '--games': None}},
                 {'files': ['chess/page.py'], 'args': {'--board': '{out}/board.json', '--out': '{out}'}}]
        _, rec = self.run_extras([ex('chess', steps=steps)])
        self.assertEqual(rec['chess']['status'], 'ok', rec['chess'].get('reason'))
        self.assertTrue(os.path.isfile(os.path.join(self.site, 'chess', 'board.json')))

    def test_data_only_extra_has_no_card(self):
        e = ex('ident', 'data/gen.py')
        e['data_ok'] = True
        e['keep'] = ['identity.json']
        _, rec = self.run_extras([e, ex('nodata', 'data/gen.py')])
        self.assertEqual(rec['ident']['status'], 'data')
        self.assertEqual(os.listdir(os.path.join(self.site, 'ident')), ['identity.json'])
        self.assertEqual(rec['nodata']['status'], 'failed')  # data without data_ok is not enough
        self.assertNotIn('ident/', self.hub())
        self.assertIn('ident/identity.json', open(os.path.join(self.site, 'llms-extras.txt')).read())

    def test_required_flag_missing_is_pending(self):
        _, rec = self.run_extras([ex('bb', steps=[{'files': ['empty/gen.py'], 'require_flags': ['--src']}])])
        self.assertEqual(rec['bb']['status'], 'pending')
        self.assertIn('--src', rec['bb']['reason'])

    def test_post_processors(self):
        ok = {'slug': 'theme', 'title': 't', 'files': ['theme/inject.py'], 'args': {'--site': '{site}'}}
        bad = {'slug': 'bad', 'title': 'b', 'files': ['theme/bad.py']}
        gone = {'slug': 'gone', 'title': 'g', 'files': ['nope/inject.py']}
        rc = E.main(['--site', self.site], extras=[ex('good', 'good/gen.py')], roots=[self.root], posts=[ok, bad, gone])
        self.assertEqual(rc, 0)
        post = {p['slug']: p['status'] for p in json.load(open(os.path.join(self.site, 'extras.json')))['post']}
        self.assertEqual(post, {'theme': 'ok', 'bad': 'failed', 'gone': 'pending'})
        self.assertIn('data-ec-theme', self.hub())  # post runs after the hub is written
        self.assertIn('href="good/index.html"', self.hub())

    def test_lab_graph_path(self):
        """lab.html's '../site7/explore-code/visual/graph.json' must become '../visual/graph.json', never '..../'."""
        d = os.path.join(self.tmp, 'labstage')
        os.makedirs(d)
        open(os.path.join(d, 'index.html'), 'w').write(
            "var GRAPH = '../site7/explore-code/visual/graph.json'; getJSON('keys.json'); x('/tmp/lab-out/a.json')")
        E.fix_paths(d, self.site, os.path.join(self.site, 'lab'))
        out = open(os.path.join(d, 'index.html')).read()
        self.assertIn("var GRAPH = '../visual/graph.json'", out)
        self.assertNotIn('..../', out)
        self.assertIn("x('a.json')", out)

    def test_slim_kuiper_keeps_shape(self):
        d = os.path.join(self.tmp, 'k')
        os.makedirs(d)
        rec = {'fields': ['name', 'synopsis', 'signatures'],
               'files': [['a.js', 'Draws the map. It also does many other things in great detail.',
                          ['export drawMap(w, ctx, {a=1})', 'def load(path)', 'async function go()']]]}
        json.dump(rec, open(os.path.join(d, 'r.json'), 'w'))
        E.slim_kuiper(d)
        out = json.load(open(os.path.join(d, 'r.json')))
        self.assertEqual(out['files'][0], ['a.js', 'Draws the map.', ['drawMap', 'load', 'go']])

    def test_audit_mass_flags_code_bodies(self):
        d = os.path.join(self.tmp, 'm')
        os.makedirs(d)
        json.dump({'ok': 'short', 'refs': ['repo@abc p.js:1-9 blob']}, open(os.path.join(d, 'a.json'), 'w'))
        self.assertEqual(E.audit_mass(d), [])
        json.dump({'code': 'line\n' * 40}, open(os.path.join(d, 'b.json'), 'w'))
        self.assertTrue(E.audit_mass(d)[0].startswith('b.json:/code'))

    def test_copy_step_and_optional_paths(self):
        os.makedirs(os.path.join(self.root, 'demo'))
        open(os.path.join(self.root, 'demo', 'index.html'), 'w').write('<title>Demo</title>')
        open(os.path.join(self.root, 'demo', 'data.js'), 'w').write('var D=1')
        steps = [{'files': ['demo/index.html'], 'copy': ['demo/index.html', 'demo/data.js']}]
        _, rec = self.run_extras([ex('laws', steps=steps)])
        self.assertEqual(rec['laws']['status'], 'ok')
        self.assertEqual(sorted(os.listdir(os.path.join(self.site, 'laws'))), ['data.js', 'index.html'])
        ctx = {'out': '/o', 'site': self.site, 'graph': 'g', 'base': '', 'src': None}
        self.assertIsNone(E.expand('?{site}/nope.json', ctx))
        self.assertEqual(E.expand('?{site}/build_graph.json', ctx), os.path.join(self.site, 'build_graph.json'))
        self.assertIsNone(E.expand('{src}/x', ctx))  # unknown value -> flag left out

    def test_loop_defined_flags_get_overrides(self):
        p = os.path.join(self.root, 'loop', 'gen.py')
        os.makedirs(os.path.dirname(p))
        open(p, 'w').write(textwrap.dedent('''
            import argparse, os
            ap = argparse.ArgumentParser()
            for k in ('graph', 'out'):
                ap.add_argument('--' + k)
            a = ap.parse_args()
            open(os.path.join(os.path.dirname(a.out), 'index.html'), 'w').write('<title>L</title>')
        '''))
        _, rec = self.run_extras([ex('loop', steps=[{'files': ['loop/gen.py'], 'args': {'--out': '{out}/x.json',
                                                                                      '--graph': '{graph}'}}])])
        self.assertEqual(rec['loop']['status'], 'ok', rec['loop'].get('reason'))

    def test_phases_late_extra_runs_after_pre_post(self):
        mark = textwrap.dedent('''
            import argparse, os
            ap = argparse.ArgumentParser(); ap.add_argument('--site', required=True); a = ap.parse_args()
            open(os.path.join(a.site, 'pilot.html'), 'w').write('<title>P</title>')
        ''')
        late = textwrap.dedent('''
            import argparse, os, sys
            ap = argparse.ArgumentParser(); ap.add_argument('--site'); ap.add_argument('--out'); a = ap.parse_args()
            if not os.path.exists(os.path.join(a.site, 'pilot.html')): sys.exit('pre post step has not run')
            open(os.path.join(a.out, 'index.html'), 'w').write('<title>S</title>')
        ''')
        for name, src in (('pre/mark.py', mark), ('late/show.py', late)):
            q = os.path.join(self.root, name)
            os.makedirs(os.path.dirname(q))
            open(q, 'w').write(src)
        show = ex('show', 'late/show.py')
        show['phase'] = 'late'
        show['steps'][0]['args'] = {'--site': '{site}', '--out': '{out}'}
        pre = {'slug': 'mark', 'title': 'm', 'when': 'pre', 'files': ['pre/mark.py'], 'args': {'--site': '{site}'}}
        _, rec = self.run_extras([ex('good', 'good/gen.py'), show], posts=[pre])
        self.assertEqual(rec['show']['status'], 'ok', rec['show'].get('reason'))
        h = self.hub()
        self.assertLess(h.index('good/index.html'), h.index('show/index.html'))

    def test_parse_flags(self):
        flags, pos = E.parse_flags("ap.add_argument('--graph', default=X)\nap.add_argument('-o', '--out', required=True)\n"
                                   "ap.add_argument('--fast', action='store_true')")
        self.assertIn('--graph', flags)
        self.assertTrue(flags['--out']['required'])
        self.assertIs(flags['-o'], flags['--out'])
        self.assertTrue(flags['--fast']['store_true'])
        self.assertEqual(pos, [])

    def test_paths_made_relative(self):
        d = os.path.join(self.tmp, 'stage')
        os.makedirs(os.path.join(d, 'sub'))
        open(os.path.join(d, 'index.html'), 'w').write("var G='../site7/explore-code/visual/graph.json'; f('%s/x.json')" % d)
        open(os.path.join(d, 'sub', 'a.html'), 'w').write('<a href="%s/s/0001.html">' % self.site)
        E.fix_paths(d, self.site, os.path.join(self.site, 'lab'))
        self.assertEqual(open(os.path.join(d, 'index.html')).read(), "var G='../visual/graph.json'; f('x.json')")
        self.assertEqual(open(os.path.join(d, 'sub', 'a.html')).read(), '<a href="../../s/0001.html">')


if __name__ == '__main__':
    unittest.main()

Test Ship

A test in the explore folder of Cosmic that checks Ship. It sets up (`setUp`) and runs ship (`run_ship`).

testcosmic / tools/explore/test_ship.py · lines 1–208 of 208 · Entry point · pattern tearDown (shared by 38 files)

What it does
It tests its inputs. Defines 17 functions or classes, including ShipTest, setUp, tearDown, put, full_tools. Uses libraries json, os, sys, tempfile, textwrap. Side effects: reads or writes files; starts processes; uses storage (browser storage, DuckDB or Parquet).
Inputs & outputs
In: JSON file args.json; DuckDB queries; command-line arguments. Out: JSON file build_graph.json.
Downstream impact
It is itself an entry point (test); no other file was found loading it.
What it achieves
Tests for `ship.py`: a failing optional step is skipped with a warning; only `build.py` failing stops the run. It accepts `--src`, `--out` and `--base`.
Why it matters
Guards the behaviour of Ship.
Application
cosmic · tools/explore · test
Uses
Ship (import), json, os, sys, tempfile, textwrap, unittest, argparse, shutil
Used by
none found
Produces
ShipTest
Defines here
ShipTest, setUp, tearDown, put, full_tools, run_ship, test_all_ok, test_failing_optional_step_is_skipped_and_run_continues, test_missing_optional_script_is_skipped, test_optional_timeout_is_skipped, test_build_failure_stops_the_run, test_build_without_outputs_counts_as_failure, test_clean_manifest_passed_only_when_supported, test_duckdb_vendor_copied, test_duckdb_dir_handed_to_build_when_supported, test_size_budget_top_of_report, test_small_duplicates_ignored
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
cosmic@51bebf892d63a617408bc5e25b270b9f893e9c03 tools/explore/test_ship.py:1-208 · blob 78582b6f8dffb1207c40b4ca74c198fec9b6fbbb · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process, storage · domain stage: unknown · users: none · canonical: unknown
"""Tests for ship.py: a failing optional step is skipped with a warning; only build.py failing stops the run.

Runs against tiny stub step scripts in a temporary tools folder (no clones, no real build: cheap on CPU).
    python -m pytest tools/explore/test_ship.py -q
"""
import json
import os
import sys
import tempfile
import textwrap
import unittest

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import ship  # noqa: E402

BUILD_OK = '''
import argparse, json, os
ap = argparse.ArgumentParser(); ap.add_argument('--src'); ap.add_argument('--out'); ap.add_argument('--base')
ap.add_argument('--kuiper-tools', default=''){extra}
a = ap.parse_args()
os.makedirs(a.out, exist_ok=True)
json.dump({{'contract': 'explore-build-graph-v1'}}, open(os.path.join(a.out, 'build_graph.json'), 'w'))
open(os.path.join(a.out, 'index.html'), 'w').write('<html lang="en"><title>x</title></html>')
open(os.path.join(a.out, 'args.json'), 'w').write(json.dumps(vars(a)))
'''
BUILD_FAIL = 'import sys; print("boom"); sys.exit(3)\n'
WRITES = '''
import argparse, os
ap = argparse.ArgumentParser(); ap.add_argument('--site'); ap.add_argument('--out'); ap.add_argument('--graph')
ap.add_argument('--base'); ap.add_argument('--src'); ap.add_argument('--timeout'); ap.add_argument('--link-index', action='store_true')
ap.add_argument('--quiet', action='store_true')
a, _ = ap.parse_known_args()
d = a.out or a.site
os.makedirs(os.path.join(d, '{folder}'), exist_ok=True)
open(os.path.join(d, '{folder}', 'index.html'), 'w').write('<p>{folder}</p>')
'''
FAIL = 'import sys; sys.stderr.write("optional step broke\\n"); sys.exit(2)\n'
SLEEP = 'import time; time.sleep(30)\n'
MANY = '''
import argparse, os
ap = argparse.ArgumentParser(); ap.add_argument('--site'); a, _ = ap.parse_known_args()
d = os.path.join(a.site, 'bigextra'); os.makedirs(d, exist_ok=True)
for i in range(520):
    open(os.path.join(d, 'p%d.html' % i), 'w').write('x')
blob = os.urandom(60 * 1024)
for n in ('dup1.bin', 'dup2.bin'):
    open(os.path.join(a.site, n), 'wb').write(blob)
'''


class ShipTest(unittest.TestCase):
    def setUp(self):
        self.tmp = tempfile.TemporaryDirectory()
        self.d = self.tmp.name
        self.tools = os.path.join(self.d, 'tools')
        self.src = os.path.join(self.d, 'clones')
        os.makedirs(os.path.join(self.src, 'repo1'))
        self.out = os.path.join(self.d, 'site', 'explore-code')
        self.report = os.path.join(self.d, 'ship', 'SHIP-REPORT.md')

    def tearDown(self):
        self.tmp.cleanup()

    def put(self, rel, code):
        p = os.path.join(self.tools, rel)
        os.makedirs(os.path.dirname(p), exist_ok=True)
        open(p, 'w').write(textwrap.dedent(code))

    def full_tools(self, build=None, **over):
        self.put('build.py', build if build is not None else BUILD_OK.format(extra=''))
        scripts = {'visualise.py': WRITES.format(folder='visual'), 'extras.py': WRITES.format(folder='more'),
                   'periodic/feed.py': WRITES.format(folder='periodic'),
                   'theme/inject.py': 'import sys; sys.exit(9)\n',  # extras.py runs theme/periodic, never ship.py
                   'verify/vaccines.py': 'import sys; sys.exit(0)\n'}
        scripts.update(over)
        for rel, code in scripts.items():
            if code is not None:
                self.put(rel, code)

    def run_ship(self, *extra):
        argv = ['--src', self.src, '--out', self.out, '--report', self.report, '--tools', self.tools,
                '--clean-proposals', os.path.join(self.d, 'noproposals'), '--clean-out',
                os.path.join(self.d, 'ship', 'clean', 'manifest.json')] + list(extra)
        rc = ship.main(argv)
        rec = json.load(open(os.path.splitext(self.report)[0] + '.json'))
        return rc, {s['name']: s for s in rec['steps']}, open(self.report).read(), rec

    def test_all_ok(self):
        self.full_tools()
        rc, st, rep, _ = self.run_ship()
        self.assertEqual(rc, 0)
        for n in ('clean', 'build', 'duckdb', 'visualise', 'extras', 'verify'):
            self.assertIn(n, st)
        for n in ('build', 'visualise', 'extras', 'verify'):
            self.assertEqual(st[n]['status'], 'ok', n)
        self.assertNotIn('theme', st)
        self.assertNotIn('periodic', st)
        self.assertFalse(os.path.isdir(os.path.join(self.out, 'periodic')))
        self.assertFalse(os.path.isdir(os.path.join(self.out, 'theme')))
        self.assertIn('| 2 | build (required) | ok |', rep)

    def test_failing_optional_step_is_skipped_and_run_continues(self):
        self.full_tools(**{'visualise.py': FAIL})
        rc, st, rep, _ = self.run_ship()
        self.assertEqual(rc, 0)
        self.assertEqual(st['visualise']['status'], 'warning')
        self.assertIn('exit 2', st['visualise']['reason'])
        self.assertEqual(st['extras']['status'], 'ok')
        self.assertEqual(st['verify']['status'], 'ok')
        self.assertIn('**visualise** (warning)', rep)

    def test_missing_optional_script_is_skipped(self):
        self.full_tools(**{'extras.py': None})
        rc, st, rep, _ = self.run_ship()
        self.assertEqual(rc, 0)
        self.assertEqual(st['extras']['status'], 'skipped')
        self.assertIn('script not found', st['extras']['reason'])
        self.assertEqual(st['verify']['status'], 'ok')

    def test_optional_timeout_is_skipped(self):
        self.full_tools(**{'visualise.py': SLEEP})
        rc, st, _, _ = self.run_ship('--timeout-visualise', '1')
        self.assertEqual(rc, 0)
        self.assertEqual(st['visualise']['status'], 'warning')
        self.assertIn('timed out', st['visualise']['reason'])
        self.assertEqual(st['extras']['status'], 'ok')

    def test_build_failure_stops_the_run(self):
        self.full_tools(build=BUILD_FAIL)
        rc, st, rep, _ = self.run_ship()
        self.assertEqual(rc, 1)
        self.assertEqual(st['build']['status'], 'FAILED')
        for n in ('visualise', 'extras', 'verify'):
            self.assertEqual(st[n]['status'], 'skipped', n)
            self.assertIn('build.py failed', st[n]['reason'])
        self.assertIn('BUILD FAILED', rep)

    def test_build_without_outputs_counts_as_failure(self):
        self.full_tools(build='print("did nothing")\n')
        rc, st, _, _ = self.run_ship()
        self.assertEqual(rc, 1)
        self.assertIn('wrote no build_graph.json', st['build']['reason'])

    def test_clean_manifest_passed_only_when_supported(self):
        man = os.path.join(self.d, 'manifest.json')
        json.dump({'dry_run': True}, open(man, 'w'))
        self.full_tools()
        rc, st, _, _ = self.run_ship('--clean-manifest', man)
        self.assertNotIn('clean_manifest', json.load(open(os.path.join(self.out, 'args.json'))))
        self.assertIn('no --clean-manifest yet', st['build']['note'])
        self.full_tools(build=BUILD_OK.format(extra="\nap.add_argument('--clean-manifest', default='')"))
        rc, st, _, _ = self.run_ship('--clean-manifest', man)
        self.assertEqual(json.load(open(os.path.join(self.out, 'args.json')))['clean_manifest'], man)

    def test_duckdb_vendor_copied(self):
        v = os.path.join(self.d, 'vendor')
        os.makedirs(v)
        for f in ('duckdb-browser.mjs', 'duckdb-eh.wasm', 'VERSION'):
            open(os.path.join(v, f), 'w').write('x')
        self.full_tools()
        rc, st, _, _ = self.run_ship('--duckdb-vendor', v)
        self.assertEqual(st['duckdb']['status'], 'ok')
        self.assertTrue(os.path.isfile(os.path.join(self.out, 'vendor', 'duckdb', 'duckdb-eh.wasm')))
        rc, st, _, _ = self.run_ship()
        self.assertEqual(st['duckdb']['status'], 'skipped')

    def test_duckdb_dir_handed_to_build_when_supported(self):
        v = os.path.join(self.d, 'vendor')
        os.makedirs(v)
        for f in ('duckdb-browser.mjs', 'duckdb-eh.wasm'):
            open(os.path.join(v, f), 'w').write('x')
        build = BUILD_OK.format(extra="\nap.add_argument('--duckdb-dir', default='')") + textwrap.dedent('''
            import shutil
            if a.duckdb_dir:
                shutil.copytree(a.duckdb_dir, os.path.join(a.out, 'vendor', 'duckdb'), dirs_exist_ok=True)
            ''')
        self.full_tools(build=build)
        rc, st, _, _ = self.run_ship('--duckdb-vendor', v)
        self.assertEqual(json.load(open(os.path.join(self.out, 'args.json')))['duckdb_dir'], v)
        self.assertEqual(st['duckdb']['status'], 'ok')
        self.assertIn('build.py --duckdb-dir', st['duckdb']['note'])
        self.assertEqual(st['duckdb']['files_added'], 2)

    def test_size_budget_top_of_report(self):
        self.full_tools(**{'extras.py': MANY})
        rc, st, rep, rec = self.run_ship()
        self.assertEqual(rc, 0)
        self.assertLess(rep.index('## Size budget'), rep.index('## Steps'))
        self.assertTrue(any('bigextra' in w for w in rec['budget']['warnings']), rec['budget']['warnings'])
        dup = rec['budget']['duplicates']
        self.assertEqual(len(dup), 1)
        self.assertEqual(sorted(dup[0]['paths']), ['dup1.bin', 'dup2.bin'])
        self.assertIsNone(rec['budget']['prev_files'])
        rc, st, rep, rec2 = self.run_ship()
        self.assertEqual(rec2['budget']['prev_files'], rec['budget']['files'])
        self.assertIn('| file count |', rep)

    def test_small_duplicates_ignored(self):
        root = os.path.join(self.d, 'r')
        os.makedirs(root)
        for n in ('a', 'b'):
            open(os.path.join(root, n), 'w').write('same')
        self.assertEqual(ship.duplicate_groups(root), [])
        self.assertEqual(len(ship.duplicate_groups(root, min_bytes=1)), 1)


if __name__ == '__main__':
    unittest.main()