Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : SP Boucher Source Governance9# File : tests/test_engine.py10# Description : Unit and integration tests of the header engine (stdlib11# unittest; run: python3 -m unittest discover -s tests).12# Module : tests13# Repository : https://git.spboucher.ai/spb-source-governance14# Project Website : https://git.spboucher.ai15# Created : 2026-11-2116# Last Modified : 2026-11-2117#18# =============================================================================19# AUTHOR & PROFESSIONAL AFFILIATION20# =============================================================================21#22# Author : Simon-Pierre Boucher23# Position : Professor of Finance24# Institution : Université du Québec en Outaouais (UQO)25# Department : Département des sciences administratives26# Organization : SP Boucher27#28# Website : https://spboucher.ai29# Git : https://git.spboucher.ai30#31# =============================================================================32# OFFICIAL CONTACT DIRECTORY33# =============================================================================34#35# General : info@spboucher.ai36# Professional : contact@spboucher.ai37# Direct : simon@spboucher.ai38# Research : research@spboucher.ai39# Development : dev@spboucher.ai40# Support : support@spboucher.ai41# Security/Admin : admin@spboucher.ai42# Notifications : notifications@spboucher.ai43#44# Preferred Contact: dev@spboucher.ai45#46# =============================================================================47# COPYRIGHT & INTELLECTUAL PROPERTY48# =============================================================================49#50# Copyright (c) 202651# Simon-Pierre Boucher52#53# All rights reserved where applicable.54#55# This file is governed by the applicable project license,56# copyright notices, institutional agreements and relevant law.57#58# Unless expressly authorized by the applicable license or59# rights holder, copying, redistribution, sublicensing,60# publication and commercial exploitation are not permitted.61#62# Existing third-party rights and notices remain unaffected.63#64# =============================================================================65# CONFIDENTIALITY & SECURITY66# =============================================================================67#68# Classification : Public69# Distribution : Public repository; use is governed by the project license70# Security Contact : admin@spboucher.ai71#72# Access to this source does not independently grant permission73# to redistribute or disclose confidential materials.74#75# Do not embed credentials, private keys, access tokens,76# certificates or confidential personal information.77#78# =============================================================================79# LICENSE & MAINTENANCE80# =============================================================================81#82# License : None specified (no license file in this repository)83# Maintainer : Simon-Pierre Boucher84# Technical Contact: dev@spboucher.ai85#86# =============================================================================87# END OF SP BOUCHER SOURCE HEADER88# =============================================================================8990"""Unit and integration tests of the header engine (stdlib unittest; run: python3 -m unittest discover -s tests)."""91import ast92import json93import subprocess94import sys95import tempfile96import unittest97from pathlib import Path9899sys.path.insert(0, str(Path(__file__).resolve().parent.parent))100from spbheader import core, repo as R # noqa: E402101from spbheader import cli # noqa: E402102103CFG = core.load_config()104POLICY = {105 "schema": 1, "slug": "demo", "project": "Demo Project", "category": "tool", "status": "in-scope",106 "repository_url": "https://git.spboucher.ai/demo", "project_url": "", "version": "", "contact": "dev@spboucher.ai",107 "classification": "Public", "distribution": "Public repository; use is governed by the project license",108 "copyright": {"line": "Copyright (c) 2026", "holder": "Simon-Pierre Boucher", "oneline": "(c) 2026 Simon-Pierre Boucher"},109 "license": {"name": "MIT License", "spdx": "MIT", "file": "LICENSE"}, "exclude": {"paths": []}, "variant": {},110}111112113def apply(path: str, data: bytes, policy=POLICY, dates=("2026-01-02", "2026-03-04")):114 text = data.decode("utf-8", "replace")115 syn, why = core.syntax_for(path, text, CFG)116 if syn is None:117 return None, why, None118 plan, tx = core.analyze(path, data, CFG, syn)119 if plan.action == "skip":120 return None, plan.reason, None121 variant = R.choose_variant(path, syn, policy)122 new = core.build(tx, plan, variant, R.header_values(path, policy, CFG, variant, dates), CFG, syn)123 return new, variant, (plan, syn)124125126class Splice(unittest.TestCase):127 CASES = {128 "a.py": b'#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n"""Compute things. More."""\nimport os\nx = 1\n',129 "b.swift": b"// swift-tools-version: 6.0\nimport PackageDescription\nlet package = 1\n",130 "c.ts": b'"use client";\nimport x from "y";\nexport const a = 1;\n',131 "d.tex": b"% !TEX program = xelatex\n\\documentclass{article}\n\\begin{document}x\\end{document}\n",132 "e.sh": b"#!/bin/bash\nset -euo pipefail\necho hi\n",133 "f.go": b"//go:build linux\n\npackage main\n",134 "g.R": b"x <- 1\nprint(x)\n",135 "h.jl": b"x = 1\n",136 "i.cpp": b"#include <vector>\nint main() { return 0; }\n",137 "j.sql": b"select 1;\n",138 "k.css": b"body { margin: 0; }\n",139 "l.yaml": b"---\nname: x\nitems:\n - 1\n",140 "m.toml": b'[a]\nb = "c"\n',141 "Dockerfile": b"# syntax=docker/dockerfile:1\nFROM alpine\n",142 "n.bib": b"@article{k, title={T}, author={A}}\n",143 "o.do": b"use data, clear\nreg y x\n",144 "p.m": b"x = 1;\ndisp(x)\n",145 "q.m": b"#import <Foundation/Foundation.h>\n@implementation A\n@end\n",146 "r.vue": b"<template><div/></template>\n",147 "s.test.ts": b"/** @jest-environment jsdom */\nimport { a } from './a';\n",148 }149150 def test_insert_is_reversible_and_idempotent(self):151 for path, data in self.CASES.items():152 with self.subTest(path=path):153 new, variant, ctx = apply(path, data)154 self.assertIsNotNone(new, variant)155 plan, syn = ctx156 self.assertIn(core.MARK_END.encode(), new)157 self.assertEqual(core.strip_header(new, path, CFG, syn, plan.removed_legacy, plan.sep), data)158 again, _, ctx2 = apply(path, new)159 self.assertEqual(again, new, "second pass must change nothing")160 self.assertEqual(ctx2[0].action, "update")161162 def test_prologues_stay_first(self):163 first = lambda p: apply(p, self.CASES[p])[0].split(b"\n")164 self.assertEqual(first("a.py")[0], b"#!/usr/bin/env python3")165 self.assertEqual(first("a.py")[1], b"# -*- coding: utf-8 -*-")166 self.assertEqual(first("b.swift")[0], b"// swift-tools-version: 6.0")167 self.assertEqual(first("d.tex")[0], b"% !TEX program = xelatex")168 self.assertEqual(first("e.sh")[0], b"#!/bin/bash")169 self.assertEqual(first("f.go")[0], b"//go:build linux")170 self.assertEqual(first("Dockerfile")[0], b"# syntax=docker/dockerfile:1")171 self.assertEqual(first("s.test.ts")[0], b"/** @jest-environment jsdom */")172173 def test_python_ast_and_docstring_preserved(self):174 data = self.CASES["a.py"]175 new, _, _ = apply("a.py", data)176 self.assertEqual(ast.dump(ast.parse(new)), ast.dump(ast.parse(data)))177 self.assertEqual(ast.get_docstring(ast.parse(new)), "Compute things. More.")178 self.assertIn(b"Description : Compute things.", new)179180 def test_comment_syntax(self):181 self.assertTrue(apply("i.cpp", self.CASES["i.cpp"])[0].startswith(b"/**\n * ====="))182 self.assertTrue(apply("g.R", self.CASES["g.R"])[0].startswith(b"# ====="))183 self.assertTrue(apply("j.sql", self.CASES["j.sql"])[0].startswith(b"-- ====="))184 self.assertTrue(apply("o.do", self.CASES["o.do"])[0].startswith(b"* ====="))185 self.assertTrue(apply("p.m", self.CASES["p.m"])[0].startswith(b"% =====")) # MATLAB186 self.assertTrue(apply("q.m", self.CASES["q.m"])[0].startswith(b"// =====")) # Objective-C187 self.assertTrue(apply("r.vue", self.CASES["r.vue"])[0].startswith(b"<!--\n"))188189 def test_latex_header_adds_no_blank_line(self):190 src = b"a & b \\\\\n" # fragment read with \input inside a table or math191 new, _, ctx = apply("frag.tex", src)192 self.assertTrue(new.endswith(b"% " + b"=" * 77 + b"\n" + src))193 self.assertNotIn(b"\n\n", new)194 self.assertEqual(core.strip_header(new, "frag.tex", CFG, ctx[1], "", ctx[0].sep), src)195196 def test_css_charset_stays_first(self):197 new, _, _ = apply("a.css", b'@charset "UTF-8";\nbody{}\n')198 self.assertTrue(new.startswith(b'@charset "UTF-8";\n/**'))199200 def test_third_party_latex_classes(self):201 self.assertTrue(apply("elsarticle.cls", b"%% This is file `elsarticle.cls',\n%% Copyright 2007-2020 Elsevier Ltd\n\\ProvidesClass{elsarticle}\n")[1].startswith("third-party"))202 self.assertTrue(apply("aer.bst", b"ENTRY { address }\n")[1].startswith("third-party"))203 self.assertIsNotNone(apply("mystyle.sty", b"\\ProvidesPackage{mystyle}\n")[0])204205 def test_bibtex_header_has_no_at_sign(self):206 new, variant, _ = apply("n.bib", self.CASES["n.bib"])207 self.assertEqual(variant, "SPB-BIB")208 self.assertNotIn(b"@", new.split(core.MARK_END.encode())[0])209210 def test_line_endings_bom_and_encoding(self):211 data = core.BOM + "x = 'é'\r\ny = 2\r\n".encode()212 new, _, ctx = apply("z.py", data)213 self.assertTrue(new.startswith(core.BOM))214 self.assertNotIn(b"\n", new.replace(b"\r\n", b""))215 self.assertEqual(core.strip_header(new, "z.py", CFG, ctx[1], "", ctx[0].sep), data)216 self.assertEqual(apply("y.py", "x = 'é'\n".encode("latin-1"))[1][:13], "manual-review")217218 def test_no_trailing_whitespace_and_width(self):219 new, _, _ = apply("c.ts", self.CASES["c.ts"])220 head = new.decode().split(core.MARK_END)[0]221 for ln in head.splitlines()[:-1]:222 self.assertEqual(ln, ln.rstrip())223 self.assertLessEqual(len(ln), 84)224225226class Protection(unittest.TestCase):227 def test_third_party_notice_untouched(self):228 for src in (b"// Copyright (c) 2014 Apple Inc. All rights reserved.\nimport Foundation\n",229 b"/* SPDX-License-Identifier: Apache-2.0 */\nint x;\n",230 b"# Copyright 2020 Google LLC\n# Licensed under the Apache License\nimport os\n"):231 path = "v.swift" if src.startswith(b"//") else ("v.c" if src.startswith(b"/*") else "v.py")232 new, reason, _ = apply(path, src)233 self.assertIsNone(new)234 self.assertTrue(reason.startswith("third-party"), reason)235236 def test_own_copyright_notice_preserved(self):237 src = b"// Copyright (c) 2025 Simon-Pierre Boucher. All rights reserved.\nimport Foundation\n"238 new, _, _ = apply("w.swift", src)239 self.assertTrue(new.endswith(src))240241 def test_generated_empty_binary(self):242 self.assertEqual(apply("g.swift", b"// Code generated by tool. DO NOT EDIT.\nlet a = 1\n")[1], "generated-file")243 self.assertEqual(apply("e.py", b"\n")[1], "empty-file")244 self.assertEqual(apply("b.py", b"\x00\x01\x02")[1], "binary")245 self.assertTrue(apply("s.sh", b'#!/bin/sh\n# usage: x\nsed -n "2,3p" "$0"\n')[1].startswith("manual-review"))246247 def test_formats_without_header(self):248 for p in ("a.json", "b.md", "c.html", "d.plist", "e.csv", "f.pbxproj", "g.png"):249 self.assertIsNone(core.syntax_for(p, "", CFG)[0], p)250251 def test_path_exclusions(self):252 ex = lambda p, role="source": R.path_exclusion(p, role, CFG, POLICY)253 self.assertTrue(ex("node_modules/x/a.js"))254 self.assertTrue(ex("Pods/A/a.swift"))255 self.assertTrue(ex("prisma/migrations/1/migration.sql"))256 self.assertEqual(ex("paper/soumission/main.tex", "tex"), "anonymous-submission-material")257 self.assertEqual(ex("paper/main_anonymous.tex", "tex"), "anonymous-submission-material")258 self.assertTrue(ex("paper/tables/t1.tex", "tex"))259 self.assertFalse(ex("paper/tables/make.py"))260 self.assertFalse(ex("Sources/App/Main.swift"))261 self.assertTrue(ex("App.xcodeproj/x.swift"))262263 def test_legacy_identity_block_replaced_and_restorable(self):264 src = (b"// ORIX Calc\n// File: App/Sources/A.swift\n// Description: Maps each environment to its screen.\n"265 b"//\n// Author: Simon-Pierre Boucher\n// Contact: contact@spboucher.ai\nimport SwiftUI\n")266 new, _, ctx = apply("App/Sources/A.swift", src)267 plan, syn = ctx268 self.assertEqual(new.count(b"Author"), 1)269 self.assertIn(b"Maps each environment to its screen.", new)270 self.assertEqual(core.strip_header(new, "App/Sources/A.swift", CFG, syn, plan.removed_legacy, plan.sep), src)271 mixed = b"// Author: Simon-Pierre Boucher\n// TODO: keep this important note\nimport SwiftUI\n"272 new2, _, _ = apply("B.swift", mixed)273 self.assertTrue(new2.endswith(mixed), "a block with other content is never removed")274275 def test_description_with_comment_like_text_is_stable(self):276 src = (b"# Author: Simon-Pierre Boucher\n# Description: Private API (/api/*): auth and docs/figures/*.svg files\n"277 b"import os\n")278 new, _, _ = apply("srv.py", src)279 self.assertIn(b"(/api/*): auth and docs/figures/*.svg", new)280 self.assertEqual(apply("srv.py", new)[0], new)281 ts = b"/**\n * Author: Simon-Pierre Boucher\n * Description: Routes under /admin/* only\n */\nexport {};\n"282 new, _, _ = apply("r.ts", ts)283 self.assertEqual(apply("r.ts", new)[0], new)284285 def test_public_site_is_not_a_leak_but_node_host_is(self):286 self.assertIsNone(cli.LEAK.search("Project Website : https://www.maclustr.io"))287 self.assertIsNotNone(cli.LEAK.search("see M3U96a.maclustr.io"))288 self.assertIsNotNone(cli.LEAK.search("path /Users/someone/x"))289290 def test_unknown_fields_are_omitted_not_invented(self):291 pol = json.loads(json.dumps(POLICY))292 pol["license"] = {"name": "None specified (no license file in this repository)", "spdx": "", "file": ""}293 pol["repository_url"] = ""294 new, _, _ = apply("x.go", b"package main\n", pol, dates=None)295 head = new.decode().split(core.MARK_END)[0]296 for absent in ("SPDX Identifier", "License File", "Repository ", "Created", "Version", "{{"):297 self.assertNotIn(absent, head)298299 def test_header_discloses_nothing_private(self):300 new, _, _ = apply("x.go", b"package main\n")301 self.assertIsNone(cli.LEAK.search(new.decode().split(core.MARK_END)[0]))302303304class Anonymity(unittest.TestCase):305 def test_repository_with_anonymous_variant_keeps_latex_sources_clean(self):306 with tempfile.TemporaryDirectory() as td:307 d = Path(td)308 subprocess.run(["git", "init", "-q", str(d)], check=True)309 (d / "paper").mkdir()310 (d / "paper" / "main.tex").write_text("\\documentclass{article}\\begin{document}\\input{intro}\\end{document}\n")311 (d / "paper" / "intro.tex").write_text("Text.\n")312 (d / "paper" / "titlepage_anon.tex").write_text("\\author{[Author identity withheld for review]}\n")313 (d / "run.py").write_text("x = 1\n")314 subprocess.run(["git", "-C", str(d), "add", "-A"], check=True)315 pol = dict(POLICY, category="research")316 recs = {r["path"]: r for r in cli.scan(d, pol, CFG)}317 for f in ("paper/main.tex", "paper/intro.tex", "paper/titlepage_anon.tex"):318 self.assertEqual(recs[f]["state"], "excluded", f)319 self.assertIn("anonym", recs[f]["reason"])320 self.assertEqual(recs["run.py"]["state"], "eligible")321 self.assertEqual(recs["run.py"]["variant"], "SPB-RESEARCH")322323324class Notebook(unittest.TestCase):325 def test_metadata_only(self):326 nb = {"cells": [{"cell_type": "code", "execution_count": 3, "id": "a1", "metadata": {}, "outputs": [], "source": ["x=1"]}],327 "metadata": {"kernelspec": {"name": "python3"}}, "nbformat": 4, "nbformat_minor": 5}328 data = (json.dumps(nb, indent=1) + "\n").encode()329 new, how = core.notebook_apply(data, {"project": "Demo"})330 self.assertEqual(how, "metadata")331 out = json.loads(new)332 self.assertEqual(out["cells"], nb["cells"])333 self.assertEqual(out["metadata"]["kernelspec"], nb["metadata"]["kernelspec"])334 self.assertEqual(core.notebook_apply(new, {"project": "Demo"})[1], "compliant")335 self.assertIsNone(core.notebook_apply(b'{"cells": [], "metadata": {}}', {})[0])336337338class License(unittest.TestCase):339 def test_detection(self):340 with tempfile.TemporaryDirectory() as td:341 d = Path(td)342 (d / "LICENSE").write_text("MIT License\n\nCopyright (c) 2026 Simon-Pierre Boucher <contact@spboucher.ai>\n\n"343 "Permission is hereby granted, free of charge, to any person obtaining a copy\n")344 lic = R.analyze_license(d)345 self.assertEqual((lic["spdx"], lic["holder"], lic["years"]), ("MIT", "Simon-Pierre Boucher", "2026"))346 (d / "LICENSE").write_text("Copyright (c) 2024 – 2026 Simon-Pierre Boucher\nAll rights reserved.\n")347 self.assertEqual(R.analyze_license(d)["years"], "2024-2026")348 (d / "LICENSE").write_text("ORIX Clean\nCopyright © 2026 Simon-Pierre Boucher. All rights reserved.\nThis software\n")349 lic = R.analyze_license(d)350 self.assertEqual((lic["spdx"], lic["kind"], lic["holder"]), ("", "proprietary", "Simon-Pierre Boucher"))351 (d / "LICENSE").write_text("GNU GENERAL PUBLIC LICENSE\nVersion 3, 29 June 2007\n")352 self.assertEqual(R.analyze_license(d)["spdx"], "", "GPL only/or-later is not guessed")353 (d / "LICENSE").unlink()354 self.assertEqual(R.analyze_license(d)["kind"], "none")355356357class EndToEnd(unittest.TestCase):358 def test_workspace_apply_validate_rollback(self):359 with tempfile.TemporaryDirectory() as td:360 ws = Path(td) / "ws"361 origin = Path(td) / "origin.git"362 src = Path(td) / "src"363 src.mkdir()364 g = lambda cwd, *a: subprocess.run(["git", "-C", str(cwd), "-c", "user.name=Simon-Pierre Boucher",365 "-c", "user.email=t@example.invalid", *a], check=True, capture_output=True)366 subprocess.run(["git", "init", "-q", "-b", "main", str(src)], check=True)367 (src / "pkg").mkdir()368 (src / "pkg" / "a.py").write_text('"""Module A."""\nimport os\n')369 (src / "main.swift").write_text("import Foundation\nprint(1)\n")370 (src / "data.json").write_text("{}\n")371 (src / "node_modules").mkdir()372 (src / "node_modules" / "v.js").write_text("module.exports = 1;\n")373 (src / "LICENSE").write_text("MIT License\nCopyright (c) 2026 Simon-Pierre Boucher\nPermission is hereby granted, free of charge, to any person obtaining a copy\n")374 g(src, "add", "-A", "-f")375 g(src, "commit", "-q", "-m", "init")376 subprocess.run(["git", "clone", "-q", "--bare", str(src), str(origin)], check=True)377 dest = ws / "repos" / "public" / "sp-demo"378 dest.parent.mkdir(parents=True)379 subprocess.run(["git", "clone", "-q", str(origin), str(dest)], check=True)380 g(dest, "config", "user.name", "Simon-Pierre Boucher")381 g(dest, "config", "user.email", "t@example.invalid")382 run = lambda *a: cli.main(["-w", str(ws), *a])383 self.assertEqual(run("classify"), 0)384 pol = R.load_policy(ws / "policies" / "sp-demo.toml")385 self.assertEqual((pol["category"], pol["license"]["spdx"], pol["copyright"]["holder"]),386 ("sp-app", "MIT", "Simon-Pierre Boucher"))387 self.assertEqual(run("audit"), 0)388 self.assertEqual(run("apply"), 0)389 led = json.loads((ws / "ledger" / "sp-demo.json").read_text())390 self.assertEqual(led["status"], "migrated-validated", led)391 self.assertEqual({e["path"] for e in led["files"]}, {"pkg/a.py", "main.swift"})392 self.assertEqual(run("validate"), 0)393 self.assertEqual((dest / "node_modules" / "v.js").read_text(), "module.exports = 1;\n")394 self.assertEqual(R.git(dest, "rev-parse", "--abbrev-ref", "HEAD").strip(), R.BRANCH)395 self.assertEqual(R.git(dest, "rev-parse", "main").strip(), led["baseline_commit"])396 self.assertEqual(cli.main(["check", "--repo", str(dest)]), 0)397 (dest / "new.py").write_text("x = 1\n")398 g(dest, "add", "new.py")399 self.assertEqual(cli.main(["check", "--repo", str(dest), "--staged"]), 1)400 (dest / "new.py").unlink()401 g(dest, "reset", "-q")402 self.assertEqual(run("rollback"), 0)403 self.assertEqual((dest / "pkg" / "a.py").read_text(), '"""Module A."""\nimport os\n')404 self.assertEqual(R.git(dest, "diff", "--stat", "main", "--", "pkg", "main.swift").strip(), "")405406407if __name__ == "__main__":408 unittest.main()409