GLOBALGRID2050 / EXPLORE CODE

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

Test Pilot Ticker and 1 more file

A test in the theme folder of Cosmic that checks GlobalGrid2050 — UK Renewables Pipeline Page using data from the GlobalGrid2050 and data-GB-electricity repositories.

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

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

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

In this section

  1. Test Pilot Ticker test · cosmic / tools/explore/theme/test_pilot_ticker.py lines 1–350
  2. Test Seethrough test · cosmic / tools/explore/theme/test_seethrough.py lines 1–236

Test Pilot Ticker

A test in the theme folder of Cosmic that checks GlobalGrid2050 — UK Renewables Pipeline Page using data from the GlobalGrid2050 and data-GB-electricity repositories.

testcosmic / tools/explore/theme/test_pilot_ticker.py · lines 1–350 of 350 · Not reached from any entry point (candidate for review) · pattern test_layout_targets_and_no_overlap (shared by 2 files)

What it does
It tests the REPD register and solar. Defines 21 functions or classes, including _chromium, iso, item, feed, served. Uses libraries __future__, functools, http.server, importlib.util, json. Side effects: changes the web page (DOM); reads or writes files; uses storage (browser storage, DuckDB or Parquet).
Why it exists in the grid workflow
Domain terms in the code: the REPD register, solar.
Inputs & outputs
In: data source: globalgrid2050 data; data source: data-gb-electricity data; JSON file pipeline_headlines.json; JSON file pipeline_headlines.snapshot.json; JSON file 2026.json; JSON file index.json; browser storage (getItem). Out: JSON file play-index.json; JSON file repd-fixture.json; browser storage (setItem).
What it achieves
It is built from the iso step (`iso`), the item step (`item`) and the feed step (`feed`). Browser tests for the optional Pilot ticker module (`theme/pilot-ticker.js`, MARQUEE-53).
Why it matters
Guards the behaviour of GlobalGrid2050 — UK Renewables Pipeline Page.
Application
cosmic · tools/explore/theme · test
Uses
GlobalGrid2050 — UK Renewables Pipeline Page (estate URL), __future__, functools, http.server, importlib.util, json, os, shutil, socketserver
Used by
none found
Produces
iso, item, feed, served, browser, test_malformed_dates_never_interrupt_rendering, test_stale_feed_is_labelled_overdue, test_failed_load_says_unknown_not_zero, test_offline_never_fetches, test_market_item_dated_and_historical, test_local_items_float_only_when_the_feed_names_them, test_tap_opens_card_with_pipeline_news_source
Defines here
_chromium, iso, item, feed, served, browser, _open, answer, router, _ticker, _status, test_malformed_dates_never_interrupt_rendering, test_stale_feed_is_labelled_overdue, test_failed_load_says_unknown_not_zero, test_offline_never_fetches, test_market_item_dated_and_historical, test_local_items_float_only_when_the_feed_names_them, test_tap_opens_card_with_pipeline_news_source, test_reduced_motion_is_static_and_pause_button, test_hide_toggle_persists_and_restores_from_panel, test_layout_targets_and_no_overlap
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_ticker.py:1-350 · blob 8c1b5454d7a4b6ac5c4a103cbfe216c6cd3b5d4d · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, storage · domain stage: unknown · users: none · canonical: unreached_review
"""Browser tests for the optional Pilot ticker module (theme/pilot-ticker.js, MARQUEE-53).

Builds pilot/ the way inject.py publishes it into a temp site and serves it on 127.0.0.1. Playwright routes the three
published feed URLs (Pipeline News live headlines, the saved snapshot and the data-gb-electricity price files) to
fixtures in this file. Every other external host is aborted, so nothing leaves the machine. The fixtures are
synthetic test data, not real headlines. Runs at 390x844 (phone, touch) and 1366x768.
Covers malformed dates, a stale feed, a failed load, the snapshot fallback, local relevance, tap to card, reduced
motion, the hide toggle, 44 px targets and no overlap with the HUD or controls. Skips without Playwright/Chromium.
Screenshots: $PILOT_SHOTS (default /tmp/vk/pilot200/shots).
Run: python3 -m pytest -q tools/explore/theme/test_pilot_ticker.py
"""
from __future__ import annotations

import functools, http.server, importlib.util, json, os, shutil, socketserver, tempfile, threading
from datetime import datetime, timedelta, timezone
from pathlib import Path

import pytest

