In this section
- Props storage · cosmic / tools/explore/periodic/props.py lines 461–534
- Test Feed test · cosmic / tools/explore/periodic/test_feed.py lines 1–319
- Test Props test · cosmic / tools/explore/periodic/test_props.py lines 1–139
Props
A Python command-line tool in the periodic folder of Cosmic that reads build graph, identity, elements and periodic, using SHA-256. It loads ctx (`load_ctx`) and computes element (`compute_element`).
storagecosmic / tools/explore/periodic/props.py · lines 461–534 of 534 (continued from section 1122) · Entry point · pattern evidence_key (shared by 2 files)
- What it does
- It loads build graph, identity, elements and periodic. Defines 28 functions or classes, including _read_json, stamp_time, masked, load_ctx, dev_ctx. Uses libraries collections, datetime, hashlib, json, math. Side effects: reads or writes files.
- Inputs & outputs
- In: JSON file build_graph.json; JSON file identity-files.json; JSON file elements.json; JSON file periodic.json; JSON file props.json; command-line arguments. Out: JSON file.
- Downstream impact
- Used directly by 3 files: Extras (cosmic); Exp (cosmic); Test Props (cosmic). Reached from 3 other entry points, including Ship (cosmic); Test Extras (cosmic); Test Ship (cosmic).
- What it achieves
- Measurable PROPERTIES of every code element (PHYSICIST, QUANTA-19). It accepts `--site`, `--graph` and `--periodic`.
- Why it matters
- Imported by Exp. Run by Extras. Checked by Test Props.
- Application
- cosmic · tools/explore/periodic · Python CLI
- Uses
- collections, datetime, hashlib, json, math, os, re, sys
- Used by
- run by Extras (script call), imported by Exp (sys.path import), imported by Test Props (import)
- Produces
- stamp_time, masked, load_ctx, dev_ctx, element_members, file_mass, file_valence, version_family, mass, valence, in_reach, electronegativity
- Defines here
- compute_all, digest, 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/periodic/props.py:461-534 · blob 77ab3670770b6dd5a8cf72f344230dae9c57c307 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: unknown · users: none · canonical: supporting_data
'category': el['category'], 'analogy': el.get('analogy'), 'status': el.get('status'),
'period': el.get('period'), 'group': el.get('group'), 'members': len(ids), 'file_ids': list(ids),
'mass': mass(ctx, ids), 'valence': valence(ctx, ids), 'in_degree': d, 'reach': r,
'electronegativity': electronegativity(ctx, ids),
'isotopes': iso['isotopes'], 'near_copies': iso['near_copies'], 'verbatim_copies': iso['verbatim_copies'],
'versions': iso['versions'], 'relatives': iso['relatives'], 'near_copy_ids': iso['near_copy_ids'][:200],
'half_life_days': half_life(ctx, ids), 'stability': st, 'stability_basis': basis,
'reactivity': reactivity(ctx, ids), 'spectrum': spec,
'dominant_role': ctx['roles'][max(range(len(spec)), key=lambda k: (spec[k], -k))] if ids else None,
'repos': sorted({ctx['files'][i]['repo'] for i in ids}),
'evidence': [evidence_key(ctx, i) for i in ids[:12]],
}
def compute_all(ctx):
els = element_members(ctx)
rows = [compute_element(ctx, e) for e in els]
mx = max([r['electronegativity'] for r in rows] or [0]) or 1
for r in rows:
r['electronegativity_pauling'] = round(0.7 + 3.3 * r['electronegativity'] / mx, 3)
return {
'schema': SCHEMA, 'rules': RULES, 'generated_by': 'tools/explore/periodic/props.py (QUANTA-19)',
'graph_cut': ctx['graph_cut'], 'graph_path': ctx['graph_path'], 'identity_graph_sha256': ctx['identity_graph_sha'],
'membership_source': els[0]['source'] if els else None, 'periodic_path': ctx['periodic_path'],
'inputs': {k: (os.path.basename(v) if v else None) for k, v in ctx['inputs'].items()},
'not_measured': [n for n, ok in (('near_copies, verbatim_copies, relatives (no identity)', ctx['inputs']['identity']),
('versions, half_life_days (no estate blobs)', ctx['inputs']['blobs'])) if not ok],
'roles': ctx['roles'], 'properties': PROPERTIES,
'counts': {'elements': len(rows), 'with_members': sum(1 for r in rows if r['members']),
'member_files': len({i for r in rows for i in r['file_ids']})},
'elements': {r['symbol']: r for r in rows},
}
def digest(obj):
return hashlib.sha256(json.dumps(obj, sort_keys=True).encode()).hexdigest()
def main(argv):
import argparse
ap = argparse.ArgumentParser(description='Element properties from build_graph.json (+ optional extras).')
ap.add_argument('--site', help='built explore-code directory (graph = <site>/build_graph.json)')
ap.add_argument('--graph', help='build_graph.json (default <site>/build_graph.json)')
ap.add_argument('--periodic', help='periodic.json from map.py (membership); else catalogue/identity blocks; else repo x role')
ap.add_argument('--identity', help='identity-files.json or identity.json (near copies, verbatim copies, blocks)')
ap.add_argument('--catalogue', help='elements/catalogue/elements.json (used when no periodic.json)')
ap.add_argument('--blobs', help='estate-blobs.tsv: blob<TAB>repo<TAB>path for every estate path (versions, half-life)')
ap.add_argument('--src', help='folder of clones; fills --catalogue from <src>/elements when not given')
ap.add_argument('--out', help='output props.json (default <site>/periodic/props.json, else ./props.json)')
ap.add_argument('--dev', action='store_true', help='use the team machine defaults (/tmp/vk...) for every input not given')
a = ap.parse_args(argv)
if a.dev:
for k, v in DEFAULTS.items():
if getattr(a, k, None) is None and os.path.exists(v):
setattr(a, k, v)
graph = a.graph or (os.path.join(a.site, 'build_graph.json') if a.site else None)
if not graph:
ap.error('give --graph or --site')
if not a.catalogue and a.src and os.path.exists(os.path.join(a.src, 'elements', 'catalogue', 'elements.json')):
a.catalogue = os.path.join(a.src, 'elements', 'catalogue', 'elements.json')
out = a.out or (os.path.join(a.site, 'periodic', 'props.json') if a.site else 'props.json')
ctx = load_ctx(graph, a.identity, a.catalogue, a.periodic, a.blobs)
res = compute_all(ctx)
res['digest'] = digest(res['elements'])
os.makedirs(os.path.dirname(os.path.abspath(out)), exist_ok=True)
with open(out, 'w', encoding='utf-8') as fh:
json.dump(res, fh, indent=1, sort_keys=True)
print('wrote %s: %d elements (%d with members, %d files), membership %s, digest %s'
% (out, res['counts']['elements'], res['counts']['with_members'], res['counts']['member_files'],
res['membership_source'], res['digest'][:16]))
if __name__ == '__main__':
main(sys.argv[1:])Test Feed
A test in the periodic folder of Cosmic that checks Feed.
testcosmic / tools/explore/periodic/test_feed.py · lines 1–319 of 319 · Not reached from any entry point (candidate for review) · pattern built (shared by 3 files)
- What it does
- It tests its inputs. Defines 20 functions or classes, including graph_doc, periodic_doc, props_doc, built, test_outputs_exist. Uses libraries __future__, functools, http.server, json, os. Side effects: changes the web page (DOM); reads or writes files.
- Inputs & outputs
- In: JSON file EARTH_KM.json; JSON file p.json; JSON file q.json; JSON file g.json; JSON file element-index.json; JSON file cards.json; JSON file fixture-periodic.json; JSON file fixture-props.json. Out: JSON file p.json; JSON file q.json; JSON file g.json; JSON file build_graph.json.
- What it achieves
- It is built from the graph doc helper (`graph_doc`), the periodic doc helper (`periodic_doc`) and the props doc helper (`props_doc`). Tests for `feed.py` (periodic table -> Explore Code). It writes `../index.html`.
- Why it matters
- Guards the behaviour of Feed.
- Application
- cosmic · tools/explore/periodic · test
- Uses
- Feed (import), __future__, functools, http.server, json, os, re, shutil, sys
- Used by
- none found
- Produces
- graph_doc, periodic_doc, props_doc, built, test_outputs_exist, test_candidate_never_numbered, test_element_index_hook, test_element_page_card, test_index_page, test_no_cdn_no_absolute_paths, test_llms_shard, test_idempotent_and_stale_pages_removed
- Defines here
- graph_doc, periodic_doc, props_doc, built, test_outputs_exist, test_candidate_never_numbered, test_element_index_hook, test_element_page_card, test_index_page, test_no_cdn_no_absolute_paths, test_llms_shard, test_idempotent_and_stale_pages_removed, test_no_furnace_no_link, test_fixture_and_cli, test_analogy_and_chem_table, served, new_page, test_table_page, test_element_pages_and_deeplinks, test_noscript
- 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/periodic/test_feed.py:1-319 · blob 0262fa13a9288d5ca7521ffe28c08c7864bc233f · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: unknown · users: none · canonical: unreached_review
"""Tests for feed.py (periodic table -> Explore Code). Run: python3 -m pytest -q tools/explore/periodic/test_feed.py
Unit tests use small synthetic inputs. The browser tests (Playwright, skipped when it or the built site is missing)
copy /tmp/site8/explore-code to /tmp/vk/periodic/site/explore-code, run feed.py on it with whatever periodic.json /
props.json / furnace gallery exist (fixture otherwise) and check 390x844, 820x1180, 1366x768 and 1920x1080.
"""
from __future__ import annotations
import functools
import http.server
import json
import os
import re
import shutil
import sys
import threading
from pathlib import Path
import pytest
HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
import feed # noqa: E402
SITE_SRC = Path(os.environ.get('PERIODIC_SITE_SRC', '/tmp/site8/explore-code'))
SITE_COPY = Path(os.environ.get('PERIODIC_SITE_COPY', '/tmp/vk/periodic/site'))
VIEWPORTS = [(390, 844), (820, 1180), (1366, 768), (1920, 1080)]
# ----------------------------------------------------------------------------------------- synthetic inputs
def graph_doc():
return {'repos': [{'repo': 'r1', 'commit': 'a' * 40}],
'files': [{'id': 0, 'repo': 'r1', 'path': 'engine/geo-core.js', 'section': 3, 'block': 2, 'title': 'Geo core', 'lines': 40},
{'id': 1, 'repo': 'r1', 'path': 'app/page.js', 'section': 7, 'block': 1, 'title': 'Page', 'lines': 9},
{'id': 2, 'repo': 'r1', 'path': 'x/y.py', 'section': 7, 'block': 2, 'title': 'Y', 'lines': 3}]}
def periodic_doc():
return {
'schema': 'explore-periodic-v1', 'cut': '2026-12-05T15:19:52+00:00',
'axes': {'groups': [{'id': 'geodesy', 'title': 'Geodesy', 'colour': '#00ffff'},
{'id': 'render', 'title': 'Render', 'colour': '#ff6666'}],
'periods': [{'n': 1, 'id': 'constant', 'title': 'Constants'}, {'n': 5, 'id': 'engine', 'title': 'Engines'}]},
'analogue_rules': [{'id': 'halogen', 'text': 'competing values -> halogens'}],
'elements': [
{'key': 'block:Gc', 'status': 'numbered', 'number': 13, 'symbol': 'Gc', 'proposed_symbol': None, 'name': 'geo-core.js',
'title': 'Geo core', 'group': 'geodesy', 'period': 5, 'state': 'SETTLED', 'star_family': 'engine',
'files': [0], 'file_count': 1, 'lines': 40, 'valence': 2,
'evidence': ['r1@aaaaaaaa engine/geo-core.js:1-40'], 'evidence_keys': ['block:Gc'],
'analogue': {'Z': 6, 'symbol': 'C', 'name': 'Carbon', 'rule': 'carbon', 'basis': {}}},
{'key': 'block:Ek', 'status': 'numbered', 'number': 2, 'symbol': 'Ek', 'name': 'EARTH_KM', 'group': 'geodesy',
'period': 1, 'state': 'UNSETTLED', 'competing_values': [{'value': '6371.0088', 'files': 4}, {'value': '6378.137', 'files': 2}],
'files': [], 'evidence': ['star-maker@f65c2f38 logic/EARTH_KM.json'], 'evidence_keys': [],
'analogue': {'Z': 35, 'symbol': 'Br', 'name': 'Bromine', 'rule': 'halogen'}},
{'key': 'candidate:PAGE', 'status': 'candidate', 'number': None, 'symbol': None, 'proposed_symbol': '*Pg',
'name': 'PAGE', 'group': 'render', 'period': 5, 'state': None, 'files': [1, 2], 'evidence': [], 'evidence_keys': []},
]}
def props_doc():
return {'schema': 'explore-periodic-props-v1',
'properties': [{'key': 'mass', 'label': 'Mass', 'unit': 'lines'}, {'key': 'stability', 'label': 'Stability', 'unit': ''},
{'key': 'spectrum', 'label': 'Spectrum', 'unit': 'shares'}],
'elements': {'Gc': {'mass': 40, 'stability': 'settled', 'spectrum': [1.0, 0.0]}, 'Ek': {'mass': 0, 'stability': 'unsettled'}}}
@pytest.fixture()
def built(tmp_path):
(tmp_path / 'p.json').write_text(json.dumps(periodic_doc()))
(tmp_path / 'q.json').write_text(json.dumps(props_doc()))
(tmp_path / 'g.json').write_text(json.dumps(graph_doc()))
fur = tmp_path / 'furnace'
fur.mkdir()
(fur / 'index.html').write_text('<!doctype html><title>f</title><a href="../index.html">back</a>')
(fur / 'run.py').write_text('print(1)')
out = tmp_path / 'site' / 'periodic'
res = feed.feed(tmp_path / 'site', out, tmp_path / 'p.json', tmp_path / 'q.json', tmp_path / 'g.json', fur, 'https://x.test/explore-code/')
return out, res
# ----------------------------------------------------------------------------------------- unit tests
def test_outputs_exist(built):
out, res = built
for name in ('index.html', 'Gc.html', 'Ek.html', 'candidate-Pg.html', 'llms-periodic.txt', 'element-index.json',
'cards.json', 'periodic.css', 'periodic.js', 'furnace/index.html'):
assert (out / name).exists(), name
assert not (out / 'furnace' / 'run.py').exists()
assert res['elements'] == 3 and res['furnace'] is True and res['fixture'] is False
def test_candidate_never_numbered(built):
out, _ = built
idx = json.loads((out / 'element-index.json').read_text())
assert idx['elements']['*Pg']['n'] is None and idx['elements']['*Pg']['state'] == 'candidate'
page = (out / 'candidate-Pg.html').read_text()
assert 'CANDIDATE' in page and '<dt>number</dt><dd>CANDIDATE</dd>' in page
assert idx['elements']['Gc']['n'] == 13 and idx['elements']['Ek']['state'] == 'unsettled'
def test_element_index_hook(built):
out, _ = built
idx = json.loads((out / 'element-index.json').read_text())
assert idx['schema'] == feed.SCHEMA_INDEX and idx['page'] == 'periodic/index.html'
assert idx['files'] == {'0': ['Gc'], '1': ['*Pg'], '2': ['*Pg']}
assert idx['sections'] == {'3': ['Gc'], '7': ['*Pg']}
assert idx['elements']['Gc']['url'] == 'periodic/Gc.html' and idx['elements']['Gc']['color'] == '#00ffff'
assert idx['elements']['Gc']['analogy'] == 'C'
def test_element_page_card(built):
out, _ = built
gc = (out / 'Gc.html').read_text()
assert 'href="../s/0003.html#f2"' in gc and 'r1@aaaaaaaa engine/geo-core.js:1-40' in gc and 'block:Gc' in gc
assert 'like Carbon (C, Z=6)' in gc and '<th scope="row">Mass</th><td>40 lines</td>' in gc
assert 'Spectrum' not in gc # list-valued property is not a scalar
ek = (out / 'Ek.html').read_text()
assert 'Unsettled values, side by side' in ek and '6371.0088' in ek and '6378.137' in ek and '4 files' in ek
assert 'competing values -> halogens' in ek
def test_index_page(built):
out, _ = built
s = (out / 'index.html').read_text()
assert '<noscript>' in s and 'data-view="chem"' in s and 'href="furnace/index.html"' in s
assert '<option value="p:mass">Mass</option>' in s and '<option value="p:map:valence">' in s
data = json.loads(re.search(r'id="pt-data" type="application/json">(.*?)</script>', s).group(1))
assert [e[0] for e in data['elements']] == ['Gc', 'Ek', '*Pg'] and data['pv']['mass'] == [40, 0, None]
assert 'href="Gc.html" data-sym="Gc"' in s # tiles work without JS
def test_no_cdn_no_absolute_paths(built):
out, _ = built
for p in out.rglob('*'):
if p.suffix in ('.html', '.js', '.css'):
t = p.read_text()
assert not re.search(r'(src|href)="(https?:)?//', t), p
assert '/tmp/' not in t, p
def test_llms_shard(built):
out, _ = built
t = (out / 'llms-periodic.txt').read_text()
assert t.startswith('# Periodic table of the code estate')
assert 'https://x.test/explore-code/periodic/Gc.html' in t and 'number: CANDIDATE' in t
assert 'file: r1/engine/geo-core.js -> https://x.test/explore-code/s/0003.html#f2' in t
assert 'furnace/index.html' in t
def test_idempotent_and_stale_pages_removed(built, tmp_path):
out, _ = built
(out / 'Zz.html').write_text('old')
before = {p.name: p.read_bytes() for p in out.glob('*.*') if p.name != 'Zz.html'}
feed.feed(tmp_path / 'site', out, tmp_path / 'p.json', tmp_path / 'q.json', tmp_path / 'g.json', tmp_path / 'furnace')
after = {p.name: p.read_bytes() for p in out.glob('*.*')}
assert 'Zz.html' not in after
assert {k: v for k, v in after.items() if k != 'llms-periodic.txt'} == {k: v for k, v in before.items() if k != 'llms-periodic.txt'}
def test_no_furnace_no_link(tmp_path):
(tmp_path / 'p.json').write_text(json.dumps(periodic_doc()))
out = tmp_path / 'o'
res = feed.feed(None, out, tmp_path / 'p.json', None, None, tmp_path / 'missing')
assert res['furnace'] is False and 'furnace/index.html' not in (out / 'index.html').read_text()
def test_fixture_and_cli(tmp_path):
out = tmp_path / 'site' / 'periodic'
(tmp_path / 'site').mkdir()
(tmp_path / 'site' / 'build_graph.json').write_text(json.dumps(graph_doc()))
assert feed.main(['--site', str(tmp_path / 'site'), '--periodic', str(feed.PAGE / 'fixture-periodic.json'),
'--props', str(feed.PAGE / 'fixture-props.json'), '--furnace', str(tmp_path / 'none')]) == 0
s = (out / 'index.html').read_text()
assert 'Fixture data' in s and (out / 'Ek.html').exists() and (out / 'Dt.html').exists()
idx = json.loads((out / 'element-index.json').read_text())
assert len(idx['elements']) == 47 and idx['elements']['Ek']['n'] == 2
def test_analogy_and_chem_table():
assert feed.norm_analogy('like hydrogen')['sym'] == 'H'
assert feed.norm_analogy({'Z': 26, 'rule': 'x'})['name'] == 'Iron'
assert feed.norm_analogy(None) is None
c = {x['sym']: x for x in feed.CHEM}
assert len(feed.CHEM) == 118 and c['Og']['z'] == 118
assert (c['Fe']['group'], c['Fe']['period']) == (8, 4) and (c['Hf']['group'], c['Hf']['period']) == (4, 6)
assert c['La']['row'] == 9 and c['Ac']['row'] == 10
# ----------------------------------------------------------------------------------------- browser tests
pw = pytest.importorskip('playwright.sync_api')
@pytest.fixture(scope='module')
def served():
if not (SITE_SRC / 'build_graph.json').exists():
pytest.skip('built site missing')
dst = SITE_COPY / 'explore-code'
if dst.exists():
shutil.rmtree(dst)
shutil.copytree(SITE_SRC, dst)
assert feed.main(['--site', str(dst)]) == 0
handler = functools.partial(http.server.SimpleHTTPRequestHandler, directory=str(SITE_COPY))
handler.func.log_message = lambda *a, **k: None
srv = http.server.ThreadingHTTPServer(('127.0.0.1', 0), handler)
threading.Thread(target=srv.serve_forever, daemon=True).start()
with pw.sync_playwright() as p:
browser = p.chromium.launch()
yield browser, f'http://127.0.0.1:{srv.server_address[1]}/explore-code/periodic/'
browser.close()
srv.shutdown()
SMALL_TARGETS = '''() => {
const bad = [];
document.querySelectorAll('a[href], button, select, input, summary').forEach(el => {
if (el.closest('noscript')) return;
const r = el.getBoundingClientRect(), st = getComputedStyle(el);
if (!r.width || !r.height || st.visibility === 'hidden') return;
if (r.width < 44 || r.height < 44) bad.push((el.textContent || el.tagName).trim().slice(0, 30) + ' ' + Math.round(r.width) + 'x' + Math.round(r.height));
});
return bad;
}'''
SIDEWAYS = '() => document.scrollingElement.scrollWidth - window.innerWidth'
def new_page(browser, w, h):
page = browser.new_page(viewport={'width': w, 'height': h}, has_touch=w < 1000, is_mobile=w < 600)
errors = []
page.on('console', lambda m: errors.append(m.text) if m.type == 'error' else None)
page.on('pageerror', lambda e: errors.append(str(e)))
return page, errors
@pytest.mark.parametrize('w,h', VIEWPORTS)
def test_table_page(served, w, h):
browser, url = served
page, errors = new_page(browser, w, h)
page.goto(url + 'index.html')
page.wait_for_selector('#pt-legend span')
assert page.evaluate(SIDEWAYS) <= 0
frame = page.evaluate("(() => { const f = document.getElementById('pt-frame'); return [f.scrollWidth, f.clientWidth, getComputedStyle(f).overflowX]; })()")
assert frame[2] == 'auto'
if w < 800:
assert frame[0] > frame[1] # the table scrolls inside its own frame on a phone
assert page.evaluate(SMALL_TARGETS) == []
# colour switch: property colouring changes tile fills
first = page.locator('#pt-estate .pt-el').first
c0 = first.evaluate('e => e.style.getPropertyValue("--fill")')
opts = page.eval_on_selector_all('#pt-color option', 'os => os.map(o => o.value)')
prop = next(o for o in opts if o.startswith('p:'))
page.select_option('#pt-color', prop)
assert page.locator('#pt-legend span').count() >= 2
page.select_option('#pt-color', 'state')
assert any(w_ in page.inner_text('#pt-legend') for w_ in ('settled', 'numbered', 'candidate'))
assert c0 # group colour was set before switching
page.select_option('#pt-color', 'group')
# card: tap an element that has files
sym = page.evaluate("(() => { const d = JSON.parse(document.getElementById('pt-data').textContent); const e = d.elements.find(x => x[9] > 0); return e[0]; })()")
page.locator(f'#pt-estate .pt-el[data-sym="{sym}"]').scroll_into_view_if_needed()
page.locator(f'#pt-estate .pt-el[data-sym="{sym}"]').tap() if w < 1000 else page.locator(f'#pt-estate .pt-el[data-sym="{sym}"]').click()
page.wait_for_selector('#pt-card:not([hidden]) .pt-file')
body = page.inner_text('#pt-card-body')
for word in ('number', 'state', 'Evidence keys', 'Files ('):
assert word in body
href = page.get_attribute('#pt-card .pt-file', 'href')
assert re.fullmatch(r'\.\./s/\d{4}\.html#f\d+', href)
assert page.evaluate(SMALL_TARGETS) == []
page.keyboard.press('Escape')
assert page.locator('#pt-card').is_hidden()
# chemical analogy view
chem = page.locator('[data-view=chem]')
if chem.is_enabled():
chem.click()
assert page.locator('#pt-chem .pt-z').count() == 118
z = page.locator('#pt-chem button.pt-z').first
z.scroll_into_view_if_needed()
z.click()
page.wait_for_selector('#pt-card:not([hidden]) .pt-cardtiles')
page.click('#pt-x')
assert page.evaluate(SMALL_TARGETS) == []
page.click('[data-view=estate]')
assert page.evaluate(SIDEWAYS) <= 0
assert errors == []
page.close()
@pytest.mark.parametrize('w,h', [VIEWPORTS[0], VIEWPORTS[2]])
def test_element_pages_and_deeplinks(served, w, h):
browser, url = served
page, errors = new_page(browser, w, h)
idx = json.loads((SITE_COPY / 'explore-code/periodic/element-index.json').read_text())
unsettled = next((s for s, e in idx['elements'].items() if e['state'] == 'unsettled'), None)
some_file = next(iter(idx['files']))
for sym in filter(None, [unsettled, idx['files'][some_file][0]]):
page.goto(url.rsplit('periodic/', 1)[0] + idx['elements'][sym]['url'])
assert page.evaluate(SIDEWAYS) <= 0
assert page.evaluate(SMALL_TARGETS) == []
assert 'Evidence keys' in page.inner_text('main')
if unsettled:
page.goto(url + 'index.html#' + unsettled)
page.wait_for_selector('#pt-card:not([hidden]) .pt-val')
assert page.locator('#pt-card .pt-val').count() >= 2
page.goto(url + 'index.html?file=' + some_file)
page.wait_for_selector('#pt-card:not([hidden])')
assert idx['files'][some_file][0] in page.inner_text('#pt-card-h')
if (SITE_COPY / 'explore-code/periodic/furnace/index.html').exists():
page.goto(url + 'index.html')
assert page.locator('a[href="furnace/index.html"]').count() >= 1
assert errors == []
page.close()
def test_noscript(served):
browser, url = served
ctx = browser.new_context(java_script_enabled=False, viewport={'width': 390, 'height': 844})
page = ctx.new_page()
page.goto(url + 'index.html')
assert page.locator('noscript').count() == 1
assert page.locator('#pt-estate a.pt-el').count() >= 40 # every tile is a link
ctx.close()Test Props
A test in the periodic folder of Cosmic that checks Props. It is built from the tiny graph helper (`tiny_graph`) and the tctx step (`tctx`).
testcosmic / tools/explore/periodic/test_props.py · lines 1–139 of 139 · Not reached from any entry point (candidate for review) · pattern tiny_graph (shared by 5 files)
- What it does
- It tests its inputs. Defines 12 functions or classes, including tiny_graph, tctx, test_mass_valence, test_electronegativity_and_reach, test_reactivity_and_spectrum. Uses libraries json, os, subprocess, sys, pytest. Side effects: changes the web page (DOM); reads or writes files; starts processes.
- Inputs & outputs
- In: JSON file build_graph.json; JSON file p.json; JSON file metrics.json.
- What it achieves
- Tests for `props.py` and `experiments/exp.py` (QUANTA-19). python3 -m pytest -q `test_props.py`.
- Why it matters
- Guards the behaviour of Props.
- Application
- cosmic · tools/explore/periodic · test
- Uses
- Props (import), json, os, subprocess, sys, pytest
- Used by
- none found
- Produces
- tiny_graph, tctx, test_mass_valence, test_electronegativity_and_reach, test_reactivity_and_spectrum, test_versions_half_life_stability, test_graph_only_fallback, test_cli_graph_only, test_stamp_time, test_real_props_deterministic, test_metrics_written, test_pages_playwright
- Defines here
- tiny_graph, tctx, test_mass_valence, test_electronegativity_and_reach, test_reactivity_and_spectrum, test_versions_half_life_stability, test_graph_only_fallback, test_cli_graph_only, test_stamp_time, test_real_props_deterministic, test_metrics_written, test_pages_playwright
- 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/periodic/test_props.py:1-139 · blob 14633a86a7fd81effea9ed0a3e2d2204cbf2727b · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, process · domain stage: unknown · users: none · canonical: unreached_review
"""Tests for props.py and experiments/exp.py (QUANTA-19). python3 -m pytest -q test_props.py"""
import json
import os
import subprocess
import sys
import pytest
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
import props # noqa: E402
EXP_DIR = '/tmp/vk/periodic/experiments'
PAGES = ['index', 'reactions', 'decay', 'isotopes', 'periodicity', 'barcode']
def tiny_graph():
files = []
for i, (repo, path, role, lines) in enumerate([
('a', 'lib/core.js', 'transform', 100), ('a', 'app/202601011200/page.html', 'render', 50),
('b', 'x/use.js', 'render', 30), ('b', 'x/use2.js', 'test', 20), ('c', 'z.py', 'ingest', 10)]):
files.append({'id': i, 'repo': repo, 'path': path, 'role': role, 'lines': lines, 'imports': [],
'imports_external': [], 'defines': []})
files[1]['imports'] = [0]
files[2]['imports'] = [0]
files[3]['imports'] = [2]
files[0]['defines'] = ['f', 'g']
files[0]['imports_external'] = ['node:fs']
edges = [[1, 0, 'import', ''], [2, 0, 'import', ''], [3, 2, 'import', ''], [4, 0, 'comment-url', '']]
return {'cut': 't', 'files': files, 'edges': edges, 'roles': [{'id': r} for r in ['ingest', 'transform', 'render', 'test']],
'repos': [{'repo': r, 'commit': 'c' * 40} for r in 'abc']}
@pytest.fixture
def tctx(tmp_path):
blobs = tmp_path / 'blobs.tsv'
blobs.write_text('b1\ta\tapp/202601011200/page.html\nb0\ta\tapp/202601010000/page.html\nb2\ta\tapp/202512310000/page.html\n')
return props.load_ctx(graph='tiny', g=tiny_graph(), blobs=str(blobs))
def test_mass_valence(tctx):
assert props.mass(tctx, [0, 1]) == 150
assert props.valence(tctx, [0]) == 1 + 2 # node:fs + f, g
assert props.valence(tctx, [1]) == 1 # imports file 0 (outside the element)
assert props.valence(tctx, [0, 1]) == 3 # internal import not counted
def test_electronegativity_and_reach(tctx):
assert props.in_reach(tctx, [0]) == (2, 3) # comment-url edge excluded
assert props.electronegativity(tctx, [0]) == round(0.5 * 1.584962500721156 + 0.5 * 2, 4)
assert props.electronegativity(tctx, [4]) == 0
def test_reactivity_and_spectrum(tctx):
assert props.reactivity(tctx, [0]) == 1 # only 2->0 crosses repos (1->0 same repo, 4->0 excluded)
assert props.spectrum(tctx, [0, 1]) == [0.0, 0.5, 0.5, 0.0]
def test_versions_half_life_stability(tctx):
fam = props.version_family(tctx, 1)
assert [p for _, p, _ in fam] == ['app/202512310000/page.html', 'app/202601010000/page.html', 'app/202601011200/page.html']
assert props.half_life(tctx, [1]) == 0.75 # gaps 1.0 d and 0.5 d -> median 0.75
assert props.isotopes(tctx, [1])['versions'] == 2
assert props.stability(tctx, [1])[0] == 'unsettled'
assert props.stability(tctx, [0]) == ('settled', 'no drift, no disagreeing copies, no versions')
assert props.stability(tctx, [1], 'SETTLED')[0] == 'settled'
def test_graph_only_fallback(tctx):
res = props.compute_all(tctx)
assert res['membership_source'].startswith('build_graph')
assert res['counts']['member_files'] == 5
assert any('identity' in x for x in res['not_measured'])
def test_cli_graph_only(tmp_path):
g = tmp_path / 'build_graph.json'
g.write_text(json.dumps(tiny_graph()))
out = tmp_path / 'p.json'
subprocess.run([sys.executable, os.path.join(HERE, 'props.py'), '--graph', str(g), '--out', str(out)], check=True)
d = json.loads(out.read_text())
assert d['schema'] == props.SCHEMA and d['inputs']['identity'] is None and len(d['elements']) == 5
def test_stamp_time():
assert props.stamp_time('x/202609051921/y.js').strftime('%Y%m%d%H%M') == '202609051921'
assert props.stamp_time('x/20260905/y.js').strftime('%Y%m%d') == '20260905'
assert props.stamp_time('x/y.js') is None
real = pytest.mark.skipif(not os.path.exists(props.DEFAULTS['graph']), reason='team machine inputs absent')
@real
def test_real_props_deterministic():
a = props.compute_all(props.dev_ctx())
b = props.compute_all(props.dev_ctx())
assert props.digest(a['elements']) == props.digest(b['elements'])
assert {p['key'] for p in a['properties']} >= {'mass', 'valence', 'electronegativity', 'isotopes', 'half_life_days',
'stability', 'reactivity', 'spectrum'}
for e in a['elements'].values():
assert e['stability'] in ('settled', 'unsettled')
assert 0.7 <= e['electronegativity_pauling'] <= 4.0
if e['members']:
assert abs(sum(e['spectrum']) - 1) < 0.01 and e['evidence']
@real
def test_metrics_written():
m = json.load(open(os.path.join(EXP_DIR, 'metrics.json')))
assert set(m['experiments']) == {'reactions', 'decay', 'isotopes', 'periodicity', 'barcode'}
for r in m['experiments'].values():
assert r['verdict'] in ('reveals', 'marginal', 'no') and r['basis']
@real
@pytest.mark.parametrize('vp', [(390, 844), (1366, 768)])
def test_pages_playwright(vp):
pw = pytest.importorskip('playwright.sync_api')
with pw.sync_playwright() as p:
b = p.chromium.launch()
pg = b.new_page(viewport={'width': vp[0], 'height': vp[1]})
errs, net = [], []
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: net.append(r.url) if not r.url.startswith(('file:', 'data:')) else None)
for n in PAGES:
pg.goto('file://%s/%s.html' % (EXP_DIR, n))
pg.wait_for_timeout(250)
assert pg.evaluate('document.documentElement.scrollWidth') <= vp[0], n
if n != 'index':
assert pg.evaluate("document.getElementById('cv').height") > 50, n
box = pg.locator('#cv').bounding_box()
pg.mouse.move(box['x'] + box['width'] / 2, box['y'] + box['height'] / 3)
if True:
pg.goto('file://%s/periodicity.html' % EXP_DIR)
pg.click('#ctl button[data-k=isotopes]')
b.close()
assert errs == [] and net == []