Files
scientific-agent-skills/tests/_contract/schematic.py
T
Timothy Kassis 4fb7e0bc29 Test every script-bearing skill, and enforce that it stays that way
AGENTS.md has always said that a skill shipping scripts/ puts its tests in
tests/<name>/, but nothing checked it: 54 of the 100 such skills had no suite
at all, including docx, pptx, xlsx, pdf and scanpy. All 100 now do.

tests/_meta is the guard. It runs the shared structural contract across every
skill in a single process -- safe because it parses scripts with ast and never
imports them -- and fails when a skill ships scripts/ without a suite or
without a [skills.<name>] entry in skill-requirements.toml. It needs no
scientific packages and finishes in seconds, so skill-tests.yml blocks every
pull request on it, plus the packages=[] suites.

tests/_contract holds what the per-skill suites were each reimplementing:
frontmatter conformance, the 500-line limit, no tests or bytecode under
skills/, local links resolving, scripts parsing, no eval/exec/os.system, no
standard-library shadowing, no hardcoded local paths, valid shell scripts. Also
the --help contract, which skips when a skill's packages are absent and runs
for real under --isolated, and shared behaviour for the files docx/pptx/xlsx
and five schematic-shipping skills carry byte-identical copies of, with drift
detection so they cannot diverge silently.

67 new suites, 3325 test functions. The existing suites were retrofitted: 18
no longer pin an exact skill version, so a version bump no longer breaks a
test; 11 duplicated structural methods removed; 19 wired to the --help
contract; and 5 that failed collection without their packages now skip
cleanly. run_all.py in the bare project environment goes from 6 failures to 0.

Writing the tests surfaced 19 defects in the skills, fixed here with version
bumps. The ones that changed scientific output:

  - openpiv reported vorticity 0 for a rotating flow, from a sign error in
    openpiv's y-up coordinate relabelling; solid-body rotation now gives 2w
    exactly, on grids of either orientation
  - deepchem returned solubility predictions in z-scored space while labelling
    them log(mol/L), because it transformed a y-less dataset instead of
    untransforming the output
  - neuropixels-analysis had the Allen and IBL ISI thresholds swapped,
    contradicting its own references/QUALITY_METRICS.md and inverting the two
    standards' relative strictness
  - scanpy's summarize() raised TypeError on every AnnData under anndata 0.13,
    which reports an unnamed None key on .layers; scanpy convert was broken
  - experimental-design's Latin hypercube was never reproducible: pyDOE3 draws
    from its own default_rng and ignores numpy's global seed
  - primekg shipped a hardcoded path naming a person, which is why
    no_personal_paths is now a contract rule

The remainder is upstream API drift, each verified against the installed
package: retired symbols in bioservices 1.16, gget helpers that returned lists
where a string was written, ArviZ 1.x kwargs in pymc, a positional-only
factory in pymoo, ReduceLROnPlateau(verbose=) in torch 2.13, a removed scvelo
parameter, and PyPDF2 in scientific-slides.

Two manifest environments could not build and are pinned: gget, where an
unpinned scanpy walked back to 1.9.8 and pulled llvmlite 0.36 which does not
compile on 3.13, and pymatgen, pinned to the snapshot its own _common.py
enforces rather than loosening that check. deepchem gains torch, without which
no model class exists.

python tests/run_all.py --isolated: 101 passed, 0 failed.
2026-07-28 10:20:12 -07:00

103 lines
4.6 KiB
Python

"""Shared tests for the AI schematic generator bundled by three skills.
`scientific-schematics`, `latex-posters`, and `literature-review` each ship a
byte-identical `scripts/generate_schematic.py` (a thin CLI) and
`scripts/generate_schematic_ai.py` (the generator). Rather than write the same
tests three times, each suite instantiates `schematic_test_case()` against its
own copy; `tests/_meta` separately pins the copies together.
The behaviour worth testing offline is the environment allowlist. The CLI
re-executes the generator as a subprocess, and it deliberately forwards a
named set of variables rather than the whole parent environment -- copying
everything would hand the child every unrelated secret exported in the calling
shell. Nothing here makes a network call or needs an API key.
"""
from __future__ import annotations
import importlib
import sys
import unittest
from pathlib import Path
from unittest import mock
def schematic_test_case(skill_root: Path) -> type[unittest.TestCase]:
"""Build the shared schematic-generator TestCase for one skill."""
scripts = skill_root / "scripts"
def load():
if str(scripts) not in sys.path:
sys.path.insert(0, str(scripts))
return importlib.import_module("generate_schematic")
class SchematicContractTests(unittest.TestCase):
maxDiff = None
def setUp(self) -> None:
self.module = load()
def test_only_allowlisted_variables_reach_the_subprocess(self) -> None:
environment = {
"PATH": "/usr/bin",
"HOME": "/home/someone",
"AWS_SECRET_ACCESS_KEY": "should-not-be-forwarded",
"GITHUB_TOKEN": "also-not",
}
with mock.patch.dict("os.environ", environment, clear=True):
built = self.module.build_subprocess_env(None)
self.assertEqual(built["PATH"], "/usr/bin")
self.assertEqual(built["HOME"], "/home/someone")
self.assertNotIn("AWS_SECRET_ACCESS_KEY", built)
self.assertNotIn("GITHUB_TOKEN", built)
def test_the_api_key_is_injected_under_the_expected_name(self) -> None:
with mock.patch.dict("os.environ", {"PATH": "/usr/bin"}, clear=True):
built = self.module.build_subprocess_env("sk-or-test")
self.assertEqual(built["OPENROUTER_API_KEY"], "sk-or-test")
def test_no_key_means_no_key_variable_rather_than_an_empty_one(self) -> None:
# An empty OPENROUTER_API_KEY would look configured to the child and
# fail deep inside the request instead of at the boundary.
with mock.patch.dict("os.environ", {"PATH": "/usr/bin"}, clear=True):
for value in (None, ""):
with self.subTest(value=value):
self.assertNotIn(
"OPENROUTER_API_KEY", self.module.build_subprocess_env(value)
)
def test_absent_variables_are_omitted_not_blanked(self) -> None:
with mock.patch.dict("os.environ", {"PATH": "/usr/bin"}, clear=True):
built = self.module.build_subprocess_env(None)
self.assertEqual(set(built), {"PATH"})
def test_the_allowlist_covers_proxies_tls_and_windows_startup(self) -> None:
forwarded = set(self.module.FORWARDED_ENV_VARS)
# Dropping any of these breaks the child in a way that looks like a
# model failure rather than a configuration one.
for required in (
"PATH", "HOME",
"HTTPS_PROXY", "https_proxy",
"SSL_CERT_FILE", "REQUESTS_CA_BUNDLE",
"SYSTEMROOT", "COMSPEC",
):
with self.subTest(variable=required):
self.assertIn(required, forwarded)
def test_the_allowlist_carries_no_credential_variables(self) -> None:
forwarded = " ".join(self.module.FORWARDED_ENV_VARS).upper()
for banned in ("SECRET", "TOKEN", "PASSWORD", "API_KEY", "CREDENTIAL"):
with self.subTest(term=banned):
self.assertNotIn(banned, forwarded)
def test_the_allowlist_has_no_duplicates(self) -> None:
forwarded = self.module.FORWARDED_ENV_VARS
self.assertEqual(len(set(forwarded)), len(forwarded))
def test_the_generator_script_is_shipped_alongside_the_cli(self) -> None:
self.assertTrue((scripts / "generate_schematic_ai.py").is_file())
SchematicContractTests.__qualname__ = f"SchematicContractTests[{skill_root.name}]"
return SchematicContractTests