HERE = Path(__file__).resolve().parent
SHOTS = Path(os.environ.get('PILOT_SHOTS', '/tmp/vk/pilot200/shots'))
ORIGIN = (52.2053, 0.1218)
LIVE = 'https://raw.githubusercontent.com/Ventusltd/globalgrid2050/pipeline-news-data/dist/pipeline_headlines.json'
SNAP_PART = '/uk_renewables_pipeline/202611280922/news/pipeline_headlines.snapshot.json'
PRICE_BASE = 'https://raw.githubusercontent.com/Ventusltd/data-gb-electricity/cf48c8d6fdd9ab686c4af7261149d81a0129f7fc/derived/price-daily-browser/'
PN_NEWS = 'https://globalgrid2050.com/uk_renewables_pipeline/202611280922/#headlinesHeading'
SCHEMA = 'globalgrid2050.news.pipeline-headlines.v1'


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()
pytestmark = pytest.mark.skipif(CH is None or not (HERE / 'pilot-ticker.js').is_file(), reason='Playwright or pilot-ticker.js unavailable')


def iso(dt: datetime) -> str:
    return dt.strftime('%Y-%m-%dT%H:%M:%SZ')


NOW = datetime.now(timezone.utc).replace(microsecond=0)


def item(n, date=..., **kw):
    it = {'title': f'Fixture headline {n}', 'link': f'https://example.com/{n}', 'source': 'Fixture', 'category': 'other', 'technology': None, 'possible_match': None}
    if date is not ...:
        it['date'] = date
    it.update(kw)
    return it


def feed(items, generated=None, status='ok', **kw):
    d = {'schema': SCHEMA, 'generated_at': iso(generated or NOW - timedelta(hours=2)), 'status': status,
         'counts': {'items': len(items), 'feeds_ok': 3, 'feeds_failed': 0}, 'items': items}
    d.update(kw)
    return d


MALFORMED = feed([
    item(0, iso(NOW - timedelta(hours=3))),           # valid ISO
    item(1),                                           # date omitted, no first_seen
    item(2, 'bad'),                                    # malformed string
    item(3, 0),                                        # numeric
    item(4, ['2026-11-28']),                           # array
    item(5, iso(NOW - timedelta(days=1)).replace('T', ' ')),  # not the strict form
    item(6, '2026-02-30'),                             # impossible calendar date
    item(7, None, first_seen=iso(NOW - timedelta(hours=5))),  # falls back to First collected
    item(8, iso(NOW + timedelta(days=3))),             # ahead of the clock
    item(9, {'y': 2026}),                              # object
    item(10, (NOW - timedelta(days=2)).strftime('%Y-%m-%d')),  # date only, valid
    {'title': 'Unsafe link', 'link': 'javascript:alert(1)', 'source': 'Fixture', 'date': iso(NOW)},
    {'title': 'Duplicate', 'link': 'https://example.com/0', 'source': 'Fixture', 'date': iso(NOW - timedelta(days=9))},
    {'title': '', 'link': 'https://example.com/empty', 'source': 'Fixture'},
    'not an object', None, 42,
])

PRICE_INDEX = {'schema': 'data-gb-electricity.system-sell-daily.v1.index', 'unit': 'GBP/MWh', 'last_date': '2026-10-31',
               'parts': [{'year': 2026, 'path': '2026.json'}]}
PRICE_YEAR = {'schema': 'data-gb-electricity.system-sell-daily.v1', 'unit': 'GBP/MWh', 'year': 2026, 'rows': [
    {'date': '2026-10-30', 'priced_periods': 48, 'expected_periods': 48, 'mean_available_gbp_per_mwh': 81.5, 'minimum_observed_gbp_per_mwh': 40, 'maximum_observed_gbp_per_mwh': 120, 'coverage_status': 'COMPLETE_SOURCE_DAY'},
    {'date': '2026-10-31', 'priced_periods': 0, 'expected_periods': 48, 'mean_available_gbp_per_mwh': None, 'minimum_observed_gbp_per_mwh': None, 'maximum_observed_gbp_per_mwh': None, 'coverage_status': 'NO_OBSERVATIONS'}]}


