Files
scientific-agent-skills/tests/arboreto/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

128 lines
4.9 KiB
Python

"""Tests for the Arboreto GRN inference wrapper.
GRNBoost2 on real data is a distributed, minutes-long job, so the tests stub
`grnboost2` and assert on the contract between the wrapper and the algorithm:
the expression matrix is read genes-as-columns, `tf_names` defaults to the
sentinel `'all'` rather than an empty list, the seed and limit are forwarded,
and the network is written headerless -- the format every downstream Arboreto
consumer expects.
Getting `tf_names` wrong is the failure worth guarding: passing `[]` instead of
`'all'` produces an empty network with no error at all.
"""
from __future__ import annotations
import sys
import tempfile
import unittest
from pathlib import Path
from unittest import mock
import pytest
import skill_contract
SKILL_ROOT = Path(__file__).resolve().parents[2] / "skills" / "arboreto"
SCRIPTS = SKILL_ROOT / "scripts"
sys.path.insert(0, str(SCRIPTS))
pd = pytest.importorskip("pandas", reason="arboreto needs pandas")
pytest.importorskip("arboreto", reason="basic_grn_inference imports arboreto at module scope")
import basic_grn_inference # noqa: E402
CliHelpTests = skill_contract.cli.help_test_case(SKILL_ROOT)
NETWORK = pd.DataFrame(
{
"TF": ["TF1", "TF1", "TF2"],
"target": ["G1", "G2", "G1"],
"importance": [9.5, 4.2, 1.1],
}
)
class InferenceWrapperTests(unittest.TestCase):
def setUp(self) -> None:
self._temporary = tempfile.TemporaryDirectory()
self.addCleanup(self._temporary.cleanup)
self.root = Path(self._temporary.name)
self.expression = self.root / "expression.tsv"
self.expression.write_text(
"TF1\tTF2\tG1\tG2\n"
"1.0\t2.0\t3.0\t4.0\n"
"1.5\t2.5\t3.5\t4.5\n"
"2.0\t3.0\t4.0\t5.0\n",
encoding="utf-8",
)
self.output = self.root / "network.tsv"
def run_inference(self, **kwargs):
with mock.patch.object(
basic_grn_inference, "grnboost2", return_value=NETWORK
) as algorithm:
basic_grn_inference.run_grn_inference(
str(self.expression), str(self.output), **kwargs
)
return algorithm
def test_the_expression_matrix_is_read_with_genes_as_columns(self) -> None:
algorithm = self.run_inference()
passed = algorithm.call_args.kwargs["expression_data"]
self.assertEqual(list(passed.columns), ["TF1", "TF2", "G1", "G2"])
self.assertEqual(len(passed), 3) # three observations
def test_without_a_tf_file_every_gene_is_a_candidate_regulator(self) -> None:
# The sentinel is the string 'all'; an empty list would silently return
# an empty network.
algorithm = self.run_inference()
self.assertEqual(algorithm.call_args.kwargs["tf_names"], "all")
def test_a_tf_file_restricts_the_candidate_regulators(self) -> None:
tf_file = self.root / "tfs.txt"
tf_file.write_text("TF1\nTF2\n", encoding="utf-8")
algorithm = self.run_inference(tf_file=str(tf_file))
self.assertEqual(list(algorithm.call_args.kwargs["tf_names"]), ["TF1", "TF2"])
def test_the_seed_is_forwarded_so_runs_are_reproducible(self) -> None:
self.assertEqual(self.run_inference().call_args.kwargs["seed"], 777)
self.assertEqual(self.run_inference(seed=42).call_args.kwargs["seed"], 42)
def test_the_link_limit_is_forwarded_and_defaults_to_unlimited(self) -> None:
self.assertIsNone(self.run_inference().call_args.kwargs["limit"])
self.assertEqual(self.run_inference(limit=100).call_args.kwargs["limit"], 100)
def test_the_network_is_written_headerless_and_tab_separated(self) -> None:
# Arboreto's own consumers expect three unlabelled columns.
self.run_inference()
lines = self.output.read_text(encoding="utf-8").strip().splitlines()
self.assertEqual(len(lines), 3)
self.assertNotIn("importance", lines[0])
self.assertEqual(lines[0].split("\t"), ["TF1", "G1", "9.5"])
def test_no_index_column_is_written(self) -> None:
self.run_inference()
for line in self.output.read_text(encoding="utf-8").strip().splitlines():
with self.subTest(line=line):
self.assertEqual(len(line.split("\t")), 3)
class ParserTests(unittest.TestCase):
def test_the_documented_flags_are_all_accepted(self) -> None:
source = (SCRIPTS / "basic_grn_inference.py").read_text(encoding="utf-8")
for flag in ("--tf-file", "--seed", "--limit"):
with self.subTest(flag=flag):
self.assertIn(flag, source)
def test_the_positional_arguments_are_required(self) -> None:
result = skill_contract.cli.run_help(SCRIPTS / "basic_grn_inference.py")
self.assertEqual(result.returncode, 0, result.stderr)
self.assertIn("expression_file", result.stdout)
self.assertIn("output_file", result.stdout)
if __name__ == "__main__":
unittest.main()