GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Automation and CI / globalgrid2050 / scripts

GlobalGrid2050 Test Make Publication and 2 more files

A test in the scripts folder that checks GlobalGrid2050 Make Publication, using SHA-256. It makes repo (`make_repo`), checks mode tests (`CheckModeTests`) and indexes revision tests (`IndexRevisionTests`).

530 lines of Python from globalgrid2050, in 3 files. Topic: Automation and CI. Section 1779 of 2044.

Cut 2026-12-06T03:07:51+00:00. A copy for reading; the repository at the stated commit is the source.

In the State lines below, domain stage, users and canonical status are rule-based first approximations from code and path evidence (rules explore-agent-rules-v1), not observed facts: the rules.

In this section

  1. GlobalGrid2050 Test Generate V8 Codebase Blueprint test · globalgrid2050 / scripts/test_generate_v8_codebase_blueprint.py lines 1–30
  2. GlobalGrid2050 Test Make Publication test · globalgrid2050 / scripts/test_make_publication.py lines 1–335
  3. GlobalGrid2050 Test Verify Published Versions test · globalgrid2050 / scripts/test_verify_published_versions.py lines 1–165

GlobalGrid2050 Test Generate V8 Codebase Blueprint

A test in the scripts folder covering battery storage (BESS) and solar.

testglobalgrid2050 / scripts/test_generate_v8_codebase_blueprint.py · lines 1–30 of 30 · Entry point

What it does
It tests battery storage (BESS) and solar. Uses libraries pathlib. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain terms in the code: battery storage (BESS), solar.
Downstream impact
Used directly by 2 files: GlobalGrid2050 Generate V8 Codebase Blueprint Workflow (globalgrid2050); GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050).
What it achieves
No statement of purpose was found in the file, a README line naming it, or its name.
Why it matters
Run by GlobalGrid2050 Generate V8 Codebase Blueprint Workflow and GlobalGrid2050 Project Signals Acid Workflow.
Application
globalgrid2050 · scripts · test
Uses
pathlib
Used by
run by GlobalGrid2050 Generate V8 Codebase Blueprint Workflow (workflow run), run by GlobalGrid2050 Project Signals Acid Workflow (workflow run)
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 scripts/test_generate_v8_codebase_blueprint.py:1-30 · blob a4b1c4ca100d2b2dab19f3c888f494753a14f2ae · GitHub at these lines
State
achieves: name · context: readme_derived · stage: ingest · effects: filesystem · domain stage: unknown · users: none · canonical: production_core
#!/usr/bin/env python3
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
BLUEPRINT = ROOT / "solar-bess-topology-v8" / "CODEBASE_BLUEPRINT.md"
REPORT = ROOT / "gridbot_reports" / "generate_v8_codebase_blueprint.md"

assert BLUEPRINT.exists(), "Missing V8 CODEBASE_BLUEPRINT.md"
assert REPORT.exists(), "Missing GridBot report"

text = BLUEPRINT.read_text(encoding="utf-8")
report = REPORT.read_text(encoding="utf-8")

for token in [
    "# GlobalGrid2050 V8 Codebase Blueprint",
    "## Directory Structure",
    "## File Summaries",
    "solar-bess-topology-v8/",
    "bess-pcs-standalone/",
    "bess-electrical-topology-review/",
    "HTML IDs:",
    "Signatures:",
    "DOM IDs referenced:",
]:
    assert token in text, token

assert "solar-bess-topology-v8/CODEBASE_BLUEPRINT.md" in report
assert "Create a compact code skeleton" in report

print("V8 codebase blueprint checks passed.")

GlobalGrid2050 Test Make Publication

A test in the scripts folder that checks GlobalGrid2050 Make Publication, using SHA-256. It makes repo (`make_repo`), checks mode tests (`CheckModeTests`) and indexes revision tests (`IndexRevisionTests`).

testglobalgrid2050 / scripts/test_make_publication.py · lines 1–335 of 335 · Entry point · pattern make_repo (shared by 3 files)