@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-ticker-test-'))
    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('{}')
    # REPD fixture (test only, not real data): a site 1 km north of ORIGIN and one far away in Scotland
    (tmp / 'pilot' / 'repd-fixture.json').write_text(json.dumps({'schema': 'gridatlas.browser-registry.v1', 'generation': 'test', 'source': {'dataset': 'test fixture'},
        'records': [{'repd_ref': '9001', 'name': 'Quillbrook Fen Solar Farm', 'technology': 'solar', 'status': 'operational', 'capacity_mw': 5,
                     'latitude': ORIGIN[0] + 0.009, 'longitude': ORIGIN[1]},
                    {'repd_ref': '9002', 'name': 'Farhaven Moor Wind Farm', 'technology': 'wind_onshore', 'status': 'operational', 'capacity_mw': 50,
                     'latitude': 57.5, 'longitude': -4.5}]}))
    handler = functools.partial(http.server.SimpleHTTPRequestHandler, directory=str(tmp))
    handler.log_message = lambda *a, **k: None
    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=390, h=844, live=None, snapshot=None, price=True, reduced=False, query='', storage_hidden=False):
    """live/snapshot: dict (served as JSON), int (HTTP status) or None (= 503)."""
    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')
    if storage_hidden:
        ctx.add_init_script("localStorage.setItem('p-ticker-hidden','1')")
    pg = ctx.new_page(); errs, hits = [], []
    pg.on('console', lambda m: errs.append(m.text) if m.type == 'error' and 'Failed to load resource' not in m.text else None)
    pg.on('pageerror', lambda e: errs.append(str(e)))

    def answer(route, body):
        if isinstance(body, dict):
            route.fulfill(status=200, content_type='application/json', headers={'access-control-allow-origin': '*'}, body=json.dumps(body))
        else:
            route.fulfill(status=body or 503, headers={'access-control-allow-origin': '*'}, body='unavailable')

    def router(route):
        u = route.request.url
        if u.startswith('http://127.0.0.1'):
            return route.continue_()
        hits.append(u)
        if u == LIVE:
            return answer(route, live)
        if u.endswith(SNAP_PART):
            return answer(route, snapshot)
        if u.startswith(PRICE_BASE):
            return answer(route, (PRICE_INDEX if u.endswith('index.json') else PRICE_YEAR) if price else 503)
        return route.abort()
    pg.route('**/*', router)
    pg.goto(url + query, wait_until='load')
    pg.wait_for_timeout(1500)
    return ctx, pg, errs, hits


def _ticker(pg):
    return pg.evaluate('''(() => { const b = document.querySelector('.p-ticker');
      return b ? {state: b.dataset.state, motion: b.dataset.motion, chip: b.querySelector('.p-ticker-chip').textContent,
        chipLabel: b.querySelector('.p-ticker-chip').getAttribute('aria-label'),
        titles: [...b.querySelectorAll('ul.p-ticker-list .p-ticker-t')].map(e => e.textContent),
        dates: [...b.querySelectorAll('ul.p-ticker-list .p-ticker-d')].map(e => e.textContent),
        msg: (b.querySelector('.p-ticker-msg') || {}).textContent || ''} : null; })()''')


def _status(pg):
    return pg.evaluate('new Promise(r => PILOT.emit("ticker:query", {reply: r}))')


# ---------------------------------------------------------------- data rules

def test_malformed_dates_never_interrupt_rendering(served, browser):
    ctx, pg, errs, _ = _open(browser, served, live=MALFORMED, price=False)
    t = _ticker(pg)
    assert t and t['state'] == 'live' and t['chip'].startswith('LIVE'), t
    news = [x for x in t['titles'] if x.startswith('Fixture headline')]
    assert sorted(news) == sorted(f'Fixture headline {n} — Fixture' for n in range(11)), news   # every safe headline kept, once
    assert not any('Unsafe' in x or 'Duplicate' in x for x in t['titles']), t['titles']
    by = dict(zip(t['titles'], t['dates']))
    assert by['Fixture headline 0 — Fixture'].endswith('3 h ago'), by
    assert by['Fixture headline 7 — Fixture'].endswith('5 h ago'), by          # first_seen fallback
    assert by['Fixture headline 10 — Fixture'].endswith('2 days ago'), by      # date-only form
    for n in (1, 2, 3, 4, 5, 6, 9):
        assert by[f'Fixture headline {n} — Fixture'] == 'Date unavailable', (n, by)
    assert by['Fixture headline 8 — Fixture'] == 'Date unavailable (ahead of this clock)', by
    # dated first (newest first), undated after
    first_undated = next(i for i, d in enumerate(t['dates']) if d.startswith('Date unavailable'))
    assert all(not d.startswith('Date unavailable') for d in t['dates'][:first_undated]) and all(d.startswith('Date unavailable') for d in t['dates'][first_undated:])
    # card for First collected says so
    pg.evaluate('[...document.querySelectorAll("ul.p-ticker-list .p-ticker-item")].find(b => b.textContent.includes("headline 7")).click()')
    assert 'First collected' in pg.inner_text('#card')
    assert not errs, errs
    ctx.close()


