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

226 lines
8.5 KiB
Python

"""Behavior tests for dependency-free scientific-writing scripts."""
from __future__ import annotations
import argparse
import json
import sys
import tempfile
import unittest
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2] / "skills" / "scientific-writing"
SCRIPTS = ROOT / "scripts"
sys.path.insert(0, str(SCRIPTS))
sys.path.insert(0, str(Path(__file__).resolve().parent))
import audit_claims
import check_consistency
import check_references
import lint_manuscript
import scaffold_manuscript
import select_reporting_guidelines
import validate_authorship
import validate_manifest
from _common import InputError, read_json
from synthetic_manuscript import (
valid_authorship_manifest,
valid_claim_csv,
valid_consistency_manifest,
valid_manuscript_manifest,
valid_source_manifest,
)
import skill_contract
class ScriptTests(unittest.TestCase):
def write_json(self, directory: Path, name: str, value: object) -> Path:
path = directory / name
path.write_text(json.dumps(value), encoding="utf-8")
return path
def test_valid_manuscript_and_source_manifests(self) -> None:
self.assertEqual(
validate_manifest.validate_manuscript_manifest(valid_manuscript_manifest()),
[],
)
self.assertEqual(
validate_manifest.validate_source_manifest(
valid_source_manifest(),
require_verified=True,
),
[],
)
def test_json_reader_rejects_nonfinite_values(self) -> None:
with tempfile.TemporaryDirectory() as temporary:
path = Path(temporary) / "invalid.json"
path.write_text('{"value": NaN}', encoding="utf-8")
with self.assertRaises(InputError):
read_json(path)
def test_source_template_fails_closed(self) -> None:
template = json.loads(
(ROOT / "assets" / "source_manifest_template.json").read_text(
encoding="utf-8"
)
)
issues = validate_manifest.validate_source_manifest(
template,
require_verified=True,
)
self.assertTrue(any(item.severity == "error" for item in issues))
def test_reporting_selector_and_non_scoring_coverage(self) -> None:
registry = select_reporting_guidelines.load_registry()
args = argparse.Namespace(
study_design="randomized_trial",
protocol=False,
ai=False,
llm=False,
routinely_collected=False,
qualitative_component=False,
)
primary, extensions, issues = select_reporting_guidelines.select_guidelines(
registry, args
)
self.assertIn("consort-2025", primary)
self.assertEqual(extensions, [])
self.assertEqual(issues, [])
guideline = registry["consort-2025"]
coverage = {
"schema_version": "1.0",
"guideline_id": "consort-2025",
"items": [
{
"topic_id": topic["id"],
"status": "addressed",
"locations": ["Methods"],
"rationale": "",
}
for topic in guideline["coverage_topics"]
],
}
with tempfile.TemporaryDirectory() as temporary:
path = self.write_json(Path(temporary), "coverage.json", coverage)
coverage_issues, summary = select_reporting_guidelines.check_coverage(
registry,
str(path),
)
self.assertEqual(coverage_issues, [])
self.assertIn("non-scoring", summary["disclaimer"])
def test_claim_audit_accepts_verified_mappings(self) -> None:
with tempfile.TemporaryDirectory() as temporary:
directory = Path(temporary)
sources_path = self.write_json(
directory,
"sources.json",
valid_source_manifest(),
)
claims_path = directory / "claims.csv"
claims_path.write_text(valid_claim_csv(), encoding="utf-8")
manuscript = "Verified test statement [claim:C001] [evidence:E001]\n"
sources = audit_claims.load_sources(str(sources_path))
claims, claim_issues = audit_claims.load_claims(str(claims_path), sources)
markdown_issues, used = audit_claims.audit_markdown(
manuscript,
claims,
sources,
)
self.assertEqual(claim_issues, [])
self.assertEqual(markdown_issues, [])
self.assertEqual(used, {"C001"})
def test_claim_audit_flags_untagged_number(self) -> None:
issues, _ = audit_claims.audit_markdown(
"An unsupported value is 7.\n",
{},
{},
)
self.assertTrue(any(item.code == "UNTAGGED_NUMERIC_CONTENT" for item in issues))
def test_consistency_checks_methods_results_and_numbers(self) -> None:
data = valid_consistency_manifest()
fact_issues, fact_count = check_consistency.validate_numeric_facts(data)
method_issues, method_count, result_count = (
check_consistency.validate_methods_results(data)
)
self.assertEqual(fact_issues, [])
self.assertEqual(method_issues, [])
self.assertEqual((fact_count, method_count, result_count), (2, 1, 1))
data["numeric_facts"][1]["value"] = 3
mismatch, _ = check_consistency.validate_numeric_facts(data)
self.assertTrue(
any(item.code == "CROSS_SECTION_VALUE_MISMATCH" for item in mismatch)
)
data["numeric_facts"][1]["value"] = 2
data["numeric_facts"][1]["sample_size"] = 3
mismatch, _ = check_consistency.validate_numeric_facts(data)
self.assertTrue(
any(item.code == "CROSS_SECTION_SAMPLE_SIZE_MISMATCH" for item in mismatch)
)
def test_reference_checker_is_offline_and_detects_duplicate(self) -> None:
data = valid_source_manifest()
issues, count = check_references.check_sources(data)
self.assertEqual(issues, [])
self.assertEqual(count, 1)
duplicate = dict(data["sources"][0])
duplicate["evidence_id"] = "E002"
data["sources"].append(duplicate)
issues, _ = check_references.check_sources(data)
self.assertTrue(any(item.code == "DUPLICATE_DOI" for item in issues))
def test_authorship_validator_requires_human_accountability(self) -> None:
data = valid_authorship_manifest()
issues, author_ids = validate_authorship.validate_people(data)
issues.extend(validate_authorship.validate_accountability(data, author_ids))
ai_issues, _ = validate_authorship.validate_ai_disclosure(data)
issues.extend(ai_issues)
issues.extend(validate_authorship.validate_declarations(data))
self.assertEqual(issues, [])
data["authors"][0]["is_human"] = False
issues, _ = validate_authorship.validate_people(data)
self.assertTrue(
any(item.code == "NONHUMAN_AUTHOR_PROHIBITED" for item in issues)
)
def test_lint_flags_placeholders_without_echoing_text(self) -> None:
manifest = valid_manuscript_manifest()
clean = lint_manuscript.lint_text("Verified prose without a claim.\n", manifest)
self.assertEqual(clean, [])
findings = lint_manuscript.lint_text("[[TODO: unresolved]]\n", manifest)
self.assertTrue(any(item.code == "UNRESOLVED_PLACEHOLDER" for item in findings))
self.assertTrue(all("[[TODO" not in str(item.to_dict()) for item in findings))
def test_scaffold_is_local_and_not_submission_ready(self) -> None:
with tempfile.TemporaryDirectory() as temporary:
output = Path(temporary) / "workspace"
files = scaffold_manuscript.generate(
output,
document_id="test-draft",
study_design="randomized_trial",
guidelines=["consort-2025"],
)
manifest = json.loads(
(output / "manuscript_manifest.json").read_text(encoding="utf-8")
)
self.assertFalse(manifest["submission_ready"])
self.assertIn("manuscript.md", files)
self.assertTrue((output / "claims.csv").is_file())
# The shared --help contract: every argparse CLI this skill ships answers --help
# without doing any work. It skips when the skill's packages are absent and runs
# for real under `python tests/run_all.py --isolated`.
CliHelpTests = skill_contract.cli.help_test_case(ROOT)
if __name__ == "__main__":
unittest.main()