Files
scientific-agent-skills/tests/bids/test_scripts.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

148 lines
6.4 KiB
Python

"""Tests for the BIDS schema updater.
`update_schema.py` is a maintenance script that overwrites files in the skill's
own `references/` directory from the network. Neither of those is acceptable in
a test, so every test here redirects `REFERENCES_DIR` at a temporary directory
and replaces `fetch` with a stub. Nothing reaches the network and nothing
touches the shipped references.
The other half of the suite checks the artefacts that *are* shipped: a schema
the script wrote once must still be parseable and carry its version fields,
because the skill's documentation quotes them.
"""
from __future__ import annotations
import json
import sys
import tempfile
import unittest
from pathlib import Path
from unittest import mock
import skill_contract
SKILL_ROOT = Path(__file__).resolve().parents[2] / "skills" / "bids"
SCRIPTS = SKILL_ROOT / "scripts"
REFERENCES = SKILL_ROOT / "references"
sys.path.insert(0, str(SCRIPTS))
import update_schema # noqa: E402
CliHelpTests = skill_contract.cli.help_test_case(SKILL_ROOT)
class TemporaryReferencesTestCase(unittest.TestCase):
"""Point the script's output directory at a scratch dir for the test."""
def setUp(self) -> None:
self._temporary = tempfile.TemporaryDirectory()
self.addCleanup(self._temporary.cleanup)
self.references = Path(self._temporary.name)
patcher = mock.patch.object(update_schema, "REFERENCES_DIR", self.references)
patcher.start()
self.addCleanup(patcher.stop)
class SchemaWriteTests(TemporaryReferencesTestCase):
SCHEMA = {
"schema_version": "1.2.1",
"bids_version": "1.11.1",
"objects": {"entities": {"subject": {"name": "sub"}}},
}
def test_downloaded_schema_is_reserialised_with_stable_formatting(self) -> None:
# Upstream ships minified JSON; the script re-indents so the checked-in
# copy diffs sanely on the next update.
minified = json.dumps(self.SCHEMA, separators=(",", ":")).encode("utf-8")
with mock.patch.object(update_schema, "fetch", return_value=minified):
update_schema.update_schema("https://example.invalid/schema.json")
written = self.references / "bids_schema.json"
text = written.read_text(encoding="utf-8")
self.assertEqual(json.loads(text), self.SCHEMA)
self.assertIn("\n ", text, "output should be indented")
self.assertTrue(text.endswith("\n"), "output should end with a newline")
def test_the_reported_versions_come_from_the_payload(self) -> None:
payload = json.dumps(self.SCHEMA).encode("utf-8")
with mock.patch.object(update_schema, "fetch", return_value=payload):
with mock.patch("builtins.print") as printed:
update_schema.update_schema("https://example.invalid/schema.json")
output = " ".join(str(call.args[0]) for call in printed.call_args_list)
self.assertIn("schema 1.2.1", output)
self.assertIn("BIDS 1.11.1", output)
def test_a_schema_without_version_fields_reports_unknown(self) -> None:
with mock.patch.object(update_schema, "fetch", return_value=b"{}"):
with mock.patch("builtins.print") as printed:
update_schema.update_schema("https://example.invalid/schema.json")
output = " ".join(str(call.args[0]) for call in printed.call_args_list)
self.assertIn("schema ? / BIDS ?", output)
def test_a_non_json_response_fails_before_anything_is_written(self) -> None:
with mock.patch.object(update_schema, "fetch", return_value=b"<html>404</html>"):
with self.assertRaises(json.JSONDecodeError):
update_schema.update_schema("https://example.invalid/schema.json")
self.assertFalse((self.references / "bids_schema.json").exists())
class BepsWriteTests(TemporaryReferencesTestCase):
def test_beps_are_written_verbatim_and_counted(self) -> None:
payload = (
b"# template\n"
b"- number: '004'\n title: Diffusion\n"
b"- number: '011'\n title: Structural\n"
)
with mock.patch.object(update_schema, "fetch", return_value=payload):
with mock.patch("builtins.print") as printed:
update_schema.update_beps()
written = self.references / "beps.yml"
self.assertEqual(written.read_bytes(), payload)
output = " ".join(str(call.args[0]) for call in printed.call_args_list)
self.assertIn("2 BEPs", output)
def test_the_counter_matches_the_format_of_the_shipped_file(self) -> None:
# The count is a byte-substring search, so it only stays correct while
# upstream keeps this exact indentation. Pin it against the real file.
shipped = (REFERENCES / "beps.yml").read_bytes()
self.assertEqual(shipped.count(b"\n- number:"), 25)
class FetchTests(unittest.TestCase):
def test_requests_carry_an_identifying_user_agent(self) -> None:
response = mock.MagicMock()
response.__enter__.return_value.read.return_value = b"{}"
with mock.patch("urllib.request.urlopen", return_value=response) as opened:
update_schema.fetch("https://example.invalid/x.json")
request = opened.call_args.args[0]
self.assertEqual(request.full_url, "https://example.invalid/x.json")
self.assertIn("bids-skill-updater", request.get_header("User-agent"))
def test_the_default_sources_are_https_and_upstream(self) -> None:
self.assertTrue(update_schema.SCHEMA_URL.startswith("https://"))
self.assertTrue(update_schema.BEPS_URL.startswith("https://"))
self.assertIn("bids-specification", update_schema.SCHEMA_URL)
self.assertIn("bids-standard", update_schema.BEPS_URL)
class ShippedReferenceTests(unittest.TestCase):
"""The artefacts the script produced last time it ran must still be usable."""
def test_the_shipped_schema_parses_and_is_versioned(self) -> None:
schema = json.loads((REFERENCES / "bids_schema.json").read_text(encoding="utf-8"))
self.assertRegex(schema["schema_version"], r"^\d+\.\d+\.\d+$")
self.assertRegex(schema["bids_version"], r"^\d+\.\d+\.\d+$")
self.assertIn("objects", schema)
def test_the_references_directory_is_where_the_script_writes(self) -> None:
self.assertEqual(update_schema.REFERENCES_DIR, REFERENCES)
self.assertTrue((REFERENCES / "beps.yml").is_file())
self.assertTrue((REFERENCES / "bids_schema.json").is_file())
if __name__ == "__main__":
unittest.main()