def test_stale_feed_is_labelled_overdue(served, browser):
    stale = feed([item(1, iso(NOW - timedelta(hours=50)))], generated=NOW - timedelta(hours=40))
    ctx, pg, errs, _ = _open(browser, served, live=stale, price=False)
    t = _ticker(pg)
    assert t['state'] == 'overdue' and t['chip'].startswith('STALE'), t
    assert 'refresh is overdue' in t['chipLabel'], t
    st = _status(pg)
    assert st['source'] == 'live' and st['items'] == 1
    partial = feed([item(1, iso(NOW - timedelta(hours=1)))], status='partial', counts={'feeds_ok': 40, 'feeds_failed': 9})
    ctx.close()
    ctx, pg, errs2, _ = _open(browser, served, live=partial, price=False)
    t = _ticker(pg)
    assert t['state'] == 'partial' and '40 sources succeeded, 9 failed' in t['chipLabel'], t
    assert not errs and not errs2, errs + errs2
    ctx.close()


def test_failed_load_says_unknown_not_zero(served, browser):
    ctx, pg, errs, hits = _open(browser, served, live=503, snapshot=503, price=False)
    t = _ticker(pg)
    assert t['state'] == 'unavailable' and t['chip'] == 'NO FEED', t
    assert 'unknown, not zero' in t['msg'] and not t['titles'], t
    assert LIVE in hits and any(h.endswith(SNAP_PART) for h in hits), hits
    assert 'Pipeline News' not in pg.text_content('#credit')   # no credit line for data that is not shown
    assert not errs, errs
    ctx.close()
    # an invalid live document (wrong schema) is a failure too, and falls back to the saved snapshot
    snap = feed([item(1, iso(NOW - timedelta(days=19)))], generated=NOW - timedelta(days=19))
    ctx, pg, errs, _ = _open(browser, served, live={'schema': 'wrong', 'items': []}, snapshot=snap, price=False)
    t = _ticker(pg)
    assert t['state'] == 'snapshot' and t['chip'].startswith('SAVED') and 'saved snapshot' in t['chipLabel'], t
    assert t['titles'] == ['Fixture headline 1 — Fixture'], t
    assert not errs, errs
    ctx.close()


def test_offline_never_fetches(served, browser):
    ctx, pg, errs, hits = _open(browser, served, live=MALFORMED, query='?offline=1')
    t = _ticker(pg)
    assert t['state'] == 'offline' and 'unknown, not zero' in t['msg'], t
    assert not [h for h in hits if 'githubusercontent' in h], hits
    assert not errs, errs
    ctx.close()


def test_market_item_dated_and_historical(served, browser):
    ctx, pg, errs, _ = _open(browser, served, live=feed([item(1, iso(NOW - timedelta(hours=1)))]))
    t = _ticker(pg)
    m = [d for x, d in zip(t['titles'], t['dates']) if 'system sell price' in x]
    assert m and m[0].startswith('30 Oct 2026') and m[0].endswith('historical'), t    # last priced day, never the unpriced 31st
    assert any('£81.50/MWh' in x for x in t['titles']), t
    assert 'Elexon' in pg.inner_text('#credit')
    ctx.close()


# ---------------------------------------------------------------- context, tap, motion, hide

def test_local_items_float_only_when_the_feed_names_them(served, browser):
    items = [item(1, iso(NOW - timedelta(minutes=30)), title='Unrelated grid policy news'),
             item(2, iso(NOW - timedelta(hours=6)), title='Approval for Quillbrook Fen expansion'),
             item(3, iso(NOW - timedelta(hours=7)), title='Developer buys site', possible_match={'repd_ref': '9001', 'site_name': 'Quillbrook Fen Solar Farm', 'basis': 'technology'}),
             item(4, iso(NOW - timedelta(hours=8)), title='Farhaven Moor turbines arrive'),
             item(5, iso(NOW - timedelta(hours=9)), title='Panel prices fall', technology='solar')]
    ctx, pg, errs, _ = _open(browser, served, live=feed(items), price=False, query='?repdsrc=repd-fixture.json')
    if not pg.evaluate('!!(PILOT.layer && PILOT.layer("repd") && PILOT.layer("repd")._api)'):
        ctx.close(); pytest.skip('repd module not shipped')
    before = _ticker(pg)['titles']
    assert before[0].startswith('Unrelated'), before     # nothing floats before REPD is loaded
    pg.evaluate(f'PILOT.flyTo({ORIGIN[0]}, {ORIGIN[1]}, {{instant: true}})')
    pg.evaluate('PILOT.layer("repd")._api.load()')
    pg.wait_for_timeout(1200)
    t = _ticker(pg)
    order = [x.split(' — ')[0] for x in t['titles']]
    assert order[:3] == ['Developer buys site', 'Approval for Quillbrook Fen expansion', 'Panel prices fall'], order
    assert order[3:] == ['Unrelated grid policy news', 'Farhaven Moor turbines arrive'], order   # far site (Scotland) does not float
    assert pg.evaluate('document.querySelectorAll("ul.p-ticker-list .p-ticker-near").length') == 3
    pg.evaluate('document.querySelector("ul.p-ticker-list .p-ticker-item").click()')
    card = pg.inner_text('#card')
    assert 'REPD 9001' in card and 'not a confirmed link' in card, card
    assert not errs, errs
    ctx.close()