What it does
It tests its inputs. Defines 34 functions or classes, including git, make_repo, ManifestGenerationTests, test_writes_declarations_matching_the_committed_blobs, test_manifest_never_declares_itself. Uses libraries __future__, hashlib, json, os, subprocess. Side effects: reads or writes files; starts processes.
Inputs & outputs
In: JSON file result.json; JSON file publication.json. Out: JSON file publication.json; JSON file result.json.
Downstream impact
Used directly by 1 file: GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050).
What it achieves
Unit tests for `scripts/make_publication.py`.
Why it matters
Run by GlobalGrid2050 Project Signals Acid Workflow.
Application
globalgrid2050 · scripts · test
Uses
GlobalGrid2050 Make Publication (import), __future__, hashlib, json, os, subprocess, sys, tempfile, unittest
Used by
run by GlobalGrid2050 Project Signals Acid Workflow (workflow run)
Produces
git, make_repo, ManifestGenerationTests, CheckModeTests, CrlfRegressionTests, ArchiveShapeTests, BatchReaderTests, IndexRevisionTests
Defines here
git, make_repo, ManifestGenerationTests, test_writes_declarations_matching_the_committed_blobs, test_manifest_never_declares_itself, test_is_idempotent_byte_for_byte, test_output_has_lf_endings_and_one_trailing_newline, test_narrative_fields_survive_regeneration, CheckModeTests, test_check_fails_when_a_declaration_was_hand_edited, test_check_fails_when_the_manifest_is_missing, test_check_fails_when_a_tracked_file_is_undeclared, CrlfRegressionTests, test_crlf_working_copy_does_not_change_the_manifest, test_a_crlf_derived_declaration_is_detected_and_classified, test_a_plain_wrong_byte_count_is_not_blamed_on_crlf, test_an_unrelated_digest_is_not_blamed_on_crlf, test_crlf_expansion_arithmetic_is_one_byte_per_line_ending, ArchiveShapeTests, _seed, test_stamp_relative_paths_are_preserved, test_repo_root_relative_paths_are_preserved, test_dict_keyed_files_block_is_preserved, test_check_passes_on_correct_digests_but_strict_flags_formatting, test_existing_entry_order_is_preserved_so_regeneration_is_a_no_op, test_trailing_narrative_keys_keep_their_place, test_file_keyed_entries_are_read_and_written_back_as_file, test_unknown_per_entry_keys_survive, test_path_style_can_be_forced, BatchReaderTests
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 scripts/test_make_publication.py:1-335 · blob 990264d11aed049659bd66aea28c5fe3939bdea8 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: unknown · users: none · canonical: production_core
#!/usr/bin/env python3
"""Unit tests for scripts/make_publication.py.

The tests build throwaway git repositories rather than mocking git, because the
whole point of the generator is that it reads the object database instead of
the working copy -- a mocked git would test the wrong thing. In particular
`test_crlf_working_copy_does_not_change_the_manifest` reproduces the exact
defect that produced the three bad declarations: a file whose on-disk bytes are
CRLF while its blob is LF. If the generator ever regresses to hashing the disk,
that test fails.
"""

from __future__ import annotations

import hashlib
import json
import os
import subprocess
import sys
import tempfile
import unittest
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))
import make_publication as mp


def git(repo, *args):
    subprocess.run(["git", *args], cwd=repo, check=True,
                   stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)


def make_repo(files, stamp="testcode/202601010000"):
    """Create a temp repo containing `files` (repo-relative -> bytes)."""
    root = Path(tempfile.mkdtemp(prefix="mkpub-"))
    git(root, "init", "-q")
    git(root, "config", "user.email", "t@example.invalid")
    git(root, "config", "user.name", "t")
    git(root, "config", "core.autocrlf", "false")
    for rel, blob in files.items():
        p = root / rel
        p.parent.mkdir(parents=True, exist_ok=True)
        p.write_bytes(blob)
    git(root, "add", "-A")
    git(root, "commit", "-q", "-m", "seed")
    return root, root / stamp


LF_BODY = b'{\n  "a": 1,\n  "b": 2\n}\n'
CRLF_BODY = LF_BODY.replace(b"\n", b"\r\n")


