In this section
- Homepage Browser test · globalgrid2050-homepage / tests/homepage-browser.cjs lines 1–153
- Test Active Pages test · globalgrid2050-homepage / tests/test_active_pages.py lines 1–88
- Test Cyber Resilience Entry test · globalgrid2050-homepage / tests/test_cyber_resilience_entry.py lines 1–33
- Test Explore Code Entry test · globalgrid2050-homepage / tests/test_explore_code_entry.py lines 1–31
- Test Grid Explorer Entry test · globalgrid2050-homepage / tests/test_grid_explorer_entry.py lines 1–50
- Test Grid Explorer Labels test · globalgrid2050-homepage / tests/test_grid_explorer_labels.py lines 1–45
- Test Homepage Fallback Archives test · globalgrid2050-homepage / tests/test_homepage_fallback_archives.py lines 1–80
- Test Releases test · globalgrid2050-homepage / tests/test_releases.py lines 1–158
Homepage Browser
A JavaScript module in the tests folder of GlobalGrid2050 Homepage that tests active pages and uses data from the GlobalGrid2050-ip-and-mac-addresses repository. It is built from the is app helper (`isApp`).
testglobalgrid2050-homepage / tests/homepage-browser.cjs · lines 1–153 of 153 · Entry point · pattern matches (shared by 8 files)
- What it does
- It tests active pages. Defines matches, isApp, ids. Uses libraries node:fs, node:path, node:http, node:assert/strict. Side effects: changes the web page (DOM); reads or writes files.
- Inputs & outputs
- In: data source: globalgrid2050-ip-and-mac-addresses data; JSON file homepage.json; JSON file entity-types.json; JSON file presentation.json; JSON file active-pages.json. Out: JSON file receipt.json.
- Downstream impact
- Used directly by 2 files: Pages Workflow (globalgrid2050-homepage); PR Checks Workflow (globalgrid2050-homepage).
- What it achieves
- Defines `matches`, `isApp` and `ids`.
- Why it matters
- Run by Pages Workflow and PR Checks Workflow.
- Application
- globalgrid2050-homepage · tests · JavaScript module
- Uses
- GlobalGrid2050 IP and MAC Addresses — Index Page (estate URL), node:fs, node:path, node:http, node:assert/strict
- Used by
- run by Pages Workflow (workflow run), run by PR Checks Workflow (workflow run)
- Produces
- matches, isApp, ids
- Defines here
- matches, isApp, ids
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050-homepage@551a7625b02ddb7b3e6e0181cc643b8114c7fc06 tests/homepage-browser.cjs:1-153 · blob 6bc93a6b06aebb62cec96a2e6e159eae8a3932f7 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: unknown · users: none · canonical: unknown
"use strict";
const fs=require('node:fs'),path=require('node:path'),http=require('node:http'),assert=require('node:assert/strict');
const {chromium}=require(process.env.PLAYWRIGHT_MODULE || 'playwright');
const root=path.resolve(__dirname,'..');
const catalogue=JSON.parse(fs.readFileSync(path.join(root,'data/homepage.json'),'utf8'));
const metadata=JSON.parse(fs.readFileSync(path.join(root,'data/entity-types.json'),'utf8'));
const presentation=JSON.parse(fs.readFileSync(path.join(root,'data/presentation.json'),'utf8'));
const firstPage=catalogue.entities.slice(0,presentation.page_size);
const feed=JSON.parse(fs.readFileSync(path.join(root,'data/active-pages.json'),'utf8'));
const matches=(entity,query)=>[entity.id,entity.title,entity.subtitle,entity.description,metadata.records[entity.id].type,metadata.records[entity.id].purpose,...metadata.records[entity.id].audience,...metadata.records[entity.id].roles,...entity.releases.map(r=>[r.id,r.label,r.url,r.status,r.source_ref].join(' '))].join(' ').toLocaleLowerCase().includes(query.toLocaleLowerCase());
const output=path.join(root,'browser-evidence');fs.mkdirSync(output,{recursive:true});
const isApp=url=>{const h=new URL(url).hostname;return !/(^|\.)github\.com$/i.test(h)&&!/(^|\.)githubusercontent\.com$/i.test(h);};
const server=http.createServer((req,res)=>{const pathname=new URL(req.url,'http://localhost').pathname;const file=path.resolve(root,'.'+(pathname==='/'?'/index.html':pathname));if(!file.startsWith(root+path.sep)||!fs.existsSync(file)||!fs.statSync(file).isFile()){res.writeHead(404).end();return;}res.setHeader('Content-Type',({'.html':'text/html; charset=utf-8','.js':'text/javascript; charset=utf-8 … [line shortened here: 537 characters; full line on GitHub]
(async()=>{let browser;const receipt={status:'running',checks:[],source:process.env.GITHUB_SHA||'local'};try{
if(process.platform==='win32'&&!process.env.ALLOW_LOCAL_BROWSER)throw Error('Use hosted Linux browser verification; local Windows launch disabled.');
await new Promise(r=>server.listen(0,'127.0.0.1',r));const base='http://127.0.0.1:'+server.address().port;
browser=await chromium.launch({headless:true});const page=await browser.newPage({viewport:{width:1440,height:1000}});const errors=[];page.on('pageerror',e=>errors.push(e.message));
await page.goto(base);await page.waitForSelector('.development-track');
assert.equal(await page.locator('body').evaluate(e=>getComputedStyle(e).color),'rgb(255, 255, 255)');
assert.equal(await page.locator('body').evaluate(e=>getComputedStyle(e).backgroundColor),'rgb(0, 0, 0)');
assert.equal(await page.locator('.brand').evaluate(e=>getComputedStyle(e).color),'rgb(102, 204, 255)');
assert.equal(await page.locator('#archiveLink').evaluate(e=>getComputedStyle(e).color),'rgb(102, 204, 255)');
assert.equal(await page.locator('#kuiper').evaluate(e=>getComputedStyle(e).borderTopColor),'rgb(51, 51, 51)');
assert.equal(await page.locator('body').evaluate(e=>getComputedStyle(e).fontFamily.replace(/\s/g,'')),'ui-monospace,SFMono-Regular,Consolas,monospace');
assert.equal(await page.locator('body').evaluate(e=>getComputedStyle(e).fontSize),'16px');
assert.equal(await page.locator('h1').evaluate(e=>getComputedStyle(e).fontWeight),'500');
assert.equal(await page.locator(':root').evaluate(e=>getComputedStyle(e).getPropertyValue('--cyan').trim()),'#00ffff');
receipt.checks.push('historical black/white/blue/cyan palette, grey borders and unchanged fonts');
assert.equal(await page.locator('#nests > details').count(),catalogue.view.items.length);
assert.equal(await page.locator('#kuiper').evaluate(e=>e.open),false);
assert.equal(await page.locator('.build-card,.build-highlights,.ticker-pause').count(),0);
assert.equal(await page.getByRole('button',{name:/pause|resume/i}).count(),0);
assert.equal(await page.locator('.development-group:not([aria-hidden]) a').count(),feed.items.length);
assert.deepEqual(await page.locator('.development-group:not([aria-hidden]) a').allTextContents(),feed.items.map(i=>i.label));
for(const href of await page.locator('a[href]').evaluateAll(items=>items.map(a=>a.href)))assert(isApp(href),'Only app links: '+href);
assert.equal(await page.locator('.release-url,.build-evidence').count(),0);
receipt.checks.push('closed Kuiper, no In build or pause controls, label-only live app ticker');
assert.deepEqual(await page.locator('.highlight-card').evaluateAll(cards=>cards.map(card=>card.dataset.entityId)),presentation.highlights.map(item=>item.entity_id));
assert.deepEqual(await page.locator('.highlight-label').allTextContents(),presentation.highlights.map(item=>item.label));
for(const item of presentation.highlights){const entity=catalogue.entities.find(e=>e.id===item.entity_id);assert.equal(await page.locator('.highlight-card[data-entity-id='+JSON.stringify(item.entity_id)+']').getAttribute('href'),entity.releases.find(r=>r.id===entity.operative_release_id).url);}
assert(await page.evaluate(()=>Boolean(document.getElementById('highlights').compareDocumentPosition(document.querySelector('.development-strip'))&Node.DOCUMENT_POSITION_FOLLOWING)));
receipt.checks.push('four curated app destinations precede the activity ticker');
assert(await page.evaluate(()=>Boolean(document.getElementById('nests').compareDocumentPosition(document.getElementById('catalogueArchive'))&Node.DOCUMENT_POSITION_FOLLOWING)));
assert.equal(await page.locator('header p').first().innerText(),"An open grid development, engineering, procurement, construction and operations platform dedicated to documenting, analysing and improving the world's electrical energy systems as they undergo rapid electrification.");
assert.equal(await page.locator('footer p').first().innerText(),'Disclaimer: Content provided for general technical documentation and research purposes only.');
assert.equal(await page.locator('#catalogueArchive').evaluate(e=>e.open),false);
receipt.checks.push('mission leads the header, disclaimer leads the footer, the nests precede the archived catalogue');
await page.locator('#catalogueArchive > summary').click();
assert.equal(await page.locator('.highlight-card').first().evaluate(e=>getComputedStyle(e).borderTopWidth),'0px');
receipt.checks.push('plain text highlights and the sections precede the archived searchable table');
assert.equal(await page.locator('#catalogueRows tr').count(),firstPage.length);
for(const entity of firstPage){const row=page.locator('#catalogueRows tr').filter({has:page.getByRole('link',{name:entity.title,exact:true})});assert.equal(await row.count(),1);assert.equal(await row.getAttribute('data-entity-id'),entity.id);const release=entity.releases.find(r=>r.id===entity.operative_release_id);assert.equal(await row.locator('th a').getAttribute('href'),release.url);assert.equa … [line shortened here: 477 characters; full line on GitHub]
await page.locator('#catalogueRows a').first().focus();assert.equal(await page.locator('#catalogueRows a').first().evaluate(e=>e===document.activeElement),true);
receipt.checks.push('all catalogue entities share current release links, persistent IDs and keyboard access');
assert.equal(await page.locator('#catalogueRows .table-versions .release').count(),0);
assert.equal(await page.locator('#kuiper > .inside > .versions .release').count(),0);
await page.locator('#catalogueRows .table-versions > summary').first().click();
assert.match(await page.locator('#catalogueRows tr').first().innerText(),new RegExp(catalogue.entities[0].operative_release_id));
assert.equal(await page.locator('#catalogueRows .entity-key').first().innerText(),catalogue.entities[0].id);
await page.locator('#catalogueRows .table-versions > summary').first().click();
await page.locator('#catalogueRows .table-versions > summary').first().click();
assert.equal(await page.locator('#catalogueRows tr').first().locator('.table-versions .release').count(),catalogue.entities[0].releases.length);
await page.locator('#catalogueRows .table-versions > summary').first().click();
receipt.checks.push('release detail DOM is created on demand and reused without duplicates');
const search=page.locator('#homepageSearch');assert((await search.boundingBox()).y>(await page.locator('#nests').boundingBox()).y);
await search.fill('GridAtlas');assert.equal(await page.locator('#catalogueRows tr:visible').count(),catalogue.entities.filter(e=>matches(e,'GridAtlas')).length);assert.equal(await page.locator('#gridatlas').isVisible(),true);
await search.fill('unlikelynomatch');assert.match(await page.locator('#searchStatus').innerText(),/No matching/);
assert.equal(await page.locator('#catalogueRows tr:visible').count(),0);assert.equal(await page.locator('#catalogueEmpty').isVisible(),true);
await search.fill('');assert.equal(await page.locator('#nests > details:visible').count(),catalogue.view.items.length);assert.equal(await page.locator('#kuiper').evaluate(e=>e.open),false);
assert.equal(await page.locator('#catalogueRows tr:visible').count(),firstPage.length);assert.equal(await page.locator('#catalogueEmpty').isVisible(),false);
receipt.checks.push('top search filters nests and table, shows empty state and restores closed nests');
assert.deepEqual(Object.keys(metadata.records).sort(),catalogue.entities.map(e=>e.id).sort());
for(const meta of Object.values(metadata.records))assert(['engine','application','dataset','equipment','project','reference','drawing','catalogue'].includes(meta.type));
await search.fill('engine');assert.deepEqual(await page.locator('#catalogueRows tr').evaluateAll(rows=>rows.map(row=>row.dataset.entityId)),catalogue.entities.filter(entity=>matches(entity,'engine')).slice(0,presentation.page_size).map(entity=>entity.id));
await search.fill('proposal-authoring');assert.deepEqual(await page.locator('#catalogueRows tr').evaluateAll(rows=>rows.map(row=>row.dataset.entityId)),['kuiper']);
await page.locator('#catalogueRows .entity-type > summary').click();assert.match(await page.locator('#catalogueRows .entity-type').innerText(),/Intended purpose:/);assert.match(await page.locator('#catalogueRows .entity-type').innerText(),/Recorded evidence:/);assert.match(await page.locator('#catalogueRows .entity-type').innerText(),/LLM-assisted/);
await search.fill('');receipt.checks.push('typed catalogue searches purpose, audience and intended roles separately from recorded evidence');
for(const child of catalogue.entities.filter(entity=>{if(!entity.parent_id)return false;let ancestor=entity;while(ancestor.parent_id)ancestor=catalogue.entities.find(item=>item.id===ancestor.parent_id);return catalogue.view.items.some(item=>item.entity_id===ancestor.id);})){
await search.fill(child.title);
assert.equal(await page.locator('[id='+JSON.stringify(child.id)+']').isVisible(),true);
let parentId=child.parent_id;
while(parentId){assert.equal(await page.locator('[id='+JSON.stringify(parentId)+']').evaluate(e=>e.open),true);parentId=catalogue.entities.find(entity=>entity.id===parentId).parent_id;}
assert.deepEqual(await page.locator('#catalogueRows tr:visible').evaluateAll(rows=>rows.map(row=>row.dataset.entityId)),catalogue.entities.filter(entity=>matches(entity,child.title)).map(entity=>entity.id));
}
await search.fill('');
assert.equal(await page.locator('#kuiper').evaluate(e=>e.open),false);
receipt.checks.push('child searches expose parent nests and filter matching catalogue rows');
await page.locator('#identity-registry > summary').click();assert.equal(await page.locator('#identity-registry .launch').getAttribute('href'),'https://ventusltd.github.io/globalgrid2050-ip-and-mac-addresses/');
await page.locator('#kuiper > summary').click();await page.locator('#kuiper > .inside > .versions > summary').click();assert.match(await page.locator('#kuiper > .inside > .versions').innerText(),/Archived/i);assert.equal(await page.locator('#archiveLink').getAttribute('href'),catalogue.view.archive_url);receipt.checks.push('identity launch, operative history and archive retained');
await page.locator('#kuiper > summary').click();await page.locator('#identity-registry > summary').click();
await search.evaluate(e=>e.blur());await page.mouse.move(0,0);
assert.equal(await page.locator('.development-track').evaluate(e=>getComputedStyle(e).animationDuration),'24s');
await page.locator('.development-strip').hover();assert.equal(await page.locator('.development-track').evaluate(e=>getComputedStyle(e).animationPlayState),'paused');
await page.mouse.move(0,0);await page.locator('.development-group:not([aria-hidden]) a').first().focus();assert.equal(await page.locator('.development-track').evaluate(e=>getComputedStyle(e).animationName),'none');await page.locator('.development-group:not([aria-hidden]) a').first().evaluate(e=>e.blur());
assert.equal(await page.locator('.development-group[aria-hidden] a').first().getAttribute('tabindex'),'-1');
await page.screenshot({path:path.join(output,'desktop.png'),fullPage:true});receipt.checks.push('24-second ticker, hover/focus pause and one keyboard link per destination');
await page.setViewportSize({width:390,height:844});assert(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth));assert.equal(await page.locator('.catalogue-scroll').evaluate(e=>getComputedStyle(e).overflowX),'auto');assert(await page.locator('.catalogue-scroll').evaluate(e=>e.scrollWidth>e.clientWidth));await page.screenshot({path:path.join(output,'mobile.png'),fullPage:true}) … [line shortened here: 463 characters; full line on GitHub]
await page.emulateMedia({reducedMotion:'reduce'});assert.equal(await page.locator('.development-track').evaluate(e=>getComputedStyle(e).animationName),'none');assert.equal(await page.locator('.development-group[aria-hidden]').isVisible(),false);receipt.checks.push('reduced motion retains static links');
await page.emulateMedia({reducedMotion:'no-preference'});await page.goto(base);await page.waitForSelector('.development-track');
const destination=await page.locator('.development-group[aria-hidden] a').first().getAttribute('href');
await page.route(destination,route=>route.fulfill({status:200,contentType:'text/html',body:'<title>Destination click verified</title>'}));
await page.locator('.development-track').evaluate(e=>{e.style.animation='none';e.style.transform='translateX(-50%)';});
await page.locator('.development-group[aria-hidden] a').first().click();assert.equal(page.url(),destination);receipt.checks.push('visible repeated ticker link really navigates');
await page.route('**/data/active-pages.json',route=>route.fulfill({status:200,contentType:'application/json',body:JSON.stringify({items:[{label:'Repository',url:'https://github.com/Ventusltd/example'}]})}));
await page.goto(base);await page.waitForSelector('#searchControls:not([hidden])',{state:'attached'});await page.locator('#catalogueArchive').evaluate(e=>{e.open=true;});await page.waitForLoadState('networkidle');assert.equal(await page.locator('.development-strip').count(),0);assert.equal(await page.locator('#nests > details').count(),catalogue.view.items.length);receipt.checks.push('invalid optio … [line shortened here: 449 characters; full line on GitHub]
const fallback=await browser.newPage({javaScriptEnabled:false,viewport:{width:390,height:844}});await fallback.goto(base);assert.equal(await fallback.locator('#catalogueRows tr').count(),firstPage.length);assert.equal(await fallback.locator('#catalogueArchive #catalogue').count(),1);await fallback.locator('#catalogueArchive').evaluate(e=>{e.open=true;});for(const entity of firstPage){const release … [line shortened here: 1,022 characters; full line on GitHub]
for(const entity of catalogue.entities){let ancestor=entity;while(ancestor.parent_id)ancestor=catalogue.entities.find(item=>item.id===ancestor.parent_id);if(!catalogue.view.items.some(item=>item.entity_id===ancestor.id))continue;const release=entity.releases.find(item=>item.id===entity.operative_release_id);const nest=fallback.locator('[id='+JSON.stringify(entity.id)+']');assert.equal(await nest.c … [line shortened here: 561 characters; full line on GitHub]
await fallback.close();receipt.checks.push('static closed nests and archive survive disabled JavaScript');
const paged=await browser.newPage();
const large=structuredClone(catalogue);const largeMetadata=structuredClone(metadata);
for(let i=0;i<presentation.page_size+6;i++){const entity=structuredClone(catalogue.entities[0]);entity.id='pagination-probe-'+i;entity.title='Pagination probe '+i;delete entity.parent_id;large.entities.push(entity);largeMetadata.records[entity.id]=structuredClone(metadata.records[catalogue.entities[0].id]);}
await paged.route('**/data/homepage.json',route=>route.fulfill({status:200,contentType:'application/json',body:JSON.stringify(large)}));
await paged.route('**/data/entity-types.json',route=>route.fulfill({status:200,contentType:'application/json',body:JSON.stringify(largeMetadata)}));
await paged.goto(base);await paged.waitForSelector('#searchControls:not([hidden])',{state:'attached'});await paged.locator('#catalogueArchive').evaluate(e=>{e.open=true;});
assert.equal(await paged.locator('#catalogueRows tr').count(),presentation.page_size);
assert.equal(await paged.locator('#cataloguePrevious').isDisabled(),true);
assert.equal(await paged.locator('#catalogueNext').isDisabled(),false);
const ids=()=>paged.locator('#catalogueRows tr').evaluateAll(rows=>rows.map(row=>row.dataset.entityId));
await paged.locator('#catalogueNext').click();assert.deepEqual(await ids(),large.entities.slice(presentation.page_size,2*presentation.page_size).map(e=>e.id));
await paged.locator('#cataloguePrevious').click();assert.deepEqual(await ids(),large.entities.slice(0,presentation.page_size).map(e=>e.id));
await paged.locator('#homepageSearch').fill(large.entities.at(-1).id);assert.deepEqual(await ids(),[large.entities.at(-1).id]);assert.equal(await paged.locator('#catalogueNext').isDisabled(),true);
await paged.locator('#homepageSearch').fill('');assert.deepEqual(await ids(),large.entities.slice(0,presentation.page_size).map(e=>e.id));
while(!await paged.locator('#catalogueNext').isDisabled())await paged.locator('#catalogueNext').click();assert(await paged.locator('#catalogueRows tr').count()<=presentation.page_size);assert((await ids()).includes(large.entities.at(-1).id));
await paged.close();receipt.checks.push('synthetic multi-page catalogue bounds DOM rows, paginates in both directions and searches off-page permanent keys');
const invalidPresentation=await browser.newPage();
await invalidPresentation.route('**/data/presentation.json',route=>route.fulfill({status:200,contentType:'application/json',body:JSON.stringify({...presentation,page_size:1000000})}));
await invalidPresentation.goto(base);await invalidPresentation.waitForFunction(()=>document.getElementById('searchStatus').textContent.includes('unavailable'));
assert.equal(await invalidPresentation.locator('#searchControls').isVisible(),false);
assert.equal(await invalidPresentation.locator('.highlight-card').count(),presentation.highlights.length);
assert.equal(await invalidPresentation.locator('#catalogueRows tr').count(),firstPage.length);
await invalidPresentation.close();receipt.checks.push('invalid page-size configuration preserves bounded static fallback');
const unavailable=await browser.newPage();
await unavailable.route('**/data/homepage.json',route=>route.abort('timedout'));
await unavailable.goto(base);await unavailable.waitForFunction(()=>document.getElementById('searchStatus').textContent.includes('unavailable'));
assert.equal(await unavailable.locator('.highlight-card').count(),presentation.highlights.length);
assert.equal(await unavailable.locator('#nests > details').count(),catalogue.view.items.length);
await unavailable.close();receipt.checks.push('unavailable catalogue preserves static highlights and app links');
for(const scenario of ['missing-record','same-size-orphan','invalid-type','unsafe-evidence-url']){
const badMetadata=await browser.newPage();const unknown=structuredClone(metadata);
if(scenario==='missing-record')delete unknown.records.kuiper;
else if(scenario==='same-size-orphan'){unknown.records['unknown-entity']=unknown.records.kuiper;delete unknown.records.kuiper;}
else if(scenario==='invalid-type')unknown.records.kuiper.type='unrecognized';
else unknown.records.kuiper.capability_evidence.url='javascript:alert(1)';
await badMetadata.route('**/data/entity-types.json',route=>route.fulfill({status:200,contentType:'application/json',body:JSON.stringify(unknown)}));
await badMetadata.goto(base);await badMetadata.waitForFunction(()=>document.getElementById('searchStatus').textContent.includes('unavailable'));
assert.equal(await badMetadata.locator('#searchControls').isVisible(),false,scenario);
assert.equal(await badMetadata.locator('#catalogueRows tr').count(),firstPage.length,scenario);
assert.equal(await badMetadata.locator('.highlight-card').count(),presentation.highlights.length,scenario);
await badMetadata.close();
}
receipt.checks.push('missing, orphan, unknown-type and unsafe-evidence metadata preserve the static catalogue');
assert.deepEqual(errors,[]);receipt.checks.push('no browser runtime errors');receipt.status='pass';
}catch(error){receipt.status='fail';receipt.error=error.stack;process.exitCode=1;}finally{if(browser)await browser.close();server.close();fs.writeFileSync(path.join(output,'receipt.json'),JSON.stringify(receipt,null,2));console.log(JSON.stringify(receipt,null,2));}})();Test Active Pages
A test in the tests folder of GlobalGrid2050 Homepage using data from GitHub API and the SLD repository.
testglobalgrid2050-homepage / tests/test_active_pages.py · lines 1–88 of 88 · Entry point
- What it does
- It tests its inputs. Defines 17 functions or classes, including FakeAPI, get, ActivePageTests, config, test_rejects_repo_raw_and_insecure_destinations. Uses libraries datetime, importlib.util, json, pathlib, tempfile. Side effects: reads or writes files.
- Inputs & outputs
- In: data source: GitHub API; data source: sld data; JSON file homepage.json.
- Downstream impact
- Used directly by 3 files: Build Homepage Release Candidate Workflow (globalgrid2050-homepage); Pages Workflow (globalgrid2050-homepage); PR Checks Workflow (globalgrid2050-homepage).
- What it achieves
- It is built from the fake API class (`FakeAPI`), the active page tests class (`ActivePageTests`) and the config step (`config`). Defines `FakeAPI`, `get`, `ActivePageTests` and 14 more.
- Why it matters
- Run by Build Homepage Release Candidate Workflow, Pages Workflow and PR Checks Workflow.
- Application
- globalgrid2050-homepage · tests · test
- Uses
- datetime, importlib.util, json, pathlib, tempfile, unittest
- Used by
- run by Build Homepage Release Candidate Workflow (workflow run), run by Pages Workflow (workflow run), run by PR Checks Workflow (workflow run)
- Produces
- FakeAPI, ActivePageTests
- Defines here
- FakeAPI, get, ActivePageTests, config, test_rejects_repo_raw_and_insecure_destinations, test_deduplicates_live_routes, test_activity_excludes_self_refresh_and_marks_cap, test_network_failure_preserves_existing_file, fail, RecentAPI, get, test_private_repository_cannot_enter_public_feed, PrivateAPI, get, test_missing_pages_is_explicitly_skipped, MissingAPI, get
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050-homepage@551a7625b02ddb7b3e6e0181cc643b8114c7fc06 tests/test_active_pages.py:1-88 · blob 95411d047184c0a1ce6edfd200a6a6e7ebd73331 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: filesystem · domain stage: unknown · users: none · canonical: unknown
from datetime import datetime, timezone
import importlib.util
import json
from pathlib import Path
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[1]
spec = importlib.util.spec_from_file_location("active_pages", ROOT / "scripts/fetch_active_pages.py")
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
class FakeAPI:
def get(self, path, missing_ok=False):
if path.startswith("users/"):
return [{"name": "one", "has_pages": True}]
if path.endswith("/pages"):
return {"html_url": "https://example.org/app/", "status": "built"}
return [{"commit": {"message": "real work", "committer": {"date": "2026-09-24T00:00:00Z"}}}]
class ActivePageTests(unittest.TestCase):
def config(self):
config = json.loads((ROOT / "config/active-pages.yaml").read_text())
config["candidates"] = [{"repository": "one", "label": "One"}, {"repository": "one", "label": "Duplicate"}]
return config
def test_rejects_repo_raw_and_insecure_destinations(self):
for url in ["https://github.com/a/b", "https://gitlab.com/a/b", "https://bitbucket.org/a/b", "https://raw.githubusercontent.com/a/b", "http://example.org", "https://api.github.com/repos/a/b", "https://user:pass@example.org"]:
with self.assertRaises(ValueError):
module.app_url(url)
self.assertEqual(module.app_url("https://ventusltd.github.io/sld/"), "https://ventusltd.github.io/sld/")
def test_deduplicates_live_routes(self):
ticker = module.create_ticker(self.config(), FakeAPI(), lambda url, limit: url, datetime(2026, 9, 25, tzinfo=timezone.utc))
self.assertEqual(len(ticker["items"]), 1)
self.assertEqual(ticker["items"][0]["activity_count"], 1)
self.assertEqual(ticker["method"]["skipped"][0]["reason"], "duplicate_final_url")
def test_activity_excludes_self_refresh_and_marks_cap(self):
config = self.config()
config["commits_per_repository"] = 2
commits = [{"commit": {"message": title, "committer": {"date": "2026-09-24T00:00:00Z"}}} for title in ["real change", "chore: refresh active pages"]]
count, date, capped = module.activity(commits, config, datetime(2026, 9, 1, tzinfo=timezone.utc))
self.assertEqual(count, 1)
self.assertTrue(capped)
def test_network_failure_preserves_existing_file(self):
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / "homepage.json"
previous = b'{"entities": [], "ticker": {"old": true}}'
path.write_bytes(previous)
def fail(url, limit):
raise OSError("network failure")
class RecentAPI(FakeAPI):
# Keep the fixture commit inside the rolling activity window so the
# probe (and its network failure) is reached whatever today's date is.
def get(self, path, missing_ok=False):
result = super().get(path, missing_ok)
if isinstance(result, list) and result and "commit" in result[0]:
result[0]["commit"]["committer"]["date"] = module.stamp(datetime.now(timezone.utc))
return result
with self.assertRaises(OSError):
module.refresh(self.config(), path, RecentAPI(), fail)
self.assertEqual(path.read_bytes(), previous)
def test_private_repository_cannot_enter_public_feed(self):
class PrivateAPI(FakeAPI):
def get(self, path, missing_ok=False):
if path.startswith("users/"):
return [{"name": "one", "has_pages": True, "private": True}]
raise AssertionError("Private repository must not be probed")
with self.assertRaises(ValueError):
module.create_ticker(self.config(), PrivateAPI(), lambda url, limit: url, datetime(2026, 9, 25, tzinfo=timezone.utc))
def test_missing_pages_is_explicitly_skipped(self):
class MissingAPI(FakeAPI):
def get(self, path, missing_ok=False):
if path.endswith("/pages"):
return None
return super().get(path, missing_ok)
with self.assertRaisesRegex(ValueError, "No verified"):
module.create_ticker(self.config(), MissingAPI(), lambda url, limit: url, datetime(2026, 9, 25, tzinfo=timezone.utc))
if __name__ == "__main__":
unittest.main()Test Cyber Resilience Entry
A test in the tests folder of GlobalGrid2050 Homepage that checks Cyber Resilience — Index Page using data from the cyber-resilience repository.
testglobalgrid2050-homepage / tests/test_cyber_resilience_entry.py · lines 1–33 of 33 · Entry point
- What it does
- It tests cables. Defines CyberResilienceEntryTests, test_catalogue_metadata_fallback_remain_aligned. Uses libraries json, pathlib, unittest. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain terms in the code: cables.
- Inputs & outputs
- In: data source: cyber-resilience data; JSON file homepage.json; JSON file entity-types.json.
- Downstream impact
- Used directly by 3 files: Build Homepage Release Candidate Workflow (globalgrid2050-homepage); Pages Workflow (globalgrid2050-homepage); PR Checks Workflow (globalgrid2050-homepage).
- What it achieves
- It is built from the cyber resilience entry tests class (`CyberResilienceEntryTests`). The cyber resilience entry extends, rather than replaces, the homepage.
- Why it matters
- Run by Build Homepage Release Candidate Workflow, Pages Workflow and PR Checks Workflow.
- Application
- globalgrid2050-homepage · tests · test
- Uses
- Cyber Resilience — Index Page (estate URL), json, pathlib, unittest
- Used by
- run by Build Homepage Release Candidate Workflow (workflow run), run by Pages Workflow (workflow run), run by PR Checks Workflow (workflow run)
- Produces
- CyberResilienceEntryTests
- Defines here
- CyberResilienceEntryTests, test_catalogue_metadata_fallback_remain_aligned
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050-homepage@551a7625b02ddb7b3e6e0181cc643b8114c7fc06 tests/test_cyber_resilience_entry.py:1-33 · blob 95f7e167e28f790b62792cd050fb9fc7a9834d49 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: ingest · effects: filesystem · domain stage: unknown · users: none · canonical: unknown
"""The cyber resilience entry extends, rather than replaces, the homepage."""
import json
from pathlib import Path
import unittest
ROOT = Path(__file__).resolve().parents[1]
ID = "cyber-resilience-log"
class CyberResilienceEntryTests(unittest.TestCase):
def test_catalogue_metadata_fallback_remain_aligned(self):
catalogue = json.loads((ROOT / "data/homepage.json").read_text(encoding="utf-8"))
metadata = json.loads((ROOT / "data/entity-types.json").read_text(encoding="utf-8"))
html = (ROOT / "index.html").read_text(encoding="utf-8")
by_id = {entity["id"]: entity for entity in catalogue["entities"]}
self.assertEqual(len(by_id), len(catalogue["entities"]))
self.assertGreaterEqual(len(by_id), 28)
self.assertEqual(set(by_id), set(metadata["records"]))
self.assertEqual(catalogue["view"]["items"][9], {"entity_id": ID, "open": False})
self.assertEqual([item["entity_id"] for item in catalogue["view"]["items"][:9]],
["solar-design-studio","kuiper","gridatlas","ventus-grid-engine",
"pipeline-news","identity-registry","electricity-market-intelligence",
"metals-cable-prices","cable-engineering"])
entity = by_id[ID]
self.assertEqual(entity["operative_release_id"], "20261113")
self.assertEqual(entity["releases"][0]["url"], "https://ventusltd.github.io/cyber-resilience/")
self.assertEqual(html.count('<details id="cyber-resilience-log">'), 1)
self.assertIn('Cyber Resilience Log<small>', html)
self.assertIn('id="catalogueArchive"', html)
self.assertIn("Privacy", html)
self.assertIn("Kuiper", html)
if __name__ == "__main__":
unittest.main()Test Explore Code Entry
A test in the tests folder of GlobalGrid2050 Homepage using data from the cosmic repository. It is built from the explore code entry tests class (`ExploreCodeEntryTests`).
testglobalgrid2050-homepage / tests/test_explore_code_entry.py · lines 1–31 of 31 · Entry point
- What it does
- It tests its inputs. Defines ExploreCodeEntryTests, test_explore_code_section. Uses libraries json, unittest, pathlib. Side effects: reads or writes files.
- Inputs & outputs
- In: data source: cosmic data; JSON file homepage.json; JSON file entity-types.json.
- Downstream impact
- Used directly by 3 files: Build Homepage Release Candidate Workflow (globalgrid2050-homepage); Pages Workflow (globalgrid2050-homepage); PR Checks Workflow (globalgrid2050-homepage).
- What it achieves
- The Explore Code entry extends, rather than replaces, the homepage.
- Why it matters
- Run by Build Homepage Release Candidate Workflow, Pages Workflow and PR Checks Workflow.
- Application
- globalgrid2050-homepage · tests · test
- Uses
- json, unittest, pathlib
- Used by
- run by Build Homepage Release Candidate Workflow (workflow run), run by Pages Workflow (workflow run), run by PR Checks Workflow (workflow run)
- Produces
- ExploreCodeEntryTests
- Defines here
- ExploreCodeEntryTests, test_explore_code_section
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050-homepage@551a7625b02ddb7b3e6e0181cc643b8114c7fc06 tests/test_explore_code_entry.py:1-31 · blob 910dcbf16cf956e4e8c766f67973ebf487cefd21 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: ingest · effects: filesystem · domain stage: unknown · users: none · canonical: unknown
"""The Explore Code entry extends, rather than replaces, the homepage."""
import json
import unittest
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
ID = "explore-code"
class ExploreCodeEntryTests(unittest.TestCase):
def test_explore_code_section(self):
d = json.loads((ROOT / "data/homepage.json").read_text(encoding="utf-8"))
m = json.loads((ROOT / "data/entity-types.json").read_text(encoding="utf-8"))
h = (ROOT / "index.html").read_text(encoding="utf-8")
e = [e for e in d["entities"] if e["id"] == ID]
self.assertEqual(len(e), 1)
self.assertEqual(d["view"]["items"][12], {"entity_id": ID, "open": False})
self.assertEqual(d["view"]["items"][11]["entity_id"], "satnav-concept")
rel = {r["id"]: r for r in e[0]["releases"]}[e[0]["operative_release_id"]]
self.assertEqual(rel["url"], "https://ventusltd.github.io/cosmic/explore-code/")
self.assertRegex(rel["source_ref"], r"^https://github\.com/Ventusltd/(kuiper-belt|cosmic)/commit/[0-9a-f]{40}$")
self.assertEqual(rel["status"], "available")
self.assertEqual(m["records"][ID]["type"], "catalogue")
self.assertEqual(h.count('<details id="explore-code">'), 1)
self.assertIn('href="https://ventusltd.github.io/cosmic/explore-code/">Open Explore Code', h)
self.assertLess(h.index('id="satnav-concept"'), h.index('id="explore-code"'))
self.assertLess(h.index('id="explore-code"'), h.index('id="catalogueArchive"'))
if __name__ == "__main__":
unittest.main()Test Grid Explorer Entry
A test in the tests folder of GlobalGrid2050 Homepage that checks Kuiper Belt — See Through Page and Overlay using data from the cosmic and kuiper-belt repositories.
testglobalgrid2050-homepage / tests/test_grid_explorer_entry.py · lines 1–50 of 50 · Entry point
- What it does
- It tests solar. Defines GridExplorerEntryTests, test_grid_explorer_section. Uses libraries json, unittest, pathlib. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain terms in the code: solar.
- Inputs & outputs
- In: data source: cosmic data; data source: kuiper-belt data; JSON file homepage.json; JSON file entity-types.json.
- Downstream impact
- Used directly by 3 files: Build Homepage Release Candidate Workflow (globalgrid2050-homepage); Pages Workflow (globalgrid2050-homepage); PR Checks Workflow (globalgrid2050-homepage).
- What it achieves
- It is built from the grid explorer entry tests class (`GridExplorerEntryTests`). Section 01 is Grid Explorer: renamed from Solar Design Studio, links kept.
- Why it matters
- Run by Build Homepage Release Candidate Workflow, Pages Workflow and PR Checks Workflow.
- Application
- globalgrid2050-homepage · tests · test
- Uses
- Kuiper Belt — See Through Page (estate URL), Overlay (estate URL), json, unittest, pathlib
- Used by
- run by Build Homepage Release Candidate Workflow (workflow run), run by Pages Workflow (workflow run), run by PR Checks Workflow (workflow run)
- Produces
- GridExplorerEntryTests
- Defines here
- GridExplorerEntryTests, test_grid_explorer_section
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050-homepage@551a7625b02ddb7b3e6e0181cc643b8114c7fc06 tests/test_grid_explorer_entry.py:1-50 · blob 2d0ecb3100e7f6eea4ac74402ecd078c07267ec2 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: ingest · effects: filesystem · domain stage: unknown · users: none · canonical: unknown
"""Section 01 is Grid Explorer: renamed from Solar Design Studio, links kept."""
import json
import unittest
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
ID = "solar-design-studio"
DRONE = "https://ventusltd.github.io/cosmic/explore-code/drone/"
SEE = "https://ventusltd.github.io/kuiper-belt/see-through/"
KEPT = [
"https://globalgrid2050.com/energy-transition-simulator/202609282123/overlay.html",
"https://globalgrid2050.com/solar-design-studio/202609262041-site-world/",
]
class GridExplorerEntryTests(unittest.TestCase):
def test_grid_explorer_section(self):
d = json.loads((ROOT / "data/homepage.json").read_text(encoding="utf-8"))
m = json.loads((ROOT / "data/entity-types.json").read_text(encoding="utf-8"))
h = (ROOT / "index.html").read_text(encoding="utf-8")
by = {e["id"]: e for e in d["entities"]}
g = by[ID]
self.assertEqual(g["title"], "Grid Explorer")
self.assertEqual(g["operative_release_id"], "ets-202609282123")
self.assertEqual(len(g["releases"]), 13)
self.assertEqual(d["view"]["items"][0], {"entity_id": ID, "open": False})
children = [e["id"] for e in d["entities"] if e.get("parent_id") == ID]
self.assertEqual(children, ["electrical-scene-explorer", "energy-transition-simulator", "drone-view", "grid-explorer-see-through"])
for cid, url in (("drone-view", DRONE), ("grid-explorer-see-through", SEE)):
rel = {r["id"]: r for r in by[cid]["releases"]}[by[cid]["operative_release_id"]]
self.assertEqual(rel["url"], url)
self.assertEqual(rel["status"], "available")
self.assertIn(cid, m["records"])
self.assertEqual(by["see-through"]["parent_id"], "kuiper")
self.assertNotIn("Solar Design Studio", [e["title"] for e in d["entities"]])
nest = h[h.index('<details id="solar-design-studio">'):h.index('<details id="kuiper">')]
self.assertIn('<span class="title">Grid Explorer<small>', nest)
self.assertNotIn(">Solar Design Studio<", nest)
for url in [DRONE, SEE] + KEPT:
self.assertIn(f'href="{url}"', nest)
self.assertIn('<strong>Grid Explorer</strong>', h)
self.assertEqual(h.count('id="drone-view"'), 1)
roots = [i["entity_id"] for i in d["view"]["items"]]
self.assertEqual(len(roots), 13)
self.assertFalse([r for r in roots if "solar" in by[r]["title"].lower()], "no separate solar section")
self.assertIn("network researchers", m["records"][ID]["audience"])
if __name__ == "__main__":
unittest.main()Test Grid Explorer Labels
A test in the tests folder of GlobalGrid2050 Homepage that checks Solar Battery Energy Storage System (BESS) Topology V7 — GIS Single-Line Diagram (SLD) Financial Sandbox Page.
testglobalgrid2050-homepage / tests/test_grid_explorer_labels.py · lines 1–45 of 45 · Entry point
- What it does
- It tests solar. Defines GridExplorerLabelTests, test_sub_heading, test_fallback_html, test_ticker_label. Uses libraries json, unittest, pathlib. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain terms in the code: solar.
- Inputs & outputs
- In: JSON file homepage.json; JSON file active-pages.json.
- Downstream impact
- Used directly by 3 files: Build Homepage Release Candidate Workflow (globalgrid2050-homepage); Pages Workflow (globalgrid2050-homepage); PR Checks Workflow (globalgrid2050-homepage).
- What it achieves
- It is built from the grid explorer label tests class (`GridExplorerLabelTests`). Owner decision, 6 Dec 2026 01:34 Europe/London: the last visible "Solar Design Studio" labels (the Electrical Scene Explorer sub-heading and the ticker label) read "Grid Explorer".
- Why it matters
- Run by Build Homepage Release Candidate Workflow, Pages Workflow and PR Checks Workflow.
- Application
- globalgrid2050-homepage · tests · test
- Uses
- Solar Battery Energy Storage System (BESS) Topology V7 — GIS Single-Line Diagram (SLD) Financial Sandbox Page (estate URL), json, unittest, pathlib
- Used by
- run by Build Homepage Release Candidate Workflow (workflow run), run by Pages Workflow (workflow run), run by PR Checks Workflow (workflow run)
- Produces
- GridExplorerLabelTests
- Defines here
- GridExplorerLabelTests, test_sub_heading, test_fallback_html, test_ticker_label
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050-homepage@551a7625b02ddb7b3e6e0181cc643b8114c7fc06 tests/test_grid_explorer_labels.py:1-45 · blob d78bfd66cdc8dcd28040c72e666989404017457d · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: ingest · effects: filesystem · domain stage: unknown · users: none · canonical: unknown
"""Owner decision, 6 Dec 2026 01:34 Europe/London: the last visible
"Solar Design Studio" labels (the Electrical Scene Explorer sub-heading and the
ticker label) read "Grid Explorer". IDs, URLs and releases are unchanged and no
solar section is added. Audit records (promotion reasons) and the privacy
statement are left as written."""
import json
import unittest
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
SANDBOX = "https://globalgrid2050.com/solar-bess-topology-v7/gis-sld-financial-sandbox/index.html"
class GridExplorerLabelTests(unittest.TestCase):
def test_sub_heading(self):
d = json.loads((ROOT / "data/homepage.json").read_text(encoding="utf-8"))
by = {e["id"]: e for e in d["entities"]}
e = by["electrical-scene-explorer"]
self.assertEqual(e["subtitle"], "Grid Explorer drawing prototype")
self.assertEqual(e["parent_id"], "solar-design-studio")
self.assertEqual(e["operative_release_id"], "world-202609262041")
for entity in d["entities"]:
for key in ("title", "subtitle", "launch_label", "description"):
self.assertNotIn("Solar Design Studio", entity.get(key, ""), (entity["id"], key))
roots = [i["entity_id"] for i in d["view"]["items"]]
self.assertEqual(len(roots), 13)
self.assertFalse([r for r in roots if "solar" in by[r]["title"].lower()], "no separate solar section")
def test_fallback_html(self):
h = (ROOT / "index.html").read_text(encoding="utf-8")
self.assertEqual(h.count("Grid Explorer drawing prototype"), 2)
body = h[:h.index('<details id="privacy"')]
self.assertNotIn("Solar Design Studio", body)
def test_ticker_label(self):
for path in ("data/active-pages.json", "config/active-pages.yaml"):
data = json.loads((ROOT / path).read_text(encoding="utf-8"))
rows = data.get("items") or data.get("candidates")
labels = {row["url"]: row["label"] for row in rows if "url" in row}
self.assertEqual(labels[SANDBOX], "Grid Explorer", path)
self.assertNotIn("Solar Design Studio", labels.values(), path)
if __name__ == "__main__":
unittest.main()Test Homepage Fallback Archives
A test in the tests folder of GlobalGrid2050 Homepage that checks Build Homepage Fallback using data from the GridAtlas repository.
testglobalgrid2050-homepage / tests/test_homepage_fallback_archives.py · lines 1–80 of 80 · Entry point · pattern Links (shared by 3 files)
- What it does
- It tests its inputs. Defines 8 functions or classes, including Links, __init__, handle_starttag, handle_data, handle_endtag. Uses libraries copy, html, html.parser, json, pathlib. Side effects: reads or writes files; starts processes.
- Inputs & outputs
- In: data source: gridatlas data; JSON file homepage.json; JSON file entity-types.json; JSON file presentation.json.
- Downstream impact
- Used directly by 3 files: Build Homepage Release Candidate Workflow (globalgrid2050-homepage); Pages Workflow (globalgrid2050-homepage); PR Checks Workflow (globalgrid2050-homepage).
- What it achieves
- It is built from the links class (`Links`), the handle starttag helper (`handle_starttag`) and the handle data helper (`handle_data`). Couple real Python fallback links to the actual JavaScript archive rule.
- Why it matters
- Run by Build Homepage Release Candidate Workflow, Pages Workflow and PR Checks Workflow.
- Application
- globalgrid2050-homepage · tests · test
- Uses
- Build Homepage Fallback (sys.path import), copy, html, html.parser, json, pathlib, re, shutil, subprocess
- Used by
- run by Build Homepage Release Candidate Workflow (workflow run), run by Pages Workflow (workflow run), run by PR Checks Workflow (workflow run)
- Produces
- Links, FallbackArchiveTests
- Defines here
- Links, __init__, handle_starttag, handle_data, handle_endtag, FallbackArchiveTests, test_archive_decisions_match_actual_javascript_renderer, test_real_v191_archive_and_all_other_navigation_remain_correct
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050-homepage@551a7625b02ddb7b3e6e0181cc643b8114c7fc06 tests/test_homepage_fallback_archives.py:1-80 · blob 6b92de158aa94bcecf2e1d187088765bff31086d · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: ingest · effects: filesystem, process · domain stage: unknown · users: none · canonical: unknown
"""Couple real Python fallback links to the actual JavaScript archive rule."""
import copy
from html import unescape
from html.parser import HTMLParser
import json
from pathlib import Path
import re
import shutil
import subprocess
import sys
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'scripts'))
import build_homepage_fallback as fallback
class Links(HTMLParser):
def __init__(self, html):
super().__init__(); self.entity = None; self.anchor = None; self.links = {}; self.feed(html)
def handle_starttag(self, tag, attrs):
attrs = dict(attrs)
if tag == 'tr': self.entity = attrs.get('data-entity-id')
if tag == 'a' and self.entity: self.anchor = [attrs.get('href'), '']
def handle_data(self, text):
if self.anchor is not None: self.anchor[1] += text
def handle_endtag(self, tag):
if tag == 'a' and self.anchor is not None:
self.links[(self.entity, self.anchor[1].strip())] = self.anchor[0]; self.anchor = None
if tag == 'tr': self.entity = None
class FallbackArchiveTests(unittest.TestCase):
def test_archive_decisions_match_actual_javascript_renderer(self):
base = {'id': 'old', 'label': 'Old build', 'status': 'available', 'url': 'https://example.com/live/', 'archive_url': 'https://example.com/v/old/?a=1&b=2', 'archive_kind': 'app'}
cases = [{'release': copy.deepcopy(base), 'operative': flag} for flag in (False, True)]
for changes in ({'archive_kind': 'manifest'}, {'archive_url': 'https://github.com/owner/repo/blob/main/manifest.json'}, {'archive_url': None}, {'status': 'candidate'}):
cases.append({'release': {**base, **changes}, 'operative': False})
javascript = (ROOT / 'assets/versioned-homepage.js').read_text(encoding='utf8')
functions = []
for name in ('safeUrl', 'appUrl', 'releaseRow'):
match = re.search(r' function ' + name + r'\([^\n]*\) \{.*?\n \}', javascript, re.S)
self.assertIsNotNone(match, name); functions.append(match.group(0))
program = """const fs=require('node:fs'),vm=require('node:vm');
const input=JSON.parse(fs.readFileSync(0,'utf8'));
const context={URL,node:(tag,text,className)=>({tag,text,className,children:[],append(...nodes){this.children.push(...nodes);}}),link:(text,href)=>({text,href})};
vm.createContext(context);vm.runInContext(input.functions.join('\\n'),context);
process.stdout.write(JSON.stringify(input.cases.map(c=>context.releaseRow(c.release,c.operative).children[1].href)));
"""
result = subprocess.run(['node', '-e', program], input=json.dumps({'functions': functions, 'cases': cases}), text=True, capture_output=True, check=True)
actual = [unescape(fallback.release_app_url(c['release'], c['operative'])) for c in cases]
self.assertEqual(actual, json.loads(result.stdout))
self.assertEqual(actual[0], base['archive_url']); self.assertEqual(actual[1], base['url'])
def test_real_v191_archive_and_all_other_navigation_remain_correct(self):
data = json.loads((ROOT / 'data/homepage.json').read_text(encoding='utf8'))
original_data = json.dumps(data, sort_keys=True)
before = Links((ROOT / 'index.html').read_text(encoding='utf8')).links
with tempfile.TemporaryDirectory() as directory:
root = Path(directory); (root / 'data').mkdir()
for name in ('homepage.json', 'entity-types.json', 'presentation.json'):
shutil.copyfile(ROOT / 'data' / name, root / 'data' / name)
shutil.copyfile(ROOT / 'index.html', root / 'index.html')
fallback.build(root)
first = (root / 'index.html').read_bytes(); after = Links(first.decode()).links
atlas = next(e for e in data['entities'] if e['id'] == 'gridatlas')
old = next(r for r in atlas['releases'] if r['id'] == '202611161720')
self.assertEqual(after[('gridatlas', old['label'])], 'https://ventusltd.github.io/gridatlas/atlas/v/202611161720/')
for entity in data['entities']:
operative = next(r for r in entity['releases'] if r['id'] == entity['operative_release_id'])
if (entity['id'], entity['title']) in after:
self.assertEqual(after[(entity['id'], entity['title'])], operative['url'])
for release in entity['releases']:
key = (entity['id'], release['label'])
if key not in after: continue
if entity['id'] != 'gridatlas': self.assertEqual(after[key], before[key])
if release['id'] == entity['operative_release_id']: self.assertEqual(after[key], release['url'])
self.assertEqual(json.dumps(json.loads((root / 'data/homepage.json').read_text(encoding='utf8')), sort_keys=True), original_data)
fallback.build(root); self.assertEqual((root / 'index.html').read_bytes(), first)
if __name__ == '__main__': unittest.main()Test Releases
A test in the tests folder of GlobalGrid2050 Homepage. It is built from the fixture step (`fixture`) and the release contract tests class (`ReleaseContractTests`).
testglobalgrid2050-homepage / tests/test_releases.py · lines 1–158 of 158 · Entry point · pattern fixture (shared by 30 files)
- What it does
- It tests its inputs. Defines 12 functions or classes, including fixture, ReleaseContractTests, test_promotion_and_rollback_preserve_every_release, test_candidate_and_repeated_promotion_refused, test_invalid_references_and_duplicates. Uses libraries copy, importlib.util, json, pathlib, subprocess. Side effects: reads or writes files; starts processes.
- Inputs & outputs
- In: JSON file homepage.json; JSON file bad.json.
- Downstream impact
- Used directly by 3 files: Build Homepage Release Candidate Workflow (globalgrid2050-homepage); Pages Workflow (globalgrid2050-homepage); PR Checks Workflow (globalgrid2050-homepage).
- What it achieves
- Contract and transition tests; fixtures never modify the real catalogue.
- Why it matters
- Run by Build Homepage Release Candidate Workflow, Pages Workflow and PR Checks Workflow.
- Application
- globalgrid2050-homepage · tests · test
- Uses
- copy, importlib.util, json, pathlib, subprocess, sys, tempfile, unittest
- Used by
- run by Build Homepage Release Candidate Workflow (workflow run), run by Pages Workflow (workflow run), run by PR Checks Workflow (workflow run)
- Produces
- fixture, ReleaseContractTests
- Defines here
- fixture, ReleaseContractTests, test_promotion_and_rollback_preserve_every_release, test_candidate_and_repeated_promotion_refused, test_invalid_references_and_duplicates, test_parent_chain_and_cycle, test_dangerous_urls, test_archive_manifest_and_development, test_catalogue_growth_has_no_fixed_entity_count, test_audit_drift_rejected, test_cli_writes_then_reads_back_and_refusal_preserves_bytes, test_duplicate_json_property_rejected
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050-homepage@551a7625b02ddb7b3e6e0181cc643b8114c7fc06 tests/test_releases.py:1-158 · blob c3db8610194d3597b4dc1b4794559b85254978b2 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: unknown · users: none · canonical: unknown
"""Contract and transition tests; fixtures never modify the real catalogue."""
import copy
import importlib.util
import json
from pathlib import Path
import subprocess
import sys
import tempfile
import unittest
SCRIPT = Path(__file__).resolve().parents[1] / "scripts" / "releases.py"
SPEC = importlib.util.spec_from_file_location("releases", SCRIPT)
releases = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(releases)
def fixture():
return {
"schema_version": 1,
"entities": [{
"id": "tool", "title": "Tool", "subtitle": "Engineering",
"description": "Example tool", "launch_label": "Open tool",
"operative_release_id": "A",
"releases": [{
"id": rid, "label": f"Release {rid}",
"url": f"https://example.com/releases/{rid}/",
"published_at": "2026-09-25", "status": status,
"source_ref": f"owner/repo@{rid}",
} for rid, status in (("A", "available"), ("B", "available"), ("C", "candidate"))],
}],
"view": {"items": [{"entity_id": "tool", "open": True}], "archive_url": "https://example.com/archive/"},
}
class ReleaseContractTests(unittest.TestCase):
def test_promotion_and_rollback_preserve_every_release(self):
original = fixture()
expected_releases = copy.deepcopy(original["entities"][0]["releases"])
promoted = releases.promote(original, "tool", "B", "Target release tested")
self.assertEqual(promoted["entities"][0]["operative_release_id"], "B")
self.assertEqual(original["entities"][0]["operative_release_id"], "A")
self.assertEqual(promoted["entities"][0]["releases"], expected_releases)
archived = [r for r in promoted["entities"][0]["releases"] if r["status"] == "available" and r["id"] != "B"]
self.assertEqual([r["url"] for r in archived], ["https://example.com/releases/A/"])
rolled_back = releases.promote(promoted, "tool", "A", "Regression rollback")
self.assertEqual(rolled_back["entities"][0]["operative_release_id"], "A")
self.assertEqual(rolled_back["entities"][0]["releases"], expected_releases)
self.assertEqual([(p["from_release_id"], p["to_release_id"]) for p in rolled_back["promotions"]], [("A", "B"), ("B", "A")])
self.assertTrue(all(p["promoted_at"].endswith("Z") for p in rolled_back["promotions"]))
def test_candidate_and_repeated_promotion_refused(self):
for target in ("C", "A", "missing"):
with self.subTest(target=target), self.assertRaises(ValueError):
releases.promote(fixture(), "tool", target, "Testing refusal")
with self.assertRaises(ValueError):
releases.promote(fixture(), "tool", "B", " ")
def test_invalid_references_and_duplicates(self):
mutations = [
lambda d: d["entities"].append(copy.deepcopy(d["entities"][0])),
lambda d: d["entities"][0]["releases"].append(copy.deepcopy(d["entities"][0]["releases"][0])),
lambda d: d["entities"][0].update(operative_release_id="missing"),
lambda d: d["entities"][0].update(operative_release_id="C"),
lambda d: d["entities"][0].update(parent_id="missing"),
lambda d: d["entities"][0].update(parent_id="tool"),
lambda d: d["view"]["items"][0].update(entity_id="missing"),
lambda d: d["view"]["items"].append(copy.deepcopy(d["view"]["items"][0])),
lambda d: d["view"]["items"][0].update(open="true"),
lambda d: d.update(schema_version=True),
lambda d: d["entities"][0]["releases"][0].update(source_ref=" "),
lambda d: d["entities"][0]["releases"][0].update(published_at="2026-02-30"),
lambda d: d["entities"][0]["releases"][0].update(published_at="2026-09-25T12:00:00"),
lambda d: d.update(unexpected="schema drift"),
]
for i, mutation in enumerate(mutations):
data = fixture()
mutation(data)
with self.subTest(case=i), self.assertRaises(ValueError):
releases.validate(data)
def test_parent_chain_and_cycle(self):
data = fixture()
child = copy.deepcopy(data["entities"][0])
child.update(id="variant", parent_id="tool")
data["entities"].append(child)
releases.validate(data)
data["entities"][0]["parent_id"] = "variant"
with self.assertRaisesRegex(ValueError, "cycle"):
releases.validate(data)
def test_dangerous_urls(self):
for url in ("javascript:alert(1)", "data:text/html,test", "http://example.com", "//example.com", "https://user:secret@example.com", "https://example.com\\@evil.com", "https://example.com/\npath", "https://", "https://example.com:bad", "https://example.com:99999", "https://%65xample.com"):
with self.subTest(url=url), self.assertRaises(ValueError):
data = fixture()
data["entities"][0]["releases"][0]["url"] = url
releases.validate(data)
def test_archive_manifest_and_development(self):
data = fixture()
data["entities"][0]["releases"][0]["published_at"] = None
data["entities"][0]["releases"][0].update(archive_url="https://example.com/commit/abc/manifest.json", archive_kind="manifest")
data["development"] = [{"entity_id": "tool", "label": "Tool development", "status": "In development", "url": "https://example.com/repo/", "description": "A compact development highlight.", "evidence_summary": "Synthetic fixture tested."}]
releases.validate(data)
promoted = releases.promote(data, "tool", "B", "Verified")
self.assertEqual(promoted["entities"][0]["releases"][0]["archive_kind"], "manifest")
for key, value in (("entity_id", "missing"), ("status", "available"), ("url", "javascript:evil"), ("description", " "), ("evidence_summary", 12)):
invalid = copy.deepcopy(data)
invalid["development"][0][key] = value
with self.subTest(key=key), self.assertRaises(ValueError):
releases.validate(invalid)
del data["entities"][0]["releases"][0]["archive_url"]
with self.assertRaises(ValueError):
releases.validate(data)
def test_catalogue_growth_has_no_fixed_entity_count(self):
data = fixture()
for number in range(8):
extra = copy.deepcopy(data["entities"][0])
extra["id"] = f"extra-{number}"
data["entities"].append(extra)
data["view"]["items"].append({"entity_id": extra["id"], "open": False})
releases.validate(data)
self.assertEqual(len(data["entities"]), 9)
def test_audit_drift_rejected(self):
data = releases.promote(fixture(), "tool", "B", "Verified")
data["entities"][0]["operative_release_id"] = "A"
with self.assertRaisesRegex(ValueError, "promotion history"):
releases.validate(data)
def test_cli_writes_then_reads_back_and_refusal_preserves_bytes(self):
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / "homepage.json"
path.write_text(json.dumps(fixture()), encoding="utf-8")
result = subprocess.run([sys.executable, str(SCRIPT), "--file", str(path), "promote", "tool", "B", "--reason", "Verified target"], capture_output=True, text=True)
self.assertEqual(result.returncode, 0, result.stderr)
data = releases.load(path)
self.assertEqual(data["entities"][0]["operative_release_id"], "B")
before = path.read_bytes()
result = subprocess.run([sys.executable, str(SCRIPT), "promote", "tool", "B", "--reason", "Repeat", "--file", str(path)], capture_output=True, text=True)
self.assertNotEqual(result.returncode, 0)
self.assertEqual(path.read_bytes(), before)
result = subprocess.run([sys.executable, str(SCRIPT), "validate", "--file", str(path)], capture_output=True, text=True)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(list(Path(directory).iterdir()), [path])
def test_duplicate_json_property_rejected(self):
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / "bad.json"
path.write_text('{"schema_version": 1, "schema_version": 1}', encoding="utf-8")
with self.assertRaisesRegex(ValueError, "duplicate JSON property"):
releases.load(path)
if __name__ == "__main__":
unittest.main()