In this section
- Test Pilot Lightning test · cosmic / tools/explore/theme/test_pilot_lightning.py lines 1–177
- Test Pilot Static test · cosmic / tools/explore/theme/test_pilot_static.py lines 1–257
Test Pilot Lightning
A test in the theme folder of Cosmic that checks Inject, using haversine and SHA-256.
testcosmic / tools/explore/theme/test_pilot_lightning.py · lines 1–177 of 177 · Not reached from any entry point (candidate for review) · pattern browser (shared by 8 files)
- What it does
- It tests its inputs. Defines 14 functions or classes, including git_show, _flash_feature, reference, bearing, site. Uses libraries __future__, functools, hashlib, http.server, importlib.util. Side effects: changes the web page (DOM); reads or writes files; starts processes.
- Inputs & outputs
- In: GeoJSON file grid_substations.geojson; GeoJSON file uk_lightning.geojson; JSON file in.json. Out: JSON file in.json; JSON file play-index.json; GeoJSON file grid_substations.geojson.
- What it achieves
- It is built from the git show helper (`git_show`), the reference step (`reference`) and the bearing step (`bearing`). Lightning parity acceptance (ChatGPT round 2 item 1; W10 CAPSTAN-41). It reads `in.json` and writes `in.json`.
- Why it matters
- Guards the behaviour of Inject.
- Application
- cosmic · tools/explore/theme · test
- Uses
- Inject (script call), __future__, functools, hashlib, http.server, importlib.util, json, math, shutil
- Used by
- none found
- Produces
- git_show, reference, bearing, site, browser, pilot_readout, test_parity_with_reference_engine_on_a_real_flash, test_flash_time_pin, test_empty_dataset, test_polygon_and_multipolygon_locations, test_voltage_filter, test_tie_order_matches_reference
- Defines here
- git_show, _flash_feature, reference, bearing, site, browser, pilot_readout, test_parity_with_reference_engine_on_a_real_flash, test_flash_time_pin, test_empty_dataset, test_polygon_and_multipolygon_locations, test_voltage_filter, test_tie_order_matches_reference, test_failed_load_is_unknown_not_none
- 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/theme/test_pilot_lightning.py:1-177 · blob ddbdbf6c56416d49ea0e3bd53761358142235364 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, process · domain stage: unknown · users: none · canonical: unreached_review
"""Lightning parity acceptance (ChatGPT round 2 item 1; W10 CAPSTAN-41).
Pilot's lightning readout must equal the Ventus Grid Engine lightning context engine GridAtlas's lab imports
(ventus-grid-engine@69b4e88 engine/lightning-click-context.js, run here from the ORIGINAL ES modules in node) on a
pinned real flash and the pinned substation dataset: same ordered identities, unrounded distances within 1 mm. Bearings
are checked separately against an independent haversine-sphere calculation in Python. Extra cases: empty dataset,
polygon location, voltage filter, a tie, a failed load. Needs node, Playwright and the clones (skips otherwise).
Run: python3 -m pytest -q tools/explore/theme/test_pilot_lightning.py
"""
from __future__ import annotations
import functools, hashlib, http.server, importlib.util, json, math, shutil, socketserver, subprocess, tempfile, threading
from pathlib import Path
import pytest
HERE = Path(__file__).resolve().parent
SRC = Path('/home/claude/src')
VGE, VGE_SHA = SRC / 'ventus-grid-engine', '69b4e88c8464f0310bd67e47ec83ee8afa9e1921'
GA, GA_SHA = SRC / 'gridatlas', 'f944f8dcbc09cd09c0895f0126682ec241cd576f'
SUBS_PATH = 'atlas/releases/202608300453-atlas-v9/data/grid_substations.geojson'
LG, LG_SHA = SRC / 'lightning', '2882145e28a0412de3a5bcfa40a12d7cd894ba90'
FEED_SHA256 = '933f117a61805ee149e75adac90c7aec2605d508fba06fe5ba71443972397b66'
FLASH_ID = 'W_XX-EUMETSAT-Darmstadt,IMG+SAT,MTI1+LI-2-LFL--FD--x-x--ARC-x_C_EUMT_20261027035022_L2PF_OPE_20261027034009_20261027035009_N__O_0023_0000:6916'
FLASH_T = '2026-10-27T03:49:11.939Z'
FLASH_LL = (-5.4567, 57.456001) # lon, lat as published
from datetime import datetime as _dt
FLASH_MS = int(_dt.fromisoformat(FLASH_T.replace('Z', '+00:00')).timestamp() * 1000)
OPTS = {'radiusKm': 20, 'minimumKv': 132, 'substationLimit': 6, 'solarLimit': 30}
have = shutil.which('node') and all((p / '.git').exists() for p in (VGE, GA, LG))
pytestmark = pytest.mark.skipif(not have, reason='node or clones unavailable')
def git_show(repo: Path, sha: str, path: str) -> bytes:
return subprocess.run(['git', '-C', str(repo), 'show', f'{sha}:{path}'], capture_output=True, check=True).stdout
def _flash_feature():
feed = git_show(LG, LG_SHA, 'data/uk_lightning.geojson')
assert hashlib.sha256(feed).hexdigest() == FEED_SHA256
f = [x for x in json.loads(feed)['features'] if x['id'] == FLASH_ID]
assert len(f) == 1 and f[0]['properties']['time_utc'] == FLASH_T and tuple(f[0]['geometry']['coordinates'][:2]) == FLASH_LL
return f[0]
def reference(features, flash, opts):
"""The original engine, unmodified ES modules from the clone."""
d = Path(tempfile.mkdtemp(prefix='vge-ref-'))
for rel in ('engine/lightning-click-context.js', 'engine/v9-geodesy.js', 'engine/v9-nearest-search.js', 'deeplink/contract.js'):
(d / rel).parent.mkdir(parents=True, exist_ok=True)
(d / rel).write_bytes(git_show(VGE, VGE_SHA, rel))
(d / 'package.json').write_text('{"type": "module"}')
(d / 'in.json').write_text(json.dumps({'features': features, 'flash': flash, 'opts': opts}))
(d / 'run.mjs').write_text("import fs from 'node:fs';import {createLightningContextEngine} from './engine/lightning-click-context.js';"
"const i=JSON.parse(fs.readFileSync('in.json','utf8'));const e=createLightningContextEngine({substations:i.features});"
"const c=e.selectFlash(i.flash,i.opts);console.log(JSON.stringify(c.substations.map(s=>({name:s.name,id:s.source_site_id,km:s.km,kv:s.voltages_kv,loc:s.location}))));")
r = subprocess.run(['node', 'run.mjs'], capture_output=True, text=True, cwd=d)
assert r.returncode == 0, r.stderr
shutil.rmtree(d, ignore_errors=True)
return json.loads(r.stdout)
def bearing(lon1, lat1, lon2, lat2):
p1, p2, dl = math.radians(lat1), math.radians(lat2), math.radians(lon2 - lon1)
return (math.degrees(math.atan2(math.sin(dl) * math.cos(p2), math.cos(p1) * math.sin(p2) - math.sin(p1) * math.cos(p2) * math.cos(dl))) + 360) % 360
@pytest.fixture(scope='module')
def site():
spec = importlib.util.spec_from_file_location('inject', HERE / 'inject.py')
inj = importlib.util.module_from_spec(spec); spec.loader.exec_module(inj)
tmp = Path(tempfile.mkdtemp(prefix='pilot-lg-'))
inj.sync_pilot(tmp, inj.copy_assets(tmp))
(tmp / 'index.html').write_text('x'); (tmp / 'theme' / 'play-index.json').write_text('{}')
subs = git_show(GA, GA_SHA, SUBS_PATH)
fx = {
'real': subs,
'empty': b'{"type":"FeatureCollection","features":[]}',
'poly': json.dumps({'type': 'FeatureCollection', 'features': [
{'type': 'Feature', 'id': 'way/1', 'properties': {'name': 'Square yard', 'voltage': '132000'},
'geometry': {'type': 'Polygon', 'coordinates': [[[-1.01, 52.0], [-0.99, 52.0], [-0.99, 52.02], [-1.01, 52.02], [-1.01, 52.0]]]}},
{'type': 'Feature', 'id': 'way/2', 'properties': {'name': 'Multi yard', 'voltage': '400000'},
'geometry': {'type': 'MultiPolygon', 'coordinates': [[[[-1.2, 52.1], [-1.18, 52.1], [-1.18, 52.12], [-1.2, 52.12], [-1.2, 52.1]]]]}}]}).encode(),
'tie': json.dumps({'type': 'FeatureCollection', 'features': [
{'type': 'Feature', 'id': 'node/' + n, 'properties': {'name': 'Tie ' + n, 'voltage': '132000'}, 'geometry': {'type': 'Point', 'coordinates': c}}
for n, c in (('b', [-1.0, 52.01]), ('a', [-1.0, 51.99]), ('c', [-0.98, 52.0]))]}).encode(),
}
for k, v in fx.items():
(tmp / 'fx' / k).mkdir(parents=True); (tmp / 'fx' / k / 'grid_substations.geojson').write_bytes(v)
h = functools.partial(http.server.SimpleHTTPRequestHandler, directory=str(tmp)); h.log_message = lambda *a, **k: None
srv = socketserver.ThreadingTCPServer(('127.0.0.1', 0), h); srv.daemon_threads = True
threading.Thread(target=srv.serve_forever, daemon=True).start()
yield f'http://127.0.0.1:{srv.server_address[1]}', fx
srv.shutdown(); shutil.rmtree(tmp, ignore_errors=True)
@pytest.fixture(scope='module')
def browser():
from playwright.sync_api import sync_playwright
exe = next(iter(sorted(Path('/opt/pw-browsers').glob('chromium-*/chrome-linux64/chrome'))), None)
with sync_playwright() as p:
b = p.chromium.launch(**({'executable_path': str(exe)} if exe else {}))
yield b
b.close()
def pilot_readout(browser, base, fx, lon, lat, kind, info, min_kv=132):
pg = browser.new_page(viewport={'width': 390, 'height': 844})
pg.route('**/*', lambda r: r.continue_() if r.request.url.startswith('http://127.0.0.1') else r.abort())
pg.goto(f'{base}/pilot/index.html?lgga={base}/fx/{fx}/', wait_until='load')
pg.wait_for_function('window.PILOT && PILOT.layer && PILOT.layer("lightning") && PILOT.layer("lightning")._api')
out = pg.evaluate('''async ([lon, lat, kind, info, kv]) => { const A = PILOT.layer('lightning')._api; A.S.minKv = kv;
PILOT.card(A.choose(lon, lat, kind, info));
for (let i = 0; i < 200; i++) { await new Promise(r => setTimeout(r, 50));
if (A.S.sel && A.S.sel.lat === lat && A.S.sel.lon === lon) return {rows: A.S.sel.rows.map(a => ({name: a.name, id: a.id, km: a.km, kv: a.kv, at: a.at, bearing: a.bearing}))};
const el = document.querySelector('.p-lightning-ro'); if (el && /UNKNOWN/.test(el.textContent)) return {failed: el.textContent}; }
return {timeout: true}; }''', [lon, lat, kind, info, min_kv])
pg.close()
return out
def test_parity_with_reference_engine_on_a_real_flash(site, browser):
base, fx = site
flash = _flash_feature()
feats = json.loads(fx['real'])['features']
ref = reference(feats, flash, OPTS)
assert len(ref) == 6
t = FLASH_MS
got = pilot_readout(browser, base, 'real', FLASH_LL[0], FLASH_LL[1], 'flash', {'id': FLASH_ID, 't': t})
rows = got['rows']
assert [(r['name'], r['id']) for r in rows] == [(r['name'] or '', r['id']) for r in ref]
for a, b in zip(rows, ref):
assert abs(a['km'] - b['km']) <= 1e-6, (a, b) # 1 mm
assert a['kv'] == b['kv'] and a['at'] == [b['loc']['lon'], b['loc']['lat']]
assert abs(a['bearing'] - bearing(FLASH_LL[0], FLASH_LL[1], *a['at'])) < 1e-9
def test_flash_time_pin():
from datetime import datetime
assert int(datetime.fromisoformat(FLASH_T.replace('Z', '+00:00')).timestamp() * 1000) == FLASH_MS
def test_empty_dataset(site, browser):
base, _ = site
assert pilot_readout(browser, base, 'empty', -1.0, 52.0, 'point', {'from': 'test'}) == {'rows': []}
def test_polygon_and_multipolygon_locations(site, browser):
base, fx = site
rows = pilot_readout(browser, base, 'poly', -1.0, 52.0, 'point', {'from': 'test'}, 0)['rows']
assert [r['name'] for r in rows] == ['Square yard', 'Multi yard']
# the engine's representativePoint (ring vertex mean, closing vertex included) lies inside the yard
assert -1.01 < rows[0]['at'][0] < -0.99 and 52.0 < rows[0]['at'][1] < 52.02
def test_voltage_filter(site, browser):
base, _ = site
rows = pilot_readout(browser, base, 'poly', -1.0, 52.0, 'point', {'from': 'test'}, 400)['rows']
assert [r['name'] for r in rows] == ['Multi yard'] and rows[0]['kv'] == [400]
def test_tie_order_matches_reference(site, browser):
base, fx = site
feats = json.loads(fx['tie'])['features']
flash = {'type': 'Feature', 'id': 'tie-test', 'geometry': {'type': 'Point', 'coordinates': [-1.0, 52.0]},
'properties': {'observation_kind': 'optical_lightning_flash', 'time_utc': FLASH_T}}
ref = reference(feats, flash, OPTS)
got = pilot_readout(browser, base, 'tie', -1.0, 52.0, 'flash', {'id': 'tie-test', 't': FLASH_MS})['rows']
assert [r['id'] for r in got] == [r['id'] for r in ref]
assert abs(got[0]['km'] - got[1]['km']) < 1e-9 # a real tie (1.11 km north and south)
def test_failed_load_is_unknown_not_none(site, browser):
base, _ = site
out = pilot_readout(browser, base, 'missing', -1.0, 52.0, 'point', {'from': 'test'})
assert 'UNKNOWN' in out.get('failed', ''), outTest Pilot Static
A test in the theme folder of Cosmic that checks Inject and Pilot using data from postcodes.io.
testcosmic / tools/explore/theme/test_pilot_static.py · lines 1–257 of 257 · Entry point · pattern _strip_comments (shared by 2 files)
- What it does
- It tests postcodes. Defines 20 functions or classes, including _inject, _strip_comments, test_page_has_module_markers_once_in_contract_order, test_source_page_tags_each_module_literally_once_in_order, test_inject_tags_every_shipped_module_in_order_and_is_idempotent. Uses libraries __future__, importlib.util, re, shutil, subprocess. Side effects: changes the web page (DOM); reads or writes files; makes network requests; starts processes.
- Why it exists in the grid workflow
- Domain terms in the code: postcodes.
- Inputs & outputs
- In: data source: postcodes.io; JSON file places.json; JSON file pilot-places.json.
- Downstream impact
- Used directly by 1 file: CI Chess Workflow (cosmic).
- What it achieves
- Static tests for the Pilot / Drone View page and its modules (Pilot-200, W10 CAPSTAN-41).
- Why it matters
- Run by CI Chess Workflow.
- Application
- cosmic · tools/explore/theme · test
- Uses
- Inject (script call), Pilot (script call), __future__, importlib.util, re, shutil, subprocess, tempfile, pathlib, pytest
- Used by
- run by CI Chess Workflow (workflow run)
- Produces
- test_page_has_module_markers_once_in_contract_order, test_source_page_tags_each_module_literally_once_in_order, test_inject_tags_every_shipped_module_in_order_and_is_idempotent, test_inject_with_no_modules_and_absent_files, test_sync_pilot_copies_modules, test_js_parses, test_module_shell_follows_contract, test_module_css_is_prefixed, test_external_hosts_are_allow_listed, test_imagery_and_data_hosts_carry_attribution, test_photon_rule_file_sizes, test_no_religious_terms
- Defines here
- _inject, _strip_comments, test_page_has_module_markers_once_in_contract_order, test_source_page_tags_each_module_literally_once_in_order, test_inject_tags_every_shipped_module_in_order_and_is_idempotent, test_inject_with_no_modules_and_absent_files, test_sync_pilot_copies_modules, test_js_parses, test_module_shell_follows_contract, test_module_css_is_prefixed, test_external_hosts_are_allow_listed, test_imagery_and_data_hosts_carry_attribution, test_photon_rule_file_sizes, test_no_religious_terms, test_modules_escape_fetched_text, test_modules_respect_offline_flag, _pilot_py, test_clip_runs_cuts_each_segment_at_the_radius, test_places_cache_declares_exception, test_licence_manifest_rows_and_notices
- 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/theme/test_pilot_static.py:1-257 · blob 2b7c4b8d7b8d01b3d37e30f7d2da36e5b0372f22 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, network, process · domain stage: unknown · users: none · canonical: unknown
"""Static tests for the Pilot / Drone View page and its modules (Pilot-200, W10 CAPSTAN-41).
Module contract: theme/pilot.js exposes window.PILOT; each workstream ships theme/pilot-<name>.js (+ optional .css),
tagged into pilot/index.html by inject.py (pilot_modules / pilot_module_html). These checks need no browser.
Run: python3 -m pytest -q tools/explore/theme/test_pilot_static.py
"""
from __future__ import annotations
import importlib.util, re, shutil, subprocess, tempfile
from pathlib import Path
import pytest
HERE = Path(__file__).resolve().parent
PILOT_HTML, PILOT_JS = HERE / 'pilot.html', HERE / 'pilot.js'
MOD_RE = re.compile(r'^pilot-([a-z0-9]+)\.(js|css)$')
MODULES = sorted(p for p in HERE.iterdir() if MOD_RE.match(p.name))
MOD_JS = [p for p in MODULES if p.suffix == '.js']
MOD_CSS = [p for p in MODULES if p.suffix == '.css']
ALL_JS = [PILOT_JS] + MOD_JS
# Every external host the Pilot page may contact, with why. A new host must be reviewed and added here.
ALLOWED_HOSTS = {
'server.arcgisonline.com': 'Esri World Imagery (SAT mode)',
's3.amazonaws.com': 'AWS Terrain Tiles (elevation)',
'api.postcodes.io': 'postcode / place search (GridAtlas geocoder lane 1)',
'nominatim.openstreetmap.org': 'address search (GridAtlas geocoder lane 2)',
'tile.openstreetmap.org': 'OpenStreetMap standard tiles (overview / MAP)',
'www.openstreetmap.org': 'OpenStreetMap copyright link (attribution)',
'ventusltd.github.io': 'GridAtlas published data (photon rule: stream, never copy)',
'raw.githubusercontent.com': 'estate published data files',
'basemaps.cartocdn.com': 'CARTO basemap (MAP mode, as GridAtlas uses)',
'router.project-osrm.org': 'OSRM public router (SatNav road routing, as the simulator uses)',
'opendata.arcgis.com': 'ArcGIS open-data hosting (credit links)',
'ukpowernetworks.opendatasoft.com': 'UKPN Open Data (credit link)',
'www.gov.uk': 'REPD source (credit link)',
'creativecommons.org': 'licence link (credit)',
'www.esri.com': 'Esri credit link',
'github.com': 'source links',
'globalgrid2050.com': 'Pipeline News site link (estate homepage domain)',
'code.globalgrid2050.com': 'Explore Code itself (section links), cosmic custom domain',
'carto.com': 'CARTO attributions link',
'www.arcgis.com': 'Esri World Imagery item page (credit link)',
'registry.opendata.aws': 'AWS Terrain Tiles registry page (credit link)',
}
RELIGIOUS = re.compile(r'\b(god|gods|goddess|holy|divine|sacred|temple|church|prayer|pray|blessed|heaven|hell|deity|worship|scripture)\b', re.I)
MAX_FILE_BYTES = 300_000 # photon rule: no bundled datasets in cosmic
def _inject():
spec = importlib.util.spec_from_file_location('inject', HERE / 'inject.py')
mod = importlib.util.module_from_spec(spec); spec.loader.exec_module(mod)
return mod
def _strip_comments(js: str) -> str:
return re.sub(r'/\*.*?\*/', '', js, flags=re.S)
# ---------------------------------------------------------------- page wiring
def test_page_has_module_markers_once_in_contract_order():
html = PILOT_HTML.read_text()
assert html.count('<!--pilot-module-css-->') == 1 and html.count('<!--pilot-module-js-->') == 1
i_css, i_mcss = html.index('href="pilot.css"'), html.index('<!--pilot-module-css-->')
i_js, i_mjs = html.index('src="pilot.js"'), html.index('<!--pilot-module-js-->')
assert i_css < i_mcss < html.index('</head>') < i_js < i_mjs < html.index('</body>')
assert not re.search(r'<(script|link)[^>]+(src|href)="https?://', html), 'no external scripts or styles'
assert not re.search(r'<script[^>]+\b(defer|async|type="module")', html), 'contract: plain script tags'
def test_source_page_tags_each_module_literally_once_in_order():
"""Literal tags give Explore Code's build the pilot.html -> module edges (SPLICE-73 M1)."""
inj = _inject()
html = PILOT_HTML.read_text()
for p in MODULES:
pat = rf'<script src="{p.name}"></script>' if p.suffix == '.js' else rf'<link rel="stylesheet" href="{p.name}">'
assert html.count(pat) == 1, f'{p.name} must be tagged exactly once in pilot.html'
for ext in ('css', 'js'):
names = re.findall(rf'(?:href|src)="pilot-([a-z0-9]+)\.{ext}"', html)
rank = {k: i for i, k in enumerate(inj.PILOT_MODULE_ORDER)}
assert names == sorted(names, key=lambda k: (rank.get(k, 99), k)), names
def test_inject_tags_every_shipped_module_in_order_and_is_idempotent():
inj = _inject()
mods = inj.pilot_modules(HERE)
names = [n for n, e in mods if e == 'js']
rank = {n: i for i, n in enumerate(inj.PILOT_MODULE_ORDER)}
assert names == sorted(names, key=lambda n: (rank.get(n, 99), n))
assert {p.stem[6:] for p in MOD_JS} == set(names)
page = inj.pilot_module_html(PILOT_HTML.read_text(), HERE)
for n in names:
assert re.search(rf'<script src="pilot-{n}\.js\?v=[0-9a-f]{{10}}"></script>', page), n
pos = [page.index(f'src="pilot-{n}.js') for n in names]
assert pos == sorted(pos) and all(p > page.index('src="pilot.js') for p in pos)
for p in MOD_CSS:
assert f'href="{p.name}?v=' in page
assert 'src="pilot.js?v=' in page and 'href="pilot.css?v=' in page
def test_inject_with_no_modules_and_absent_files(tmp_path):
inj = _inject()
(tmp_path / 'pilot.html').write_text(PILOT_HTML.read_text())
(tmp_path / 'pilot.js').write_text('//p')
page = inj.pilot_module_html((tmp_path / 'pilot.html').read_text(), tmp_path)
assert 'pilot-' not in re.sub(r'<!--pilot-module-(css|js)-->', '', page).replace('places.json', '')
(tmp_path / 'pilot-zeta.js').write_text('//z'); (tmp_path / 'pilot-goto.js').write_text('//g'); (tmp_path / 'pilot-goto.css').write_text('')
assert inj.pilot_modules(tmp_path) == [('goto', 'css'), ('goto', 'js'), ('zeta', 'js')]
def test_sync_pilot_copies_modules(tmp_path):
inj = _inject()
site = tmp_path / 'site'; site.mkdir()
vers = inj.copy_assets(site)
inj.sync_pilot(site, vers)
for p in MODULES:
assert (site / 'pilot' / p.name).read_bytes() == p.read_bytes()
first = (site / 'pilot' / 'index.html').read_text()
inj.sync_pilot(site, vers)
assert (site / 'pilot' / 'index.html').read_text() == first
# ---------------------------------------------------------------- module contract
@pytest.mark.parametrize('path', ALL_JS, ids=lambda p: p.name)
def test_js_parses(path):
if not shutil.which('node'):
pytest.skip('node not installed')
r = subprocess.run(['node', '--check', str(path)], capture_output=True, text=True)
assert r.returncode == 0, r.stderr
@pytest.mark.parametrize('path', MOD_JS, ids=lambda p: p.name)
def test_module_shell_follows_contract(path):
name = path.stem[len('pilot-'):]
js = _strip_comments(path.read_text())
head = js.lstrip()[:400]
assert re.match(r"\(function\s*\(\)\s*\{", head) or head.startswith('(() =>'), 'module must be an IIFE'
reg = re.search(rf"""\.module\(\s*['"]{name}['"]""", js)
assert reg, f"registers PILOT.module('{name}', ...)"
names = set(re.findall(r'(\w+)\s*=\s*(?:\w+\.)?PILOT\b', js)) | {'window.PILOT', r'\w+\.PILOT'}
alt = '|'.join(n if '\\' in n else re.escape(n) for n in names)
guard = re.search(rf'if\s*\((?:[^()]*\|\|)?\s*!\s*(?:{alt})\s*\)\s*return', js)
assert guard and guard.start() < reg.start(), 'returns early when window.PILOT is missing, before registering'
assert not re.search(r'^\s*(var|let|const|function)\s', js.split('\n', 1)[0]), 'no top-level globals'
assert 'document.write' not in js and 'eval(' not in js
assert not re.search(r'<script[^>]+src=|import\s*\(|\bimport\s+[\w{]', js), 'no libraries, CDN or ES modules'
@pytest.mark.parametrize('path', MOD_CSS, ids=lambda p: p.name)
def test_module_css_is_prefixed(path):
name = path.stem[len('pilot-'):]
css = re.sub(r'/\*.*?\*/', '', path.read_text(), flags=re.S)
core = set(re.findall(r'\bid="([\w-]+)"', PILOT_HTML.read_text())) | set(re.findall(r'\bclass="([\w -]+)"', PILOT_HTML.read_text()))
core = {c for v in core for c in v.split()}
for sel in re.findall(r'([^{}@;]+)\{', css):
for tok in re.findall(r'[.#]([a-zA-Z][\w-]*)', re.sub(r'url\([^)]*\)|\d+\.\d+', '', sel)):
assert tok.startswith(f'p-{name}-') or tok.startswith('p-') or tok in core, f'{path.name}: unprefixed {tok}'
# ---------------------------------------------------------------- rules: hosts, attribution, photon, words, motion
def test_external_hosts_are_allow_listed():
seen = {}
for p in ALL_JS + [PILOT_HTML]:
for h in re.findall(r'https://([a-z0-9.-]+\.[a-z]{2,})', p.read_text()):
h = re.sub(r'^\{?[a-z]\}?\.', '', h) if h.startswith(('a.', 'b.', 'c.', 'd.')) else h
seen.setdefault(h, set()).add(p.name)
bad = {h: sorted(f) for h, f in seen.items() if h not in ALLOWED_HOSTS and not h.endswith('.basemaps.cartocdn.com')}
assert not bad, f'review and allow-list these hosts: {bad}'
def test_imagery_and_data_hosts_carry_attribution():
blob = '\n'.join(p.read_text() for p in ALL_JS)
if 'server.arcgisonline.com' in blob:
assert 'Esri' in blob
if 'tile.openstreetmap.org' in blob or 'nominatim.openstreetmap.org' in blob:
assert 'OpenStreetMap' in blob
if 'basemaps.cartocdn.com' in blob:
assert 'CARTO' in blob
if 'api.postcodes.io' in blob:
assert re.search(r'postcodes\.io|Ordnance Survey|ONS', blob.replace('https://api.postcodes.io', ''))
for p in MOD_JS:
js = p.read_text()
if 'addLayer(' in js and re.search(r'data\.GA\b|ventusltd\.github\.io/gridatlas', js):
assert re.search(r'credit\s*:', js), f'{p.name}: data layers must set credit (as GridAtlas gives it)'
def test_photon_rule_file_sizes():
for p in HERE.iterdir():
if p.name.startswith('pilot') and p.is_file():
if p.name == 'pilot-places.json': # code places index (pilot.py), pre-existing; capped separately
assert p.stat().st_size <= 600_000; continue
assert p.stat().st_size <= MAX_FILE_BYTES, f'{p.name} is {p.stat().st_size} bytes; stream big data from GridAtlas'
total = sum(p.stat().st_size for p in HERE.iterdir() if p.name.startswith('pilot') and p.suffix in ('.js', '.css', '.html'))
assert total <= 1_200_000, f'first-load code budget exceeded: {total}'
def test_no_religious_terms():
for p in ALL_JS + MOD_CSS + [PILOT_HTML, HERE / 'pilot.css']:
m = RELIGIOUS.search(p.read_text())
assert not m, f'{p.name}: {m.group(0)!r}'
def test_modules_escape_fetched_text():
for p in MOD_JS:
js = p.read_text()
if ('fetchJSON(' in js or 'fetchText(' in js or 'fetch(' in js) and ('innerHTML' in js or 'html:' in js or '.hud(' in js or '.panel(' in js):
assert re.search(r'\besc\(|\.esc\b|textContent', js), f'{p.name}: fetched text shown as HTML must go through PILOT.esc'
def test_modules_respect_offline_flag():
for p in MOD_JS:
js = p.read_text()
if re.search(r'fetchJSON\(|fetchText\(|\bfetch\(', js):
assert 'offline' in js, f'{p.name}: must honour PILOT.offline (?offline=1)'
# ---------------------------------------------------------------- places cache clipping (review round 2, item 3)
def _pilot_py():
spec = importlib.util.spec_from_file_location('pilot_places', HERE / 'pilot.py')
mod = importlib.util.module_from_spec(spec); spec.loader.exec_module(mod)
return mod
def test_clip_runs_cuts_each_segment_at_the_radius():
m = _pilot_py(); c = (52.0, 0.0)
km = lambda q: m.km(c, (q[1], q[0]))
# a straight line through the circle with no vertex inside is kept, ending on the circle at both sides
(run,) = m.clip_runs([[-0.5, 52.0], [0.5, 52.0]], c, 6.0)
assert len(run) == 2 and all(abs(km(q) - 6.0) < 0.05 for q in run)
# leaving and re-entering gives two runs, never a chord across the gap
runs = m.clip_runs([[0, 52], [0.01, 52], [0.5, 52], [0.02, 52.001], [0.03, 52.001]], c, 6.0)
assert len(runs) == 2 and runs[0][:2] == [[0, 52], [0.01, 52]] and runs[1][-2:] == [[0.02, 52.001], [0.03, 52.001]]
# fully inside: unchanged; fully outside: nothing
inside = [[0, 52], [0.01, 52.01], [0.02, 52]]
assert m.clip_runs(inside, c, 6.0) == [inside]
assert m.clip_runs([[1, 53], [1.1, 53]], c, 6.0) == []
def test_places_cache_declares_exception():
import json as _j
d = _j.loads((HERE / 'pilot-places.json').read_text())
ce = d.get('cache_exception') or {}
assert 'derived cache' in ce.get('kind', '') and ce.get('source_release', '').startswith('atlas/releases/')
def test_licence_manifest_rows_and_notices():
md = (HERE / 'LICENSE-MANIFEST.md').read_text()
rows = [r.split('|')[1:-1] for r in md.splitlines() if r.startswith('| Ventusltd/')]
assert len(rows) >= 25
for repo, commit, path, blob, dst, grant in [[c.strip() for c in r] for r in rows]:
assert re.fullmatch(r'[0-9a-f]{40}', commit) and re.fullmatch(r'[0-9a-f]{40}', blob), (repo, path)
f = dst.split(' ')[0].rstrip(';')
assert (HERE / f).exists(), f
if grant.startswith('MIT'):
assert 'Permission is hereby granted' in (HERE / f).read_text(), f'{f}: MIT notice missing'
if 'CERN' in grant:
assert 'Ventus Ltd additionally licenses this material under Apache-2.0' in (HERE / f).read_text(), f