@pytest.mark.parametrize('w,h', [(390, 844), (1366, 768)])
def test_tap_opens_card_with_pipeline_news_source(served, browser, w, h):
    ctx, pg, errs, _ = _open(browser, served, w, h, live=feed([item(1, iso(NOW - timedelta(hours=2))), item(2, iso(NOW - timedelta(hours=4)))]))
    assert _ticker(pg)['motion'] == 'flowing'
    pg.evaluate('[...document.querySelectorAll("ul.p-ticker-list .p-ticker-item")].find(b => b.textContent.includes("Fixture headline 1")).click()')
    pg.wait_for_timeout(200)
    links = pg.evaluate('[...document.querySelectorAll("#card a.p-ticker-link")].map(a => [a.textContent, a.href, a.target, a.rel])')
    assert [PN_NEWS] == [l[1] for l in links if l[0] == 'Open in Pipeline News'], links
    assert any(l[1].startswith('https://example.com/') and 'noreferrer' in l[3] for l in links), links
    assert 'Publisher date' in pg.inner_text('#card') and 'h ago' in pg.inner_text('#card')
    assert _ticker(pg)['motion'] == 'static'      # reading pauses the strip
    assert not errs, errs
    ctx.close()


def test_reduced_motion_is_static_and_pause_button(served, browser):
    two = feed([item(1, iso(NOW - timedelta(hours=2))), item(2, iso(NOW - timedelta(hours=4)))])
    ctx, pg, errs, _ = _open(browser, served, live=two, reduced=True, price=False)
    t = _ticker(pg)
    assert t['motion'] == 'static', t
    assert pg.evaluate('getComputedStyle(document.querySelector(".p-ticker-track")).animationName') == 'none'
    assert pg.evaluate('document.querySelector("[data-p-ticker-pause]").hidden')
    ctx.close()
    ctx, pg, errs, _ = _open(browser, served, live=two, price=False)
    pg.click('[data-p-ticker-pause]')
    assert _ticker(pg)['motion'] == 'static' and pg.get_attribute('[data-p-ticker-pause]', 'aria-pressed') == 'true'
    pg.click('[data-p-ticker-pause]')
    assert _ticker(pg)['motion'] == 'flowing'
    assert not errs, errs
    ctx.close()


def test_hide_toggle_persists_and_restores_from_panel(served, browser):
    ctx, pg, errs, _ = _open(browser, served, live=feed([item(1, iso(NOW - timedelta(hours=2)))]), price=False)
    pg.click('[data-p-ticker-hide]')
    assert _ticker(pg) is None
    assert pg.evaluate('localStorage.getItem("p-ticker-hidden")') == '1'
    pg.evaluate('PILOT.openPanel("ticker")')
    pg.click('[data-p-ticker-toggle]')
    assert _ticker(pg) is not None
    ctx.close()
    ctx, pg, errs2, _ = _open(browser, served, live=feed([item(1, iso(NOW - timedelta(hours=2)))]), price=False, storage_hidden=True)
    assert _ticker(pg) is None and _status(pg)['hidden'] is True
    assert not errs and not errs2
    ctx.close()


@pytest.mark.parametrize('w,h', [(390, 844), (1366, 768)])
def test_layout_targets_and_no_overlap(served, browser, w, h):
    many = feed([item(n, iso(NOW - timedelta(hours=n + 1)), title=f'A fairly long fixture headline number {n} about a grid connection') for n in range(12)])
    ctx, pg, errs, _ = _open(browser, served, w, h, live=many)
    pg.wait_for_timeout(500)
    SHOTS.mkdir(parents=True, exist_ok=True)
    pg.screenshot(path=str(SHOTS / f'pilot-ticker-{w}x{h}.png'))
    sw, iw = pg.evaluate('[document.documentElement.scrollWidth, innerWidth]')
    assert sw <= iw, (sw, iw)
    r = pg.evaluate('''(() => { const box = document.querySelector('.p-ticker').getBoundingClientRect();
      const hit = (sel) => [...document.querySelectorAll(sel)].filter(e => { const s = getComputedStyle(e); return s.display !== 'none' && s.visibility !== 'hidden'; })
        .map(e => [sel + (e.id ? '#' + e.id : ''), e.getBoundingClientRect()]).filter(([, r]) => r.width > 0 && r.height > 0)
        .filter(([, r]) => Math.min(r.right, box.right) - Math.max(r.left, box.left) > 1 && Math.min(r.bottom, box.bottom) - Math.max(r.top, box.top) > 1).map(([n]) => n);
      const small = [...document.querySelectorAll('.p-ticker button')].filter(b => !b.hidden).map(b => b.getBoundingClientRect())
        .filter(r => r.right > box.left && r.left < box.right).filter(r => Math.min(r.width, r.height) < 43.5).length;
      return {box: [box.left, box.top, box.right, box.bottom], hits: hit('#hud, #hud *, #pad, #pad *, #p-fast, #p-tabs, #joy, #credit, #card, .p-hud-left, .p-hud-right, .p-hud-status, .p-hud-top > .p-hud-sub:not(.p-ticker-host)'), small,
              h: box.height}; })()''')
    assert not r['hits'], r
    assert r['small'] == 0, r
    assert 44 <= r['h'] <= 48, r                 # thin: one 44 px row
    assert r['box'][0] >= 0 and r['box'][2] <= w, r
    assert not errs, errs
    ctx.close()

