In this section
- Test Pilot Dark test · cosmic / tools/explore/theme/test_pilot_dark.py lines 1–290
- Test Pilot Darkfx test · cosmic / tools/explore/theme/test_pilot_darkfx.py lines 1–355
Test Pilot Dark
A test in the theme folder of Cosmic that checks Inject, using SHA-256.
testcosmic / tools/explore/theme/test_pilot_dark.py · lines 1–290 of 290 · Not reached from any entry point (candidate for review) · pattern test_js_parses (shared by 2 files)
- What it does
- It tests its inputs. Defines 22 functions or classes, including js, test_module_shell, test_no_animation_in_module, test_css_prefixed_and_touch_targets, test_dock_pill_style_matches_gridatlas. Uses libraries __future__, functools, hashlib, http.server, importlib.util. Side effects: changes the web page (DOM); reads or writes files; starts processes; uses storage (browser storage, DuckDB or Parquet).
- Why it exists in the grid workflow
- Domain stage upstream_foresight (voltage levels 132kV (all 132kV or above)): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: 132kV.
- Inputs & outputs
- In: GeoJSON file grid_400kv.geojson; GeoJSON file grid_275kv.geojson; GeoJSON file grid_132kv.geojson; GeoJSON file grid_66kv.geojson; GeoJSON file grid_substations.geojson. Out: JSON file play-index.json; browser storage (setItem). Voltage levels named: 132kV.
- What it achieves
- It is built from the served step (`served`), the quiet class (`Quiet`) and the log message helper (`log_message`). Tests for the DARK GRID Pilot module (`theme/pilot-dark.js` + `pilot-dark.css`; DARK GRID 1 / UMBRA-63). Its code works with 132 kV.
- 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, os, re
- Used by
- none found
- Produces
- js, test_module_shell, test_no_animation_in_module, test_css_prefixed_and_touch_targets, test_dock_pill_style_matches_gridatlas, test_band_colours_pinned_to_gridatlas, test_vendored_wireframe_is_verbatim, test_vendored_grid_runs_in_node, test_js_parses, served, browser, test_toggle_by_button_hash_readout_and_shots
- Defines here
- js, test_module_shell, test_no_animation_in_module, test_css_prefixed_and_touch_targets, test_dock_pill_style_matches_gridatlas, test_band_colours_pinned_to_gridatlas, test_vendored_wireframe_is_verbatim, test_vendored_grid_runs_in_node, test_js_parses, _chromium, served, Quiet, log_message, browser, _open, _dbg, _wait_lines, _overflow_and_small, test_toggle_by_button_hash_readout_and_shots, test_hash_starts_dark_and_key_toggles, test_fast_mode_widens_focus_and_events, test_reduced_motion_and_frame_budget
- 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_dark.py:1-290 · blob bbdf18d4a8d87d2a57288df4f187c6d14f8115b7 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, process, storage · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
"""Tests for the DARK GRID Pilot module (theme/pilot-dark.js + pilot-dark.css; DARK GRID 1 / UMBRA-63).
Static: contract shell, CSS prefix, GridAtlas band colours and dock-pill style pinned, the vendored site-world
wireframe grid() byte-identical to its source when that checkout is present, no animation in the module.
Node: the vendored grid() runs and drapes on a height function.
Browser (Playwright, skipped without Chromium): builds pilot/ as inject.py publishes it into a temp site, serves
GridAtlas grid GeoJSON from a local checkout through the grid module's ?ga= override (localhost only; every other
host is blocked), toggles DARK by button, hash and key, checks the readout, radius, wire ground, frame budget,
reduced motion, no sideways scroll at 390 px and 44 px tap targets. Screenshots: $DARK_SHOTS (default /tmp/vk/dark).
Run: python3 -m pytest -q tools/explore/theme/test_pilot_dark.py
"""
from __future__ import annotations
import functools, hashlib, http.server, importlib.util, json, os, re, shutil, socketserver, subprocess, tempfile, threading
from pathlib import Path
import pytest
HERE = Path(__file__).resolve().parent
JS = HERE / 'pilot-dark.js'
CSS = HERE / 'pilot-dark.css'
SHOTS = Path(os.environ.get('DARK_SHOTS', '/tmp/vk/dark'))
GA = Path(os.environ.get('GRIDATLAS_DIR', '/home/claude/gridatlas'))
GA_REL = GA / 'atlas/releases/202608300453-atlas-v9'
SITE_WORLD = Path(os.environ.get('GEOS_DIR', '/home/claude/src/graphics-engines-open-source')) / \
'web/versions/202609262227-site-world/world/layers/ground-grid.mjs'
ORIGIN = (51.5072, -0.1276) # central London: dense 400/275/132 kV and many substations
def js():
return JS.read_text()
# ---------------------------------------------------------------- static
def test_module_shell():
s = re.sub(r'/\*.*?\*/', '', js(), flags=re.S).lstrip()
assert s.startswith('(function () {')
assert s.index('if (!window.PILOT) return;') < s.index("P.module('dark'")
assert 'document.write' not in s and 'eval(' not in s and not re.search(r'\bimport\s+[\w{]', s)
assert not re.search(r'window\.\w+\s*=', s), 'no globals'
def test_no_animation_in_module():
s = js()
assert 'requestAnimationFrame' not in s and 'setInterval' not in s
assert not re.search(r'Math\.sin\([^)]*now', s), 'nothing driven by time'
def test_css_prefixed_and_touch_targets():
css = re.sub(r'/\*.*?\*/', '', CSS.read_text(), flags=re.S)
for sel in re.findall(r'([^{}@;]+)\{', css):
for tok in re.findall(r'[.#]([a-zA-Z][\w-]*)', sel):
assert tok.startswith('p-dark-'), tok
assert 'min-height: 44px' in css and 'min-width: 44px' in css
def test_dock_pill_style_matches_gridatlas():
css = CSS.read_text()
for frag in ('font: 600 11px/1 system-ui', 'background: #081820ed', 'color: #e4f7f7', 'border: 1px solid #367078',
'border-radius: 6px', 'height: 44px'):
assert frag in css, frag
assert ' •' in js(), 'active dot as GridAtlas "SATNAV •"'
dock = GA / 'atlas/modules/g204-compact-dock.js'
if dock.is_file():
d = dock.read_text()
for frag in ('background:#081820ed', 'color:#e4f7f7', 'border:1px solid #367078', 'border-radius:6px',
'font:600 11px/1 system-ui,sans-serif', "SATNAV •"):
assert frag in d, frag
def test_band_colours_pinned_to_gridatlas():
s = js()
want = {'400': ('#0054ff', '2.5'), '275': ('#ff0000', '2.0'), '220': ('#ff9900', '1.8'), '132': ('#00cc00', '1.5'), '66': ('#b200ff', '1.2')}
for k, (c, w) in want.items():
assert re.search(rf"'{k}': \{{ col: '{c}', w: {w} \}}", s), k
idx = GA_REL / 'index.html'
if idx.is_file():
h = idx.read_text()
for k, (c, w) in want.items():
assert re.search(rf'id: "{k}",\s+label: "{k}kV",\s+color: "{c}", type: "line", width: {w}', h), k
def test_vendored_wireframe_is_verbatim():
s = js()
block = s.split('// >>> site-world ground-grid begin\n', 1)[1].split(' // <<< site-world ground-grid end', 1)[0]
if not SITE_WORLD.is_file():
pytest.skip('graphics-engines-open-source checkout not present')
assert hashlib.sha256(SITE_WORLD.read_bytes()).hexdigest() == 'eff6bebb995cd463b493bef05e458ab70b34ae511c4b398b21e89fde51201b22'
src = SITE_WORLD.read_text().split('\n')
want = '\n'.join([src[19][len('export '):]] + [src[57][len('export '):]] + src[58:94] + [src[143]]) + '\n'
assert block == want
def test_vendored_grid_runs_in_node():
if not shutil.which('node'):
pytest.skip('node not installed')
s = js()
block = s.split('// >>> site-world ground-grid begin\n', 1)[1].split(' // <<< site-world ground-grid end', 1)[0]
prog = block + r'''
const p = grid(0, 0, { spacing: 100, radius: 500 }, (x, y) => x * 0.01 + 5, { origin: [0, 0, 0] });
const n = 5, segs = (2 * n + 1) * (2 * n) * 2;
if (p.length !== segs * 6) throw Error('count ' + p.length);
for (let i = 0; i < p.length; i += 3) if (Math.abs(p[i + 2] - (p[i] * 0.01 + 5)) > 1e-4) throw Error('drape');
console.log('ok', segs);
'''
r = subprocess.run(['node', '-e', prog], capture_output=True, text=True)
assert r.returncode == 0 and r.stdout.startswith('ok'), r.stderr
def test_js_parses():
if not shutil.which('node'):
pytest.skip('node not installed')
r = subprocess.run(['node', '--check', str(JS)], capture_output=True, text=True)
assert r.returncode == 0, r.stderr
# ---------------------------------------------------------------- browser
def _chromium():
try:
from playwright.sync_api import sync_playwright # noqa: F401
except Exception:
return None
for c in sorted(Path('/opt/pw-browsers').glob('chromium-*/chrome-linux64/chrome')):
return str(c)
return ''
CH = _chromium()
browser_only = pytest.mark.skipif(CH is None, reason='Playwright unavailable')
@pytest.fixture(scope='module')
def served():
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-dark-'))
vers = inj.copy_assets(tmp)
inj.sync_pilot(tmp, vers)
(tmp / 'index.html').write_text('<!doctype html><title>Explore Code</title><p>hub</p>')
(tmp / 'favicon.ico').write_bytes(b'')
(tmp / 'theme' / 'play-index.json').write_text('{}')
ga = tmp / 'ga'
have_ga = (GA_REL / 'data' / 'grid_400kv.geojson').is_file()
if have_ga: # real GridAtlas files served locally, never copied into cosmic
ga.mkdir()
for f in ('grid_400kv.geojson', 'grid_275kv.geojson', 'grid_132kv.geojson', 'grid_66kv.geojson', 'grid_substations.geojson'):
if (GA_REL / 'data' / f).is_file():
shutil.copyfile(GA_REL / 'data' / f, ga / f)
class Quiet(http.server.SimpleHTTPRequestHandler):
def log_message(self, *a, **k):
pass
handler = functools.partial(Quiet, directory=str(tmp))
srv = socketserver.ThreadingTCPServer(('127.0.0.1', 0), handler)
srv.daemon_threads = True
threading.Thread(target=srv.serve_forever, daemon=True).start()
base = f'http://127.0.0.1:{srv.server_address[1]}'
yield {'url': base + '/pilot/index.html', 'ga': base + '/ga/' if have_ga else None}
srv.shutdown(); shutil.rmtree(tmp, ignore_errors=True)
@pytest.fixture(scope='module')
def browser():
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
b = p.chromium.launch(**({'executable_path': CH} if CH else {}))
yield b
b.close()
def _open(browser, served, w, h, hash_='', reduced=False, grid_on=True):
ctx = browser.new_context(viewport={'width': w, 'height': h}, has_touch=w < 900, is_mobile=w < 900,
reduced_motion='reduce' if reduced else 'no-preference')
ctx.route(re.compile(r'^https?://(?!127\.0\.0\.1).*'), lambda r: r.abort())
if grid_on:
ctx.add_init_script("try{localStorage.setItem('p-grid-on',JSON.stringify({'400':true,'275':true,'132':true,'66':true,subs:true}))}catch(e){}")
pg = ctx.new_page(); errs = []
pg.on('console', lambda m: errs.append(m.text) if m.type == 'error' and 'net::ERR' not in m.text and 'Failed to load resource' not in m.text else None)
pg.on('pageerror', lambda e: errs.append(str(e)))
q = ('?ga=' + served['ga']) if served['ga'] else '?offline=1'
pg.goto(served['url'] + q + f'#at={ORIGIN[0]},{ORIGIN[1]},600' + hash_, wait_until='load')
pg.wait_for_function('window.PILOT && PILOT.modules().some(m => m.name === "dark")', timeout=10000)
pg.wait_for_timeout(1500)
return ctx, pg, errs
def _dbg(pg):
return pg.evaluate("new Promise(r => PILOT.emit('dark:debug', {reply: r}))")
def _wait_lines(pg, ms=20000):
if not pg.evaluate("location.search.indexOf('ga=') >= 0"):
return
pg.wait_for_function("new Promise(r => PILOT.emit('dark:debug', {reply: d => r(d.lines.length >= 2)}))", timeout=ms)
def _overflow_and_small(pg):
return pg.evaluate('''() => {
const small = [...document.querySelectorAll('.p-dark-row button')].filter(b => { const r = b.getBoundingClientRect(); return r.width && (r.width < 44 || r.height < 44); }).map(b => b.textContent);
return { sx: document.documentElement.scrollWidth > innerWidth, small };
}''')
@browser_only
@pytest.mark.parametrize('w,h', [(390, 844), (1366, 768)])
def test_toggle_by_button_hash_readout_and_shots(served, browser, w, h):
SHOTS.mkdir(parents=True, exist_ok=True)
ctx, pg, errs = _open(browser, served, w, h)
pg.screenshot(path=str(SHOTS / f'dark-off-{w}x{h}.png'))
btn = pg.locator('.p-dark-btn')
assert btn.count() == 1 and btn.inner_text().strip() == 'DARK'
btn.click()
assert btn.get_attribute('aria-pressed') == 'true' and '•' in btn.inner_text()
assert 'dark=2' in pg.evaluate('location.hash')
assert pg.evaluate("document.documentElement.classList.contains('p-dark-on')")
_wait_lines(pg)
pg.wait_for_timeout(1800)
d = _dbg(pg)
assert d['on'] and d['km'] == 2 and d['R'] >= 2000
st = pg.locator('.p-dark-status').inner_text()
assert 'DARK GRID' in st and 'Focus 2 km' in st and 'Nearest grid:' in st
if served['ga']:
assert d['near'] and d['near']['d'] < 5000, d['near'] # central London has grid assets within 5 km
assert d['halos']['subs'] > 0
o = _overflow_and_small(pg)
assert not o['sx'] and not o['small'], o
pg.screenshot(path=str(SHOTS / f'dark-on-{w}x{h}.png'))
# overhead: the focus vignette reads best looking down
pg.evaluate(f"PILOT.flyTo({ORIGIN[0]}, {ORIGIN[1]}, {{alt: 3200, dist: 0, pitch: -1.2, instant: true, beacon: false}}).catch(() => 0)")
pg.wait_for_timeout(1500)
pg.screenshot(path=str(SHOTS / f'dark-overhead-{w}x{h}.png'))
pg.locator('.p-dark-chip[data-p-dark-km="5"]').click()
assert 'dark=5' in pg.evaluate('location.hash') and _dbg(pg)['km'] == 5
pg.locator('.p-dark-chip[data-p-dark="wire"]').click()
pg.wait_for_timeout(900)
assert 'darkg=wire' in pg.evaluate('location.hash') and _dbg(pg)['ground'] == 'wire'
pg.screenshot(path=str(SHOTS / f'dark-wire-5km-{w}x{h}.png'))
btn.click()
assert btn.get_attribute('aria-pressed') == 'false' and 'dark=' not in pg.evaluate('location.hash')
assert pg.locator('.p-dark-status').count() == 0 or not pg.locator('.p-dark-status').is_visible()
assert not errs, errs
ctx.close()
@browser_only
def test_hash_starts_dark_and_key_toggles(served, browser):
ctx, pg, errs = _open(browser, served, 390, 844, hash_='&dark=10&darkg=wire')
d = _dbg(pg)
assert d['on'] and d['km'] == 10 and d['ground'] == 'wire'
pg.keyboard.press('k')
assert not _dbg(pg)['on']
pg.keyboard.press('K')
assert _dbg(pg)['on']
assert not errs, errs
ctx.close()
@browser_only
def test_fast_mode_widens_focus_and_events(served, browser):
ctx, pg, errs = _open(browser, served, 390, 844, hash_='&dark=1')
pg.evaluate("() => { window.__ds = []; PILOT.on('dark:state', s => __ds.push(s)); window.__df = 0; PILOT.on('dark:focus', f => { window.__df++; window.__lf = f; }); }")
pg.evaluate('PILOT.setFast(3); PILOT.setSpeed(2500)')
pg.wait_for_timeout(2500)
d = _dbg(pg)
assert d['R'] > 5000, d['R'] # 1 km chosen, widened with speed/height
assert 'auto' in pg.locator('.p-dark-status').inner_text()
ev = pg.evaluate('({n: __ds.length, last: __ds[__ds.length-1], df: __df, lf: window.__lf && Object.keys(window.__lf)})')
assert ev['n'] >= 1 and ev['last']['on'] and ev['last']['bands']['400']['col'] == '#0054ff' and ev['last']['glowByDark']
assert ev['df'] >= 1 and set(ev['lf']) >= {'lat', 'lon', 'radiusM', 'lines', 'subs'}
q = pg.evaluate("new Promise(r => PILOT.emit('dark:query', {reply: (f, s) => r([!!f, s.on])}))")
assert q == [True, True]
pg.evaluate('PILOT.setFast(0)')
assert not errs, errs
ctx.close()
@browser_only
def test_reduced_motion_and_frame_budget(served, browser):
ctx, pg, errs = _open(browser, served, 390, 844, hash_='&dark=2', reduced=True)
_wait_lines(pg)
pg.wait_for_timeout(2500)
d = _dbg(pg)
ms = d['ms']
# headless software rendering is slower than a phone GPU; generous ceiling per DARK layer
assert ms['grid'] < 12 and ms['mask'] < 6 and ms['ground'] < 8, ms
st = pg.evaluate("new Promise(r => PILOT.emit('dark:query', {reply: (f, s) => r(s)}))")
assert st['reduced'] is True
a = pg.screenshot(); pg.wait_for_timeout(400); b = pg.screenshot()
pg.screenshot(path=str(SHOTS / 'dark-reduced-390x844.png'))
assert not errs, errs
ctx.close()Test Pilot Darkfx
A test in the theme folder of Cosmic. It is built from the served step (`served`), the quiet class (`Quiet`) and the log message helper (`log_message`).
testcosmic / tools/explore/theme/test_pilot_darkfx.py · lines 1–355 of 355 · Not reached from any entry point (candidate for review) · pattern _measure (shared by 2 files)
- What it does
- It tests its inputs. Defines 24 functions or classes, including _src, _code, test_module_shell_and_registration, test_layer_ids_orders_and_css_prefix, test_honesty_captions_present. Uses libraries __future__, functools, http.server, importlib.util, json. Side effects: changes the web page (DOM); reads or writes files; makes network requests.
- Inputs & outputs
- Out: JSON file play-index.json; JSON file fx-budget-390x844-cpu4x.json.
- What it achieves
- Tests for the dark Pilot effects layer, `theme/pilot-darkfx.js` + `pilot-darkfx.css` (DARK GRID 2, NOCTILUCENT-27).
- Why it matters
- No other file in the estate was found to import it.
- Application
- cosmic · tools/explore/theme · test
- Uses
- __future__, functools, http.server, importlib.util, json, math, os, re
- Used by
- none found
- Produces
- test_module_shell_and_registration, test_layer_ids_orders_and_css_prefix, test_honesty_captions_present, test_animation_is_guarded_by_reduced_motion, test_bolts_stop_above_ground, served, browser, test_darkfx_draws_within_budget, test_budget_phone_cpu_throttled, test_substation_tap_pulse_is_adjacency_only, test_lightning_flashes_stop_above_ground_with_captions, test_reduced_motion_nothing_animates
- Defines here
- _src, _code, test_module_shell_and_registration, test_layer_ids_orders_and_css_prefix, test_honesty_captions_present, test_animation_is_guarded_by_reduced_motion, test_bolts_stop_above_ground, _chromium, _fixture, served, Quiet, log_message, browser, _open, _go_dark, _frame_costs, _measure, _p95, test_darkfx_draws_within_budget, test_budget_phone_cpu_throttled, test_substation_tap_pulse_is_adjacency_only, test_lightning_flashes_stop_above_ground_with_captions, test_reduced_motion_nothing_animates, test_effects_toggle_and_glow_handover
- 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_darkfx.py:1-355 · blob 22f715e11dc3480011639b6f37fe55a92fe8ae6b · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, network · domain stage: unknown · users: none · canonical: unreached_review
"""Tests for the dark Pilot effects layer, theme/pilot-darkfx.js + pilot-darkfx.css (DARK GRID 2, NOCTILUCENT-27).
Static checks (contract shell, honesty captions, reduced-motion guards, no data words that imply measured flow,
ratings or fault paths) and Playwright checks at 390x844 and 1366x768, offline (?offline=1, no external hosts).
The browser tests drive the module through the agreed event API exactly as pilot-dark.js (UMBRA-63) does:
'dark:state' {on,...} and 'dark:focus' {lines, subs}. The focus set is a SYNTHETIC TEST FIXTURE (a made-up radial
network round Cambridge), not real grid data. Frame cost is measured by the module itself (performance.now()
round every fx draw) and must stay under 4 ms per frame at 390x844.
Screenshots: $DARK_SHOTS (default /tmp/vk/dark).
Run: python3 -m pytest -q tools/explore/theme/test_pilot_darkfx.py
"""
from __future__ import annotations
import functools, http.server, importlib.util, json, math, os, re, shutil, socketserver, statistics, tempfile, threading
from pathlib import Path
import pytest
HERE = Path(__file__).resolve().parent
JS = HERE / 'pilot-darkfx.js'
CSS = HERE / 'pilot-darkfx.css'
SHOTS = Path(os.environ.get('DARK_SHOTS', '/tmp/vk/dark'))
ORIGIN = (52.2053, 0.1218)
BUDGET_MS = 4.0
def _src():
return JS.read_text(encoding='utf-8')
def _code():
return re.sub(r'/\*.*?\*/', '', _src(), flags=re.S)
# ---------------------------------------------------------------- static
def test_module_shell_and_registration():
js = _code().lstrip()
assert js.startswith('(function () {')
i_guard, i_reg = js.index('if (!window.PILOT) return;'), js.index("P.module('darkfx'")
assert i_guard < i_reg
assert 'eval(' not in js and 'document.write' not in js and not re.search(r'\bimport\s*\(|<script', js)
assert not re.search(r'\bfetch\(|fetchJSON|fetchText|XMLHttpRequest', js), 'fx draws only what pilot-dark.js / pilot-lightning give it'
assert not re.search(r'shadowBlur|setLineDash|filter\s*=', js), 'no shadowBlur / dashing / filters (slow on phones): pre-rendered sprites and a quarter-res bloom'
def test_layer_ids_orders_and_css_prefix():
js = _code()
for lid, order in (('darkfx-sky', 2), ('darkfx', 34), ('darkfx-nodes', 54), ('darkfx-flash', 76)):
assert re.search(rf"id: '{lid}'[^}}]*?order: {order}\b", js, re.S), lid
assert not re.search(r'\bpick\s*:', js), 'fx layers never take taps'
css = re.sub(r'/\*.*?\*/', '', CSS.read_text(), flags=re.S)
for sel in re.findall(r'([^{}@;]+)\{', css):
for tok in re.findall(r'[.#]([a-zA-Z][\w-]*)', sel):
assert tok.startswith('p-darkfx-'), tok
def test_honesty_captions_present():
s = _src()
for t in ('decorative, not measured power flow', 'not a power direction', 'network adjacency only',
'not a power flow, rating or fault path', 'optical flash, not a ground strike', 'risk screening'):
assert t in s, t
# every mention of power flow / fault path / rating in UI text is a negation
for m in re.finditer(r'power flow|fault path|rating', s):
before = s[max(0, m.start() - 60):m.start()].lower()
assert re.search(r'\bnot\b|\bnever\b|\bno\b', before), s[max(0, m.start() - 60):m.end()]
assert not re.search(r'\bMW\b|\bamps?\b|\bloading\b|\bcapacity\b', _code(), re.I), 'no measured-quantity words'
def test_animation_is_guarded_by_reduced_motion():
js = _code()
assert 'var REDUCED = !!P.reduced' in js
assert 'if (!REDUCED && q >= 1) {' in js, 'flow dashes only without reduced motion'
assert 'if (REDUCED || !st.cand.length)' in js, 'no lightning flicker under reduced motion'
assert 'var f = REDUCED ? 1 :' in js, 'pulse is static under reduced motion'
def test_bolts_stop_above_ground():
m = re.search(r'BOLT_TOP = (\d+), BOLT_STOP = (\d+)', _code())
assert m and int(m.group(2)) >= 200 and int(m.group(1)) > int(m.group(2))
# ---------------------------------------------------------------- browser
def _chromium():
try:
from playwright.sync_api import sync_playwright # noqa: F401
except Exception:
return None
for c in sorted(Path('/opt/pw-browsers').glob('chromium-*/chrome-linux64/chrome')):
return str(c)
return ''
CH = _chromium()
browser_only = pytest.mark.skipif(CH is None, reason='Playwright unavailable')
def _fixture():
"""SYNTHETIC radial network round ORIGIN (test only, not real data): 1 hub, 12 spokes of 3 sections, a ring."""
la0, lo0 = ORIGIN
kx = 1 / (111320 * math.cos(math.radians(la0))); ky = 1 / 111320
lines, subs = [], [{'id': 'hub', 'name': 'Fixture hub', 'kv': 400, 'lat': la0, 'lon': lo0}]
kvs = [400, 275, 132, 132, 66, 33]
for s in range(12):
a = s / 12 * 2 * math.pi; kv = kvs[s % len(kvs)]
for sec in range(3):
r0, r1 = 150 + sec * 900, 150 + (sec + 1) * 900
ll = []
for k in range(41):
r = r0 + (r1 - r0) * k / 40; w = 40 * math.sin(k / 6 + s)
x, y = math.sin(a) * r + math.cos(a) * w, math.cos(a) * r - math.sin(a) * w
ll += [la0 + y * ky, lo0 + x * kx]
lines.append({'id': f's{s}-{sec}', 'kv': kv, 'll': ll})
subs.append({'id': f'n{s}-{sec}', 'name': f'Fixture {s}-{sec}', 'kv': kv, 'lat': ll[-2], 'lon': ll[-1]})
ring = []
for k in range(241):
a = k / 240 * 2 * math.pi; r = 1950
ring += [la0 + math.cos(a) * r * ky, lo0 + math.sin(a) * r * kx]
lines.append({'id': 'ring', 'kv': 132, 'll': ring})
return {'lat': la0, 'lon': lo0, 'radiusM': 3000, 'lines': lines, 'subs': subs}
FIX = _fixture()
@pytest.fixture(scope='module')
def served():
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-darkfx-'))
vers = inj.copy_assets(tmp)
inj.sync_pilot(tmp, vers)
(tmp / 'index.html').write_text('<!doctype html><title>Explore Code</title><p>hub</p>')
(tmp / 'favicon.ico').write_bytes(b'')
(tmp / 'theme' / 'play-index.json').write_text('{}')
class Quiet(http.server.SimpleHTTPRequestHandler):
def log_message(self, *a, **k):
pass
handler = functools.partial(Quiet, directory=str(tmp))
srv = socketserver.ThreadingTCPServer(('127.0.0.1', 0), handler)
srv.daemon_threads = True
threading.Thread(target=srv.serve_forever, daemon=True).start()
yield f'http://127.0.0.1:{srv.server_address[1]}/pilot/index.html'
srv.shutdown(); shutil.rmtree(tmp, ignore_errors=True)
@pytest.fixture(scope='module')
def browser():
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
b = p.chromium.launch(**({'executable_path': CH} if CH else {}))
yield b
b.close()
def _open(browser, url, w, h, reduced=False):
ctx = browser.new_context(viewport={'width': w, 'height': h}, has_touch=w < 900, is_mobile=w < 900,
reduced_motion='reduce' if reduced else 'no-preference')
pg = ctx.new_page(); errs, ext = [], []
pg.on('console', lambda m: errs.append(m.text) if m.type == 'error' else None)
pg.on('pageerror', lambda e: errs.append(str(e)))
pg.on('request', lambda r: ext.append(r.url) if not r.url.startswith(('http://127.0.0.1', 'data:', 'blob:')) else None)
pg.goto(url + '?offline=1', wait_until='load')
pg.wait_for_timeout(1000)
assert pg.evaluate("PILOT.modules().some(m => m.name === 'darkfx')"), 'darkfx not loaded'
return ctx, pg, errs, ext
def _go_dark(pg):
la, lo = ORIGIN
pg.evaluate(f'PILOT.flyTo({la}, {lo}, {{instant: true, alt: 900, dist: 2600, hdg: 20}})')
pg.wait_for_timeout(300)
pg.evaluate(f"""(() => {{ PILOT.emit('dark:state', {{on: true, lat: {la}, lon: {lo}, radiusM: 3000, glowByDark: false}});
PILOT.emit('dark:focus', {json.dumps(FIX)}); }})()""")
pg.wait_for_timeout(600)
def _frame_costs(pg, ms=2000):
pg.evaluate('PILOT.darkfx._test.state.samples.length = 0')
pg.wait_for_timeout(ms)
return pg.evaluate('PILOT.darkfx._test.state.samples.slice()')
SWAY = """PILOT.steer(() => { const t = performance.now() / 1000;
return {speed: 0, hdg: (380 + 25 * Math.sin(t)) % 360, pitch: -0.32 + 0.08 * Math.sin(t * 1.3)}; })"""
def _measure(pg, raster, runs=3):
"""Frame cost of all fx layers while the camera sways (bloom/paths rebuilt every frame).
raster=False: script time, as PILOT.debug() layer ms. raster=True: each fx layer flushes the canvas before and
after drawing (getImageData 1 px), so rasterising is included (an upper bound: it adds the readback itself).
Best of `runs` (the CI box is shared; the best run is the least disturbed one)."""
pg.evaluate(f'PILOT.darkfx._test.state.measure = {str(raster).lower()}')
best = None
for _ in range(runs):
c = _frame_costs(pg)
r = {'frames': len(c), 'p50_ms': round(statistics.median(c), 3), 'p95_ms': round(_p95(c), 3), 'max_ms': round(max(c), 3)}
if best is None or r['p95_ms'] < best['p95_ms']:
best = r
pg.evaluate('PILOT.darkfx._test.state.measure = false')
return best
def _p95(xs):
xs = sorted(xs); return xs[min(len(xs) - 1, int(len(xs) * 0.95))]
@browser_only
@pytest.mark.parametrize('w,h', [(390, 844), (1366, 768)])
def test_darkfx_draws_within_budget(served, browser, w, h):
ctx, pg, errs, ext = _open(browser, served, w, h)
st0 = pg.evaluate('PILOT.darkfx.status()')
assert st0['active'] is False, 'inactive until pilot-dark.js says dark is on'
_go_dark(pg)
s = pg.evaluate('PILOT.darkfx.status()')
assert s['active'] and s['animating'] and s['lines'] == len(FIX['lines']) and s['subs'] == len(FIX['subs']), s
lay = {d['id']: d for d in pg.evaluate('PILOT.darkfx._test.layers()')}
assert lay['darkfx']['segs'] > 100 and lay['darkfx-nodes']['n'] > 5, lay
cap = pg.evaluate("(document.querySelector('[data-p-darkfx-cap]') || {}).textContent || ''")
assert 'decorative, not measured power flow' in cap, cap
SHOTS.mkdir(parents=True, exist_ok=True)
pg.screenshot(path=str(SHOTS / f'fx-{w}x{h}.png'))
pg.evaluate(SWAY)
pg.wait_for_timeout(800)
rec = {'viewport': f'{w}x{h}', 'camera': 'swaying (paths and bloom rebuilt every frame)', 'segments': lay['darkfx']['segs'],
'vertices': lay['darkfx']['verts'], 'nodes': lay['darkfx-nodes']['n'], 'load_avg': os.getloadavg()[0], 'cpus': os.cpu_count(), 'quality': {}}
for q in (2, 1, 0): # quality locked so each level is measured on its own (adaptive stepping off)
pg.evaluate(f'(() => {{ const s = PILOT.darkfx._test.state; s.lockQ = true; s.quality = {q}; s.bloomKey = ""; }})()')
pg.wait_for_timeout(300)
rec['quality'][q] = {'script': _measure(pg, raster=False, runs=2), 'raster_inclusive': _measure(pg, raster=True, runs=1)}
pg.evaluate('PILOT.darkfx._test.state.lockQ = false')
(SHOTS / f'fx-budget-{w}x{h}.json').write_text(json.dumps(rec, indent=1))
if w == 390 and os.getloadavg()[0] / (os.cpu_count() or 1) > 3:
pytest.skip(f'box overloaded (load {os.getloadavg()[0]:.1f} on {os.cpu_count()} CPUs): timings recorded in fx-budget-{w}x{h}.json, not gated')
if w == 390:
# gate: quality 1 (start level) and 0. Quality 2 (bloom) is only entered by the adaptive step-up after ~4 s at
# > 56 fps and < 1.4 ms, i.e. on devices with headroom; its numbers are recorded, not gated.
for q in (1, 0):
r = rec['quality'][q]['script']
assert r['frames'] > 30 and r['p95_ms'] < BUDGET_MS, f'quality {q}: fx script time p95 {r["p95_ms"]} ms >= {BUDGET_MS} ms at 390x844: {rec}'
pg.evaluate('PILOT.steer(null)')
sw, iw = pg.evaluate('[document.documentElement.scrollWidth, innerWidth]')
assert sw <= iw
# off again: layers hidden, caption gone
pg.evaluate("PILOT.emit('dark:state', {on: false})")
pg.wait_for_timeout(200)
assert pg.evaluate('PILOT.darkfx.status().active') is False
assert pg.evaluate("!document.querySelector('[data-p-darkfx-cap]')")
assert not errs, errs
assert not ext, ext[:5]
ctx.close()
@browser_only
def test_budget_phone_cpu_throttled(served, browser):
"""Phone proxy: 4x CPU throttle at 390x844, camera swaying, adaptive quality on. Recorded in fx-budget-390x844-cpu4x.json."""
ctx, pg, errs, _ = _open(browser, served, 390, 844)
cdp = ctx.new_cdp_session(pg); cdp.send('Emulation.setCPUThrottlingRate', {'rate': 4})
_go_dark(pg)
pg.evaluate(SWAY)
pg.wait_for_timeout(3000) # let the adaptive quality settle
script = _measure(pg, raster=False)
rec = {'viewport': '390x844', 'cpu_throttle': 4, 'script': script, 'quality': pg.evaluate('PILOT.darkfx.status().quality'),
'load_avg': os.getloadavg()[0], 'cpus': os.cpu_count()}
(SHOTS / 'fx-budget-390x844-cpu4x.json').write_text(json.dumps(rec, indent=1))
pg.screenshot(path=str(SHOTS / 'fx-390x844-cpu4x.png'))
assert script['frames'] >= 5, rec # recorded as a phone proxy; quality adapts, the hard gate is the 390x844 test above
assert not errs, errs
ctx.close()
@browser_only
def test_substation_tap_pulse_is_adjacency_only(served, browser):
ctx, pg, errs, _ = _open(browser, served, 390, 844)
_go_dark(pg)
la, lo = ORIGIN
pg.evaluate(f"PILOT.emit('pick', {{layer: 'grid-subs', item: {{id: 'grid-sub-1', title: 'Fixture hub', lat: {la}, lon: {lo}}}}})")
pg.wait_for_timeout(900)
s = pg.evaluate('PILOT.darkfx.status()')
assert s['pulse'], s
seq = pg.evaluate('PILOT.darkfx._test.state.pulse.seq.map(x => [x.hop, x.li])')
hops = [h for h, _ in seq]
assert hops == sorted(hops) and hops[0] == 0 and max(hops) >= 2, seq
first = {li for h, li in seq if h == 0}
assert first == {i for i, L in enumerate(FIX['lines']) if L['id'].endswith('-0')}, 'hop 0 = the 12 spokes whose mapped end meets the hub'
cap = pg.evaluate("(document.querySelector('[data-p-darkfx-cap]') || {}).textContent || ''")
assert 'network adjacency only' in cap and 'not a power flow, rating or fault path' in cap, cap
pg.screenshot(path=str(SHOTS / 'fx-pulse-390x844.png'))
pg.wait_for_timeout(4500)
assert pg.evaluate('PILOT.darkfx.status().pulse') is False, 'pulse ends by itself'
assert not errs, errs
ctx.close()
@browser_only
def test_lightning_flashes_stop_above_ground_with_captions(served, browser):
ctx, pg, errs, _ = _open(browser, served, 1366, 768)
_go_dark(pg)
la, lo = ORIGIN
# SYNTHETIC flashes (test only) in the packFlashes shape pilot-lightning uses
fl = {'on': True, 'lat': [la + 0.004 * k for k in range(-3, 4)], 'lon': [lo + 0.006 * ((k * 5) % 7 - 3) for k in range(7)],
't': [0] * 7, 'id': [f'fx-test-{k}' for k in range(7)]}
pg.evaluate(f"PILOT.emit('lightning:flashes', {json.dumps(fl)})")
pg.wait_for_timeout(1500)
s = pg.evaluate('PILOT.darkfx.status()')
assert s['bolts'] == 7 and s['flashSource'] == 'event', s
cap = pg.evaluate("(document.querySelector('[data-p-darkfx-cap]') || {}).textContent || ''")
assert 'optical flash, not a ground strike' in cap and 'risk screening' in cap, cap
agl = pg.evaluate('PILOT.darkfx._test.state.cand.map(b => b.pts[b.pts.length - 1][2] - b.ground)')
assert min(agl) >= 300, f'strokes must stop above the ground: {agl}'
shot = False
for _ in range(160): # wait for a flash to be on screen, then capture it
if pg.evaluate('PILOT.darkfx._test.state.drawnBolts') > 0:
pg.screenshot(path=str(SHOTS / 'fx-flash-1366x768.png')); shot = True; break
pg.wait_for_timeout(50)
assert shot or pg.evaluate('PILOT.darkfx._test.state.bolts') > 0, 'no flash drawn in 8 s'
assert pg.evaluate('PILOT.darkfx._test.state.minBoltAgl') >= 300
pg.evaluate("PILOT.emit('lightning:flashes', {on: false})")
pg.wait_for_timeout(1300)
assert pg.evaluate('PILOT.darkfx.status().bolts') == 0
assert not errs, errs
ctx.close()
@browser_only
def test_reduced_motion_nothing_animates(served, browser):
ctx, pg, errs, _ = _open(browser, served, 390, 844, reduced=True)
_go_dark(pg)
la, lo = ORIGIN
pg.evaluate(f"PILOT.emit('lightning:flashes', {{on: true, lat: [{la}], lon: [{lo + 0.004}], t: [0], id: ['fx-test-r']}})")
pg.evaluate(f"PILOT.emit('pick', {{layer: 'grid-subs', item: {{id: 'grid-sub-1', title: 'Fixture hub', lat: {la}, lon: {lo}}}}})")
s = pg.evaluate('PILOT.darkfx.status()')
assert s['reduced'] and s['active'] and not s['animating'], s
pg.wait_for_timeout(8000)
assert pg.evaluate('PILOT.darkfx._test.state.bolts') == 0, 'no lightning flicker under reduced motion'
cap = pg.evaluate("(document.querySelector('[data-p-darkfx-cap]') || {}).textContent || ''")
assert 'nothing animates' in cap, cap
pg.screenshot(path=str(SHOTS / 'fx-reduced-390x844.png'))
assert not errs, errs
ctx.close()
@browser_only
def test_effects_toggle_and_glow_handover(served, browser):
ctx, pg, errs, _ = _open(browser, served, 390, 844)
_go_dark(pg)
pg.evaluate("PILOT.emit('darkfx:set', {on: false})")
s = pg.evaluate('PILOT.darkfx.status()')
assert s['on'] is False and s['active'] is False
assert 'Effects off' in pg.evaluate("(document.querySelector('[data-p-darkfx-cap]') || {}).textContent || ''")
pg.evaluate("PILOT.emit('darkfx:set', {on: true}); PILOT.emit('dark:state', {on: true, glowByDark: true})")
pg.wait_for_timeout(300)
assert pg.evaluate('PILOT.darkfx.status().active') and pg.evaluate('PILOT.darkfx._test.state.glowByDark')
assert not errs, errs
ctx.close()