In this section
- Clarity render · cosmic / tools/explore/translator/clarity.py lines 494–577
- Glyphs render · cosmic / tools/explore/translator/glyphs.py lines 1–202
- Test No Tmp test · cosmic / tools/explore/translator/test_no_tmp.py lines 1–50
- Test Translator test · cosmic / tools/explore/translator/test_translator.py lines 1–182
Clarity
A Python command-line tool in the translator folder of Cosmic that draws build graph. It joins words (`join_words`), counts line (`count_line`) and filters nav (`filter_nav`).
rendercosmic / tools/explore/translator/clarity.py · lines 494–577 of 577 (continued from section 1164) · Entry point · pattern neutral (shared by 2 files)
- What it does
- It draws build graph. Defines 26 functions or classes, including neutral, esc, slugify, section_href, folder_of. Uses libraries __future__, argparse, collections, html, json. Side effects: changes the web page (DOM); reads or writes files; starts processes.
- Inputs & outputs
- In: JSON file build_graph.json; JSON file clarity.json; command-line arguments. Out: SVG drawing.
- Downstream impact
- Used directly by 3 files: Extras (cosmic); Test No Tmp (cosmic); Test Translator (cosmic). Reached from 3 other entry points, including Ship (cosmic); Test Extras (cosmic); Test Ship (cosmic).
- What it achieves
- Clarity view: read the whole estate as fields of pictograms and see what is real. It accepts `--graph` and `--out`.
- Why it matters
- Run by Extras. Checked by 2 tests, including Test No Tmp.
- Application
- cosmic · tools/explore/translator · Python CLI
- Uses
- Glyphs (import), __future__, argparse, collections, html, json, os, re, sys
- Used by
- run by Extras (script call), run by Test No Tmp (script call), imported by Test Translator (import)
- Produces
- neutral, esc, slugify, section_href, folder_of, reach_from_entries, classify, synopsis_clause, plural, join_words, repo_paragraph, page
- Defines here
- write, 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/translator/clarity.py:494-577 · blob 9ed90260d14fe25ead11c1594bccf8fca7d63755 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, process · domain stage: unknown · users: none · canonical: unknown
.seg{display:block;height:100%;min-width:2px}
.cats{display:grid;gap:4px 12px}
.cats dt{font-weight:600;display:flex;align-items:center;gap:8px}
.cats dd{margin:0 0 8px;color:var(--muted)}
.legend summary{cursor:pointer;min-height:44px;display:flex;align-items:center;font-weight:600;color:var(--link)}
.lg-row{border-top:1px solid var(--line);padding:8px 0}
.lg-row h3{margin:0}.lg-row p{margin:2px 0 6px;color:var(--muted)}
.lg-demo{display:flex;flex-wrap:wrap;gap:6px 12px}
.lg-item{display:inline-flex;align-items:center;gap:4px;font-size:.85rem}
.lg-item svg{flex:none}
.chips{display:flex;flex-wrap:wrap;gap:6px}
.repo{border-top:1px solid var(--line);margin-top:18px;padding-top:4px}
.repo-h{margin:10px 0 0}
.rlink{display:inline-flex;min-width:44px;align-items:center;min-height:44px;text-decoration:none}
.folder-h{font-weight:600;margin:10px 0 2px}
.field{display:flex;flex-wrap:wrap;gap:0}
.g{display:block;width:44px;height:44px;padding:2px;border-radius:6px}
.g svg{display:block;width:40px;height:40px}
.g:hover{background:var(--panel)}
.g.c-via{box-shadow:inset 0 0 0 2px var(--hl);border-radius:6px;outline:1px dotted var(--hl);outline-offset:-4px}
body[data-show=core] .g:not(.c-core),body[data-show=copy] .g:not(.c-copy),body[data-show=via] .g:not(.c-via),body[data-show=unreached] .g:not(.c-unreached){display:none}
body[data-show=core] .folder:not(.has-core),body[data-show=copy] .folder:not(.has-copy),body[data-show=via] .folder:not(.has-via),body[data-show=unreached] .folder:not(.has-unreached),
body[data-show=core] .repo:not(.has-core),body[data-show=copy] .repo:not(.has-copy),body[data-show=via] .repo:not(.has-via),body[data-show=unreached] .repo:not(.has-unreached){display:none}
.cards{display:grid;gap:10px;margin:12px 0}
.card{display:flex;flex-direction:column;gap:6px;text-decoration:none;color:var(--text);margin:0}
.card-h{display:flex;align-items:center;gap:8px;font-weight:600;color:var(--link)}
.card-h b{color:var(--text)}
.repos{list-style:none;margin:0;padding:0}
.repos li{border-top:1px solid var(--line)}
.row{display:grid;gap:4px;padding:8px 4px;min-height:44px;text-decoration:none;color:var(--text)}
.row:hover{background:var(--panel)}
.row-h{color:var(--link);font-weight:600}
.nums{display:flex;flex-wrap:wrap;gap:4px 14px;color:var(--muted)}
.nums>span{display:inline-flex;align-items:center;gap:5px}
.strip{display:block;width:100%;max-width:480px;height:auto}
.hero{display:grid;gap:12px}
.pic{margin:0}
.picture{display:block;width:100%;height:auto;max-height:calc(100vh - 160px)}
.picture .pl{fill:#fff;font:600 12px system-ui,sans-serif}
.about p{margin:6px 0}
@media (min-width:700px){.cards{grid-template-columns:repeat(2,1fr)}.row{grid-template-columns:minmax(0,1.2fr) minmax(0,1fr) minmax(0,1.3fr);align-items:center}.filters{position:sticky;top:0;z-index:2}h1{font-size:1.9rem}main{padding:0 20px 60px}.cats{grid-template-columns:repeat(2,1fr)}}
@media (min-width:1000px){.cards{grid-template-columns:repeat(4,1fr)}.hero{grid-template-columns:minmax(0,560px) minmax(0,1fr);align-items:start}.cats{grid-template-columns:repeat(4,1fr)}}
"""
JS = """(function(){'use strict';
var b=document.body,btns=[].slice.call(document.querySelectorAll('[data-filter]'));
if(!btns.length)return;
function apply(f){b.setAttribute('data-show',f);btns.forEach(function(x){x.setAttribute('aria-pressed',x.getAttribute('data-filter')===f?'true':'false');x.classList.toggle('here',x.getAttribute('data-filter')===f);});}
btns.forEach(function(x){x.addEventListener('click',function(e){e.preventDefault();var f=x.getAttribute('data-filter');apply(f);try{history.replaceState(null,'',f==='all'?location.pathname:'#show-'+f);}catch(_){}});});
var m=/^#show-(core|copy|via|unreached)$/.exec(location.hash);if(m)apply(m[1]);
})();
"""
def write(out_dir: str, files: dict[str, str]) -> None:
os.makedirs(out_dir, exist_ok=True)
for name in sorted(files):
with open(os.path.join(out_dir, name), "w", encoding="utf-8", newline="\n") as fh:
fh.write(files[name])
def main(argv=None) -> int:
ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
ap.add_argument("--graph", default=DEFAULT_GRAPH)
ap.add_argument("--out", default=DEFAULT_OUT)
a = ap.parse_args(argv)
if not os.path.isfile(a.graph):
sys.exit("clarity.py: build_graph.json not found at %r; pass --graph or set EXPLORE_GRAPH" % a.graph)
try:
with open(a.graph, encoding="utf-8") as fh:
graph = json.load(fh)
except ValueError as e:
sys.exit("clarity.py: %s is not valid JSON (%s)" % (a.graph, e))
if not isinstance(graph, dict) or not isinstance(graph.get("files"), list):
sys.exit("clarity.py: %s has no files list; is it a build_graph.json?" % a.graph)
files = build(graph)
write(a.out, files)
counts = json.loads(files["clarity.json"])["counts"]
print("wrote %d files to %s; %s" % (len(files), a.out, ", ".join("%s %d" % (k, counts[k]) for k in CATS)))
return 0
if __name__ == "__main__":
sys.exit(main())Glyphs
A Python module in the translator folder of Cosmic that sizes step (`size_step`).
rendercosmic / tools/explore/translator/glyphs.py · lines 1–202 of 202 · pattern palette (shared by 3 files)
- What it does
- It draws its content. Defines 14 functions or classes, including Glyph, palette, size_step, link_count, encode. Uses libraries __future__, math, typing. Side effects: changes the web page (DOM).
- Inputs & outputs
- Out: SVG drawing.
- Downstream impact
- Used directly by 3 files: Clarity (cosmic); Test No Tmp (cosmic); Test Translator (cosmic). Reached from 4 other entry points, including Extras (cosmic); Ship (cosmic); Test Extras (cosmic).
- What it achieves
- It is built from the glyph class (`Glyph`), the palette step (`palette`) and the link count helper (`link_count`). Pictorial translator: one deterministic pictogram per estate file.
- Why it matters
- Imported by Clarity. Checked by 2 tests, including Test No Tmp.
- Application
- cosmic · tools/explore/translator · Python module
- Uses
- __future__, math, typing
- Used by
- imported by Clarity (import), run by Test No Tmp (script call), imported by Test Translator (import)
- Produces
- Glyph, palette, size_step, link_count, encode, key, body, svg, symbol, sprite, describe
- Defines here
- Glyph, palette, size_step, link_count, encode, key, _fmt, _shape, body, svg, symbol, sprite, _esc, describe
- 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/translator/glyphs.py:1-202 · blob 97ae18377e3d8e960e7ebe9e23d3309c6cfd1e85 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: unknown · users: none · canonical: unknown
"""Pictorial translator: one deterministic pictogram per estate file.
Input is a file record from build_graph.json (schema explore-build-graph-v1) plus the
top-level ``roles`` palette. Output is a small SVG. Every visual property is a pure
function of evidence fields, so the same graph always gives byte-identical pictures.
Encoding (also written out in words by ``LEGEND`` for pages):
role -> fill / stroke colour, from build_graph ``roles`` (site palette)
stage -> shape: ingest = funnel (down triangle), transform = diamond,
output = square, unknown = circle
size -> scale, four steps by line count (<50, <200, <800, >=800)
reach -> solid shape if reachable from an entry point, outline if not
uniqueness -> one shape if unique, two stacked shapes if a copy (duplicate_of set)
entry point -> white ring around the shape
links -> short rays around the edge, one per import or dependent, up to 8
Stdlib only (numpy is allowed by the project brief but is not needed here).
"""
from __future__ import annotations
import math
from typing import NamedTuple
VIEW = 40 # viewBox is 0 0 40 40
CENTRE = 20.0
BASE_R = 11.0 # radius of the largest shape
RING_R = 15.0
RAY_IN, RAY_OUT = 16.6, 19.4
MAX_RAYS = 8
RAY_COLOUR = "#a6adbb"
RING_COLOUR = "#ffffff"
PANEL = "#0b0e14"
FALLBACK_COLOUR = "#4c5a65"
STAGES = ("ingest", "transform", "output", "unknown")
STAGE_SHAPE = {"ingest": "funnel", "transform": "diamond", "output": "square", "unknown": "circle"}
# (upper bound exclusive, step name, scale)
SIZE_STEPS = ((50, "XS", 0.55), (200, "S", 0.70), (800, "M", 0.85), (None, "L", 1.00))
class Glyph(NamedTuple):
role: str
colour: str
stage: str
shape: str
size: str
scale: float
solid: bool # reachable
stacked: bool # a copy of another file
ring: bool # entry point
rays: int # links shown (0..MAX_RAYS)
links: int # true link count (imports + dependents)
def palette(roles: list[dict]) -> dict[str, str]:
"""role id -> colour, from build_graph ``roles``."""
return {r["id"]: r["colour"] for r in roles}
def size_step(lines: int) -> tuple[str, float]:
n = int(lines or 0)
for bound, name, scale in SIZE_STEPS:
if bound is None or n < bound:
return name, scale
raise AssertionError("unreachable")
def link_count(f: dict) -> int:
return len(set(f.get("imports") or [])) + len(set(f.get("dependents") or []))
def encode(f: dict, colours: dict[str, str]) -> Glyph:
role = f.get("role") or "other"
stage = f.get("stage") if f.get("stage") in STAGE_SHAPE else "unknown"
size, scale = size_step(f.get("lines", 0))
links = link_count(f)
return Glyph(
role=role,
colour=colours.get(role, FALLBACK_COLOUR),
stage=stage,
shape=STAGE_SHAPE[stage],
size=size,
scale=scale,
solid=bool(f.get("reachable")),
stacked=f.get("duplicate_of") is not None,
ring=bool(f.get("entry")),
rays=min(MAX_RAYS, links),
links=links,
)
def key(g: Glyph) -> str:
"""Stable symbol id; equal keys draw identical pictures."""
return "g-%s-%s%s%s%s%s%d" % (
g.role, g.stage[0], g.size.lower(), "s" if g.solid else "o",
"d" if g.stacked else "u", "e" if g.ring else "n", g.rays)
def _fmt(v: float) -> str:
s = "%.1f" % v
return s.rstrip("0").rstrip(".") if "." in s else s
def _shape(shape: str, cx: float, cy: float, r: float, attrs: str) -> str:
if shape == "circle":
return '<circle cx="%s" cy="%s" r="%s"%s/>' % (_fmt(cx), _fmt(cy), _fmt(r * 0.92), attrs)
if shape == "square":
h = r * 0.82
return '<rect x="%s" y="%s" width="%s" height="%s"%s/>' % (
_fmt(cx - h), _fmt(cy - h), _fmt(2 * h), _fmt(2 * h), attrs)
if shape == "diamond":
pts = [(cx, cy - r), (cx + r, cy), (cx, cy + r), (cx - r, cy)]
elif shape == "funnel": # triangle pointing down: things pour in
pts = [(cx - r, cy - r * 0.72), (cx + r, cy - r * 0.72), (cx, cy + r)]
else:
raise ValueError(shape)
return '<polygon points="%s"%s/>' % (" ".join("%s,%s" % (_fmt(x), _fmt(y)) for x, y in pts), attrs)
def body(g: Glyph) -> str:
"""Inner SVG markup (no outer <svg>), in a 40x40 box."""
out = []
r = BASE_R * g.scale
if g.solid:
front = ' fill="%s"' % g.colour
else:
front = ' fill="none" stroke="%s" stroke-width="2.2"' % g.colour
if g.stacked:
d = 3.2
back = ' fill="%s" stroke="%s" stroke-width="1.6"' % (PANEL, g.colour)
out.append(_shape(g.shape, CENTRE + d, CENTRE - d, r, back))
cx, cy = CENTRE - d * 0.5, CENTRE + d * 0.5
if g.solid:
front += ' stroke="%s" stroke-width="1.6"' % PANEL
else:
cx = cy = CENTRE
out.append(_shape(g.shape, cx, cy, r, front))
if g.ring:
out.append('<circle cx="20" cy="20" r="%s" fill="none" stroke="%s" stroke-width="1.4"/>'
% (_fmt(RING_R), RING_COLOUR))
if g.rays:
d = []
for i in range(g.rays):
a = -math.pi / 2 + 2 * math.pi * i / g.rays
c, s = math.cos(a), math.sin(a)
d.append("M%s %sL%s %s" % (_fmt(CENTRE + RAY_IN * c), _fmt(CENTRE + RAY_IN * s),
_fmt(CENTRE + RAY_OUT * c), _fmt(CENTRE + RAY_OUT * s)))
out.append('<path class="rays" d="%s" stroke="%s" stroke-width="1.6" stroke-linecap="round" data-n="%d"/>'
% ("".join(d), RAY_COLOUR, g.rays))
return "".join(out)
def svg(g: Glyph, size: int = 40, title: str | None = None) -> str:
"""Stand-alone SVG for one glyph."""
t = "<title>%s</title>" % _esc(title) if title else ""
hidden = "" if title else ' aria-hidden="true"'
return ('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 40 40" width="%d" height="%d"%s>%s%s</svg>'
% (size, size, hidden, t, body(g)))
def symbol(g: Glyph) -> str:
return '<symbol id="%s" viewBox="0 0 40 40">%s</symbol>' % (key(g), body(g))
def sprite(glyphs) -> str:
"""Hidden SVG sprite holding one <symbol> per distinct key (sorted, deterministic)."""
seen = {}
for g in glyphs:
seen.setdefault(key(g), g)
syms = "".join(symbol(seen[k]) for k in sorted(seen))
return ('<svg xmlns="http://www.w3.org/2000/svg" width="0" height="0" style="position:absolute" '
'aria-hidden="true" focusable="false">%s</svg>' % syms)
def _esc(s: str) -> str:
return (s.replace("&", "&").replace("<", "<").replace(">", ">").replace('"', """))
def describe(g: Glyph, roles_title: dict[str, str] | None = None) -> str:
"""The glyph in words (for tooltips / accessible names)."""
rt = (roles_title or {}).get(g.role, g.role)
bits = [rt, "stage " + g.stage, "size " + g.size,
"reachable" if g.solid else "not reached",
"copy" if g.stacked else "unique"]
if g.ring:
bits.append("entry point")
bits.append("%d link%s" % (g.links, "" if g.links == 1 else "s"))
return ", ".join(bits)
LEGEND = [
("Colour", "what the file does (its role), using the site palette below."),
("Shape", "its stage: funnel = brings data in (ingest), diamond = converts or calculates (transform), "
"square = draws or writes output, circle = stage not known."),
("Size", "how long it is: four steps, under 50 lines, under 200, under 800, 800 or more."),
("Solid or outline", "solid = reachable from some entry point; outline = nothing that runs reaches it."),
("Single or stacked", "one shape = unique code; two stacked shapes = a copy of another file."),
("White ring", "an entry point: a web page, workflow, command-line tool or loaded script."),
("Rays", "one short line per link to or from another file (imports plus users), up to 8."),
]Test No Tmp
A test in the translator folder of Cosmic that checks Test Translator and Clarity. It is built from the no tmp test class (`NoTmpTest`).
testcosmic / tools/explore/translator/test_no_tmp.py · lines 1–50 of 50 · Entry point · pattern test_source_has_no_host_paths (shared by 2 files)
- What it does
- It tests its inputs. Defines NoTmpTest, test_source_has_no_host_paths, test_runs_from_env_only, test_missing_graph_is_a_clear_error. Uses libraries json, os, re, subprocess, sys. Side effects: reads or writes files; starts processes.
- Inputs & outputs
- In: JSON file build_graph.json; JSON file clarity.json. Out: JSON file.
- Downstream impact
- It is itself an entry point (test); no other file was found loading it.
- What it achieves
- CI check: `clarity.py` runs on a clean machine with only `build_graph.json` (no /tmp inputs), as `extras.py` runs it.
- Why it matters
- Guards the behaviour of Test Translator, Clarity and Glyphs.
- Application
- cosmic · tools/explore/translator · test
- Uses
- Test Translator (import), Clarity (script call), Glyphs (script call), json, os, re, subprocess, sys, tempfile, unittest
- Used by
- none found
- Produces
- NoTmpTest
- Defines here
- NoTmpTest, test_source_has_no_host_paths, test_runs_from_env_only, test_missing_graph_is_a_clear_error
- 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/translator/test_no_tmp.py:1-50 · blob a12bf851a700b6421484bdd53c34772611ca6fda · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: unknown · users: none · canonical: unknown
"""CI check: clarity.py runs on a clean machine with only build_graph.json (no /tmp inputs), as extras.py runs it.
python -m unittest tools/explore/translator/test_no_tmp.py
"""
import json
import os
import re
import subprocess
import sys
import tempfile
import unittest
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
from test_translator import f # noqa: E402
class NoTmpTest(unittest.TestCase):
def test_source_has_no_host_paths(self):
for g in ('clarity.py', 'glyphs.py'):
with open(os.path.join(HERE, g), encoding='utf-8') as fh:
self.assertIsNone(re.search(r"['\"]/(tmp|home/claude)/", fh.read()), g)
def test_runs_from_env_only(self):
work = tempfile.mkdtemp()
g = {'schema': 'explore-build-graph-v1', 'cut': 'ci', 'roles': [], 'edges': [],
'files': [f(0, entry=True), f(1, imports=[0]), f(2, duplicate_of=1), f(3, reachable=False)]}
gpath = os.path.join(work, 'build_graph.json')
with open(gpath, 'w') as fh:
json.dump(g, fh)
out = os.path.join(work, 'out')
env = dict(os.environ, EXPLORE_GRAPH=gpath, EXTRA_OUT=out)
p = subprocess.run([sys.executable, os.path.join(HERE, 'clarity.py')], cwd=work, env=env,
capture_output=True, text=True, timeout=120)
self.assertEqual(p.returncode, 0, p.stderr[-800:])
for name in ('index.html', 'clarity.json', 'core.html'):
self.assertTrue(os.path.isfile(os.path.join(out, name)), name)
def test_missing_graph_is_a_clear_error(self):
work = tempfile.mkdtemp()
env = dict(os.environ)
env.pop('EXPLORE_GRAPH', None)
p = subprocess.run([sys.executable, os.path.join(HERE, 'clarity.py'), '--out', work], cwd=work, env=env,
capture_output=True, text=True, timeout=60)
self.assertNotEqual(p.returncode, 0)
self.assertIn('build_graph.json not found', p.stderr)
if __name__ == '__main__':
unittest.main()Test Translator
A test in the explore folder of Cosmic that checks Clarity and Glyphs.
testcosmic / tools/explore/translator/test_translator.py · lines 1–182 of 182 · Entry point · pattern test_no_religious_terms (shared by 3 files)
- What it does
- It tests 400kV and cables. Defines 23 functions or classes, including f, mini_graph, GlyphTests, test_encodings, test_svg_reflects_encoding. Uses libraries collections, json, os, re, sys. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (voltage levels 400kV (all 132kV or above)): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: 400kV, cables.
- Inputs & outputs
- In: JSON file clarity.json. Voltage levels named: 400kV.
- Downstream impact
- Used directly by 1 file: Test No Tmp (cosmic).
- What it achieves
- It sets up class (`setUpClass`) and is built from the mini graph helper (`mini_graph`) and the glyph tests class (`GlyphTests`). Tests for the pictorial translator: python3 -m pytest `translator/test_translator.py` (or run directly). Its code works with 400 kV.
- Why it matters
- Checked by Test No Tmp.
- Application
- cosmic · tools/explore/translator · test
- Uses
- Clarity (import), Glyphs (import), collections, json, os, re, sys, unittest
- Used by
- imported by Test No Tmp (import)
- Produces
- f, mini_graph, GlyphTests, ClarityTests, RealGraphTests
- Defines here
- f, mini_graph, GlyphTests, test_encodings, test_svg_reflects_encoding, test_keys_unique_per_picture, test_deterministic, ClarityTests, test_classify_mini, test_build_mini_deterministic_and_links, test_synopsis_clause, test_neutral, RealGraphTests, setUpClass, test_counts_add_up, test_filter_pages_match_counts, test_index_phone_sized, test_every_glyph_links_to_its_section, test_deterministic_real, test_no_religious_terms, test_generated_wording_has_no_religious_terms, test_names_shown_as_is, test_palette_only
- 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/translator/test_translator.py:1-182 · blob 52105c6fd37310847cd8dd2451dca3cd8fe32471 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: ingest · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unknown
"""Tests for the pictorial translator: python3 -m pytest translator/test_translator.py (or run directly)."""
import collections
import json
import os
import re
import sys
import unittest
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
import clarity # noqa: E402
import glyphs # noqa: E402
GRAPH = os.environ.get("CLARITY_GRAPH", clarity.DEFAULT_GRAPH)
ROLES = [{"id": "render", "title": "Render (DOM, canvas, maps, HTML)", "colour": "#ff6666"},
{"id": "transform", "title": "Transform (pure maths and conversion)", "colour": "#00ff88"},
{"id": "other", "title": "Other", "colour": "#4c5a65"}]
COL = glyphs.palette(ROLES)
RELIGIOUS = re.compile(r"\b(vedic|veda|sutras?|gods?|goddess|temple|karma|mantra|yoga|gita|prayer|divine|holy|sacred|"
r"angel|heaven|spiritual|church|bible|scripture|sanskrit|dharma|shiva|vishnu|krishna|brahma|"
r"buddha|religion|religious|worship|deity|puja|guru|upanishad)\b", re.I)
def f(i, **kw):
base = dict(id=i, repo="r", path="a/f%d.js" % i, folder_hierarchy=["r", "a"], lines=100, section=1, block=i + 1,
title="F%d" % i, synopsis="A JavaScript module in R that draws maps.", role="render", stage="output",
reachable=True, entry=False, duplicate_of=None, imports=[], dependents=[], kind="JavaScript module")
base.update(kw)
return base
def mini_graph():
# 0 entry -> 1 (core); 0 -> 2 (copy of 1) -> 3 (via: only through the copy); 4 unreached; 5 entry that is a copy
files = [f(0, entry=True, imports=[1, 2]), f(1, dependents=[0]), f(2, duplicate_of=1, imports=[3], dependents=[0]),
f(3, dependents=[2]), f(4, reachable=False), f(5, entry=True, duplicate_of=0, imports=[6]),
f(6, dependents=[5], repo="s", path="b/x.py", folder_hierarchy=["s"])]
return {"cut": "test", "roles": ROLES, "files": files}
class GlyphTests(unittest.TestCase):
def test_encodings(self):
g = glyphs.encode(f(0, lines=10, entry=True, imports=[1, 2, 3], dependents=[4]), COL)
self.assertEqual((g.colour, g.shape, g.size, g.solid, g.stacked, g.ring, g.rays),
("#ff6666", "square", "XS", True, False, True, 4))
self.assertEqual(glyphs.encode(f(0, stage="ingest"), COL).shape, "funnel")
self.assertEqual(glyphs.encode(f(0, stage="transform"), COL).shape, "diamond")
self.assertEqual(glyphs.encode(f(0, stage="weird"), COL).shape, "circle")
self.assertEqual([glyphs.encode(f(0, lines=n), COL).size for n in (1, 49, 50, 199, 200, 799, 800, 99999)],
["XS", "XS", "S", "S", "M", "M", "L", "L"])
self.assertEqual(glyphs.encode(f(0, imports=list(range(20))), COL).rays, 8)
self.assertEqual(glyphs.encode(f(0, role="nope"), COL).colour, glyphs.FALLBACK_COLOUR)
def test_svg_reflects_encoding(self):
solid = glyphs.svg(glyphs.encode(f(0), COL))
outline = glyphs.svg(glyphs.encode(f(0, reachable=False), COL))
self.assertIn('fill="#ff6666"', solid)
self.assertIn('fill="none" stroke="#ff6666"', outline)
self.assertEqual(solid.count("<rect"), 1)
self.assertEqual(glyphs.svg(glyphs.encode(f(0, duplicate_of=3), COL)).count("<rect"), 2)
self.assertNotIn('r="15"', solid)
self.assertIn('r="15"', glyphs.svg(glyphs.encode(f(0, entry=True), COL)))
self.assertIn('data-n="3"', glyphs.svg(glyphs.encode(f(0, imports=[1, 2, 3]), COL)))
self.assertEqual(glyphs.svg(glyphs.encode(f(0, imports=[1, 2, 3]), COL)).count("M"), 3)
big = glyphs.body(glyphs.encode(f(0, lines=5000), COL))
small = glyphs.body(glyphs.encode(f(0, lines=5), COL))
self.assertNotEqual(big, small)
def test_keys_unique_per_picture(self):
seen = {}
for st in glyphs.STAGES:
for lines in (1, 100, 500, 5000):
for reach in (True, False):
for dup in (None, 1):
for entry in (True, False):
for n in (0, 1, 8):
g = glyphs.encode(f(0, stage=st, lines=lines, reachable=reach, duplicate_of=dup,
entry=entry, imports=list(range(n))), COL)
b = glyphs.body(g)
self.assertEqual(seen.setdefault(glyphs.key(g), b), b)
self.assertEqual(len(set(seen.values())), len(seen))
def test_deterministic(self):
a = glyphs.sprite(glyphs.encode(x, COL) for x in mini_graph()["files"])
b = glyphs.sprite(glyphs.encode(x, COL) for x in reversed(mini_graph()["files"]))
self.assertEqual(a, b)
class ClarityTests(unittest.TestCase):
def test_classify_mini(self):
cat = clarity.classify(mini_graph()["files"])
self.assertEqual(cat, {0: "core", 1: "core", 2: "copy", 3: "via", 4: "unreached", 5: "copy", 6: "via"})
def test_build_mini_deterministic_and_links(self):
a, b = clarity.build(mini_graph()), clarity.build(mini_graph())
self.assertEqual(a, b)
self.assertIn('href="../s/0001.html#f4"', a["via-copies.html"])
self.assertIn('href="repo-r.html"', a["index.html"])
self.assertIn("repo-r.html", a)
data = json.loads(a["clarity.json"])
self.assertEqual(data["counts"], {"core": 2, "copy": 2, "via": 2, "unreached": 1})
def test_synopsis_clause(self):
self.assertEqual(clarity.synopsis_clause("A JavaScript module in GridAtlas that draws grid 400kV."),
"draws grid 400kV")
self.assertEqual(clarity.synopsis_clause("A style sheet in GlobalGrid2050."), "")
self.assertEqual(clarity.synopsis_clause("A file covering cables. Served at https://x.y/."), "covering cables")
def test_neutral(self):
# existing repo and tool names are shown exactly as they are
self.assertEqual(clarity.neutral("VEDIC Snapshot from vedic- repo"), "VEDIC Snapshot from vedic- repo")
self.assertEqual(clarity.slugify("vedic-"), "vedic")
@unittest.skipUnless(os.path.exists(GRAPH), "build_graph.json not present")
class RealGraphTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
with open(GRAPH, encoding="utf-8") as fh:
cls.g = json.load(fh)
cls.out = clarity.build(cls.g)
cls.data = json.loads(cls.out["clarity.json"])
def test_counts_add_up(self):
files = self.g["files"]
c = self.data["counts"]
self.assertEqual(sum(c.values()), len(files))
self.assertEqual(c["copy"], sum(1 for x in files if x["duplicate_of"] is not None))
self.assertEqual(c["unreached"], sum(1 for x in files if not x["reachable"] and x["duplicate_of"] is None))
self.assertEqual(c["core"] + c["via"], sum(1 for x in files if x["reachable"] and x["duplicate_of"] is None))
for repo, rc in self.data["repos"].items():
self.assertEqual(sum(rc.values()), sum(1 for x in files if x["repo"] == repo), repo)
self.assertEqual({k: sum(r[k] for r in self.data["repos"].values()) for k in c}, c)
def test_filter_pages_match_counts(self):
for cat, page in clarity.CAT_PAGE.items():
self.assertEqual(self.out[page].count('class="g c-%s"' % cat), self.data["counts"][cat], page)
self.assertEqual(self.out["index.html"].count('class="g c-'), 0)
repo_pages = sum(v.count('class="g c-') for k, v in self.out.items() if k.startswith("repo-"))
self.assertEqual(repo_pages, len(self.g["files"]))
def test_index_phone_sized(self):
self.assertLess(len(self.out["index.html"].encode()), 300 * 1024)
for repo in self.data["repos"]:
self.assertIn(">%s <span" % repo, self.out["index.html"])
def test_every_glyph_links_to_its_section(self):
hrefs = [h for k in clarity.CAT_PAGE.values()
for h in re.findall(r'class="g c-\w+" href="([^"]+)"', self.out[k])]
want = sorted("../s/%04d.html#f%d" % (x["section"], x["block"]) for x in self.g["files"])
self.assertEqual(sorted(hrefs), want)
def test_deterministic_real(self):
self.assertEqual(clarity.build(self.g), self.out)
def test_no_religious_terms(self):
for name, text in self.out.items():
if name.endswith(".html"):
visible = re.sub(r"<[^>]+>", " ", text)
titles = " ".join(re.findall(r'(?:title|aria-label|content)="([^"]*)"', text))
# existing names (repo vedic-, the VEDIC tools) are the owner's real public names, shown as-is;
# the rule covers our own generated wording
words = re.sub(r"\bvedic\b", " ", visible + " " + titles, flags=re.I)
self.assertIsNone(RELIGIOUS.search(words), name)
def test_generated_wording_has_no_religious_terms(self):
out = clarity.build(mini_graph())
for name, text in out.items():
self.assertIsNone(RELIGIOUS.search(text), name)
def test_names_shown_as_is(self):
if "vedic-" in self.data["repos"]:
self.assertIn("repo-vedic.html", self.out)
self.assertIn(">vedic- <span", self.out["index.html"])
def test_palette_only(self):
css = self.out["clarity.css"]
for c in ("#000", "#0b0e14", "#2f343d", "#fff", "#a6adbb", "#66ccff", "#00ffff"):
self.assertIn(c, css)
if __name__ == "__main__":
unittest.main()