Test Seethrough

A test in the theme folder of Cosmic that checks Seethrough Index and Kuiper Belt — See Through Page using data from the kuiper-belt repository.

testcosmic / tools/explore/theme/test_seethrough.py · lines 1–236 of 236 · Entry point · pattern Browser (shared by 2 files)

What it does
It tests substations and 400kV. Defines 29 functions or classes, including names, matcher, found, RealMatches, test_names_are_see_throughs_own. Uses libraries functools, http.server, json, os, re. Side effects: changes the web page (DOM); reads or writes files.
Why it exists in the grid workflow
Domain terms in the code: substations, 400kV, 33kV.
Inputs & outputs
In: data source: kuiper-belt data; JSON file index.json; JSON file build_graph.json. Voltage levels named: 400kV, 33kV.
Downstream impact
It is itself an entry point (test); no other file was found loading it.
What it achieves
It loads index (`load_index`), indexes evidence (`IndexEvidence`) and sets up (`setUp`). Tests for the See Through mode (PERISCOPE-64). Its code works with 400 kV and 33 kV.
Why it matters
Guards the behaviour of Seethrough Index and Kuiper Belt — See Through Page.
Application
cosmic · tools/explore/theme · test
Uses
Seethrough Index (import), Kuiper Belt — See Through Page (estate URL), functools, http.server, json, os, re, shutil, socketserver, sys
Used by
none found
Produces
names, matcher, found, RealMatches, NoFalseMatches, load_index, IndexEvidence, PageTextUnchanged, Browser
Defines here
names, matcher, found, RealMatches, test_names_are_see_throughs_own, test_exact, test_normalised, test_suffix_variant, test_longest_wins, test_single_word_needs_context, NoFalseMatches, test_common_words, test_placeholders_and_generic_names_never_link, load_index, IndexEvidence, setUp, test_every_match_is_on_its_line, test_deep_link_opens_that_name, test_repos_are_exact_cosmos_names, test_sections_point_at_linked_files, PageTextUnchanged, test_inject_touches_only_the_head, test_no_belief_words_in_shipped_files, test_live_app_by_url, _serve, Quiet, log_message, Browser, test_section_page
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_seethrough.py:1-236 · blob e8993612c70591bda97f1d76e1ccb7be5ae8b29d · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: unknown · users: none · canonical: unknown
"""Tests for the See Through mode (PERISCOPE-64). Run: python -m unittest tools/explore/theme/test_seethrough.py

Uses See Through's real substation names (kuiper-belt/see-through/<newest>/grid-data.js). The index and browser
tests use a built site when one is given in EC_SITE (default /tmp/vk/seethrough/site) and skip otherwise.
"""
import functools
import http.server
import json
import os
import re
import shutil
import socketserver
import sys
import tempfile
import threading
import unittest
from pathlib import Path

HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
import seethrough_index as SI  # noqa: E402

SRC = Path(os.environ.get('EC_SRC', '/home/claude/src'))
ST = SRC / 'kuiper-belt' / 'see-through'
SITE = Path(os.environ.get('EC_SITE', '/tmp/vk/seethrough/site'))
HAVE_ST = (ST.is_dir() and any(ST.glob('*/grid-data.js')))


@functools.lru_cache(maxsize=1)
def names():
    return SI.load_names(SI.newest_folder(ST))


@functools.lru_cache(maxsize=1)
def matcher():
    return SI.Matcher(names())


def found(line):
    return [(n, k) for n, k, a, b in matcher().scan(line)]


