In this section
- Test Pilot Subfind test · cosmic / tools/explore/theme/test_pilot_subfind.py lines 1–377
Test Pilot Subfind
A test in the theme folder of Cosmic that checks GridAtlas — Atlas Page using data from the GridAtlas repository.
testcosmic / tools/explore/theme/test_pilot_subfind.py · lines 1–377 of 377 · 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 postcodes, 400kV and 33kV. Defines 21 functions or classes, including _chromium, feat, served, browser, _open. 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: postcodes, 400kV, 33kV, 132kV, 0.75kV.
- Inputs & outputs
- In: data source: gridatlas data; GeoJSON file grid_substations.geojson; browser storage (getItem). Out: JSON file play-index.json; GeoJSON file grid_substations.geojson. Voltage levels named: 400kV, 132kV, 33kV, 0.75kV.
- What it achieves
- It is built from the feat step (`feat`), the served step (`served`) and the browser step (`browser`). Browser tests for the optional Pilot "Find substations" module (`theme/pilot-subfind.js`, AZIMUTH-47). Its code works with 400 kV, 33 kV and 132 kV.
- Why it matters
- Guards the behaviour of GridAtlas — Atlas Page.
- Application
- cosmic · tools/explore/theme · test
- Uses
- GridAtlas — Atlas Page (estate URL), __future__, functools, http.server, importlib.util, json, os, shutil, socketserver
- Used by
- none found
- Produces
- feat, served, browser, test_postcode_with_space_ranks_nearest_with_ties_and_caveat, test_town_name_gives_point_then_list, test_substation_name_matches_directly, test_unknown_place_says_so_never_silent, test_geocoder_failure_is_clear_and_unknown, test_data_failure_is_clear_with_retry, test_ukpn_failure_is_unknown, test_voltage_and_radius_filters, test_fly_route_and_recent
- Defines here
- _chromium, feat, served, browser, _open, router, _search, _rows, _status, test_postcode_with_space_ranks_nearest_with_ties_and_caveat, test_town_name_gives_point_then_list, test_substation_name_matches_directly, test_unknown_place_says_so_never_silent, test_geocoder_failure_is_clear_and_unknown, test_data_failure_is_clear_with_retry, test_ukpn_failure_is_unknown, test_voltage_and_radius_filters, test_fly_route_and_recent, test_offline_never_geocodes, test_layout_targets_and_no_overlap, test_reduced_motion_fly_is_instant_and_motion_fly_animates
- 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_subfind.py:1-377 · blob 2a977447e07d4b3c9af9c8afc2542d496ccb045a · 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 "Find substations" module (theme/pilot-subfind.js, AZIMUTH-47).
Builds pilot/ the way inject.py publishes it into a temp site and serves it on 127.0.0.1. The substations come from a
SYNTHETIC fixture (not real data) served through the grid layer's ?ga= localhost override; postcodes.io and Nominatim
are answered by Playwright routes with mocked responses; every other external host is aborted, so nothing leaves the
machine. Covers: a postcode with a space, a town, an unknown place, a geocoder failure, a data failure, a voltage
filter, a radius filter, ties, a substation name match, recent searches, Fly there / Route there / Open in GridAtlas,
reduced motion, offline, UKPN failure, 44 px targets and no overlap with the HUD, ticker or DARK row at 390x844 and
1366x768. Skips without Playwright/Chromium. Screenshots: $PILOT_SHOTS (default /tmp/vk/pilot200/shots).
Run: python3 -m pytest -q tools/explore/theme/test_pilot_subfind.py
"""
from __future__ import annotations
import functools, http.server, importlib.util, json, os, shutil, socketserver, tempfile, threading
from pathlib import Path
from urllib.parse import urlparse, parse_qs
import pytest
HERE = Path(__file__).resolve().parent
SHOTS = Path(os.environ.get('PILOT_SHOTS', '/tmp/vk/pilot200/shots'))
RECEIVER = 'https://ventusltd.github.io/gridatlas/atlas/'
# Search point for the mocked postcode: exactly representable, so the two tie fixtures are exactly equidistant.
PC_LAT, PC_LON = 51.5, -0.125
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-subfind.js').is_file(), reason='Playwright or pilot-subfind.js unavailable')
def feat(name, voltage, lat, lon, operator=''):
return {'type': 'Feature', 'geometry': {'type': 'Point', 'coordinates': [lon, lat]},
'properties': {k: v for k, v in (('name', name), ('voltage', voltage), ('operator', operator)) if v is not None}}
# Synthetic fixture (test only): names are invented.
SUBS = {'type': 'FeatureCollection', 'features': [
feat('Mystery Substation', '', PC_LAT + 0.01, PC_LON), # ~1.1 km N, voltage unknown
feat('Beta Substation', '132000', PC_LAT, PC_LON - 0.0625, 'Fixture Networks'), # tie (west)
feat('Alpha Grid Substation', '132000;33000', PC_LAT, PC_LON + 0.0625, 'Fixture Networks'), # tie (east)
feat('Epsilon', '33000', PC_LAT + 0.05, PC_LON + 0.05),
feat('Gamma 275', '275000', PC_LAT - 0.06, PC_LON),
feat('Delta', '66000', PC_LAT + 0.08, PC_LON - 0.12),
feat('Walpole 400kV Substation', '400000;132000', 52.73, 0.20, 'National Grid'),
feat('Peterborough Central', '132000;33000', 52.58, -0.25, 'Fixture Networks'),
feat(None, '33000', 55.0, -3.0),
feat('Railway Traction Feeder', '750', PC_LAT + 0.001, PC_LON), # 0.75 kV only: outside the 33 kV+ scope
]}
PC = {'/postcodes/SW1A1AA': {'status': 200, 'result': {'postcode': 'SW1A 1AA', 'latitude': PC_LAT, 'longitude': PC_LON,
'admin_district': 'Westminster', 'region': 'London'}}}
PLACES = {'peterborough': [{'name_1': 'Peterborough', 'latitude': 52.5735, 'longitude': -0.2420, 'local_type': 'City',
'county_unitary': 'Peterborough', 'region': 'East of England'}]}
@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-subfind-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('{}')
(tmp / 'fx').mkdir()
(tmp / 'fx' / 'grid_substations.geojson').write_text(json.dumps(SUBS))
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, geo='ok', ga='/fx/', reduced=True, query=''):
"""geo: 'ok' (mocked answers) or 'fail' (postcodes.io and Nominatim answer 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')
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)))
cors = {'access-control-allow-origin': '*'}
def router(route):
u = route.request.url
if u.startswith('http://127.0.0.1'):
if 'grid_substations.geojson' in u:
hits.append(u)
return route.continue_()
hits.append(u)
p = urlparse(u)
if p.hostname in ('api.postcodes.io', 'nominatim.openstreetmap.org') and geo == 'fail':
return route.fulfill(status=503, headers=cors, body='unavailable')
if p.hostname == 'api.postcodes.io':
if p.path.startswith('/places'):
q = parse_qs(p.query).get('q', [''])[0].lower()
return route.fulfill(status=200, content_type='application/json', headers=cors, body=json.dumps({'status': 200, 'result': PLACES.get(q, [])}))
if p.path in PC:
return route.fulfill(status=200, content_type='application/json', headers=cors, body=json.dumps(PC[p.path]))
return route.fulfill(status=404, content_type='application/json', headers=cors, body=json.dumps({'status': 404, 'error': 'Invalid postcode'}))
if p.hostname == 'nominatim.openstreetmap.org':
return route.fulfill(status=200, content_type='application/json', headers=cors, body='[]')
return route.abort()
pg.route('**/*', router)
sep = '&' if query else '?'
pg.goto(url + (query or '') + (sep + 'ga=' + ga if ga else ''), wait_until='load')
pg.wait_for_function('window.PILOT && PILOT.subfind && document.querySelector("#p-subfind-q")')
return ctx, pg, errs, hits
def _search(pg, text):
pg.evaluate('PILOT.openPanel("subfind")')
pg.fill('#p-subfind-q', text)
pg.click('.p-subfind-go')
pg.wait_for_function('!PILOT.subfind.state().busy', timeout=20000)
pg.wait_for_timeout(100)
def _rows(pg, sel='.p-subfind-near'):
return pg.evaluate('''(sel) => [...document.querySelectorAll(sel + ' .p-subfind-row')].map(li => ({
name: li.querySelector('.p-subfind-name').textContent, kv: li.querySelector('.p-subfind-kv').textContent,
op: (li.querySelector('.p-subfind-op') || {}).textContent || '', d: (li.querySelector('.p-subfind-d') || {}).textContent || '',
brg: (li.querySelector('.p-subfind-brg') || {}).textContent || '', tie: !!li.querySelector('.p-subfind-tie'), ga: (li.querySelector('a.p-subfind-ga') || {}).href || '',
acts: [...li.querySelectorAll('.p-subfind-acts > *')].map(b => b.textContent)}))''', sel)
def _status(pg):
return pg.evaluate('(() => { const s = document.querySelector(".p-subfind-status"); return {text: s.textContent, cls: s.className}; })()')
# ---------------------------------------------------------------- search kinds
def test_postcode_with_space_ranks_nearest_with_ties_and_caveat(served, browser):
ctx, pg, errs, hits = _open(browser, served)
_search(pg, 'sw1a 1aa')
assert any(h.endswith('/postcodes/SW1A1AA') for h in hits), hits
assert 'SW1A 1AA' in pg.inner_text('.p-subfind-origin')
r = _rows(pg)
names = [x['name'] for x in r]
# tie: engine order = file order (Beta is before Alpha in the file), never alphabetical (parity with GridAtlas / M2)
assert names[:3] == ['Mystery Substation', 'Beta Substation', 'Alpha Grid Substation'], names
assert r[1]['d'] == r[2]['d'] and r[1]['brg'].startswith('W ') and r[2]['brg'].startswith('E '), r[1:3]
assert [x['tie'] for x in r[:4]] == [False, True, True, False], r[:4] # ties flagged, never hidden
assert 'Railway Traction Feeder' not in names # below 33 kV: out of scope (as M2)
assert r[0]['kv'] == 'voltage unknown' and r[0]['brg'].startswith('N '), r[0] # unknown, never zero
assert r[2]['kv'] == '132 / 33 kV' and r[2]['op'] == 'Fixture Networks' and r[1]['kv'] == '132 kV', r[1:3]
assert r[0]['acts'] == ['Fly there', 'Route there', 'Open in GridAtlas'], r[0]
st = pg.evaluate('PILOT.subfind.state().grid.filter(s => s.name.startsWith("Alpha") || s.name.startsWith("Beta")).map(s => s.m)')
assert st[0] == st[1], st # exact tie from the estate maths
ga = urlparse(r[2]['ga'])
assert r[2]['ga'].startswith(RECEIVER) and list(parse_qs(ga.query)) == ['project', 'latitude', 'longitude', 'zoom'], r[2]['ga']
q = parse_qs(ga.query)
assert q['project'] == ['Alpha Grid Substation'] and q['zoom'] == ['12'] and float(q['latitude'][0]) == PC_LAT, q
foot = pg.inner_text('.p-subfind-foot')
assert 'straight-line distance' in foot and 'not a connection offer' in foot and 'not capacity' in foot, foot
assert 'does not confirm capacity' in foot, foot # estate STRAIGHT_LINE_CAVEAT.substation
assert pg.evaluate('JSON.parse(localStorage.getItem("p-subfind-recent"))[0].q') == 'sw1a 1aa'
assert len([h for h in hits if 'grid_substations.geojson' in h]) == 1, hits # same memoised fetch as pilot-grid
assert 'SW1A 1AA' in pg.inner_text('#p-hud-status') or 'Mystery' in pg.inner_text('#p-hud-status')
assert not errs, errs
ctx.close()
def test_town_name_gives_point_then_list(served, browser):
ctx, pg, errs, hits = _open(browser, served)
_search(pg, 'Peterborough')
assert any('/places?q=Peterborough' in h for h in hits), hits
assert 'Peterborough' in pg.inner_text('.p-subfind-origin')
r = _rows(pg)
assert r[0]['name'] == 'Peterborough Central' and r[0]['d'] == '904 m', r[0]
# the substation literally named "Peterborough ..." is also listed as a direct name match
assert [x['name'] for x in _rows(pg, '.p-subfind-named')] == ['Peterborough Central']
assert _status(pg)['text'] == ''
assert not errs, errs
ctx.close()
def test_substation_name_matches_directly(served, browser):
ctx, pg, errs, _ = _open(browser, served)
_search(pg, 'walpole')
named = _rows(pg, '.p-subfind-named')
assert [x['name'] for x in named] == ['Walpole 400kV Substation'], named
assert named[0]['kv'] == '400 / 132 kV' and named[0]['op'] == 'National Grid', named
assert 'p-subfind-error' not in _status(pg)['cls']
ctx.close()
def test_unknown_place_says_so_never_silent(served, browser):
ctx, pg, errs, _ = _open(browser, served)
_search(pg, 'Zzyzxqq')
s = _status(pg)
assert 'No postcode, town, place or substation named “Zzyzxqq”' in s['text'] and 'p-subfind-none' in s['cls'], s
assert not _rows(pg) and not _rows(pg, '.p-subfind-named')
_search(pg, 'ZZ99 9ZZ') # well-formed postcode that does not exist
assert 'No such postcode' in _status(pg)['text'] or 'No postcode' in _status(pg)['text'], _status(pg)
assert not errs, errs
ctx.close()
def test_geocoder_failure_is_clear_and_unknown(served, browser):
ctx, pg, errs, _ = _open(browser, served, geo='fail')
_search(pg, 'SW1A 1AA')
s = _status(pg)
assert 'p-subfind-error' in s['cls'] and 'could not be reached' in s['text'] and 'unknown, not zero' in s['text'], s
assert not _rows(pg)
_search(pg, 'Nowhereton')
s = _status(pg)
assert 'p-subfind-error' in s['cls'] and 'unknown, not zero' in s['text'], s
ctx.close()
def test_data_failure_is_clear_with_retry(served, browser):
ctx, pg, errs, _ = _open(browser, served, ga='/missing/')
_search(pg, 'SW1A 1AA')
out = pg.inner_text('.p-subfind-out')
assert 'could not load' in out and 'unknown, not zero' in out, out
assert pg.locator('[data-p-subfind-act="retry"]').count() == 1
assert not _rows(pg)
ctx.close()
def test_ukpn_failure_is_unknown(served, browser):
ctx, pg, errs, _ = _open(browser, served)
_search(pg, 'SW1A 1AA')
pg.click('[data-p-subfind-ukpn]')
pg.wait_for_function('!PILOT.subfind.state().busy', timeout=45000)
out = pg.inner_text('.p-subfind-out')
assert 'UKPN secondaries' in out and 'unknown, not zero' in out, out
ctx.close()
# ---------------------------------------------------------------- filters
def test_voltage_and_radius_filters(served, browser):
ctx, pg, errs, _ = _open(browser, served)
_search(pg, 'SW1A 1AA')
pg.click('[data-p-subfind-kv="400"]')
assert [x['name'] for x in _rows(pg)] == ['Walpole 400kV Substation']
assert '1 substation with unknown voltage hidden' in pg.inner_text('.p-subfind-out')
pg.click('[data-p-subfind-kv="400"]'); pg.click('[data-p-subfind-kv="132"]')
assert [x['name'] for x in _rows(pg)] == ['Beta Substation', 'Alpha Grid Substation', 'Peterborough Central', 'Walpole 400kV Substation']
pg.click('[data-p-subfind-r="5"]')
assert [x['name'] for x in _rows(pg)] == ['Beta Substation', 'Alpha Grid Substation'] # 4.35 km each, file order
pg.click('[data-p-subfind-kv="132"]'); pg.click('[data-p-subfind-kv="275"]')
assert not _rows(pg) and 'No mapped substation matches these filters within 5 km' in pg.inner_text('.p-subfind-out')
pg.click('[data-p-subfind-r="25"]')
assert [x['name'] for x in _rows(pg)] == ['Gamma 275']
assert pg.get_attribute('[data-p-subfind-r="25"]', 'aria-pressed') == 'true' and pg.get_attribute('[data-p-subfind-r="5"]', 'aria-pressed') == 'false'
assert not errs, errs
ctx.close()
# ---------------------------------------------------------------- actions, recents, motion
def test_fly_route_and_recent(served, browser):
ctx, pg, errs, _ = _open(browser, served, reduced=True)
_search(pg, 'SW1A 1AA')
pg.evaluate('window.__navs = []; PILOT.on("nav:route", d => window.__navs.push(d)); 0')
pg.locator('.p-subfind-near .p-subfind-row').nth(2).locator('[data-p-subfind-act="route"]').click()
pg.wait_for_function('window.__navs.length > 0', timeout=5000)
nav = pg.evaluate('window.__navs')
assert len(nav) == 1 and nav[0]['name'] == 'Alpha Grid Substation' and nav[0]['source'] == 'subfind:grid', nav
assert 'air legs' in pg.inner_text('#note')
pg.evaluate('PILOT.openPanel("subfind")')
pg.evaluate('window.__arr = []; PILOT.on("arrive", d => window.__arr.push(d)); 0')
pg.locator('.p-subfind-near .p-subfind-row').nth(2).locator('[data-p-subfind-act="fly"]').click()
pg.wait_for_function('window.__arr.length > 0', timeout=5000)
c = pg.evaluate('PILOT.camLL()')
d = pg.evaluate(f'PILOT.dist({c["lat"]}, {c["lon"]}, {PC_LAT}, {PC_LON + 0.0625})')
assert d < 1500, (c, d) # reduced motion: instant jump, stand-off 600 m
assert 'Alpha Grid Substation' in pg.inner_text('#card') and 'Open in GridAtlas' in pg.inner_text('#card')
assert pg.evaluate('document.getElementById("p-sheet").hidden') # phone: panel closes to show the view
# recent searches survive a reload and re-run from the stored point without a new geocode
pg.reload(); pg.wait_for_function('window.PILOT && PILOT.subfind && document.querySelector("#p-subfind-q")')
pg.evaluate('PILOT.openPanel("subfind")')
pg.click('[data-p-subfind-recent="0"]')
pg.wait_for_function('!PILOT.subfind.state().busy && PILOT.subfind.state().rows.length > 0', timeout=20000)
assert _rows(pg)[0]['name'] == 'Mystery Substation'
assert not errs, errs
ctx.close()
def test_offline_never_geocodes(served, browser):
ctx, pg, errs, hits = _open(browser, served, query='?offline=1')
_search(pg, 'SW1A 1AA')
s = _status(pg)
assert 'Offline' in s['text'] and 'unknown, not zero' in s['text'], s
assert not [h for h in hits if 'postcodes.io' in h or 'nominatim' in h], hits
ctx.close()
# ---------------------------------------------------------------- layout
OVERLAP_JS = '''(sel) => { const box = document.querySelector(sel).getBoundingClientRect();
const vis = e => { const s = getComputedStyle(e); return s.display !== 'none' && s.visibility !== 'hidden'; };
const hits = [...document.querySelectorAll('#hud, #hud *, #pad, #pad *, #p-fast, #p-tabs, #joy, #credit, .p-hud-right, .p-hud-left, .p-ticker, .p-ticker *, .p-dark-row, .p-dark-row *, .p-hud-top > .p-hud-sub')]
.filter(e => vis(e) && !e.contains(document.querySelector(sel)) && !document.querySelector(sel).contains(e))
.map(e => [e.id || e.className, 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, r]) => String(n).slice(0, 40) + ' ' + [r.left, r.top, r.right, r.bottom].map(Math.round));
return {box: [box.left, box.top, box.right, box.bottom].map(Math.round), hits}; }'''
SMALL_JS = '''() => [...document.querySelectorAll('.p-subfind-hudbtn, #p-sheet button, #p-sheet a.pbtn, #p-sheet a.p-subfind-link, #p-sheet input')]
.filter(e => e.offsetParent && (e.closest('[data-p-panel="subfind"]') || e.closest('#p-sheet') && document.querySelector('#p-subfind-q').offsetParent))
.map(e => [e.textContent.trim().slice(0, 24) || e.id, e.getBoundingClientRect()])
.filter(([, r]) => r.width > 0 && Math.min(r.width, r.height) < 43.5).map(([n, r]) => n + ' ' + Math.round(r.width) + 'x' + Math.round(r.height))'''
@pytest.mark.parametrize('w,h', [(390, 844), (1366, 768)])
def test_layout_targets_and_no_overlap(served, browser, w, h):
ctx, pg, errs, _ = _open(browser, served, w, h, reduced=False)
pg.wait_for_timeout(1500)
sw, iw = pg.evaluate('[document.documentElement.scrollWidth, innerWidth]')
assert sw <= iw, (sw, iw)
hud = pg.evaluate(OVERLAP_JS, '.p-subfind-hudbtn')
assert not hud['hits'], hud
b = hud['box']
assert b[2] - b[0] >= (200 if w < 900 else 44) and b[3] - b[1] >= 44, b # big button on the phone
assert pg.evaluate('getComputedStyle(document.querySelector(".p-subfind-hudbtn")).pointerEvents') != 'none'
pg.click('.p-subfind-hudbtn')
pg.wait_for_timeout(200)
assert pg.evaluate('document.activeElement && document.activeElement.id') == 'p-subfind-q'
_search(pg, 'SW1A 1AA')
pg.click('[data-p-subfind-kv="132"]'); pg.click('[data-p-subfind-kv="132"]')
SHOTS.mkdir(parents=True, exist_ok=True)
pg.screenshot(path=str(SHOTS / f'pilot-subfind-{w}x{h}.png'))
small = pg.evaluate(SMALL_JS)
assert not small, small
sw, iw = pg.evaluate('[document.documentElement.scrollWidth, innerWidth]')
assert sw <= iw, (sw, iw)
sheet = pg.evaluate('(() => { const s = document.getElementById("p-sheet"); return [s.scrollWidth, s.clientWidth]; })()')
assert sheet[0] <= sheet[1] + 1, sheet # no sideways scroll inside the sheet
assert not errs, errs
ctx.close()
def test_reduced_motion_fly_is_instant_and_motion_fly_animates(served, browser):
ctx, pg, errs, _ = _open(browser, served, 1366, 768, reduced=True)
_search(pg, 'Peterborough')
pg.evaluate('window.__arr = []; PILOT.on("arrive", d => window.__arr.push(d)); 0')
pg.locator('.p-subfind-near .p-subfind-row').first.locator('[data-p-subfind-act="fly"]').click()
pg.wait_for_function('window.__arr.length > 0', timeout=5000)
c = pg.evaluate('PILOT.camLL()')
assert pg.evaluate(f'PILOT.dist({c["lat"]}, {c["lon"]}, 52.58, -0.25)') < 1500, c
ctx.close()
ctx, pg, errs, _ = _open(browser, served, 1366, 768, reduced=False)
_search(pg, 'Peterborough')
pg.evaluate('window.__dep = []; PILOT.on("depart", d => window.__dep.push(d)); 0')
pg.locator('.p-subfind-near .p-subfind-row').first.locator('[data-p-subfind-act="fly"]').click()
pg.wait_for_function('window.__dep.length > 0', timeout=5000)
pg.wait_for_timeout(300)
dep = pg.evaluate('window.__dep')
assert dep and dep[0]['source'] == 'subfind', dep
c = pg.evaluate('PILOT.camLL()')
assert pg.evaluate(f'PILOT.dist({c["lat"]}, {c["lon"]}, 52.58, -0.25)') > 5000, c # long hop: still on its arc
ctx.close()