class ManifestGenerationTests(unittest.TestCase):
    def test_writes_declarations_matching_the_committed_blobs(self):
        root, stamp = make_repo({
            "testcode/202601010000/result.json": LF_BODY,
            "testcode/202601010000/README.md": b"hello\n",
        })
        self.assertEqual(0, mp.process(str(stamp), "HEAD", check=False, quiet=True))
        doc = json.loads((stamp / "publication.json").read_text(encoding="utf-8"))
        by_path = {e["path"]: e for e in doc["files"]}
        # A folder with no prior manifest gets the archive's dominant
        # convention: paths relative to the stamp folder.
        self.assertEqual({"README.md", "result.json"}, set(by_path))
        self.assertEqual(len(LF_BODY), by_path["result.json"]["bytes"])
        self.assertEqual(hashlib.sha256(LF_BODY).hexdigest(),
                         by_path["result.json"]["sha256"])
        self.assertEqual(mp.SCHEMA, doc["schema"])
        self.assertEqual("202601010000", doc["stamp"])

    def test_manifest_never_declares_itself(self):
        root, stamp = make_repo({"testcode/202601010000/a.txt": b"a\n"})
        mp.process(str(stamp), "HEAD", check=False, quiet=True)
        doc = json.loads((stamp / "publication.json").read_text(encoding="utf-8"))
        self.assertNotIn("publication.json",
                         [os.path.basename(e["path"]) for e in doc["files"]])

    def test_is_idempotent_byte_for_byte(self):
        root, stamp = make_repo({"testcode/202601010000/a.txt": b"a\n"})
        mp.process(str(stamp), "HEAD", check=False, quiet=True)
        first = (stamp / "publication.json").read_bytes()
        mp.process(str(stamp), "HEAD", check=False, quiet=True)
        self.assertEqual(first, (stamp / "publication.json").read_bytes())
        git(root, "add", "-A")
        git(root, "commit", "-q", "-m", "manifest")
        self.assertEqual(0, mp.process(str(stamp), "HEAD", check=True, quiet=True))

    def test_output_has_lf_endings_and_one_trailing_newline(self):
        root, stamp = make_repo({"testcode/202601010000/a.txt": b"a\n"})
        mp.process(str(stamp), "HEAD", check=False, quiet=True)
        raw = (stamp / "publication.json").read_bytes()
        self.assertNotIn(b"\r", raw)
        self.assertTrue(raw.endswith(b"}\n"))
        self.assertFalse(raw.endswith(b"\n\n"))

    def test_narrative_fields_survive_regeneration(self):
        root, stamp = make_repo({"testcode/202601010000/a.txt": b"a\n"})
        (stamp / "publication.json").write_bytes(json.dumps({
            "schema": mp.SCHEMA,
            "stamp": "202601010000",
            "status": "test-only candidate; not promoted",
            "limitations": ["served-byte check pending"],
            "files": [],
        }, indent=2).encode("utf-8") + b"\n")
        mp.process(str(stamp), "HEAD", check=False, quiet=True)
        doc = json.loads((stamp / "publication.json").read_text(encoding="utf-8"))
        self.assertEqual("test-only candidate; not promoted", doc["status"])
        self.assertEqual(["served-byte check pending"], doc["limitations"])
        self.assertEqual(1, len(doc["files"]))


class CheckModeTests(unittest.TestCase):
    def test_check_fails_when_a_declaration_was_hand_edited(self):
        root, stamp = make_repo({"testcode/202601010000/a.txt": b"a\n"})
        mp.process(str(stamp), "HEAD", check=False, quiet=True)
        doc = json.loads((stamp / "publication.json").read_text(encoding="utf-8"))
        doc["files"][0]["bytes"] = 999
        (stamp / "publication.json").write_bytes(
            json.dumps(doc, indent=2).encode("utf-8") + b"\n")
        self.assertEqual(1, mp.process(str(stamp), "HEAD", check=True, quiet=True))

    def test_check_fails_when_the_manifest_is_missing(self):
        root, stamp = make_repo({"testcode/202601010000/a.txt": b"a\n"})
        self.assertEqual(1, mp.process(str(stamp), "HEAD", check=True, quiet=True))

    def test_check_fails_when_a_tracked_file_is_undeclared(self):
        root, stamp = make_repo({
            "testcode/202601010000/a.txt": b"a\n",
            "testcode/202601010000/b.txt": b"b\n",
        })
        mp.process(str(stamp), "HEAD", check=False, quiet=True)
        doc = json.loads((stamp / "publication.json").read_text(encoding="utf-8"))
        doc["files"] = [e for e in doc["files"] if not e["path"].endswith("b.txt")]
        (stamp / "publication.json").write_bytes(
            json.dumps(doc, indent=2).encode("utf-8") + b"\n")
        self.assertEqual(1, mp.process(str(stamp), "HEAD", check=True, quiet=True))