@unittest.skipUnless(HAVE_ST, 'See Through source not present')
class RealMatches(unittest.TestCase):
    def test_names_are_see_throughs_own(self):
        self.assertGreater(len(names()), 4000)
        self.assertIn('Cottam Substation', names().values())

    def test_exact(self):
        self.assertEqual(found("    substation: 'Cottam Substation',"), [('Cottam Substation', 'exact')])
        self.assertEqual(found("'a new 400 kV four-bay substation is under construction at Thorpe Marsh',"), [('Thorpe Marsh', 'exact')])

    def test_normalised(self):
        self.assertIn(('Thorpe Marsh', 'normalised'), found('"circuit":"C-drax--thorpe-marsh--400"'))
        self.assertIn(('West Burton', 'normalised'), found('for site, n in (("COTTAM", 4), ("WEST BURTON", 4),'))

    def test_suffix_variant(self):
        self.assertEqual(found('never meets "Norwich Main 400kV Substation"'), [('Norwich Main Substation', 'suffix')])
        self.assertEqual(found("normalise('COWLEY SUBSTATION') === 'COWLEY'"), [('Cowley Substation', 'suffix')])

    def test_longest_wins(self):
        # "Burton Substation" is a name too, but here it is part of "West Burton Substation"
        self.assertEqual(found("substation: 'West Burton Substation',"), [('West Burton Substation', 'exact')])

    def test_single_word_needs_context(self):
        self.assertEqual(found("// a name used twice ('Drax' is 1182 and 1368) as substation"), [('Drax', 'exact')])
        self.assertEqual(found('Drax'), [])


@unittest.skipUnless(HAVE_ST, 'See Through source not present')
class NoFalseMatches(unittest.TestCase):
    LINES = [
        'the pool is idle, so close the file and open the university page',
        'if (pool.idle) close(); // flint, harden, shin, tulip',
        'She moved from Chester to Bradford last year.',
        'Dallas, Texas and Richmond, Virginia are not in Great Britain',
        'Berwick Bank was told its nearest substation is far away',      # a wind farm, not Berwick
        "project: 'Thorpe Marsh Power Station - Battery Energy Storage'",  # a project named after the place
        'Financial close for the West Burton C battery energy storage',
        '#     (Port Talbot: blast furnaces, sinter, coke ovens, BOS)',   # lower-case prose
        'Eccles Grid Stability Ltd',
        'grid substation kv 400 132 33 primary bsp gsp',
        'const station = new Station(grid); // sub station',
        'Kingston upon Thames, Newtown, Greenfield, Belmont grid',
    ]

    def test_common_words(self):
        for line in self.LINES:
            self.assertEqual(found(line), [], line)

    def test_placeholders_and_generic_names_never_link(self):
        m = matcher()
        linkable = {nm for lst in m.full.values() for _, nm, _ in lst}
        for nm in linkable:
            self.assertNotIn('__', nm)
            self.assertIsNone(SI.BELIEF.search(nm), nm)
        self.assertNotIn('33kV Substation', linkable)
        self.assertNotIn('Sub Station', linkable)


def load_index():
    p = SITE / 'seethrough' / 'index.json'
    return json.loads(p.read_text(encoding='utf-8')) if p.is_file() else None


@unittest.skipUnless(HAVE_ST and load_index(), 'no built site with seethrough/index.json')
class IndexEvidence(unittest.TestCase):
    def setUp(self):
        self.idx = load_index()
        self.g = json.loads((SITE / 'build_graph.json').read_text(encoding='utf-8'))
        self.files = {str(f['id']): f for f in self.g['files']}

    def test_every_match_is_on_its_line(self):
        known = set(names().values())
        checked = 0
        for fid, rec in self.idx['files'].items():
            f = self.files[fid]
            self.assertEqual(rec['k'], '%s/%s' % (f['repo'], f['path']))
            self.assertEqual((rec['s'], rec['b']), (f['section'], f['block']))
            lines = (SRC / f['repo'] / f['path']).read_text(encoding='utf-8', errors='replace').splitlines()
            for name, line, kind, ev in rec['m']:
                self.assertIn(name, known)
                self.assertIn(kind, ('exact', 'normalised', 'suffix'))
                if line:
                    hits = [n for n, k, a, b in matcher().scan(lines[line - 1])]
                    self.assertIn(name, hits, '%s:%d' % (rec['k'], line))
                    checked += 1
        self.assertGreater(checked, 50)

    def test_deep_link_opens_that_name(self):
        nm = names()
        for rec in self.idx['files'].values():
            for m in rec['m'][:5]:
                self.assertEqual(SI.landing(nm, m[0]), m[0])

    def test_repos_are_exact_cosmos_names(self):
        tsv = SI.load_repos(ST.parent / 'cosmos')
        for repo, name in self.idx['repos'].items():
            self.assertIn(name, tsv)
            self.assertEqual(repo.lower(), name.lower())

    def test_sections_point_at_linked_files(self):
        for sec, ids in self.idx['sections'].items():
            for i in ids:
                self.assertEqual(str(self.idx['files'][str(i)]['s']), sec)


