In this section
- Test Build test · cosmic / tools/explore/test_build.py lines 701–927
- Test Describe test · cosmic / tools/explore/test_describe.py lines 1–470
Test Build
A test in the explore folder of Cosmic that checks Build and Agentdocs, using haversine using data from UK Power Networks open data and the GlobalGrid2050 and delta repositories.
testcosmic / tools/explore/test_build.py · lines 701–927 of 927 (continued from section 1138) · Entry point · pattern tearDownClass (shared by 3 files)
- What it does
- It tests A roads and overhead lines (OHL). Defines 64 functions or classes, including read, make_repo, Links, __init__, handle_starttag. Uses libraries contextlib, html.parser, io, json, os. Side effects: changes the web page (DOM); reads or writes files; makes network requests; starts processes; uses storage (browser storage, DuckDB or Parquet).
- Why it exists in the grid workflow
- Domain terms in the code: A roads, overhead lines (OHL), 132kV, 33kV.
- Inputs & outputs
- In: data source: UK Power Networks open data; data source: globalgrid2050 data; data source: delta data; GeoJSON file 132kv_ohl.geojson; JSON file build_graph.json; JSON file missing.json; DuckDB queries; command-line arguments. Out: JSON file; interactive map. Voltage levels named: 132kV, 33kV.
- Downstream impact
- It is itself an entry point (test); no other file was found loading it.
- What it achieves
- It makes repo (`make_repo`), checks links (`check_links`) and builds test (`BuildTest`). Tests for `tools/explore/build.py` (unittest, no network). Its code works with 132 kV and 33 kV. It reads `data/132kv_ohl.geojson`.
- Why it matters
- Guards the behaviour of Build and Agentdocs.
- Application
- cosmic · tools/explore · test
- Uses
- Build (import), Agentdocs (import), contextlib, html.parser, io, json, os, re, subprocess, sys
- Used by
- none found
- Produces
- read, make_repo, Links, parse, check_links, BuildTest, EdgeTest, SwarmV2Test
- Defines here
- test_estate_urls_cross_repo, test_comment_links_are_mentions_not_loads, test_duplicate_blob, test_unreferenced_stays_unreached, test_contract_and_used_by, SwarmV2Test, setUpClass, tearDownClass, page, test_generator_version_and_repos_filter, test_phone_css, test_index_first_screen, test_search_page, test_clean_manifest, test_missing_manifest_is_safe, test_core_hooks_drafts
- 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_build.py:701-927 · blob dbf5152d60aa5a85c16ba8b93eb9407c76c640b8 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, network, process, storage · domain stage: unknown · users: none · canonical: unknown
def test_estate_urls_cross_repo(self):
d = lambda p: ('delta', p)
g = lambda p: ('globalgrid2050', p)
self.assertEdge(d('page.html'), g('js/shared.js'), 'script-src', 'url') # CNAME host
self.assertEdge(d('loader.js'), g('py/raw_target.py'), 'estate-url', 'url') # raw.githubusercontent.com
self.assertEdge(d('loader.js'), g('js/cdn_target.js'), 'estate-url', 'url') # jsDelivr
self.assertEdge(d('loader.js'), g('js/blob_target.js'), 'estate-url', 'url') # GitHub blob
self.assertEdge(d('loader.js'), d('sub/index.html'), 'estate-url', 'url+index') # Pages directory URL
# an older timestamped version maps to the kept newest member, and says so
self.assertNotIn(('globalgrid2050', 'releases/202601010000-widget.js'), self.byp)
self.assertEdge(d('loader.js'), g('releases/202602010000-widget.js'), 'estate-url', 'url+family')
# a template URL is not guessed
self.assertEqual(len([1 for x, y, k, v in self.g['edges'] if x == self.f(*d('loader.js'))['id']]), 5)
for p in ('py/raw_target.py', 'js/cdn_target.js', 'js/blob_target.js', 'js/shared.js'):
self.assertTrue(self.f(*g(p))['reachable'], p)
def test_comment_links_are_mentions_not_loads(self):
d = lambda p: ('delta', p)
g = lambda p: ('globalgrid2050', p)
self.assertEdge(d('notes.js'), g('js/only_mentioned.js'), 'comment-url', 'url')
self.assertEdge(d('notes.py'), g('py/doc_only.py'), 'comment-url', 'url') # docstring and # comment
self.assertEdge(d('notes.js'), g('js/both.js'), 'estate-url', 'url') # also in code: a real reference
self.assertEqual([k for k, v in self.edge(d('notes.js'), g('js/both.js'))], ['estate-url'])
self.assertTrue(self.f(*d('notes.js'))['reachable']) # the mentioning file is itself reached
for p in ('js/only_mentioned.js', 'py/doc_only.py'):
f = self.f(*g(p))
self.assertEqual(f['dependents'], [], p)
self.assertFalse(f['reachable'], p)
self.assertEqual(f['why'], '', p)
self.assertTrue(f['mentioned_by'], p)
om = self.f(*g('js/only_mentioned.js'))
with open(os.path.join(self.out, 's', '%04d.html' % om['section']), encoding='utf-8') as fh:
page = fh.read()
self.assertRegex(page, r'mentioned in <a href="[^"]+">[^<]+</a> \(comment link\)')
self.assertIn('Not reached from any entry point (candidate for review)', page)
def test_duplicate_blob(self):
# delta is read first, so its copy is kept; globalgrid2050's own path follows it
self.assertNotIn(('globalgrid2050', 'js/dupe.js'), self.byp)
self.assertEdge(('globalgrid2050', 'index.html'), ('delta', 'vendorish/dupe.js'), 'script-src', 'duplicate')
def test_unreferenced_stays_unreached(self):
for p in ('dead.js', 'dead.py'):
f = self.f('globalgrid2050', p)
self.assertFalse(f['entry'], p)
self.assertFalse(f['reachable'], p)
self.assertEqual(f['dependents'], [], p)
def test_contract_and_used_by(self):
g = self.g
kinds = [k['id'] for k in g['edge_kinds']]
self.assertEqual(kinds, [k for k, v, l, d in build.EDGE_KINDS])
files = g['files']
for f in files:
self.assertEqual(len(f['edge_kinds']), len(f['imports']))
for j, k in zip(f['imports'], f['edge_kinds']):
self.assertIn(k, kinds)
self.assertIn(f['id'], files[j]['dependents'])
for a, b, k, v in g['edges']:
self.assertIn(b, files[a]['mentions'] if k == 'comment-url' else files[a]['imports'])
self.assertIn(k, kinds)
self.assertIsInstance(v, str)
used = set(k for a, b, k, v in g['edges'])
for k in kinds:
if k != 'import': # plain imports are covered by BuildTest
self.assertIn(k, used, k)
app = self.f('globalgrid2050', 'js/app.js')
with open(os.path.join(self.out, 's', '%04d.html' % app['section']), encoding='utf-8') as fh:
page = fh.read()
self.assertRegex(page, r'loaded by <a href="[^"]+">[^<]+</a> \(script src\)')
self.assertIn('(dynamic import)', page)
n, bad = check_links(self.out)
self.assertEqual([b for b in bad if not b[1].startswith('visual/')], [])
self.assertIn('estate-url', self.stats['edges'])
class SwarmV2Test(unittest.TestCase):
"""GENERATOR 2.0.0: phone CSS, play row, search page, --repos, --clean-manifest, CORE_HOOKS drafts."""
@classmethod
def setUpClass(cls):
cls.tmp = tempfile.TemporaryDirectory()
t = cls.tmp.name
src = os.path.join(t, 'src')
make_repo(src, 'alpha', ALPHA)
make_repo(src, 'beta', BETA)
make_repo(src, 'gamma', {'README.md': '# Gamma\n\nGamma is left out by --repos.\n', 'g.js': 'export const g = 1;\n'})
es = os.path.join(t, 'essays', 'beta')
os.makedirs(es)
with open(os.path.join(es, 'index.md'), 'w') as fh:
fh.write('# Beta, by people\n\nHUMANBETA wrote this repository essay.\n')
blob = subprocess.run(['git', '-C', os.path.join(src, 'alpha'), 'rev-parse', 'HEAD:orphan.js'],
capture_output=True, text=True, check=True).stdout.strip()
tgt = 'beta@x main.js:1-2 -'
man = {'schema': 'clean-manifest-v1', 'dry_run': True, 'graph_cut': 'old', 'summary': 'SUMMARYTEXT',
'main_view': [], 'set_aside': [
{'file_id': 0, 'key': 'alpha@x orphan.js:1-3 %s' % blob, 'category': 'near-copy-of', 'target': tgt,
'reason': 'REASONTEXT orphan is a near copy.', 'evidence': ['EVIDENCETEXT line-jaccard 0.99'],
'confidence': 0.95, 'proposer': 'families.py'},
{'file_id': 1, 'key': 'alpha@x map/app.js:1-9 ' + '0' * 40, 'category': 'noise-generated', 'target': None,
'reason': 'stale blob', 'evidence': [], 'confidence': 1.0, 'proposer': 'noise.py'}]}
cls.manifest = os.path.join(t, 'manifest.json')
with open(cls.manifest, 'w') as fh:
json.dump(man, fh)
cls.out = os.path.join(t, 'out', 'explore-code')
vend = os.path.join(t, 'vendor')
os.makedirs(os.path.join(vend, 'ext', 'v1.1.1', 'wasm_eh'))
for n in ('duckdb-browser.mjs', 'duckdb-eh.wasm', 'duckdb-browser-eh.worker.js', 'VERSION',
'ext/v1.1.1/wasm_eh/parquet.duckdb_extension.wasm'):
with open(os.path.join(vend, n), 'w') as fh:
fh.write('x')
old = dict(build.CORE_HOOKS)
build.CORE_HOOKS.update({'alpha': 'HOOKALPHA maps the overhead lines. Second sentence.', 'beta': 'HOOKBETA.'})
err = io.StringIO()
try:
with contextlib.redirect_stderr(err), contextlib.redirect_stdout(io.StringIO()):
build.build(src, cls.out, 'https://example.org/explore-code/', 10, 40, os.path.join(t, 'nowhere'),
os.path.join(t, 'essays'), repos=['alpha', 'beta'], clean_manifest=cls.manifest, duckdb_dir=vend)
cls.out2 = os.path.join(t, 'out2')
build.build(src, cls.out2, 'https://example.org/explore-code/', 10, 40, os.path.join(t, 'nowhere'),
os.path.join(t, 'essays'), repos=['beta'], clean_manifest=os.path.join(t, 'missing.json'))
finally:
build.CORE_HOOKS.clear()
build.CORE_HOOKS.update(old)
cls.log = err.getvalue()
cls.g = json.loads(read(os.path.join(cls.out, 'build_graph.json')))
cls.byp = {(f['repo'], f['path']): f for f in cls.g['files']}
@classmethod
def tearDownClass(cls):
cls.tmp.cleanup()
def page(self, rel):
return read(os.path.join(self.out, rel))
def test_generator_version_and_repos_filter(self):
self.assertEqual(self.g['generator_version'], build.GENERATOR_VERSION)
self.assertEqual({r['repo'] for r in self.g['repos']}, {'alpha', 'beta'})
self.assertIn('<meta name="generator" content="explore build.py %s">' % build.GENERATOR_VERSION, self.page('index.html'))
def test_phone_css(self):
css = self.page('explore.css')
for rule in ('box-sizing:border-box', ':focus-visible', 'prefers-reduced-motion:reduce', 'min-height:44px',
'dl.v{grid-template-columns:1fr', 'table{display:block;overflow-x:auto', 'font-size:16px'):
self.assertIn(rule, css)
def test_index_first_screen(self):
idx = self.page('index.html')
nav = re.search(r'<nav aria-label="Site">(.*?)</nav>', idx).group(1)
self.assertNotIn('build_graph.json', nav)
self.assertRegex(idx, r'<a href="build_graph.json">build_graph.json</a> \(\d+ (KB|MB);')
self.assertIn('<details class="k"><summary>About this build</summary>', idx)
self.assertNotIn('CORE_REPOS in build.py', idx)
self.assertIn('<ul class="cards play">', idx)
self.assertIn('id="surprise"', idx)
self.assertIn('data-probe="chess/index.html"', idx)
self.assertNotIn('href="chess/', idx) # extras get their href only when the page answers
self.assertIn('<ul class="cards"><li><a class="t" href="topics/', idx)
def test_search_page(self):
s = self.page('search.html')
self.assertIn('<label for="q">', s)
self.assertNotIn('autofocus', s)
self.assertNotIn('size="40"', s)
self.assertIn('aria-live="polite"', s)
self.assertIn('downloads the search engine', s)
self.assertIn('DUCK="vendor/duckdb/"', s)
self.assertIn('custom_extension_repository', s)
self.assertIn('id="fb"', s)
self.assertIn('data-q="haversine"', s)
for n in ('duckdb-browser.mjs', 'duckdb-eh.wasm', 'VERSION', 'ext/v1.1.1/wasm_eh/parquet.duckdb_extension.wasm'):
self.assertTrue(os.path.isfile(os.path.join(self.out, 'vendor', 'duckdb', n)), n)
def test_clean_manifest(self):
orphan, app = self.byp[('alpha', 'orphan.js')], self.byp[('alpha', 'map/app.js')]
self.assertEqual(orphan['clean_status'], 'near-copy-of')
self.assertEqual(app['clean_status'], 'main') # blob changed since the manifest: stays
self.assertEqual(self.g['clean']['set_aside'], 1)
sec = read(os.path.join(self.out, 's', '%04d.html' % orphan['section']))
self.assertIn('Set aside from the main view: REASONTEXT', sec)
self.assertIn('EVIDENCETEXT', sec)
self.assertIn('set-aside.html#c-near-copy-of', sec)
self.assertIn('lonelyHelper', sec) # the code is still published, once
repo = self.page('repos/alpha.html')
files_part = repo.split('<h2>Files by folder</h2>', 1)[1]
self.assertNotIn('>Orphan<', files_part.split('Set aside (1)')[0])
self.assertIn('set-aside.html#r-alpha', repo)
sa = self.page('set-aside.html')
self.assertIn('Set aside (1), with reasons', sa)
self.assertIn('id="c-near-copy-of"', sa)
self.assertIn('id="r-alpha"', sa)
self.assertNotIn('lonelyHelper', sa) # links to the code, never repeats it
self.assertIn('href="set-aside.html"', self.page('index.html'))
self.assertIn('WARNING: --clean-manifest', self.log)
n, bad = check_links(self.out)
self.assertEqual([b for b in bad if not b[1].startswith('visual/')], [])
def test_missing_manifest_is_safe(self):
self.assertFalse(os.path.exists(os.path.join(self.out2, 'set-aside.html')))
g2 = json.loads(read(os.path.join(self.out2, 'build_graph.json')))
self.assertNotIn('clean', g2)
self.assertNotIn('clean_status', g2['files'][0])
def test_core_hooks_drafts(self):
rep = {r['repo']: r for r in self.g['repos']}
self.assertEqual(rep['alpha']['descriptor_provenance'], 'core_hook_draft')
self.assertEqual(rep['alpha']['descriptor_status'], 'draft_awaiting_owner_approval')
self.assertTrue(rep['alpha']['descriptor'].startswith('HOOKALPHA'))
self.assertNotEqual(rep['beta']['descriptor_provenance'], 'core_hook_draft') # the human essay wins
self.assertNotIn('HOOKBETA', self.page('repos/beta.html'))
self.assertIn('HUMANBETA', self.page('repos/beta.html'))
a = self.page('repos/alpha.html')
self.assertIn('HOOKALPHA', a)
self.assertIn('a draft awaiting owner approval', a)
for r in build.CORE_REPOS:
self.assertIn(r, build.CORE_HOOKS)
self.assertLessEqual(len(build.CORE_HOOKS[r]), 400)
if __name__ == '__main__':
if len(sys.argv) == 3 and sys.argv[1] == '--check-links':
n, bad = check_links(sys.argv[2])
print('%d internal links checked, %d broken' % (n, len(bad)))
for b in bad[:30]:
print('BROKEN', *b)
sys.exit(1 if bad else 0)
unittest.main()Test Describe
A test in the explore folder of Cosmic that checks Describe and GridAtlas — Atlas Page, using IEC 60287-1-1 and IEC 60287-2-1 using data from the GridAtlas repository.
testcosmic / tools/explore/test_describe.py · lines 1–470 of 470 · Entry point · pattern test_workflow (shared by 2 files)
- What it does
- It tests cables, 33kV, the REPD register and substations. Defines 67 functions or classes, including ev, evidence_of, CommentCleaning, test_status_header_dropped_purpose_kept, test_todo_version_ai_banner_hash_date_dropped. Uses libraries os, re, sys, unittest, json. Side effects: changes the web page (DOM); reads or writes files.
- Why it exists in the grid workflow
- Domain terms in the code: cables, 33kV, the REPD register, substations, 132kV.
- Inputs & outputs
- In: data source: gridatlas data; data source: a data; data source: ets data; JSON file build_graph.json; JSON file cables.json. Out: interactive map; canvas drawing. Voltage levels named: 132kV, 33kV.
- Downstream impact
- It is itself an entry point (test); no other file was found loading it.
- What it achieves
- It builds adapter (`BuildAdapter`) and is built from the evidence of helper (`evidence_of`) and the comment cleaning class (`CommentCleaning`). Tests for `tools/explore/describe.py` (unittest, no network). Its code works with 33 kV, 132 kV and 000 MVA. It reads `/tmp/site5/explore-code/build_graph.json` and writes `report.md`. It accepts `--out`.
- Why it matters
- Guards the behaviour of Describe and GridAtlas — Atlas Page.
- Application
- cosmic · tools/explore · test
- Uses
- Describe (import), GridAtlas — Atlas Page (estate URL), os, re, sys, unittest, json
- Used by
- none found
- Produces
- ev, evidence_of, CommentCleaning, Glossary, CodeEvidence, Synopsis, Achieves, Why, Discipline, BuildAdapter, RealEstateSample, Version2
- Defines here
- ev, evidence_of, CommentCleaning, test_status_header_dropped_purpose_kept, test_todo_version_ai_banner_hash_date_dropped, test_file_name_prefix_and_star_leaks, test_shouted_banner_and_box_drawing, test_usage_lines_dropped, test_title_restating_sentence_skipped, test_identifiers_quoted_as_code, test_word_limit_and_clause_cut, test_midcode_comment_not_taken_as_purpose, Glossary, test_capitalisation, test_code_and_urls_untouched, test_expand_once_and_not_when_title_has_it, test_articles, test_polish_title, test_collapse_expansions, CodeEvidence, test_names_formulas_drawing_inputs_units, test_formulas, test_python_has_no_drawing_or_form_evidence, test_synopsis_uses_code_evidence_and_never_invents, Synopsis, test_not_generic_template_and_no_title, test_thin_evidence_says_less, test_junk_objects_and_placeholders_dropped, test_draws_needs_rendering_role, test_repo_sources_named_by_title
- 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_describe.py:1-470 · blob 635dc1d6de2f94bff22b1a5175585e71b00c001f · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: unknown · users: none · canonical: unknown
#!/usr/bin/env python3
"""Tests for tools/explore/describe.py (unittest, no network). Run: python -m unittest tools/explore/test_describe.py"""
import os
import re
import sys
import unittest
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import describe as D # noqa: E402
COPIED_HEADER = """// COPIED UNCHANGED from the v12 world (web/world/cable-rating.mjs) at v12 commit 3adcee9 (file last changed 604729d). Modular star family: not known
// Do not edit here: change the source and re-copy. Everything below this header is byte-identical to the source.
// cable-rating.mjs: continuous current rating of a 33 kV single-core aluminium XLPE cable laid direct in trefoil,
// by the steady-state method of IEC 60287-1-1 (losses) and IEC 60287-2-1 (thermal resistances).
//
// Indicative only: a real design uses the manufacturer's data and a rating study.
export function rate() {}
"""
def ev(**kw):
base = {'title': 'Cable Rating', 'kind': 'JavaScript module', 'role': 'electrical', 'repo': 'energy-transition-simulator',
'repo_title': 'Energy Transition Simulator', 'path': 'prototype/mod/engine/cable-rating.mjs'}
base.update(kw)
return base
def evidence_of(e):
return D.evidence_text(e)
class CommentCleaning(unittest.TestCase):
def test_status_header_dropped_purpose_kept(self):
raw = D.leading_comment('engine/cable-rating.mjs', COPIED_HEADER)
out = D.clean_comment(raw, 'engine/cable-rating.mjs', title='Cable Rating')
self.assertTrue(out.startswith('Continuous current rating of a 33kV'), out)
for bad in ('COPIED', 'commit', '3adcee9', 'Do not edit', 'cable-rating.mjs'):
self.assertNotIn(bad, out)
def test_todo_version_ai_banner_hash_date_dropped(self):
raw = ('# Generated by ChatGPT in session 42\n# TODO: tidy\n# v1.2: first cut\n'
'# Loads substation polygons from the DNO export (commit 9f3c2ab1e4) on 2026-11-02.\n')
out = D.clean_comment(raw, 'load_substations.py')
self.assertNotIn('ChatGPT', out)
self.assertNotIn('TODO', out)
self.assertNotIn('9f3c2ab1e4', out)
self.assertNotIn('2026-11-02', out)
self.assertTrue(out.startswith('Loads substation polygons from the DNO export'))
def test_file_name_prefix_and_star_leaks(self):
raw = '/* repd-rows.mjs — every REPD row on every surface the estate publishes, and\n * the link it should have.\n */'
out = D.clean_comment(D.leading_comment('drivers/repd-rows.mjs', raw), 'drivers/repd-rows.mjs')
self.assertEqual(out, 'Every REPD row on every surface the estate publishes, and the link it should have.')
def test_shouted_banner_and_box_drawing(self):
raw = ('# ── NAEI POINT SOURCES UPDATER v1.0 ─────────────\n# Downloads the NAEI Point Sources Excel from '
'energysecurity.gov.uk\n# Parses to GeoJSON with coordinates, site name, sector, and emissions.\n')
out = D.clean_comment(raw, 'fetch_naei.py')
# the line break before "Parses" ends a sentence, so the domain is not glued to the next line
self.assertEqual(out, 'Downloads the NAEI Point Sources Excel from energysecurity.gov.uk.')
self.assertNotIn('UPDATER', out)
self.assertNotIn('─', out)
def test_usage_lines_dropped(self):
raw = '// cells.test.mjs - run with: node apparatus/cells.test.mjs\n// Every check reads the cells at a tick.\n'
self.assertEqual(D.clean_comment(raw, 'apparatus/cells.test.mjs'), 'Every check reads the cells at a tick.')
def test_title_restating_sentence_skipped(self):
raw = 'GlobalGrid2050 repository size guard.\n\nFails when changed files exceed size budgets.'
out = D.clean_comment(raw, 'scripts/gridbot_repo_size_guard.py', ['globalgrid2050'],
title='GlobalGrid2050 Gridbot Repository Size Guard')
self.assertEqual(out, 'Fails when changed files exceed size budgets.')
def test_identifiers_quoted_as_code(self):
out = D.clean_comment('// Wraps fetchJson and parse_rows; see tools/x.py for the CLI.', 'a.js')
self.assertIn('`fetchJson`', out)
self.assertIn('`parse_rows`', out)
self.assertNotRegex(re.sub(r'`[^`]*`', '', out), r'[a-z]+[A-Z]\w+|\w+_\w+')
def test_word_limit_and_clause_cut(self):
raw = '// ' + ', '.join('item %d of the long list' % i for i in range(30)) + '.'
out = D.clean_comment(raw, 'a.js')
self.assertLessEqual(len(out.split()), 41)
def test_midcode_comment_not_taken_as_purpose(self):
text = "import x from './x.mjs';\nfunction run(){\n // Independent parametric clipping oracle.\n}\n"
self.assertEqual(D.leading_comment('a.test.mjs', text), '')
class Glossary(unittest.TestCase):
def test_capitalisation(self):
self.assertEqual(D.fix_case('the 33 kv and 132kv lines from repd, gridatlas and satnav in gb'),
'the 33kV and 132kV lines from REPD, GridAtlas and SatNav in GB')
self.assertEqual(D.fix_case('lidar terrain as geojson'), 'LiDAR terrain as GeoJSON')
def test_code_and_urls_untouched(self):
self.assertEqual(D.fix_case('`repd_rows` at https://x.org/repd'), '`repd_rows` at https://x.org/repd')
def test_expand_once_and_not_when_title_has_it(self):
self.assertEqual(D.expand_once('DNO data; DNO areas', ''),
'distribution network operator (DNO) data; DNO areas')
self.assertEqual(D.expand_once('DNO data', 'Distribution Network Operator (DNO) Boundaries'), 'DNO data')
def test_articles(self):
self.assertEqual(D.article('HTML page'), 'an')
self.assertEqual(D.article('JavaScript module'), 'a')
self.assertEqual(D.article('SQL query'), 'an')
self.assertEqual(D.article('unit test'), 'a')
self.assertEqual(D.article('overhead line'), 'an')
def test_polish_title(self):
self.assertEqual(D.polish_title('Fetch Naei Point Sourcesv7'), 'Fetch NAEI Point Sources v7')
self.assertEqual(D.polish_title('{GEN} Bbc Rss Pipeline'), 'BBC RSS Pipeline')
self.assertEqual(D.polish_title('Control Solar Daily Mwh Chart'), 'Control Solar Daily MWh Chart')
self.assertEqual(D.polish_title('Experiment a'), 'Experiment A')
def test_collapse_expansions(self):
self.assertEqual(D.collapse_expansions('Check Renewable Energy Planning Database (REPD) Source'),
'Check REPD Source')
class CodeEvidence(unittest.TestCase):
"""code_facts(): what the code computes, from identifiers, formulas, drawing calls and form inputs only."""
JS = ("export function computeTrefoilSpacing(d) { return d * 2; }\n"
"export function computeBendRadius(d) { return d * 15; }\n"
"function drawCrossSection(ctx) { ctx.beginPath(); ctx.arc(0, 0, 5, 0, 6.3); }\n"
"const c = canvas.getContext('2d');\n"
"const len = document.getElementById('cableLength').value;\n"
"const kv = 33; const cable_kv = kv; const mm2 = 240; const area_mm2 = mm2;\n")
def test_names_formulas_drawing_inputs_units(self):
cf = D.code_facts(self.JS, 'JavaScript module', ['computeTrefoilSpacing', 'computeBendRadius', 'drawCrossSection'])
# Big Bang R1: one clause per name, each name after its plain words; a shared verb is said once
self.assertTrue(cf['phrase'].startswith('computes trefoil spacing (`computeTrefoilSpacing`) and bend radius '
'(`computeBendRadius`)'), cf['phrase'])
self.assertIn('draws cross section', cf['phrase'])
self.assertIn('reads inputs for cable length', cf['phrase'])
self.assertIn('kV', cf['phrase'])
self.assertIn('mm²', cf['phrase'])
def test_formulas(self):
hav = ('function d(a, b) { const R = 6371; const x = Math.sin(a) * Math.cos(b);\n'
' return 2 * R * Math.atan2(Math.sqrt(x), 1); }\n')
self.assertIn('great-circle distances', D.code_facts(hav, 'script', [])['phrase'])
self.assertIn('resistive (I²R) losses', D.code_facts('loss = I**2 * R\n', 'Python module', [])['phrase'])
self.assertEqual(D.code_facts('x = 1\n', 'Python module', ['x']), {})
self.assertEqual(D.code_facts(self.JS, 'workflow', ['computeBendRadius']), {})
def test_python_has_no_drawing_or_form_evidence(self):
cf = D.code_facts('js = "canvas.getContext(\'2d\')"\n', 'Python CLI', [])
self.assertEqual(cf, {})
def test_synopsis_uses_code_evidence_and_never_invents(self):
e = ev(title='App', kind='script', repo='cable-trench-or-drill', repo_title='Cable Trench or Drill',
path='app.js', objects=['cables'], defines=['computeTrefoilSpacing', 'computeBendRadius'])
e['code'] = D.code_facts(self.JS, 'script', e['defines'], 'App')
d = D.describe(e)
self.assertTrue(d['synopsis'].startswith('A JavaScript file in Cable Trench or Drill that computes trefoil '
'spacing (`computeTrefoilSpacing`) and bend radius'), d['synopsis'])
self.assertFalse(D.generic_synopsis(d['synopsis']))
self.assertTrue(D.generic_synopsis('A JavaScript file in Cable Trench or Drill covering cables.'))
self.assertEqual(D.invented(d['synopsis'], D.evidence_text(e)), [])
self.assertLessEqual(len(d['synopsis'].split()), 31)
class Synopsis(unittest.TestCase):
def test_not_generic_template_and_no_title(self):
d = D.describe(ev(verb='calculates', objects=['cables', '33kV']))
self.assertEqual(d['synopsis'], 'A JavaScript module in the engine folder of Energy Transition Simulator that works with cables and 33kV.')
self.assertNotIn('Cable Rating', d['synopsis'])
self.assertNotRegex(d['synopsis'], r'^\w[\w ]* for ')
def test_thin_evidence_says_less(self):
d = D.describe(ev(title='Audit', kind='Python module', repo='data_uk_dno_and_tso',
repo_title='Data UK DNO and TSO', path='scripts/lib/audit.py'))
self.assertEqual(d['synopsis'], 'A Python module in the scripts folder of Data UK DNO and TSO.')
self.assertEqual(d['achieves'], '')
self.assertEqual(d['provenance']['achieves_detail'], 'none')
def test_junk_objects_and_placeholders_dropped(self):
d = D.describe(ev(kind='Python CLI', verb='fetches', objects=['data'], sources=['%s:%d', '127.0.0.1:${PORT}']))
self.assertNotIn('%s', d['synopsis'])
self.assertNotIn('127.0.0.1', d['synopsis'])
self.assertNotIn('data', d['synopsis'].split(' in ')[0])
d = D.describe(ev(verb='calculates', objects=['"\'+esc(s["repository"])+\'"', 'style', '9ab451f4bf19 fast news']))
self.assertNotRegex(d['synopsis'], r'esc|style|9ab451')
def test_draws_needs_rendering_role(self):
d = D.describe(ev(title='Physics Generated', kind='script', role='electrical', verb='draws'))
self.assertNotIn('draws', d['synopsis'])
def test_repo_sources_named_by_title(self):
d = D.describe(ev(kind='page', role='render', has_map=True, verb='maps', objects=['substations', '132kV'],
sources=['gridatlas data', 'ventus-grid-engine data'],
repo_titles={'gridatlas': 'GridAtlas', 'ventus-grid-engine': 'Ventus Grid Engine'}))
self.assertIn('A map page in the engine folder of Energy Transition Simulator that maps substations and 132kV, and uses data from '
'the GridAtlas and Ventus Grid Engine repositories.', d['synopsis'])
def test_published_only_for_served_kinds(self):
url = 'https://ventusltd.github.io/gridatlas/atlas/'
self.assertIn('Published at ' + url, D.describe(ev(kind='page', published=url))['synopsis'])
self.assertIn('Served with the page at', D.describe(ev(kind='script', published=url))['synopsis'])
self.assertNotIn(url, D.describe(ev(kind='Python module', published=url))['synopsis'])
def test_word_limit(self):
d = D.describe(ev(kind='page', verb='maps', has_map=True, published='https://ventusltd.github.io/a/b/',
objects=['substations', 'cables', 'overhead lines (OHL)', 'the REPD register', 'solar'],
sources=['NESO data portal', 'Elexon BMRS', 'postcodes.io']))
self.assertLessEqual(len(d['synopsis'].split()), 30)
def test_workflow(self):
wf = D.workflow_facts('name: Deploy static Pages\non:\n push:\n workflow_dispatch:\njobs:\n b:\n steps:\n'
' - run: python tools/build.py\n - uses: actions/deploy-pages@v4\n')
self.assertEqual(wf, {'name': 'Deploy static Pages', 'triggers': ['push', 'workflow_dispatch'],
'runs': ['tools/build.py'], 'publishes': True})
d = D.describe(ev(title='Pages Workflow', kind='workflow', role='automation', verb='builds and publishes',
workflow=dict(wf, run_titles={'tools/build.py': 'Build'})))
self.assertEqual(d['synopsis'], 'A GitHub Actions workflow in the engine folder of Energy Transition Simulator that builds and '
'publishes the site. Runs on push and by hand.')
self.assertEqual(d['achieves'], 'Named “Deploy static Pages”; runs Build (`tools/build.py`); publishes to GitHub Pages.')
class Achieves(unittest.TestCase):
def test_order_comment_first(self):
d = D.describe(ev(comment=D.leading_comment('a.mjs', COPIED_HEADER), defines=['rate'],
vedic={'function': 'dropPercent', 'output': 'drop percent', 'inputs': ['drop volts'], 'word': 'PERCENT'}))
self.assertEqual(d['provenance']['achieves'], 'comment')
self.assertTrue(d['achieves'].startswith('Continuous current rating'))
def test_vedic_wording(self):
d = D.describe(ev(vedic={'function': 'distanceKm', 'output': 'distance km', 'inputs': ['coordinate pair',
'coordinate pair'], 'word': 'MEASURE'}))
self.assertEqual(d['achieves'], 'Its `distanceKm` function gives distance km from two coordinate pairs (VEDIC: measure).')
def test_name_fallback_and_defines(self):
d = D.describe(ev(title='Fetch NESO DNO Boundaries', kind='Python CLI', defines=['main', 'fetch_page', '_hdr']))
self.assertEqual(d['achieves'], 'Its name says it fetches NESO DNO boundaries. Defines `fetch_page`.')
d = D.describe(ev(title='Run V9 22', kind='shell script', defines=['walk']))
self.assertEqual(d['achieves'], 'Defines `walk`.')
def test_config_summary(self):
text = 'manifestVersion: 1\ntitle: Generation Data Discipline Mega Upgrade\nsummary: >\n Lift the solar chart into its own module.\n'
self.assertEqual(D.config_summary('m.yml', text), 'Lift the solar chart into its own module.')
d = D.describe(ev(title='002 Solar Daily MWh', kind='configuration', config=D.config_summary('m.yml', text)))
self.assertEqual(d['achieves'], 'Lift the solar chart into its own module.')
def test_main_only(self):
self.assertEqual(D.main_only('#!/usr/bin/env python3\nfrom .export import main\nmain()\n'), '.export')
self.assertEqual(D.main_only('import x\ndef f():\n return 1\nf()\n'), '')
def test_readme_sentences_join_wrapped_lines(self):
text = '# T\n\nThe `engine.js` file holds pure computation\nfunctions and the canonical report.\n\n- Run node x.js first.\n'
sents = D.readme_sentences(text)
self.assertIn('The `engine.js` file holds pure computation functions and the canonical report.', sents)
def test_readme_match_needs_the_file_name(self):
sents = ['SEED preserves capabilities people can invoke, verify and combine.',
'route-constraints is the constraint-aware second result, never the first.']
self.assertEqual(D.readme_match(sents, 'src/invoke.mjs'), '')
self.assertEqual(D.readme_match(sents, 'src/route-constraints/route-constraints.js'), sents[1])
self.assertEqual(D.readme_match(['Run node x.js from the repository root.'], 'x.js'), '')
class Why(unittest.TestCase):
def test_one_dependent_no_including(self):
d = D.describe(ev(dependents=[{'title': 'Cmd Model', 'kind': 'JavaScript module', 'role': 'transform',
'repo': 'energy-transition-simulator'}]))
self.assertEqual(d['why'], 'Imported by Cmd Model.')
def test_user_facing_page_first_and_tests_separate(self):
deps = [{'title': 'Route Constraints Test', 'kind': 'test', 'role': 'test', 'repo': 'r'},
{'title': 'GridAtlas — Atlas Page', 'kind': 'page', 'role': 'render', 'repo': 'r', 'is_map': True,
'published': 'https://ventusltd.github.io/gridatlas/atlas/'}]
d = D.describe(ev(repo='r', objects=['substations'], dependents=deps))
self.assertEqual(d['why'], 'Feeds the Atlas map page (substations) at https://ventusltd.github.io/gridatlas/atlas/. '
'Checked by Route Constraints Test.')
def test_many_dependents_and_other_repos(self):
deps = [{'title': 'F%d' % i, 'kind': 'JavaScript module', 'role': 'render', 'repo': 'gridatlas' if i % 2 else 'r'}
for i in range(5)]
d = D.describe(ev(repo='r', dependents=deps, repo_titles={'gridatlas': 'GridAtlas'}))
self.assertEqual(d['why'], 'Imported by 5 files, including F0, F1 and F2, from GridAtlas.')
def test_test_guards_imports(self):
d = D.describe(ev(title='Recorder Test', kind='test', role='test', imports=[{'title': 'Recorder', 'kind': 'x'}]))
self.assertEqual(d['why'], 'Guards the behaviour of Recorder.')
self.assertEqual(d['synopsis'], 'A test in the engine folder of Energy Transition Simulator that checks Recorder.')
class Discipline(unittest.TestCase):
FIXTURES = [
ev(comment=COPIED_HEADER, verb='calculates', objects=['cables', '33kV'],
dependents=[{'title': 'Cmd Trench', 'kind': 'JavaScript module', 'role': 'transform', 'repo': 'x'}]),
ev(title='Fetch Elexon', kind='Python CLI', verb='fetches', objects=['solar', 'wind'], sources=['Elexon BMRS'],
defines=['fetch_month', 'parse_dt']),
ev(title='Atlas', kind='page', has_map=True, verb='maps', objects=['substations', '"Grid layers"'],
sources=['gridatlas data'], published='https://ventusltd.github.io/gridatlas/atlas/',
repo_titles={'gridatlas': 'GridAtlas'}),
ev(title='Pages Workflow', kind='workflow', workflow={'name': 'Deploy', 'triggers': ['push'], 'runs': [],
'publishes': True}),
ev(title='Engine', readme=['The `engine.js` module holds pure computation functions.'], path='v9/engine.js'),
ev(title='Compass', vedic={'function': 'fixQuality', 'output': 'location fix quality', 'inputs': ['fix'],
'word': 'CHECK LOCATION FIX'}),
]
def test_deterministic(self):
for f in self.FIXTURES:
self.assertEqual(D.describe(f), D.describe(dict(f)))
def test_never_invents(self):
for f in self.FIXTURES:
d = D.describe(f)
out = ' '.join((d['synopsis'], d['achieves'], d['why']))
self.assertEqual(D.invented(out, evidence_of(f)), [], out)
def test_invented_detects_new_names_and_urls(self):
self.assertEqual(D.invented('Feeds the Leaflet map at https://example.net/x.', 'feeds a map'),
['https://example.net/x.', 'Leaflet'])
def test_limits_and_flags_clean(self):
for f in self.FIXTURES:
d = D.describe(f)
self.assertLessEqual(len(d['synopsis'].split()), 30)
self.assertLessEqual(len(d['achieves'].split()), 45)
self.assertFalse(D.flags(d['title'], d['synopsis'], d['achieves'], d['why'], f['kind']) &
{'repetitive', 'jargon/identifiers', 'broken English', 'status/housekeeping',
'wrong place/URL', 'misleading why'}, d)
def test_flags_catch_old_texts(self):
old = D.flags('Gate', 'Python module for Gate that loads data. Part of GlobalGrid2050.',
'Python module for Gate: defines utc_now, write_receipts, a, b.',
'Used by 1 file in the estate, including Combine; feeds: Project |….')
self.assertTrue({'repetitive', 'jargon/identifiers', 'broken English', 'misleading why'} <= old, old)
self.assertIn('generic', D.flags('Federation', 'Configuration for Federation. Part of Data Federation.',
'Configuration for Federation.', ''))
self.assertIn('wrong place/URL', D.flags('Clicker', 'Python tool for Clicker that fetches data from %s:%d.',
'', '', 'Python CLI'))
self.assertIn('status/housekeeping', D.flags('X', 'A test.', 'COPIED UNCHANGED from v12 at commit 3adcee9f00.', ''))
def test_dedupe_words(self):
self.assertEqual(D.dedupe_words('loads data data from Test Test files'), 'loads data from Test files')
class BuildAdapter(unittest.TestCase):
def test_evidence_from_build(self):
files = [
{'title': 'Cable Rating', 'kind': 'JavaScript module', 'role': 'electrical', 'repo': 'ets',
'path': 'engine/cable-rating.mjs', 'text': COPIED_HEADER, 'defs': [('rate', 'function', 7), ('Secret', 'class', 9)],
'syn_parts': ('calculates', ['cables', '33kV'], []), 'published': '', 'vedic': [], 'links': []},
{'title': 'Ets — Index Page', 'kind': 'page', 'role': 'render', 'repo': 'ets', 'path': 'index.html',
'text': '<script>maplibregl.Map()</script>', 'defs': [], 'syn_parts': ('maps', [], []),
'published': 'https://ventusltd.github.io/ets/', 'vedic': [], 'links': [0]},
]
metas = {'ets': {'readme_sentences': {'engine': ['The `cable-rating.mjs` module rates one cable.']}}}
e = D.evidence_from_build(0, files, {0: [1]}, metas, lambda r: r.upper(), leaks=lambda s: 'Secret' in s)
self.assertEqual(e['defines'], ['rate'])
self.assertEqual(e['readme'], ['The `cable-rating.mjs` module rates one cable.'])
self.assertEqual(e['dependents'][0]['published'], 'https://ventusltd.github.io/ets/')
self.assertTrue(e['dependents'][0]['is_map'])
d = D.describe(e)
self.assertEqual(d['why'], 'Feeds the Ets map page (cables and 33kV) at https://ventusltd.github.io/ets/.')
self.assertTrue(d['achieves'].startswith('Continuous current rating'))
e1 = D.evidence_from_build(1, files, {0: [1]}, metas, lambda r: r.upper())
self.assertEqual(D.describe(e1)['synopsis'].split('.')[0], 'A map page') # repository already named in the title
@unittest.skipUnless(os.path.exists('/tmp/site5/explore-code/build_graph.json') and os.path.isdir('/home/claude/src'),
'local build_graph.json and clones not present')
class RealEstateSample(unittest.TestCase):
def test_first_400_records(self):
import json
with open('/tmp/site5/explore-code/build_graph.json') as fh:
g = json.load(fh)
rt, cache = {}, {}
for f in g['files']:
r = D.parse_synopsis(f['synopsis'], f['title'])['repo_title']
rt.setdefault(f['repo'], r or f['repo'])
for i in range(0, len(g['files']), max(1, len(g['files']) // 400)):
e = D.evidence_from_graph(g, i, '/home/claude/src', cache, rt)
d = D.describe(e)
out = ' '.join((d['synopsis'], d['achieves'], d['why']))
self.assertEqual(D.invented(out, D.evidence_text(e)), [], (i, out))
self.assertLessEqual(len(d['synopsis'].split()), 30, d['synopsis'])
self.assertNotIn(d['title'].lower(), d['synopsis'].lower() if len(d['title'].split()) > 1 else '')
class Version2(unittest.TestCase):
"""describe-2: Big Bang R4 specifics, imperative comment folded once, repository name not a sentence, status."""
def test_specifics_only_from_source(self):
self.assertEqual(D.specifics('rating per IEC 60287 using haversine'), ['IEC 60287', 'haversine'])
self.assertEqual(D.specifics('plain code'), [])
e = ev(defines=['computeBendRadius'], specifics=['IEC 60287'])
e['code'] = D.code_facts('function computeBendRadius(){}', 'JavaScript module', e['defines'], e['title'])
d = D.describe(e)
self.assertIn('using IEC 60287', d['synopsis'])
self.assertEqual(D.invented(d['synopsis'], D.evidence_text(e)), [])
def test_imperative_comment_said_once(self):
e = ev(title='Register', kind='Python module', repo='stars', repo_title='Stars', path='spider/register.py',
comment='"""Register the graphs this repository publishes for the dashboard. Each entry is checked."""')
d = D.describe(e)
self.assertIn('that registers the graphs this repository publishes', d['synopsis'])
self.assertNotIn('graphs this repository publishes', d['achieves']) # said once, not twice
def test_descriptor_sentence_is_not_a_place(self):
d = D.describe(ev(repo_title='This is the framework file.', repo='kuiper-belt'))
self.assertNotIn('framework file', d['synopsis'])
self.assertIn('Kuiper Belt', d['synopsis'])
def test_status_from_context(self):
e = ev(context={'set_aside': 'near-copy-of', 'twin': {'title': 'Block Trenches', 'repo': 'globalgrid2050',
'path': 'world/block-trenches.mjs'}})
d = D.describe(e)
self.assertIn('A near copy of Block Trenches in GlobalGrid2050; the cleaned view keeps that one.', d['why'])
self.assertEqual(D.invented(d['why'], D.evidence_text(e)), [])
self.assertEqual(D.describe(ev(context={'clarity': 'unreached'}))['why'], 'No entry point reaches it.')
self.assertEqual(D.describe(ev())['why'], '')
self.assertEqual(D.describe(ev())['provenance']['version'], D.GENERATOR_VERSION)
class BigBangRules(unittest.TestCase):
"""describe-3: distilled Big Bang rules (bigbang/DISTILLED.md), adopted one at a time on the judge."""
def test_r1_verb_clauses_and_r1b_helpers(self):
e = ev(defines=['computeRating', 'segDist', 'Cable'], comment='')
d = D.describe(e)
text = d['synopsis'] + ' ' + d['achieves']
self.assertIn('computes rating (`computeRating`)', text)
self.assertIn('the seg dist helper (`segDist`)', text)
self.assertIn('the cable class (`Cable`)', text)
self.assertEqual(D.invented(text, D.evidence_text(e)), [])
self.assertLessEqual(len(d['synopsis'].split()), 30)
self.assertTrue(d['provenance']['bigbang'])
def test_r4b_r7_source_facts(self):
src = ("import json\nap.add_argument('--out')\nopen('cables.json')\nrating = '33 kV' + ' 33 kV'\n"
"with open('report.md', 'w') as fh: pass\n")
facts = D.bb_source_facts(src, 'Python CLI')
self.assertEqual(facts['bb_units'], ['33 kV'])
self.assertEqual(facts['bb_io'], {'reads': ['cables.json'], 'writes': ['report.md'], 'flags': ['--out']})
self.assertNotIn('bb_units', D.bb_source_facts('cost = 1,000 MVA')) # never "000 MVA"
e = ev(kind='Python CLI', path='tools/rate.py', **facts)
d = D.describe(e)
self.assertIn('Its code works with 33 kV.', d['achieves'])
self.assertIn('reads `cables.json`', d['achieves'])
self.assertIn('It accepts `--out`.', d['achieves'])
self.assertEqual(D.invented(d['synopsis'] + ' ' + d['achieves'], D.evidence_text(e)), [])
def test_switch_off(self):
old = D.BIGBANG
try:
D.BIGBANG = False
d = D.describe(ev(defines=['computeRating']))
self.assertNotIn('computes rating', d['synopsis'] + d['achieves'])
finally:
D.BIGBANG = old
def test_k1_name_only_note(self):
d = D.describe({'title': 'Notes', 'path': 'misc/notes.js', 'defines': [], 'role': 'other', 'kind': 'script'})
self.assertEqual((d['provenance']['achieves'], d['provenance']['candidate']), ('name', True))
self.assertEqual(d['note'], D.NAME_ONLY)
self.assertNotIn(D.NAME_ONLY, d['achieves']) # shown beside achieves, not inside it
d2 = D.describe(ev(defines=['computeRating']))
self.assertEqual(d2['note'], '')
self.assertIn('candidate', D.NAME_ONLY)
if __name__ == '__main__':
unittest.main()