class CrlfRegressionTests(unittest.TestCase):
    """The defect this script exists to prevent."""

    def test_crlf_working_copy_does_not_change_the_manifest(self):
        root, stamp = make_repo({"testcode/202601010000/result.json": LF_BODY})
        mp.process(str(stamp), "HEAD", check=False, quiet=True)
        clean = (stamp / "publication.json").read_bytes()

        # Simulate a Windows checkout with core.autocrlf=true: the blob stays
        # LF, the file on disk becomes CRLF.
        (stamp / "result.json").write_bytes(CRLF_BODY)
        self.assertNotEqual(LF_BODY, (stamp / "result.json").read_bytes())

        mp.process(str(stamp), "HEAD", check=False, quiet=True)
        self.assertEqual(clean, (stamp / "publication.json").read_bytes())
        self.assertEqual(0, mp.process(str(stamp), "HEAD", check=True, quiet=True))

    def test_a_crlf_derived_declaration_is_detected_and_classified(self):
        root, stamp = make_repo({"testcode/202601010000/result.json": LF_BODY})
        (stamp / "publication.json").write_bytes(json.dumps({
            "schema": mp.SCHEMA,
            "stamp": "202601010000",
            "files": [{
                "path": "testcode/202601010000/result.json",
                "bytes": len(CRLF_BODY),
                "sha256": hashlib.sha256(CRLF_BODY).hexdigest(),
            }],
        }, indent=2).encode("utf-8") + b"\n")
        self.assertEqual(1, mp.process(str(stamp), "HEAD", check=True, quiet=True))
        note = mp.classify(
            {"bytes": len(CRLF_BODY), "sha256": hashlib.sha256(CRLF_BODY).hexdigest()},
            len(LF_BODY), hashlib.sha256(LF_BODY).hexdigest(), LF_BODY,
        )
        self.assertIn("CRLF drift, proven", note)
        self.assertIn(str(LF_BODY.count(b"\n")), note)

    def test_a_plain_wrong_byte_count_is_not_blamed_on_crlf(self):
        note = mp.classify(
            {"bytes": 999, "sha256": hashlib.sha256(LF_BODY).hexdigest()},
            len(LF_BODY), hashlib.sha256(LF_BODY).hexdigest(), LF_BODY,
        )
        self.assertNotIn("CRLF", note)
        self.assertIn("byte count", note)

    def test_an_unrelated_digest_is_not_blamed_on_crlf(self):
        note = mp.classify(
            {"bytes": 40, "sha256": hashlib.sha256(b"something else\n").hexdigest()},
            len(LF_BODY), hashlib.sha256(LF_BODY).hexdigest(), LF_BODY,
        )
        self.assertIn("not a CRLF expansion", note)

    def test_crlf_expansion_arithmetic_is_one_byte_per_line_ending(self):
        self.assertEqual(len(LF_BODY) + LF_BODY.count(b"\n"), len(CRLF_BODY))