class PageTextUnchanged(unittest.TestCase):
    def test_inject_touches_only_the_head(self):
        tmp = Path(tempfile.mkdtemp())
        try:
            (tmp / 's').mkdir()
            (tmp / 'repos').mkdir()
            page = '<!doctype html><html><head><title>T</title></head><body><h1>Cottam Substation</h1><p>x</p></body></html>'
            (tmp / 's' / '0001.html').write_text(page, encoding='utf-8')
            (tmp / 'repos' / 'r.html').write_text(page, encoding='utf-8')
            SI.inject(tmp)
            SI.inject(tmp)                      # idempotent
            for p in (tmp / 's' / '0001.html', tmp / 'repos' / 'r.html'):
                t = p.read_text(encoding='utf-8')
                self.assertEqual(t.split('</head>')[1], page.split('</head>')[1])
                self.assertEqual(t.count('data-ec-seethrough'), 2)
            self.assertTrue((tmp / 'theme' / 'seethrough.js').is_file())
        finally:
            shutil.rmtree(tmp)

    def test_no_belief_words_in_shipped_files(self):
        for name in ('seethrough.js', 'seethrough.css'):
            t = (HERE / name).read_text(encoding='utf-8')
            self.assertIsNone(re.search(r'(?i)\b(god|holy|divine|sacred|heaven|prayer|church|temple|spirit|soul)\b', t), name)

    def test_live_app_by_url(self):
        self.assertEqual(SI.LIVE, 'https://ventusltd.github.io/kuiper-belt/see-through/')


def _serve(root):
    class Quiet(http.server.SimpleHTTPRequestHandler):
        def log_message(self, *a):
            pass
    h = functools.partial(Quiet, directory=str(root))
    s = socketserver.ThreadingTCPServer(('127.0.0.1', 0), h)
    s.daemon_threads = True
    threading.Thread(target=s.serve_forever, daemon=True).start()
    return s


try:
    from playwright.sync_api import sync_playwright  # noqa: F401
    HAVE_PW = True
except Exception:  # pragma: no cover
    HAVE_PW = False


@unittest.skipUnless(HAVE_PW and load_index() and (SITE / 'theme' / 'seethrough.js').is_file(), 'needs playwright and an injected site')
class Browser(unittest.TestCase):
    """The page's own text is the same with and without seethrough.js; the button opens the deep link."""

    def test_section_page(self):
        from playwright.sync_api import sync_playwright
        idx = load_index()
        sec = sorted(idx['sections'], key=int)[0]
        rec = idx['files'][str(idx['sections'][sec][0])]
        srv = _serve(SITE)
        url = 'http://127.0.0.1:%d/s/%04d.html' % (srv.server_address[1], int(sec))
        strip = """() => { const c = document.body.cloneNode(true); c.querySelectorAll('[data-st]').forEach(n => n.remove());
                   return c.textContent.replace(/\\s+/g, ' ').trim(); }"""
        try:
            with sync_playwright() as p:
                b = p.chromium.launch()
                pg = b.new_page(viewport={'width': 390, 'height': 844})
                pg.route('**/theme/seethrough.js', lambda r: r.abort())
                pg.route('**/kuiper-belt/**', lambda r: r.abort())
                pg.goto(url); pg.wait_for_timeout(3000)
                before = pg.evaluate(strip)
                pg2 = b.new_page(viewport={'width': 390, 'height': 844})
                pg2.route(re.compile(r'^(?!http://127\.0\.0\.1).*'), lambda r: r.abort())
                pg2.goto(url); pg2.wait_for_timeout(3000)
                self.assertEqual(pg2.evaluate(strip), before)
                btn = pg2.locator('[data-st-file] button, button[data-st-file]').first
                btn.scroll_into_view_if_needed(); btn.click()
                if pg2.locator('.st-pick').count():
                    pg2.locator('.st-pick').first.click()
                src = pg2.locator('.st-overlay iframe').get_attribute('src')
                self.assertTrue(src.startswith(idx['base'] + '#sub='), src)
                self.assertTrue(src.endswith('&view=3d'))
                self.assertIn('mentioned in ' + rec['k'], pg2.locator('.st-where').inner_text())
                pg2.locator('.st-x').click()
                self.assertEqual(pg2.locator('.st-overlay').count(), 0)
                b.close()
        finally:
            srv.shutdown()
            srv.server_close()


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