In this section
- Test CI test · cosmic / tools/explore/ci/test_ci.py lines 1–319
- CI UI Shots automation · cosmic / tools/explore/ci/ui_shots.py lines 1–143
Test CI
A test in the explore folder of Cosmic that checks CI Newcode and CI Chess Gate.
testcosmic / tools/explore/ci/test_ci.py · lines 1–319 of 319 · Not reached from any entry point (candidate for review) · pattern synthetic_graph (shared by 2 files)
- What it does
- It tests its inputs. Defines 25 functions or classes, including settle_cable_rating, tiny_helper, brand_new_thing, Ledger, __init__. Uses libraries copy, json, os, subprocess, sys. Side effects: reads or writes files; starts processes.
- Inputs & outputs
- In: JSON file ci-newcode.json; JSON file x.json; JSON file g.json. Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid).
- What it achieves
- It runs newcode (`run_newcode`) and is built from the settle cable rating helper (`settle_cable_rating`) and the tiny helper helper (`tiny_helper`). Tests for `tools/explore/ci` (GAUNTLET-17): `newcode.py`, `chess_gate.py` and the proposed workflow.
- Why it matters
- Guards the behaviour of CI Newcode and CI Chess Gate.
- Application
- cosmic · tools/explore/ci · test
- Uses
- CI Newcode (import), CI Chess Gate (import), copy, json, os, subprocess, sys, textwrap, pytest
- Used by
- none found
- Produces
- settle_cable_rating, tiny_helper, brand_new_thing, Ledger, sh, commit, repos, run_newcode, by_name, test_newcode_classes_and_exit, test_changed_function_and_advisory_exit, test_base_from_graph_and_parent
- Defines here
- settle_cable_rating, tiny_helper, brand_new_thing, Ledger, __init__, post, sh, commit, repos, run_newcode, by_name, test_newcode_classes_and_exit, test_changed_function_and_advisory_exit, test_base_from_graph_and_parent, test_index_ignores_self_and_nested_units, test_imports_engine_regex, test_lite_extractor_js_and_py, synthetic_graph, test_gate_checks_pass_on_synthetic_graph, test_board_skip_without_graph, test_replay_catches_tampering, test_crash_is_reported_as_fail, test_release_view_promote_reserve_reinforce, test_gate_main_writes_reports, test_proposed_workflow_is_advisory
- 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/ci/test_ci.py:1-319 · blob 3f8b251897230feb3555878189725777c842cc8c · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: unknown · users: none · canonical: unreached_review
"""Tests for tools/explore/ci (GAUNTLET-17): newcode.py, chess_gate.py and the proposed workflow.
Run: python3 -m pytest -q tools/explore/ci/test_ci.py
Everything runs on temporary git repos and synthetic graphs; no network. The proposed workflow is checked
only if PROPOSED_WORKFLOW (default /tmp/vk/ci/workflow.yml) exists.
"""
import copy
import json
import os
import subprocess
import sys
import textwrap
import pytest
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
import newcode # noqa: E402
import chess_gate # noqa: E402
LONG = textwrap.dedent('''
def settle_cable_rating(load_kw, length_m, derate):
"""Long enough to be a blocking duplicate when pasted."""
total = 0
for step in range(10):
total += load_kw * step
total -= length_m / (step + 1)
if total > 1000:
total = total / 2
elif total < -1000:
total = -total
else:
total = total * derate
values = [total * k for k in range(5)]
best = max(values)
worst = min(values)
spread = best - worst
if spread > 10:
spread = spread ** 0.5
result = {"best": best, "worst": worst, "spread": spread}
result["ok"] = spread < 50
result["n"] = len(values)
return result
''')
SHORT = textwrap.dedent('''
def tiny_helper(a, b, c):
x = a + b * c
y = x - a / (b + 1)
return {"x": x, "y": y}
''')
UNIQUE = textwrap.dedent('''
def brand_new_thing(items):
seen = {}
for name, value in items:
seen.setdefault(name, []).append(value * 3 - 1)
return sorted(seen.items(), key=lambda kv: (-len(kv[1]), kv[0]))
''')
FRESH = textwrap.dedent('''
class Ledger:
def __init__(self):
self.rows = []
self.total = 0.0
def post(self, who, amount, note=''):
if not who:
raise ValueError('who')
self.rows.append((who, amount, note))
self.total += amount
return len(self.rows)
''')
HAVERSINE_JS = textwrap.dedent('''
function greatCircle(lat1, lon1, lat2, lon2) {
var R = 6371;
var dLat = (lat2 - lat1) * Math.PI / 180, dLon = (lon2 - lon1) * Math.PI / 180;
var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) * Math.sin(dLon / 2) * Math.sin(dLon / 2);
return R * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
}
''')
ENGINE_JS = textwrap.dedent('''
export function distanceKm(lon1, lat1, lon2, lat2) {
const R = 6378.137;
const p1 = lat1 * Math.PI / 180, p2 = lat2 * Math.PI / 180;
const dp = p2 - p1, dl = (lon2 - lon1) * Math.PI / 180;
const a = Math.sin(dp / 2) ** 2 + Math.cos(p1) * Math.cos(p2) * Math.sin(dl / 2) ** 2;
return 2 * R * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
}
''')
def sh(cwd, *args):
return subprocess.run(args, cwd=cwd, check=True, capture_output=True, text=True).stdout.strip()
def commit(repo, files, msg):
for path, text in files.items():
p = os.path.join(repo, path)
os.makedirs(os.path.dirname(p), exist_ok=True)
with open(p, 'w') as fh:
fh.write(text)
sh(repo, 'git', 'add', '-A')
sh(repo, 'git', '-c', 'user.name=t', '-c', 'user.email=t@t', 'commit', '-qm', msg)
return sh(repo, 'git', 'rev-parse', 'HEAD')
@pytest.fixture
def repos(tmp_path):
repo = tmp_path / 'demo'
repo.mkdir()
sh(repo, 'git', 'init', '-q')
base = commit(repo, {'lib/a.py': LONG + '\n' + SHORT, 'lib/keep.py': UNIQUE.replace('brand_new_thing', 'old_one')},
'base')
head = commit(repo, {
'lib/a.py': LONG + '\n' + SHORT + '\n' + UNIQUE.replace('brand_new_thing', 'added_in_a'),
'app/copy.py': LONG, # exact duplicate > 20 lines -> blocking
'app/small.py': SHORT, # exact duplicate < 20 lines -> advisory
'app/new.py': FRESH, # unique
'app/renamed.py': UNIQUE, # same body as base lib/keep.py old_one -> structural near
'app/geo.js': HAVERSINE_JS, # engine maths by constant
'app/uses.js': "import { distanceKm } from '../engine/v9-geodesy.js';\n" + HAVERSINE_JS.replace('greatCircle', 'local'),
'app/test_geo.py': 'def test_x():\n R = 6371\n import math\n return math.sin(1) * math.cos(2) * R + 1 + 2 + 3\n',
'README.md': 'docs\n',
}, 'head')
eng = tmp_path / 'ventus-grid-engine'
(eng / 'engine').mkdir(parents=True)
sh(eng, 'git', 'init', '-q')
commit(eng, {'engine/v9-geodesy.js': ENGINE_JS}, 'engine')
return {'repo': str(repo), 'base': base, 'head': head, 'engine': str(eng), 'tmp': tmp_path}
def run_newcode(r, *extra):
out = os.path.join(r['tmp'], 'ci-newcode.md')
js = os.path.join(r['tmp'], 'ci-newcode.json')
rc = newcode.main(['--repo', r['repo'], '--base', r['base'], '--graph', '', '--units', '', '--bng', '',
'--engine', r['engine'], '--out', out, '--json', js] + list(extra))
return rc, open(out).read(), json.load(open(js))
def by_name(doc):
return {(u['path'], u['name']): u for u in doc['results'][0]['units']}
@pytest.mark.parametrize('lite', [False, True])
def test_newcode_classes_and_exit(repos, lite):
rc, md, doc = run_newcode(repos, *(['--vedic', '/nonexistent'] if lite else []))
u = by_name(doc)
assert rc == 1, 'exact duplicate over 20 lines must exit 1'
cp = u[('app/copy.py', 'settle_cable_rating')]
assert cp['cls'] == 'duplicate-exact' and cp['exact'] and cp['n_lines'] > 20
assert cp['original'].startswith('demo@%s lib/a.py:' % repos['base'])
assert u[('app/small.py', 'tiny_helper')]['cls'] == 'duplicate-exact'
assert u[('app/new.py', 'post')]['cls'] == 'unique'
rn = u[('app/renamed.py', 'brand_new_thing')]
assert rn['cls'] == 'duplicate-near' and 'lib/keep.py' in rn['original']
geo = u[('app/geo.js', 'greatCircle')]
assert geo['cls'] == 'engine-maths' and 'ventus-grid-engine' in geo['original']
assert u[('app/uses.js', 'local')]['cls'] != 'engine-maths', 'a file that imports the engine is not flagged'
assert u[('app/test_geo.py', 'test_x')]['cls'] != 'engine-maths', 'tests are not flagged'
# only new code: the unchanged functions of lib/a.py are not listed, the added one is
assert ('lib/a.py', 'settle_cable_rating') not in u and ('lib/a.py', 'tiny_helper') not in u
assert u[('lib/a.py', 'added_in_a')]['change'] == 'new'
assert ('lib/keep.py', 'old_one') not in u
assert 'Blocking: exact duplicates over 20 lines' in md and 'Result: FAIL' in md
assert doc['results'][0]['other_files'] == [{'status': 'A', 'path': 'README.md'}]
assert ('vedic' in doc['meta']['extractor']) != lite or not os.path.isdir('/home/claude/vedic-/fingerprints')
def test_changed_function_and_advisory_exit(repos):
head2 = commit(repos['repo'], {'app/copy.py': '# removed\n', 'lib/a.py': LONG.replace('step + 1', 'step + 2') + SHORT},
'tweak')
rc = newcode.main(['--repo', repos['repo'], '--base', repos['head'], '--graph', '', '--units', '', '--bng', '',
'--engine', repos['engine'], '--out', os.path.join(repos['tmp'], 'x.md'),
'--json', os.path.join(repos['tmp'], 'x.json')])
doc = json.load(open(os.path.join(repos['tmp'], 'x.json')))
u = by_name(doc)
assert doc['results'][0]['head'] == head2
assert u[('lib/a.py', 'settle_cable_rating')]['change'] == 'changed'
assert ('lib/a.py', 'tiny_helper') not in u
assert rc == 0, 'no exact duplicate over 20 lines -> advisory exit 0'
def test_base_from_graph_and_parent(repos):
g = {'cut': 'T', 'repos': [{'repo': 'demo', 'commit': repos['base']}]}
b, why = newcode.resolve_base(repos['repo'], 'demo', repos['head'], None, g)
assert b == repos['base'] and why.startswith('build_graph cut T')
b, why = newcode.resolve_base(repos['repo'], 'demo', repos['head'], None, None)
assert b == repos['base'] and 'parent' in why
b, why = newcode.resolve_base(repos['repo'], 'demo', repos['head'], '0' * 40, g)
assert b == repos['base'], 'an all-zero github.event.before falls through to the graph'
def test_index_ignores_self_and_nested_units():
u = {'repo': 'r', 'commit': 'c', 'path': 'p', 'line_from': 10, 'line_to': 20, 'exact_hash': 'h',
'struct_hash': 's', 'n_tokens': 40, 'minhash': [1] * 64, 'blob': 'b'}
idx = newcode.Index()
idx.add(dict(u, line_from=5, line_to=30, exact_hash='other'), 3) # the enclosing unit, same file
assert idx.match(u) is None
idx.add(dict(u, path='q'), 2)
rel, orig, j = idx.match(u)
assert rel == 'exact' and orig['path'] == 'q'
def test_imports_engine_regex():
assert newcode.IMPORTS_ENGINE.search("import { distanceKm } from '../engine/v9-geodesy.js';")
assert newcode.IMPORTS_ENGINE.search("const m = await import('./world/bng.mjs');")
assert not newcode.IMPORTS_ENGINE.search('/* ported from Ventusltd/ventus-grid-engine engine/v9-geodesy.js */')
def test_lite_extractor_js_and_py():
rows = newcode.lite_rows('x.js', HAVERSINE_JS)
assert [r['name'] for r in rows] == ['greatCircle'] and rows[0]['line_from'] == 2
rows = newcode.lite_rows('x.py', LONG)
assert rows[0]['name'] == 'settle_cable_rating' and rows[0]['n_lines'] > 20
# ------------------------------------------------------------------------------------------------ chess gate
def synthetic_graph(n_comm=40):
"""n_comm communities of 3-6 files, each an import chain (separate components, so label propagation keeps them)."""
files, edges = [], []
for k in range(n_comm):
size = 3 + (k % 4)
ids = []
for j in range(size):
fid = len(files)
files.append({'id': fid, 'repo': 'core' if k % 2 == 0 else 'other', 'path': 'c%d/f%d.py' % (k, j),
'lines': 10 + j, 'role': 'transform', 'reachable': True, 'canonical_status': 'unique',
'name_words': ['alpha%d' % k, 'beta%d' % k, 'gamma%d' % k], 'title': 'f%d' % fid})
ids.append(fid)
for a, b in zip(ids, ids[1:]):
edges.append([a, b, 'import', 'x'])
return {'schema': 'explore-build-graph-v1', 'cut': 'SYN', 'files': files, 'edges': edges,
'repos': [{'repo': 'core', 'core': True, 'commit': 'a' * 40}, {'repo': 'other', 'core': False}],
'roles': [{'id': 'transform', 'title': 'Transform', 'colour': '#0f8'}]}
def test_gate_checks_pass_on_synthetic_graph(tmp_path):
g = synthetic_graph()
keep = {}
assert chess_gate.check_perft()['status'] == 'PASS'
b = chess_gate.check_board(g, keep)
assert b['status'] == 'PASS', b
t = chess_gate.check_tournament(keep, 2, 30)
assert t['status'] == 'PASS', t
p = chess_gate.check_page(g, keep, str(tmp_path))
assert p['status'] == 'PASS', p
assert (tmp_path / 'chess' / 'index.html').read_text().lower().startswith('<!doctype html')
def test_board_skip_without_graph():
assert chess_gate.check_board(None, {})['status'] == 'SKIP'
def test_replay_catches_tampering():
g = synthetic_graph()
keep = {}
chess_gate.check_board(g, keep)
chess_gate.check_tournament(keep, 1, 20)
game = keep['games']['games'][0]
by_id = {p['id']: p for p in keep['board']['pieces']}
assert chess_gate.replay(game, by_id, 20) == []
bad = copy.deepcopy(game)
bad['moves'][0]['to'] = 'e5' # a pawn cannot jump three squares
assert 'not legal' in chess_gate.replay(bad, by_id, 20)[0]
bad = copy.deepcopy(game)
bad['moves'][0]['piece'] = 'w-q'
assert 'piece' in chess_gate.replay(bad, by_id, 20)[0]
bad = copy.deepcopy(game)
bad['result'] = {'1-0': '0-1', '0-1': '1-0', '1/2-1/2': '1-0'}[game['result']]
assert 'result' in chess_gate.replay(bad, by_id, 20)[0]
def test_crash_is_reported_as_fail():
r = chess_gate.check_tournament({'board': {'pieces': []}}, 1, 10)
assert r['status'] in ('FAIL', 'PASS') and 'name' in r
def test_release_view_promote_reserve_reinforce(tmp_path):
g = synthetic_graph()
keep = {}
chess_gate.check_board(g, keep)
newcode_doc = {'results': [{
'repo': 'core', 'base': 'a' * 40, 'head': 'b' * 40,
'code_files': ([{'status': 'M', 'path': 'c0/f0.py', 'old_path': None, 'lines': 12, 'new_or_changed_units': 2}]
+ [{'status': 'A', 'path': 'big/n%d.py' % i, 'old_path': None, 'lines': 5,
'new_or_changed_units': 1} for i in range(30)]
+ [{'status': 'A', 'path': 'small/s.py', 'old_path': None, 'lines': 3, 'new_or_changed_units': 1}]),
'units': [{'path': 'big/n0.py', 'cls': 'unique'}, {'path': 'big/n1.py', 'cls': 'duplicate-exact'},
{'path': 'small/s.py', 'cls': 'engine-maths'}]}]}
rel = chess_gate.release_view(newcode_doc, g, keep['board'])
assert [p['folder'] for p in rel['promoted']] == ['big']
assert rel['promoted'][0]['displaces'] == rel['weakest_on_board']['id']
assert [r['folder'] for r in rel['reserve']] == ['small'] and rel['reserve'][0]['engine_maths'] == 1
assert rel['reinforced'] and rel['reinforced'][0]['functions'] == 2 and rel['reinforced'][0]['on_board']
assert '*big@' in rel['notation'] and '+1 reserve,' in rel['notation'] and 'not a legal chess move' in rel['rule']
page = chess_gate.release_html(rel, keep['board'])
assert page.startswith('<!doctype html>') and 'NEW' in page and 'class="scroll"' in page
def test_gate_main_writes_reports(tmp_path, repos):
gpath = tmp_path / 'g.json'
gpath.write_text(json.dumps(synthetic_graph()))
rc = chess_gate.main(['--graph', str(gpath), '--out-dir', str(tmp_path / 'o'), '--games', '1', '--ply-cap', '16'])
assert rc == 0
md = (tmp_path / 'o' / 'ci-chess.md').read_text()
assert '| perft | PASS' in md and 'Result: PASS' in md
WORKFLOW = os.environ.get('PROPOSED_WORKFLOW', '/tmp/vk/ci/workflow.yml')
@pytest.mark.skipif(not os.path.exists(WORKFLOW), reason='proposed workflow not present')
def test_proposed_workflow_is_advisory():
yaml = pytest.importorskip('yaml')
d = yaml.safe_load(open(WORKFLOW))
on = d.get('on', d.get(True))
assert 'push' in on
steps = d['jobs']['newcode-and-chess']['steps']
tools = [s for s in steps if 'python cosmic/tools/explore/ci/' in s.get('run', '')]
assert len(tools) == 2 and all(s.get('continue-on-error') is True for s in tools)
assert any('GITHUB_STEP_SUMMARY' in s.get('run', '') and s.get('if') == 'always()' for s in steps)CI UI Shots
A Python command-line tool in the explore folder of Cosmic that builds site (`build_site`), covering play and UI metrics.
automationcosmic / tools/explore/ci/ui_shots.py · lines 1–143 of 143 · Entry point · pattern build_site (shared by 2 files)
- What it does
- It lists and searches play and UI metrics. Defines 6 functions or classes, including serve, Quiet, log_message, build_site, chromium. Uses libraries argparse, functools, http.server, importlib.util, json. Side effects: changes the web page (DOM); reads or writes files.
- Inputs & outputs
- In: JSON file play-index.json; command-line arguments. Out: JSON file ui-metrics.json.
- Downstream impact
- It is itself an entry point (Python CLI); no other file was found loading it.
- What it achieves
- It is built from the serve step (`serve`), the quiet class (`Quiet`) and the log message helper (`log_message`). UI pass for the CI advice: screenshots + measured issues for the chess page, the release board and Pilot. It accepts `--chess` and `--out`.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- cosmic · tools/explore/ci · Python CLI
- Uses
- argparse, functools, http.server, importlib.util, json, os, shutil, socketserver
- Used by
- none found
- Produces
- serve, build_site, chromium, main
- Defines here
- serve, Quiet, log_message, build_site, chromium, main
- 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/ci/ui_shots.py:1-143 · blob f13ef624c4002e556d39ff655cbbf64229493922 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: unknown · users: none · canonical: unknown
#!/usr/bin/env python3
"""UI pass for the CI advice: screenshots + measured issues for the chess page, the release board and Pilot.
python tools/explore/ci/ui_shots.py --chess DIR_WITH_chess/index.html --out /tmp/vk/ci/shots
Pilot is published exactly as W10's test does (theme/inject.py copy_assets + sync_pilot into a temp site) and
opened with ?offline=1, so no external host is contacted. Viewports: 390x844 (touch, mobile) and 1366x768.
Per page and viewport it writes <name>-<w>x<h>.png (first screen) and -full.png, and ui-metrics.json with:
sideways overflow, tap targets under 44 px (visible, interactive), text under 12 px, console errors, the largest
fixed overlay share of the first screen, and controls without an accessible name.
"""
import argparse
import functools
import http.server
import importlib.util
import json
import os
import shutil
import socketserver
import tempfile
import threading
from pathlib import Path
HERE = Path(__file__).resolve().parent
THEME = HERE.parent / 'theme'
VIEWPORTS = [(390, 844), (1366, 768)]
PROBE = r"""() => {
const vw = innerWidth, vh = innerHeight, out = {};
out.overflowX = document.documentElement.scrollWidth - vw;
const vis = e => { const r = e.getBoundingClientRect(), s = getComputedStyle(e);
return r.width > 0 && r.height > 0 && s.visibility !== 'hidden' && s.display !== 'none' && +s.opacity > 0.05 &&
r.bottom > 0 && r.right > 0 && r.top < vh && r.left < vw; };
const name = e => (e.getAttribute('aria-label') || e.title || e.innerText || e.value || e.alt || '').trim();
const desc = e => (e.id ? '#' + e.id : e.tagName.toLowerCase() + (e.className && typeof e.className === 'string' ? '.' + e.className.trim().split(/\s+/).slice(0,2).join('.') : '')) + ' "' + name(e).slice(0, 24) + '"';
const ctl = [...document.querySelectorAll('a[href],button,input,select,textarea,summary,[role=button],[onclick],[tabindex]:not([tabindex="-1"])')].filter(vis);
out.controls = ctl.length;
out.smallTargets = ctl.map(e => [e, e.getBoundingClientRect()]).filter(([e, r]) => r.width < 44 || r.height < 44)
.map(([e, r]) => desc(e) + ' ' + Math.round(r.width) + 'x' + Math.round(r.height)).slice(0, 25);
out.smallTargetCount = ctl.filter(e => { const r = e.getBoundingClientRect(); return r.width < 44 || r.height < 44; }).length;
out.unnamed = ctl.filter(e => !name(e) && !e.getAttribute('aria-labelledby')).map(desc).slice(0, 15);
const texts = [...document.querySelectorAll('body *')].filter(e => e.childNodes.length && [...e.childNodes].some(n => n.nodeType === 3 && n.textContent.trim()) && vis(e));
const small = texts.filter(e => parseFloat(getComputedStyle(e).fontSize) < 12);
out.smallText = small.length; out.textNodes = texts.length;
out.smallTextSamples = small.slice(0, 8).map(e => desc(e) + ' ' + getComputedStyle(e).fontSize);
let best = 0, bestDesc = '';
for (const e of document.querySelectorAll('body *')) {
const s = getComputedStyle(e); if (s.position !== 'fixed' && s.position !== 'sticky') continue; if (!vis(e)) continue;
const r = e.getBoundingClientRect();
const a = Math.max(0, Math.min(r.right, vw) - Math.max(r.left, 0)) * Math.max(0, Math.min(r.bottom, vh) - Math.max(r.top, 0));
if (a / (vw * vh) > best && a / (vw * vh) < 0.98) { best = a / (vw * vh); bestDesc = desc(e); }
}
out.fixedOverlayShare = Math.round(best * 100) / 100; out.fixedOverlay = bestDesc;
out.title = document.title; out.h1 = (document.querySelector('h1') || {}).innerText || '';
out.docHeightScreens = Math.round(document.documentElement.scrollHeight / vh * 10) / 10;
return out;
}"""
def serve(root):
class Quiet(http.server.SimpleHTTPRequestHandler):
def log_message(self, *a):
pass
handler = functools.partial(Quiet, directory=str(root))
srv = socketserver.ThreadingTCPServer(('127.0.0.1', 0), handler)
srv.daemon_threads = True
threading.Thread(target=srv.serve_forever, daemon=True).start()
return srv, 'http://127.0.0.1:%d/' % srv.server_address[1]
def build_site(chess_dir):
tmp = Path(tempfile.mkdtemp(prefix='ci-ui-'))
spec = importlib.util.spec_from_file_location('inject', THEME / 'inject.py')
inj = importlib.util.module_from_spec(spec)
spec.loader.exec_module(inj)
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'')
pi = tmp / 'theme' / 'play-index.json'
if not pi.exists():
pi.write_text('{}')
if chess_dir and (Path(chess_dir) / 'chess' / 'index.html').exists():
shutil.copytree(Path(chess_dir) / 'chess', tmp / 'chess')
if chess_dir and (Path(chess_dir) / 'release-board.html').exists():
shutil.copy(Path(chess_dir) / 'release-board.html', tmp / 'release-board.html')
return tmp
def chromium():
for c in sorted(Path('/opt/pw-browsers').glob('chromium-*/chrome-linux64/chrome')):
return str(c)
return None
def main(argv=None):
ap = argparse.ArgumentParser(description=__doc__.split('\n')[0])
ap.add_argument('--chess', default='/tmp/vk/ci', help='folder holding chess/index.html and release-board.html')
ap.add_argument('--out', default='/tmp/vk/ci/shots')
a = ap.parse_args(argv)
from playwright.sync_api import sync_playwright
out = Path(a.out)
out.mkdir(parents=True, exist_ok=True)
site = build_site(a.chess)
srv, base = serve(site)
pages = [('chess', 'chess/index.html'), ('release', 'release-board.html'), ('pilot', 'pilot/index.html?offline=1')]
metrics = {}
ch = chromium()
with sync_playwright() as p:
b = p.chromium.launch(**({'executable_path': ch} if ch else {}))
for name, path in pages:
if not (site / path.split('?')[0]).exists():
continue
for w, h in VIEWPORTS:
ctx = b.new_context(viewport={'width': w, 'height': h}, has_touch=w < 900, is_mobile=w < 900)
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(base + path, wait_until='load')
pg.wait_for_timeout(1500)
stem = '%s-%dx%d' % (name, w, h)
pg.screenshot(path=str(out / (stem + '.png')))
pg.screenshot(path=str(out / (stem + '-full.png')), full_page=True)
m = pg.evaluate(PROBE)
m['console_errors'] = errs[:10]
m['external_requests'] = sorted(set(ext))[:10]
metrics[stem] = m
ctx.close()
b.close()
srv.shutdown()
shutil.rmtree(site, ignore_errors=True)
(out / 'ui-metrics.json').write_text(json.dumps(metrics, indent=1))
for k, m in metrics.items():
print('%-22s overflowX=%s small targets %d/%d small text %d/%d overlay %.2f errors %d' % (
k, m['overflowX'], m['smallTargetCount'], m['controls'], m['smallText'], m['textNodes'],
m['fixedOverlayShare'], len(m['console_errors'])))
return 0
if __name__ == '__main__':
raise SystemExit(main())