class ArchiveShapeTests(unittest.TestCase):
    """The archive holds two path conventions and two `files` shapes.

    A --check that rewrote either would report drift on folders whose digests
    are entirely correct, so both must be inferred and reproduced.
    """

    def _seed(self, files_block):
        root, stamp = make_repo({"testcode/202601010000/a.txt": b"a\n"})
        (stamp / "publication.json").write_bytes(json.dumps({
            "schema": mp.SCHEMA, "stamp": "202601010000", "files": files_block,
        }, indent=2).encode("utf-8") + b"\n")
        return root, stamp

    def test_stamp_relative_paths_are_preserved(self):
        sha = hashlib.sha256(b"a\n").hexdigest()
        root, stamp = self._seed([{"path": "a.txt", "bytes": 2, "sha256": sha}])
        self.assertEqual(0, mp.process(str(stamp), "HEAD", check=True, quiet=True))
        mp.process(str(stamp), "HEAD", check=False, quiet=True)
        doc = json.loads((stamp / "publication.json").read_text(encoding="utf-8"))
        self.assertEqual(["a.txt"], [e["path"] for e in doc["files"]])

    def test_repo_root_relative_paths_are_preserved(self):
        sha = hashlib.sha256(b"a\n").hexdigest()
        root, stamp = self._seed([{"path": "testcode/202601010000/a.txt",
                                   "bytes": 2, "sha256": sha}])
        self.assertEqual(0, mp.process(str(stamp), "HEAD", check=True, quiet=True))
        mp.process(str(stamp), "HEAD", check=False, quiet=True)
        doc = json.loads((stamp / "publication.json").read_text(encoding="utf-8"))
        self.assertEqual(["testcode/202601010000/a.txt"], [e["path"] for e in doc["files"]])

    def test_dict_keyed_files_block_is_preserved(self):
        sha = hashlib.sha256(b"a\n").hexdigest()
        root, stamp = self._seed({"a.txt": {"bytes": 2, "sha256": sha}})
        self.assertEqual(0, mp.process(str(stamp), "HEAD", check=True, quiet=True))
        mp.process(str(stamp), "HEAD", check=False, quiet=True)
        doc = json.loads((stamp / "publication.json").read_text(encoding="utf-8"))
        self.assertIsInstance(doc["files"], dict)
        self.assertEqual(2, doc["files"]["a.txt"]["bytes"])

    def test_check_passes_on_correct_digests_but_strict_flags_formatting(self):
        sha = hashlib.sha256(b"a\n").hexdigest()
        root, stamp = self._seed({"a.txt": {"sha256": sha, "bytes": 2}})
        self.assertEqual(0, mp.process(str(stamp), "HEAD", check=True, quiet=True))
        self.assertEqual(1, mp.process(str(stamp), "HEAD", check=True, strict=True, quiet=True))

    def test_existing_entry_order_is_preserved_so_regeneration_is_a_no_op(self):
        root, stamp = make_repo({
            "testcode/202601010000/a.txt": b"a\n",
            "testcode/202601010000/z.txt": b"z\n",
        })
        # deliberately unsorted, as several archived manifests are
        (stamp / "publication.json").write_bytes(json.dumps({
            "schema": mp.SCHEMA, "stamp": "202601010000", "files": {
                "z.txt": {"bytes": 2, "sha256": hashlib.sha256(b"z\n").hexdigest()},
                "a.txt": {"bytes": 2, "sha256": hashlib.sha256(b"a\n").hexdigest()},
            },
        }, indent=2).encode("utf-8") + b"\n")
        before = (stamp / "publication.json").read_bytes()
        mp.process(str(stamp), "HEAD", check=False, quiet=True)
        self.assertEqual(before, (stamp / "publication.json").read_bytes())
        self.assertEqual(0, mp.process(str(stamp), "HEAD", check=True, strict=True, quiet=True))

    def test_trailing_narrative_keys_keep_their_place(self):
        root, stamp = make_repo({"testcode/202601010000/a.txt": b"a\n"})
        (stamp / "publication.json").write_bytes(json.dumps({
            "schema": mp.SCHEMA, "stamp": "202601010000",
            "files": [{"path": "a.txt", "bytes": 2,
                       "sha256": hashlib.sha256(b"a\n").hexdigest()}],
            "supersedes": "202512310000",
        }, indent=2).encode("utf-8") + b"\n")
        before = (stamp / "publication.json").read_bytes()
        mp.process(str(stamp), "HEAD", check=False, quiet=True)
        after = (stamp / "publication.json").read_bytes()
        self.assertEqual(before, after)
        self.assertLess(after.index(b'"files"'), after.index(b'"supersedes"'))

    def test_file_keyed_entries_are_read_and_written_back_as_file(self):
        """Two archived manifests name the path field `file`, not `path`.

        Reading only `path` made the generator call 243 correctly declared
        entries undeclared, which is worse than useless in CI.
        """
        root, stamp = self._seed([{"file": "a.txt", "bytes": 2,
                                   "sha256": hashlib.sha256(b"a\n").hexdigest()}])
        self.assertEqual(0, mp.process(str(stamp), "HEAD", check=True, quiet=True))
        mp.process(str(stamp), "HEAD", check=False, quiet=True)
        doc = json.loads((stamp / "publication.json").read_text(encoding="utf-8"))
        self.assertEqual(["a.txt"], [e["file"] for e in doc["files"]])
        self.assertNotIn("path", doc["files"][0])

    def test_unknown_per_entry_keys_survive(self):
        root, stamp = self._seed([{"file": "a.txt", "bytes": 2,
                                   "sha256": hashlib.sha256(b"a\n").hexdigest(),
                                   "mtime_utc": "2026-09-15T01:12:16.382Z"}])
        mp.process(str(stamp), "HEAD", check=False, quiet=True)
        doc = json.loads((stamp / "publication.json").read_text(encoding="utf-8"))
        self.assertEqual("2026-09-15T01:12:16.382Z", doc["files"][0]["mtime_utc"])

    def test_path_style_can_be_forced(self):
        sha = hashlib.sha256(b"a\n").hexdigest()
        root, stamp = self._seed([{"path": "a.txt", "bytes": 2, "sha256": sha}])
        mp.process(str(stamp), "HEAD", check=False, quiet=True, path_style="repo")
        doc = json.loads((stamp / "publication.json").read_text(encoding="utf-8"))
        self.assertEqual(["testcode/202601010000/a.txt"], [e["path"] for e in doc["files"]])


class BatchReaderTests(unittest.TestCase):
    def test_batch_read_matches_single_file_read(self):
        blobs = {
            "testcode/202601010000/a.txt": b"a\n",
            "testcode/202601010000/big.bin": bytes(range(256)) * 400,
            "testcode/202601010000/empty.txt": b"",
            "testcode/202601010000/utf8.txt": "café — ünicode\n".encode("utf-8"),
        }
        root, stamp = make_repo(blobs)
        with mp.BatchReader(str(root)) as reader:
            for rel, expected in blobs.items():
                self.assertEqual(expected, reader.read("HEAD:" + rel), rel)
                self.assertEqual(mp.committed_bytes(str(root), rel, "HEAD"),
                                 reader.read("HEAD:" + rel), rel)

    def test_batch_reader_rejects_a_missing_path(self):
        root, stamp = make_repo({"testcode/202601010000/a.txt": b"a\n"})
        with mp.BatchReader(str(root)) as reader:
            with self.assertRaises(mp.GitError):
                reader.read("HEAD:testcode/202601010000/nope.txt")


class IndexRevisionTests(unittest.TestCase):
    def test_empty_rev_reads_the_index_so_a_new_stamp_can_be_manifested(self):
        root, stamp = make_repo({"testcode/202601010000/a.txt": b"a\n"})
        (stamp / "new.txt").write_bytes(b"new\n")
        git(root, "add", "-A")  # staged but not committed
        self.assertEqual(0, mp.process(str(stamp), "", check=False, quiet=True))
        doc = json.loads((stamp / "publication.json").read_text(encoding="utf-8"))
        paths = [e["path"] for e in doc["files"]]
        self.assertIn("new.txt", paths)


if __name__ == "__main__":
    unittest.main(verbosity=2)

GlobalGrid2050 Test Verify Published Versions

A test in the scripts folder that checks GlobalGrid2050 Verify Published Versions, using SHA-256 using data from GitHub API and the GridAtlas repository.

testglobalgrid2050 / scripts/test_verify_published_versions.py · lines 1–165 of 165 · Entry point · pattern Response (shared by 4 files)

What it does
It tests its inputs. Defines 11 functions or classes, including PublicationTruthTests, test_every_published_snapshot_is_reachable_and_the_newest_is_first, test_the_newest_published_wrapper_is_complete_and_hash_bound, test_github_token_is_scoped_to_github_api_and_raw_hosts, Response. Uses libraries __future__, hashlib, re, sys, unittest. Side effects: reads or writes files; makes network requests.
Inputs & outputs
In: data source: GitHub API; data source: gridatlas data; JSON file current.json.
Downstream impact
Used directly by 2 files: GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050); GlobalGrid2050 Verify Published Versions Workflow (globalgrid2050).
What it achieves
It is built from the publication truth tests class (`PublicationTruthTests`), the response class (`Response`) and the read step (`read`). Unit tests for fail-closed homepage publication and lineage checks.
Why it matters
Run by GlobalGrid2050 Project Signals Acid Workflow and GlobalGrid2050 Verify Published Versions Workflow.
Application
globalgrid2050 · scripts · test
Uses
GlobalGrid2050 Verify Published Versions (import), __future__, hashlib, re, sys, unittest, pathlib
Used by
run by GlobalGrid2050 Project Signals Acid Workflow (workflow run), run by GlobalGrid2050 Verify Published Versions Workflow (workflow run)
Produces
PublicationTruthTests, WorkflowExecutionBudgetTests
Defines here
PublicationTruthTests, test_every_published_snapshot_is_reachable_and_the_newest_is_first, test_the_newest_published_wrapper_is_complete_and_hash_bound, test_github_token_is_scoped_to_github_api_and_raw_hosts, Response, __enter__, __exit__, read, fake_urlopen, WorkflowExecutionBudgetTests, test_pinned_playwright_install_jobs_have_viable_timeouts
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 scripts/test_verify_published_versions.py:1-165 · blob c69424f466876bf279d214b17b6ef037384ec6fa · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem, network · domain stage: unknown · users: none · canonical: production_core
#!/usr/bin/env python3
"""Unit tests for fail-closed homepage publication and lineage checks."""

from __future__ import annotations

import hashlib
import re
import sys
import unittest
from pathlib import Path
from unittest import mock

sys.path.insert(0, str(Path(__file__).resolve().parent))
import verify_published_versions as verifier


class PublicationTruthTests(unittest.TestCase):
    """What this file still asserts, and what it stopped asserting.

    Sixteen tests here used to drive check_gridatlas_homepage_identity() against
    index.html: the GRIDATLAS_V9_AUTOMATION markers, the AREAS directory, the
    os-strip identity line, the 127-row version catalogue and its promotion and
    retention rules. None of that has been in the homepage since c9fd7dad put the
    catalogue view back, so thirteen of them failed on every push for a week and
    the workflow never reached the script they were guarding. They are removed
    with the check they exercised - the structure they described survives in
    homepage_versions/homepage_v034.html and in git, and the live Grid Atlas
    composition is still read over the network by check_network().

    What is left is what is still true: every published snapshot must be
    reachable, the newest must be presented first, the newest published wrapper
    must be internally hash-bound, and the GitHub token must not leak to hosts
    that are not GitHub."""

    def test_every_published_snapshot_is_reachable_and_the_newest_is_first(self) -> None:
        published = verifier.published_snapshots()
        named = verifier.named_on_homepage(verifier.INDEX.read_text(encoding="utf-8"))
        self.assertEqual(sorted(published, reverse=True), named)
        self.assertEqual(max(published), named[0])

    def test_the_newest_published_wrapper_is_complete_and_hash_bound(self) -> None:
        # This named 202609040144 as the newest published generation. Four newer
        # snapshots have been published since and the literal was never moved, so
        # the test asserted the repository was five days ago. The newest wrapper is
        # now derived; what is asserted is the property, not the date: every file
        # the wrapper ships is listed in its own sha256sums.txt and hashes to the
        # digest recorded there, and nothing is shipped that is not listed.
        newest = verifier.published_snapshots()[-1]
        wrapper = verifier.SNAPSHOTS / newest
        sums = wrapper / "sha256sums.txt"
        if not sums.is_file():
            self.skipTest(f"{newest} ships no sha256sums.txt to bind it to")
        files = sorted(path for path in wrapper.rglob("*") if path.is_file())
        declared: dict[str, str] = {}
        for line in sums.read_text(encoding="utf-8").splitlines():
            digest, relative = line.split("  ", 1)
            declared[relative] = digest
        shipped = {
            path.relative_to(wrapper).as_posix()
            for path in files
            if path.name != "sha256sums.txt"
        }
        self.assertEqual(shipped, set(declared))
        for relative, expected in declared.items():
            self.assertEqual(
                expected,
                hashlib.sha256((wrapper / relative).read_bytes()).hexdigest(),
                relative,
            )

    def test_github_token_is_scoped_to_github_api_and_raw_hosts(self) -> None:
        seen: list[tuple[str, dict[str, str]]] = []

        class Response:
            def __enter__(self):
                return self

            def __exit__(self, *_args):
                return False

            @staticmethod
            def read() -> bytes:
                return b"ok"

        def fake_urlopen(request, timeout):
            seen.append(
                (
                    request.full_url,
                    {name.lower(): value for name, value in request.header_items()},
                )
            )
            self.assertEqual(20, timeout)
            return Response()

        urls = (
            "https://api.github.com/repos/Ventusltd/gridatlas/commits/main",
            "https://raw.githubusercontent.com/Ventusltd/gridatlas/main/atlas/current.json",
            "https://ventusltd.github.io/gridatlas/atlas/current.json",
        )
        with mock.patch.dict(verifier.os.environ, {"GITHUB_TOKEN": "unit-token"}), mock.patch.object(
            verifier.urllib.request,
            "urlopen",
            side_effect=fake_urlopen,
        ):
            for url in urls:
                self.assertEqual(b"ok", verifier.fetch(url))

        self.assertEqual("Bearer unit-token", seen[0][1].get("authorization"))
        self.assertEqual("Bearer unit-token", seen[1][1].get("authorization"))
        self.assertNotIn("authorization", seen[2][1])

class WorkflowExecutionBudgetTests(unittest.TestCase):
    def test_pinned_playwright_install_jobs_have_viable_timeouts(self) -> None:
        workflows = verifier.ROOT / ".github" / "workflows"
        browser_jobs: dict[tuple[str, str], int] = {}
        job_header = re.compile(r"^  ([A-Za-z0-9_-]+):\s*$")
        timeout_line = re.compile(r"^    timeout-minutes:\s*([0-9]+)\s*$", re.MULTILINE)

        paths = sorted((*workflows.glob("*.yml"), *workflows.glob("*.yaml")))
        for path in paths:
            lines = path.read_text(encoding="utf-8").splitlines()
            try:
                jobs_line = lines.index("jobs:")
            except ValueError:
                continue
            starts = [
                (index, match.group(1))
                for index, line in enumerate(lines[jobs_line + 1 :], jobs_line + 1)
                if (match := job_header.fullmatch(line))
            ]
            for position, (start, job_name) in enumerate(starts):
                end = starts[position + 1][0] if position + 1 < len(starts) else len(lines)
                block = "\n".join(lines[start:end])
                if "playwright install --with-deps" not in block:
                    continue
                timeouts = timeout_line.findall(block)
                relative = path.relative_to(verifier.ROOT).as_posix()
                self.assertEqual(
                    1,
                    len(timeouts),
                    f"{relative}:{job_name} must declare exactly one job timeout",
                )
                timeout = int(timeouts[0])
                browser_jobs[(relative, job_name)] = timeout
                self.assertGreaterEqual(
                    timeout,
                    12,
                    f"{relative}:{job_name} cannot fit a pinned --with-deps install and proof",
                )

        raised_after_observed_timeout = {
            (".github/workflows/deploy-pages.yml", "verify_v9_7_candidate"),
            (".github/workflows/v7-north-star.yml", "validate"),
            (".github/workflows/v9-3-validate.yml", "validate"),
            (".github/workflows/v9-4-validate.yml", "validate"),
            (".github/workflows/v9-6-validate.yml", "validate"),
        }
        self.assertEqual(
            {job: 20 for job in raised_after_observed_timeout},
            {job: browser_jobs.get(job) for job in raised_after_observed_timeout},
        )


if __name__ == "__main__":
    unittest.main()