Turn any AI agent into an AI Scientist. The #1 Agent Skills library for science, used by 250,000+ scientists worldwide. 177 ready-to-use validated skills plus 100+ scientific databases covering biology, chemistry, medicine, and drug discovery. Compatible with Cursor, Claude Code, Codex, Pi, Antigravity, and the open Agent Skills standard.
Python agent-skillsai-scientistbioinformaticschemoinformaticsclaudeclaude-skillsclaudecodeclinical-researchcomputational-biologydata-analysisdrug-discoverygenomicsmaterials-sciencemetabolomicsproteomicsscientific-computingscientific-visualization
Test every script-bearing skill, and enforce that it stays that way
Timothy Kassis4fb7e0bc2926
diff --git a/.github/workflows/skill-tests.yml b/.github/workflows/skill-tests.ymlnew file mode 100644index 00000000..a8e00273--- /dev/null+++ b/.github/workflows/skill-tests.yml@@ -0,0 +1,103 @@+name: Skill Tests++on:+ pull_request:+ paths:+ - "skills/**"+ - "tests/**"+ - "pyproject.toml"+ - "uv.lock"+ - ".github/workflows/skill-tests.yml"+ push:+ branches:+ - main+ paths:+ - "skills/**"+ - "tests/**"+ workflow_dispatch:++permissions:+ contents: read++concurrency:+ group: skill-tests-${{ github.ref }}+ cancel-in-progress: true++jobs:+ contract:+ name: Repo-wide contract and coverage guard+ runs-on: ubuntu-latest+ timeout-minutes: 15++ steps:+ - name: Checkout+ uses: actions/checkout@v6++ - name: Set up uv+ uses: astral-sh/[email protected]+ with:+ enable-cache: true+ cache-dependency-glob: uv.lock+ python-version: "3.13"++ - name: Install dependencies+ run: uv sync --python 3.13++ # tests/_meta checks every skill against the shared structural contract+ # (frontmatter, SKILL.md length, local links, scripts parse, no shipped+ # bytecode, no hardcoded local paths, ...) and enforces the repo rule that+ # a skill shipping scripts/ has a suite under tests/ and an entry in+ # tests/skill-requirements.toml. It imports no skill code and needs no+ # scientific packages, so it runs in seconds on every pull request.+ - name: Structural contract and coverage+ run: uv run --python 3.13 python -m pytest tests/_meta -q++ suites:+ name: Standard-library-only skill suites+ runs-on: ubuntu-latest+ timeout-minutes: 30+ needs: contract++ steps:+ - name: Checkout+ uses: actions/checkout@v6++ - name: Set up uv+ uses: astral-sh/[email protected]+ with:+ enable-cache: true+ cache-dependency-glob: uv.lock+ python-version: "3.13"++ # The skills whose bundled tooling is standard-library only -- read from+ # `packages = []` in tests/skill-requirements.toml, so the list needs no+ # separate maintenance. Each still gets a clean throwaway environment.+ #+ # The full `--isolated` sweep across every skill is deliberately NOT run+ # here: it builds ~100 environments including torch, qiskit, and scanpy,+ # and several skills need CUDA, a JDK, or a MATLAB install that CI does+ # not have. Run it locally or on a schedule:+ # python tests/run_all.py --isolated+ - name: Select standard-library-only skills+ id: select+ run: |+ set -euo pipefail+ SKILLS=$(python3 - <<'PY'+ import pathlib, tomllib+ manifest = tomllib.loads(+ pathlib.Path("tests/skill-requirements.toml").read_text()+ )+ names = sorted(+ name+ for name, entry in manifest["skills"].items()+ if not entry.get("packages") and "python" not in entry+ and (pathlib.Path("tests") / name).is_dir()+ )+ print(" ".join(names))+ PY+ )+ echo "Selected: $SKILLS"+ echo "skills=$SKILLS" >> "$GITHUB_OUTPUT"++ - name: Run suites, one environment each+ run: uv run --python 3.13 python tests/run_all.py --isolated ${{ steps.select.outputs.skills }}diff --git a/AGENTS.md b/AGENTS.mdindex 2f3e1413..63585fa0 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -45,6 +45,10 @@ tests/<skill-name>/ # same name as the skill directory└── fixtures/ # optional test data```+**Diagrams never live under `skills/` either.** Every skill has one generated workflow diagram at+`docs/images/<skill-name>.png`, produced by `scripts/generate_skill_image.py` and kept in step with+the skill's documentation — see [Skill diagrams](#skill-diagrams).+Tests reach their skill through an explicit anchor, never a relative walk:```python@@ -62,6 +66,11 @@ SKILL_ROOT = Path(__file__).resolve().parents[2] / "skills" / "<skill-name>"5. If the skill ships `scripts/`, put their tests in **`tests/<name>/`** — never in the skilldirectory. Fixtures go in `tests/<name>/fixtures/`.6. Validate and scan (below).+7. Generate the skill's diagram — a new skill without `docs/images/<name>.png` is incomplete:++ ```bash+ uv run python scripts/generate_skill_image.py --skill <name>+ ``````markdown---@@ -97,7 +106,17 @@ Use this skill when...4. **Bump `metadata.version` in the same change**: minor for normal improvements (`"1.2"` →`"1.3"`), major only for a breaking change or substantial redesign (`"1.9"` → `"2.0"`).5. Re-run any example, command, or script you touched, plus `tests/<name>/` if that suite exists.- Some suites assert the skill's exact version string, so a version bump can require a test edit.+ Suites check that `metadata.version` is present and quoted, not what it equals, so a version bump+ never needs a matching test edit.+6. **Regenerate the diagram in the same change** whenever the edit changes what the skill does or+ how its workflow runs — the picture is generated from `SKILL.md` and `references/`, so it goes+ stale silently. The command overwrites `docs/images/<name>.png` in place:++ ```bash+ uv run python scripts/generate_skill_image.py --skill <name>+ ```++ A typo fix, a link repair, or a version bump alone does not need a new image.## Frontmatter@@ -222,7 +241,7 @@ If the skill has tests in `tests/<name>/`, run them:```bashuv run --with pytest python -m pytest tests/<name> -q-# every skill's suite, one process each+# every skill's suite, one process each, after the repo-wide guarduv run --with pytest python tests/run_all.py```@@ -231,6 +250,47 @@ uv run --with pytest python tests/run_all.py`_common` to whichever skill imported first and silently tests the wrong files. `tests/conftest.py`refuses such a session; `tests/run_all.py` forks per skill.+### The repo-wide guard++```bash+uv run --with pytest python -m pytest tests/_meta -q+```++`tests/_meta` is the fastest useful signal in the repo: pure standard library, no scientific+packages, a couple of seconds. It runs the shared structural contract against **every** skill and+fails if a skill ships `scripts/` without a suite under `tests/<name>/` or an entry in+`tests/skill-requirements.toml`. `.github/workflows/skill-tests.yml` runs it on every pull request,+so a skill with untested scripts cannot land. A full run of `tests/run_all.py` starts with it.++It is not one of the per-skill processes because it deliberately spans all of them at once — safe+because it never imports skill code, only parses it.++### The shared contract++`tests/_contract/` holds the assertions every skill shares, so a per-skill suite contains only what+is actually specific to that skill. `tests/conftest.py` registers it as the importable module+`skill_contract`:++```python+import skill_contract++# every argparse script answers --help; skips when its packages are absent,+# runs for real under --isolated+CliHelpTests = skill_contract.cli.help_test_case(SKILL_ROOT)++# for library-style scripts with an `if __name__ == "__main__"` worked example+DemoBlockTests = skill_contract.cli.demo_test_case(SKILL_ROOT, ("doe_designs.py",))+```++- `structure` — frontmatter conformance, the 500-line limit, no tests or bytecode under `skills/`,+ local links resolve, scripts parse, no `eval`/`exec`/`os.system`, no standard-library shadowing,+ no hardcoded local paths, shell scripts valid. Run repo-wide by `tests/_meta`; do not duplicate+ these in a per-skill suite.+- `cli` — the `--help` and demo-block cases above.+- `office` / `schematic` — behaviour for files several skills ship byte-identical copies of (the+ OOXML tree under docx/pptx/xlsx; the AI schematic generator under five skills). `tests/_meta`+ separately fails if those copies drift apart, so fix them together.+### One environment per skillThe project environment deliberately does not carry the skills' scientific packages. Their upstream@@ -253,9 +313,50 @@ run on the default interpreter; uv downloads that interpreter on demand. Packageinstalled at all — a GitHub-only SDK, a conda-forge-only library, a CUDA build — are recorded under`[unavailable]` with the reason, and the runner prints them so the gap shows up in test output.-Adding a skill with `scripts/` means adding its `[skills.<name>]` entry. Use `packages = []` for-skills whose bundled tooling is standard-library only; they still get a clean environment. uv caches-wheels globally, so repeat runs create each environment in milliseconds.+Adding a skill with `scripts/` means adding its `[skills.<name>]` entry — `tests/_meta` fails+without one. Use `packages = []` for skills whose bundled tooling is standard-library only; they+still get a clean environment, and CI runs exactly that set on every pull request. uv caches wheels+globally, so repeat runs create each environment in milliseconds.++The full `--isolated` sweep is not run in CI: it builds one environment per skill, several of which+need a CUDA toolchain, a JDK, or a local MATLAB install. Run it before a release, or whenever you+touch the shared contract.++## Skill diagrams++Every skill carries one generated workflow diagram at `docs/images/<skill-name>.png`. Creating a+skill means creating its image; changing what a skill does means regenerating it. The image is not+optional decoration — it is derived from the documentation, so an out-of-date one misrepresents the+skill.++`scripts/generate_skill_image.py` is local repository tooling, standard library only, and runs in+two stages on one `OPENROUTER_API_KEY` (environment variable, repository `.env`, or `--api-key`):+a text model reads `SKILL.md` plus everything under `references/` and a manifest of `scripts/` and+`assets/`, distils it into a description of one diagram, then an image model draws it. Because it+reads the whole skill, run it **after** the documentation is final, not before.++```bash+# one skill -> docs/images/<name>.png, replacing any existing image+uv run python scripts/generate_skill_image.py --skill <name>++# see which files feed the reader, and where the image lands — no API calls, nothing billed+uv run python scripts/generate_skill_image.py --skill <name> --dry-run++# read the skill and print the diagram prompt without drawing it+uv run python scripts/generate_skill_image.py --skill <name> --prompt-only++# several skills in one batch+uv run python scripts/generate_skill_image.py --skill <name-a> <name-b>++# backfill everything missing an image, six at a time+uv run python scripts/generate_skill_image.py --all --skip-existing -j 6+```++Look at the result before committing it. Image models misspell labels and occasionally point an+arrow at the wrong card; regenerate rather than ship a diagram whose text is wrong. `--quality low`+makes iteration cheap while checking composition, but commit a `high` render. Both the art direction+and the reader's instructions live at the top of the script — change them there rather than+hand-tuning one skill's prompt, so the set stays visually consistent.## Before opening a PR@@ -266,5 +367,12 @@ wheels globally, so repeat runs create each environment in milliseconds.- `metadata.version` exists, is quoted, and is bumped if you changed an existing skill.- `metadata` is a block mapping; `openclaw` / `hermes` blocks are nested mappings.- `uv run skills-ref validate skills/<name>` passes.+- `uv run --with pytest python -m pytest tests/_meta -q` passes — this is what CI blocks on, and it+ catches a missing suite, a missing `skill-requirements.toml` entry, a broken local link, and a+ leaked local path.+- If the skill ships `scripts/`: a suite exists at `tests/<name>/`, a `[skills.<name>]` entry exists+ in `tests/skill-requirements.toml`, and `python tests/run_all.py --isolated <name>` passes.+- `docs/images/<name>.png` exists, and was regenerated if the change altered what the skill does.+ Its labels are spelled correctly and its arrows point where they should.- Examples and scripts are tested, or clearly marked illustrative.- No secrets or private data; scan results clean or explained in the PR.diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 670f404d..5c64554b 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -228,7 +228,7 @@ Good skills are specific, practical, and easy for an agent to apply.3. Make the smallest useful change that fixes or improves the skill.4. Increment `metadata.version`.5. Test changed examples, commands, and scripts.-6. Run the skill's suite if it has one: `uv run --with pytest python -m pytest tests/skill-name -q`. Some suites assert the skill's exact version string, so a version bump can require a matching test edit.+6. Run the skill's suite if it has one: `uv run --with pytest python -m pytest tests/skill-name -q`. Suites check that `metadata.version` is present and quoted, not what it equals, so a version bump never needs a matching test edit.7. Note any behavior changes in the pull request description.## Validation@@ -278,12 +278,42 @@ Run one skill's suite, or the whole tree:```bashuv run --with pytest python -m pytest tests/skill-name -q-# every skill, in a separate process each+# every skill, in a separate process each, after the repo-wide guarduv run --with pytest python tests/run_all.py```Each skill's suite must run in its own process. Skills' `scripts/` directories own plain top-level module names — 32 skills ship a `scripts/_common.py`, and names like `cluster.py` and `validate_manifest.py` recur — so collecting two skills into one interpreter would resolve those imports to whichever skill was imported first and silently test the wrong files. `tests/conftest.py` rejects a multi-skill session, and `tests/run_all.py` forks per skill.+### The repo-wide guard, and what you no longer have to write++```bash+uv run --with pytest python -m pytest tests/_meta -q+```++`tests/_meta` is the check to run first and the one CI blocks on. It needs no scientific packages and finishes in seconds. It spans every skill at once — safe, because it parses scripts with `ast` and never imports them — and it enforces the rule this whole layout exists for: **a skill that ships `scripts/` must have a suite at `tests/<name>/` and a `[skills.<name>]` entry in `skill-requirements.toml`.** It also runs the shared structural contract over every skill: frontmatter conformance, the 500-line `SKILL.md` limit, no tests or compiled bytecode under `skills/`, every local link resolving, every script parsing, no `eval`/`exec`/`os.system`, no script shadowing a standard-library module, no hardcoded local path, and valid shell scripts.++Because `tests/_meta` already covers all of that repo-wide, a per-skill suite should not repeat it. Write only what is specific to the skill, and pull the shared pieces from `tests/_contract/`, which `tests/conftest.py` registers as the importable module `skill_contract`:++```python+import skill_contract++# every argparse script answers --help; skips when the skill's packages are+# absent, and runs for real under --isolated+CliHelpTests = skill_contract.cli.help_test_case(SKILL_ROOT)++# for scripts that are importable libraries with a worked example under+# `if __name__ == "__main__":` rather than argparse CLIs+DemoBlockTests = skill_contract.cli.demo_test_case(SKILL_ROOT, ("doe_designs.py",))+```++`skill_contract.office` and `skill_contract.schematic` cover files that several skills ship byte-identical copies of — the OOXML `office/` tree under `docx`/`pptx`/`xlsx`, and the AI schematic generator under five skills. Instantiate them against your skill root rather than writing the tests again; `tests/_meta` separately fails if the copies drift apart, so those files have to be changed together.++Guard heavy imports at module scope so a suite degrades to skips rather than a collection error when a package is missing:++```python+np = pytest.importorskip("numpy", reason="skill-name needs numpy")+```+### One environment per skillFour suites fail on this repository's default environment because their scientific dependencies are not installed (`exa-search`, `qutip`, `scikit-survival`, `simpy`), and installing them all into one environment is not possible: the skills' upstream pins contradict each other. `opentrons` requires `numpy<2`; `esm` caps `transformers` below the release the `transformers` skill targets; `geniml` and `spikeinterface` pin `zarr<3` while the `zarr-python` skill targets 3.x; `bioservices` caps `lxml<6` while `matchms` requires 6.0.2+; and `pytdc`, `molfeat`, `deepchem`, `histolab`, `vaex`, and `ete3` each need an interpreter older than 3.13.@@ -297,7 +327,9 @@ python tests/run_all.py --isolated qutip exa-search # just theseNothing is installed into the project environment, so `uv sync` is unaffected. Each `[skills.<name>]` entry lists the packages that skill documents and, where needed, a `python` version for that skill alone — uv downloads the interpreter on demand. Packages that cannot be installed at all (a GitHub-only SDK, a conda-forge-only library, a CUDA build) are listed under `[unavailable]` with the reason, and the runner prints them so the gap appears in the test output.-A new skill that ships `scripts/` needs a `[skills.<name>]` entry. Use `packages = []` when its bundled tooling is standard-library only — the skill still gets a clean environment with just pytest. uv caches wheels globally, so repeat runs create each environment in milliseconds.+A new skill that ships `scripts/` needs a `[skills.<name>]` entry — `tests/_meta` fails without one. Use `packages = []` when its bundled tooling is standard-library only — the skill still gets a clean environment with just pytest. uv caches wheels globally, so repeat runs create each environment in milliseconds.++`.github/workflows/skill-tests.yml` runs `tests/_meta` plus every `packages = []` suite on each pull request, which is fast and needs no wheels beyond pytest. The full `--isolated` sweep is not run in CI: it builds an environment per skill, and several of them need a CUDA toolchain, a JDK, or a local MATLAB install that a runner does not have. Run it locally before a release, and whenever you change anything under `tests/_contract/`.## Pull Request Checklist@@ -314,6 +346,8 @@ Before submitting a pull request, confirm:- `metadata.version` exists and is quoted.- Existing skills have a version bump when changed.- The `description` clearly says what the skill does and when to use it.+- `uv run --with pytest python -m pytest tests/_meta -q` passes. This is what CI blocks on, and it catches a missing suite, a missing `skill-requirements.toml` entry, a broken local link, a leaked local path, and a `SKILL.md` over 500 lines.+- If the skill ships `scripts/`: a suite exists at `tests/<skill-name>/`, a `[skills.<skill-name>]` entry exists in `tests/skill-requirements.toml`, and `python tests/run_all.py --isolated <skill-name>` passes.- Examples and scripts have been tested or clearly marked as illustrative.- No secrets, credentials, private data, or unsafe instructions are included.- Relevant official documentation is linked where useful.diff --git a/docs/images/paperclip.png b/docs/images/paperclip.pngnew file mode 100644index 00000000..a356e400Binary files /dev/null and b/docs/images/paperclip.png differdiff --git a/docs/images/pkpd-modeling.png b/docs/images/pkpd-modeling.pngnew file mode 100644index 00000000..7cb1d2dcBinary files /dev/null and b/docs/images/pkpd-modeling.png differdiff --git a/skills/bioservices/SKILL.md b/skills/bioservices/SKILL.mdindex 56979a4a..0a04ba98 100644--- a/skills/bioservices/SKILL.md+++ b/skills/bioservices/SKILL.md@@ -5,7 +5,7 @@ license: GPLv3 licenseallowed-tools: Read Write Edit Bashcompatibility: Requires Python 3.9–3.12 and internet access to 40+ bioinformatics web APIs. NCBI BLAST requires a contact email (`NCBI_EMAIL` env var or explicit parameter).metadata:- version: "1.2"+ version: "1.3"skill-author: K-Dense Inc.openclaw:envVars:@@ -122,6 +122,12 @@ u = UniChem()chembl_id = u.get_compound_id_from_kegg("C11222") # Returns CHEMBL278315```+**Version caveat:** the per-source `get_compound_id_from_*` helpers are gone from+bioservices 1.16.0 — check `hasattr(u, "get_compound_id_from_kegg")` first, and+otherwise use the current UniChem API (`u.get_compounds(compound, source_type)`+and read `res["compounds"][0]["sources"]`). ChEMBL lookups follow the same rule:+`get_molecule`, not the pre-1.6 `get_compound_by_chemblId`.+**Common workflow:**1. Search compound by name in KEGG2. Extract KEGG compound ID@@ -206,7 +212,9 @@ annotations = g.Annotation(protein="P43403", format="tsv")### 7. Protein-Protein Interactions-Query interaction databases via PSICQUIC:+Query interaction databases via PSICQUIC. **PSICQUIC is not shipped by every+release — it is absent from 1.16.0** — so import it defensively and fall back to+`IntactComplex`, `OmniPath`, or `STRING` when it is missing:```pythonfrom bioservices import PSICQUICdiff --git a/skills/bioservices/scripts/compound_cross_reference.py b/skills/bioservices/scripts/compound_cross_reference.pyindex 997ccf91..7d240013 100755--- a/skills/bioservices/scripts/compound_cross_reference.py+++ b/skills/bioservices/scripts/compound_cross_reference.py@@ -92,6 +92,13 @@ def get_kegg_info(kegg, kegg_id):current_section = Nonefor line in entry.split("\n"):+ # KEGG field names start in column 1 and their continuation lines are+ # indented. A new field therefore ends any multi-line section --+ # without this reset, the indented DBLINKS lines that follow PATHWAY+ # would be collected as pathways.+ if line and not line.startswith(" "):+ current_section = None+if line.startswith("NAME"):compound_info['name'] = line.replace("NAME", "").strip().rstrip(";")@@ -234,7 +241,9 @@ def get_chembl_info(chembl_id):print(f"Retrieving ChEMBL entry for {chembl_id}...")- compound = c.get_compound_by_chemblId(chembl_id)+ # `get_compound_by_chemblId` was a pre-1.6 name; current releases expose+ # the same lookup as `get_molecule`.+ compound = c.get_molecule(chembl_id)if compound:print(f"\n✓ ChEMBL Information:")diff --git a/skills/bioservices/scripts/protein_analysis_workflow.py b/skills/bioservices/scripts/protein_analysis_workflow.pyindex 6b9a8d77..5756856a 100755--- a/skills/bioservices/scripts/protein_analysis_workflow.py+++ b/skills/bioservices/scripts/protein_analysis_workflow.py@@ -27,7 +27,15 @@ import reimport sysimport timeimport argparse-from bioservices import UniProt, KEGG, NCBIblast, PSICQUIC, QuickGO+from bioservices import UniProt, KEGG, NCBIblast, QuickGO++try:+ # PSICQUIC is not shipped by every bioservices release (it is absent from+ # 1.16.0). Importing it unconditionally would take the whole workflow down+ # over one optional step, so degrade instead.+ from bioservices import PSICQUIC+except ImportError: # pragma: no cover - depends on the installed release+ PSICQUIC = None_EMAIL_RE = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")@@ -260,6 +268,10 @@ def find_interactions(protein_query):print("STEP 5: Protein-Protein Interactions")print(f"{'='*70}")+ if PSICQUIC is None:+ print("⊘ Skipped (this bioservices release does not ship PSICQUIC)")+ return []+try:p = PSICQUIC()diff --git a/skills/deepchem/SKILL.md b/skills/deepchem/SKILL.mdindex 7142f8d0..96c4a16a 100644--- a/skills/deepchem/SKILL.md+++ b/skills/deepchem/SKILL.md@@ -5,7 +5,7 @@ license: MIT licenseallowed-tools: Read Write Edit Bashcompatibility: Requires Python 3.7–3.11 (PyPI 2.8.0 caps at <3.12). Install PyTorch, TensorFlow, or JAX before the matching deepchem extra. RDKit is a core dependency.metadata:- version: "1.2"+ version: "1.4"skill-author: K-Dense Inc.---diff --git a/skills/deepchem/references/core_capabilities.md b/skills/deepchem/references/core_capabilities.mdindex cf03b53e..83e17578 100644--- a/skills/deepchem/references/core_capabilities.md+++ b/skills/deepchem/references/core_capabilities.md@@ -268,9 +268,9 @@ new_smiles = ['CCO', 'c1ccccc1', 'CC(C)O']new_features = featurizer.featurize(new_smiles)new_dataset = dc.data.NumpyDataset(X=new_features)-# Apply same transformations as training-for transformer in transformers:- new_dataset = transformer.transform(new_dataset)--predictions = model.predict(new_dataset)+# Untransform the output, not the input. A NormalizationTransformer built with+# transform_y=True touches y, and a prediction dataset has no y -- transforming+# it does nothing, and the predictions come back in z-scored space. Passing the+# transformers to predict() untransforms them into the target's real units.+predictions = model.predict(new_dataset, transformers=transformers)```diff --git a/skills/deepchem/references/workflows.md b/skills/deepchem/references/workflows.mdindex 9b98011e..9488f5fa 100644--- a/skills/deepchem/references/workflows.md+++ b/skills/deepchem/references/workflows.md@@ -115,11 +115,11 @@ new_featurizer = dc.feat.CircularFingerprint(radius=2, size=2048)new_features = new_featurizer.featurize(new_smiles)new_dataset = dc.data.NumpyDataset(X=new_features)-# Apply same transformations-for transformer in transformers:- new_dataset = transformer.transform(new_dataset)--predictions = model.predict(new_dataset)+# Untransform the output, not the input. A NormalizationTransformer built with+# transform_y=True touches y, and a prediction dataset has no y -- transforming+# it does nothing, and the predictions come back in z-scored space. Passing the+# transformers to predict() untransforms them into the target's real units.+predictions = model.predict(new_dataset, transformers=transformers)```---diff --git a/skills/deepchem/scripts/graph_neural_network.py b/skills/deepchem/scripts/graph_neural_network.pyindex 6863b5b9..567666b0 100644--- a/skills/deepchem/scripts/graph_neural_network.py+++ b/skills/deepchem/scripts/graph_neural_network.py@@ -34,6 +34,18 @@ MOLNET_DATASETS = {'lipo': ('regression', 1)}+# MoleculeNet loader names that are not simply load_<dataset>. BACE ships as+# separate classification and regression loaders, so dc.molnet.load_bace does+# not exist; the entry above treats it as a classification benchmark.+MOLNET_LOADERS = {+ 'bace': 'load_bace_classification'+}+++def molnet_loader(dataset_name):+ """Return the dc.molnet loader function for a MoleculeNet dataset name."""+ return getattr(dc.molnet, MOLNET_LOADERS.get(dataset_name, f'load_{dataset_name}'))+def create_model(model_type, n_tasks, mode='classification'):"""@@ -108,7 +120,7 @@ def train_on_molnet(dataset_name, model_type, n_epochs=50):# Load dataset with graph featurizationprint(f"\nLoading {dataset_name} dataset with GraphConv featurizer...")- load_func = getattr(dc.molnet, f'load_{dataset_name}')+ load_func = molnet_loader(dataset_name)tasks, datasets, transformers = load_func(featurizer='GraphConv',splitter='scaffold'diff --git a/skills/deepchem/scripts/predict_solubility.py b/skills/deepchem/scripts/predict_solubility.pyindex a33ba35d..e2065893 100644--- a/skills/deepchem/scripts/predict_solubility.py+++ b/skills/deepchem/scripts/predict_solubility.py@@ -139,13 +139,12 @@ def predict_new_molecules(model, smiles_list, transformers=None):# Create datasetnew_dataset = dc.data.NumpyDataset(X=features)- # Apply transformers (if any)- if transformers:- for transformer in transformers:- new_dataset = transformer.transform(new_dataset)-- # Predict- predictions = model.predict(new_dataset)+ # Both training paths normalize with transform_y=True, so the model learned+ # in z-scored target space. Hand the transformers to predict() so it+ # untransforms the output back to log(mol/L) -- transforming the dataset+ # instead would do nothing (these transformers touch y, not X, and a+ # prediction dataset has no y) and leave the printed numbers z-scored.+ predictions = model.predict(new_dataset, transformers=transformers or [])# Display resultsprint("\nPredictions:")diff --git a/skills/diffdock/SKILL.md b/skills/diffdock/SKILL.mdindex ba40304f..febf8649 100644--- a/skills/diffdock/SKILL.md+++ b/skills/diffdock/SKILL.md@@ -5,7 +5,7 @@ allowed-tools: Read Write Edit Bash Glob Grepcompatibility: Requires the DiffDock repository, Python 3.9 environment from upstream environment.yml or the official Docker image, RDKit, PyTorch/PyG, and optional CUDA GPU acceleration. Current guidance targets DiffDock v1.1.3 / DiffDock-L.license: MIT licensemetadata:- version: "1.1"+ version: "1.2"skill-author: K-Dense Inc.---diff --git a/skills/diffdock/scripts/analyze_results.py b/skills/diffdock/scripts/analyze_results.pyindex b294cfec..22baabd8 100755--- a/skills/diffdock/scripts/analyze_results.py+++ b/skills/diffdock/scripts/analyze_results.py@@ -121,8 +121,11 @@ def extract_confidence_score(sdf_file, complex_dir):try:with open(sdf_file) as f:content = f.read()- # Look for confidence score in SDF properties- conf_match = re.search(r'confidence[:\s]+(-?\d+\.?\d*)', content, re.IGNORECASE)+ # Look for confidence score in SDF properties. An SDF data item is+ # written as `> <confidence>` followed by the value on the next+ # line, so the separator class has to admit the closing angle+ # bracket as well as a colon.+ conf_match = re.search(r'confidence[>:\s]+(-?\d+\.?\d*)', content, re.IGNORECASE)if conf_match:return float(conf_match.group(1))except Exception:diff --git a/skills/diffdock/scripts/prepare_batch_csv.py b/skills/diffdock/scripts/prepare_batch_csv.pyindex 24f4ef4e..fb402794 100755--- a/skills/diffdock/scripts/prepare_batch_csv.py+++ b/skills/diffdock/scripts/prepare_batch_csv.py@@ -95,8 +95,11 @@ def validate_csv(csv_path, base_dir=None):if base_dir is None:base_dir = Path(csv_path).parent- # Validate each row- for idx, row in df.iterrows():+ # Validate each row. The per-row checks index the required columns+ # directly, so they can only run once every one of them is present --+ # otherwise a CSV missing a column raises KeyError instead of reporting it.+ rows = [] if missing_cols else df.iterrows()+ for idx, row in rows:row_msgs = []# Check complex name@@ -192,8 +195,8 @@ Examples:# Create template CSVpython prepare_batch_csv.py --create --output batch_template.csv- # Create template with 5 example rows- python prepare_batch_csv.py --create --output template.csv --num-examples 5+ # Create template with 2 example rows+ python prepare_batch_csv.py --create --output template.csv --num-examples 2# Validate with custom base directory for relative pathspython prepare_batch_csv.py input.csv --validate --base-dir /path/to/data/@@ -207,7 +210,7 @@ Examples:help='Create a template CSV file')parser.add_argument('--output', '-o', help='Output path for template CSV')parser.add_argument('--num-examples', type=int, default=3,- help='Number of example rows in template (default: 3)')+ help='Number of example rows in template, 1-3 (default: 3)')parser.add_argument('--base-dir', help='Base directory for relative file paths')args = parser.parse_args()diff --git a/skills/experimental-design/SKILL.md b/skills/experimental-design/SKILL.mdindex d696d5c4..44c17b75 100644--- a/skills/experimental-design/SKILL.md+++ b/skills/experimental-design/SKILL.md@@ -5,7 +5,7 @@ allowed-tools: Read Write Edit Bashcompatibility: Requires Python >=3.10. Scripts use numpy, pandas, and pyDOE3 (DOE matrices). Install with uv as shown below.license: MIT licensemetadata:- version: "1.0"+ version: "1.1"skill-author: K-Dense Inc.---diff --git a/skills/experimental-design/scripts/doe_designs.py b/skills/experimental-design/scripts/doe_designs.pyindex fcb558f6..036fa431 100644--- a/skills/experimental-design/scripts/doe_designs.py+++ b/skills/experimental-design/scripts/doe_designs.py@@ -148,10 +148,12 @@ def latin_hypercube(factors, n_samples, criterion="maximin", seed=0,'center'/'centermaximin'/'correlation' are alternatives."""from pyDOE3 import lhs- rng_state = int(seed) # pyDOE3 lhs uses numpy global RNG; seed it for repeatability- np.random.seed(rng_state)+ # pyDOE3 draws from its own default_rng, so seeding numpy's global RNG has+ # no effect -- the seed has to be handed to lhs itself.names = list(factors)- unit = lhs(len(names), samples=n_samples, criterion=criterion) # in [0,1]+ unit = lhs( # in [0,1]+ len(names), samples=n_samples, criterion=criterion, seed=int(seed)+ )out = {}for j, n in enumerate(names):low, high = factors[n][0], factors[n][1]diff --git a/skills/gget/SKILL.md b/skills/gget/SKILL.mdindex 1337cd07..a626eca7 100644--- a/skills/gget/SKILL.md+++ b/skills/gget/SKILL.md@@ -5,7 +5,7 @@ license: BSD-2-Clause licenseallowed-tools: Read Write Edit Bashcompatibility: Requires Python >=3.8 and gget 0.30.5-compatible APIs. Optional setup modules may install scientific dependencies that lag the newest Python releases; use Python 3.9 or 3.10 if `gget setup cellxgene` or `gget setup alphafold` fails.metadata:- version: "1.2"+ version: "1.3"skill-author: K-Dense Inc.---diff --git a/skills/gget/references/workflows.md b/skills/gget/references/workflows.mdindex d31d031f..97514b6f 100644--- a/skills/gget/references/workflows.md+++ b/skills/gget/references/workflows.md@@ -39,11 +39,12 @@ print("\nStep 3: Retrieving sequences...")nucleotide_seqs = gget.seq(gene_ids)protein_seqs = gget.seq(gene_ids, translate=True)-# Save sequences+# Save sequences. gget.seq returns a list of FASTA lines, so join it first --+# f.write(list) raises TypeError.with open("gaba_receptors_nt.fasta", "w") as f:- f.write(nucleotide_seqs)+ f.write("\n".join(nucleotide_seqs) + "\n")with open("gaba_receptors_aa.fasta", "w") as f:- f.write(protein_seqs)+ f.write("\n".join(protein_seqs) + "\n")# Step 4: Get expression dataprint("\nStep 4: Getting tissue expression...")@@ -108,22 +109,20 @@ print("\n2. Retrieving protein sequences...")human_seq = gget.seq(human_gene, translate=True)mouse_seq = gget.seq(mouse_gene, translate=True)-# Save to file for alignment+# Save to file for alignment (gget.seq returns a list of FASTA lines)with open("pcsk9_sequences.fasta", "w") as f:- f.write(human_seq)- f.write("\n")- f.write(mouse_seq)+ f.write("\n".join(human_seq) + "\n")+ f.write("\n".join(mouse_seq) + "\n")-# Step 3: Align sequences+# Step 3: Align sequences. gget.muscle returns None -- it writes to `out`, or+# prints the ClustalW alignment when `out` is omitted.print("\n3. Aligning sequences...")-alignment = gget.muscle("pcsk9_sequences.fasta")-print("Alignment completed. Visualizing in ClustalW format:")-print(alignment)+gget.muscle("pcsk9_sequences.fasta", out="pcsk9_aligned.afa")# Step 4: Get existing structures from PDBprint("\n4. Searching PDB for existing structures...")-# Search by sequence using BLAST-pdb_results = gget.blast(human_seq, database="pdbaa", limit=5)+# Search by sequence using BLAST (the amino-acid line, not the FASTA header)+pdb_results = gget.blast(human_seq[1], database="pdbaa", limit=5)print("Top PDB matches:")print(pdb_results[["Description", "Max Score", "Query Coverage"]])diff --git a/skills/gget/scripts/batch_sequence_analysis.py b/skills/gget/scripts/batch_sequence_analysis.pyindex a64a0856..61c2ae3f 100755--- a/skills/gget/scripts/batch_sequence_analysis.py+++ b/skills/gget/scripts/batch_sequence_analysis.py@@ -92,10 +92,11 @@ def analyze_sequences(print("\n\nStep 2: Multiple sequence alignment...")print("-" * 60)try:- alignment = gget.muscle(fasta_file)+ # gget.muscle returns None: it writes the alignment to `out` (or+ # prints it when `out` is omitted), so the file must be requested+ # rather than written from the return value.alignment_file = output_path / "alignment.afa"- with open(alignment_file, "w") as f:- f.write(alignment)+ gget.muscle(fasta_file, out=str(alignment_file))print(f"Alignment saved to: {alignment_file}")except Exception as e:print(f"Error in alignment: {e}")diff --git a/skills/gget/scripts/gene_analysis.py b/skills/gget/scripts/gene_analysis.pyindex bed474fb..673b6641 100755--- a/skills/gget/scripts/gene_analysis.py+++ b/skills/gget/scripts/gene_analysis.py@@ -9,6 +9,20 @@ import sysimport gget+def fasta_text(sequences):+ """Render what gget.seq returned as FASTA text.++ gget.seq returns a list of FASTA lines (header, sequence, ...); older+ releases returned one already-joined string. Writing the list straight to a+ file raises TypeError, so normalise both shapes here.+ """+ if sequences is None:+ return ""+ if isinstance(sequences, str):+ return sequences if sequences.endswith("\n") else sequences + "\n"+ return "\n".join(sequences) + "\n"++def analyze_gene(gene_name, species="homo_sapiens", output_prefix=None):"""Perform comprehensive analysis of a gene.@@ -53,11 +67,11 @@ def analyze_gene(gene_name, species="homo_sapiens", output_prefix=None):protein_seq = gget.seq([gene_id], translate=True)with open(f"{output_prefix}_nucleotide.fasta", "w") as f:- f.write(nucleotide_seq)+ f.write(fasta_text(nucleotide_seq))print(f" Nucleotide sequence saved to: {output_prefix}_nucleotide.fasta")with open(f"{output_prefix}_protein.fasta", "w") as f:- f.write(protein_seq)+ f.write(fasta_text(protein_seq))print(f" Protein sequence saved to: {output_prefix}_protein.fasta")# Step 4: Get tissue expressiondiff --git a/skills/neuropixels-analysis/SKILL.md b/skills/neuropixels-analysis/SKILL.mdindex b971436f..617ce6f9 100644--- a/skills/neuropixels-analysis/SKILL.md+++ b/skills/neuropixels-analysis/SKILL.md@@ -3,7 +3,7 @@ name: neuropixels-analysisdescription: Analyze Neuropixels extracellular recordings end-to-end with SpikeInterface. Covers loading SpikeGLX/Open Ephys/NWB data, preprocessing, drift/motion correction, Kilosort4 (and CPU) spike sorting, quality metrics, and unit curation (threshold-based, model-based UnitRefine, and AI-assisted visual review). Use when working with Neuropixels 1.0/2.0 recordings, spike sorting, or extracellular electrophysiology analysis.license: MIT licensemetadata:- version: "2.1"+ version: "2.2"skill-author: K-Dense Inc.openclaw:primaryEnv: ANTHROPIC_API_KEYdiff --git a/skills/neuropixels-analysis/scripts/compute_metrics.py b/skills/neuropixels-analysis/scripts/compute_metrics.pyindex c9f246ee..4fe71722 100644--- a/skills/neuropixels-analysis/scripts/compute_metrics.py+++ b/skills/neuropixels-analysis/scripts/compute_metrics.py@@ -14,19 +14,23 @@ import pandas as pdimport spikeinterface.full as si-# Curation criteria presets+# Curation criteria presets. snr and presence_ratio are minima, the other two are+# maxima, and each preset is at least as strict as the one above it. The ISI,+# presence, and amplitude thresholds follow references/QUALITY_METRICS.md:+# Allen Visual Coding uses isi_violations_ratio < 0.5, IBL's reproducible-ephys+# criteria tighten that to < 0.1, and the strict single-unit set to < 0.01.CURATION_CRITERIA = {'allen': {'snr': 3.0,- 'isi_violations_ratio': 0.1,+ 'isi_violations_ratio': 0.5,'presence_ratio': 0.9,'amplitude_cutoff': 0.1,},'ibl': {'snr': 4.0,- 'isi_violations_ratio': 0.5,- 'presence_ratio': 0.5,- 'amplitude_cutoff': None,+ 'isi_violations_ratio': 0.1,+ 'presence_ratio': 0.9,+ 'amplitude_cutoff': 0.1,},'strict': {'snr': 5.0,diff --git a/skills/neuropixels-analysis/scripts/neuropixels_pipeline.py b/skills/neuropixels-analysis/scripts/neuropixels_pipeline.pyindex 20fa2b5a..5582d1f8 100644--- a/skills/neuropixels-analysis/scripts/neuropixels_pipeline.py+++ b/skills/neuropixels-analysis/scripts/neuropixels_pipeline.py@@ -244,6 +244,14 @@ def curate_units(qm, method: str = 'allen') -> dict:'ibl': IBL standards'strict': Strict single-unit criteria"""+ methods = ('allen', 'ibl', 'strict')+ if method not in methods:+ # Without this, an unrecognised method leaves every non-noise unit out of+ # `labels` entirely, so export_results() silently reports zero good units.+ raise ValueError(+ f"unknown curation method {method!r}; choose one of {', '.join(methods)}"+ )+print(f"Curating units (method: {method})...")labels = {}diff --git a/skills/openpiv/SKILL.md b/skills/openpiv/SKILL.mdindex c63cb870..06af8e37 100644--- a/skills/openpiv/SKILL.md+++ b/skills/openpiv/SKILL.md@@ -5,7 +5,7 @@ license: BSD-3-Clausecompatibility: Requires Python 3.10+ with openpiv installed (uv pip install openpiv). numpy, scipy, scikit-image, and matplotlib arrive as dependencies. No network access needed after install.allowed-tools: Read Write Edit Bashmetadata:- version: "1.0"+ version: "1.1"skill-author: OpenPIV Teamtested-against: "openpiv 0.25.4"---@@ -333,6 +333,12 @@ def compute_vorticity(u, v, dx=1.0, dy=None):The grid spacing is `(window_size - overlap) / scaling_factor` in physical units, so leaving `dx=1.0`yields vorticity per grid cell, not per unit length.+**Sign convention:** `runner.py` ends with `transform_coordinates`, which relabels the grid into a+right-handed y-up frame but leaves the rows in image order, so the saved `y` *decreases* as the row+index grows. The standalone forms above assume the opposite, so on a `params.npz` field they return+`-du/dy` and flip the sign of the vorticity and the shear strain — negate the `axis=0` derivatives, or+use `PIVAnalyzer`, which reads the orientation off the saved coordinates.+### Strain Rate```pythondiff --git a/skills/openpiv/scripts/analyze.py b/skills/openpiv/scripts/analyze.pyindex ac1d212c..0f8a3a13 100644--- a/skills/openpiv/scripts/analyze.py+++ b/skills/openpiv/scripts/analyze.py@@ -36,6 +36,34 @@ class PIVAnalyzer:dy = float(np.abs(np.diff(self.y, axis=0)).mean()) if self.y.shape[0] > 1 else 1.0return dx, dy+ @property+ def axis_signs(self) -> Tuple[float, float]:+ """(+-1, +-1): whether x and y increase or decrease along the array axes.++ runner.py finishes with openpiv.tools.transform_coordinates(), which relabels+ the grid into a physical right-handed (y-up) frame while leaving the rows in+ image order -- so physical y *decreases* as the row index grows. np.gradient+ only sees the array, so differentiating with a positive spacing would return+ -du/dy there and silently flip the sign of the vorticity and of the shear+ strain rate. These signs put the derivatives back on the physical axes.+ """+ x_sign = -1.0 if self.x.shape[1] > 1 and self.x[0, 1] < self.x[0, 0] else 1.0+ y_sign = -1.0 if self.y.shape[0] > 1 and self.y[1, 0] < self.y[0, 0] else 1.0+ return x_sign, y_sign++ def _steps(+ self, dx: Optional[float], dy: Optional[float]+ ) -> Tuple[float, float, float, float]:+ """(dx, dy, x_sign, y_sign) for a gradient call, defaulting to the grid."""+ gx, gy = self.grid_spacing+ x_sign, y_sign = self.axis_signs+ return (+ gx if dx is None else abs(float(dx)),+ gy if dy is None else abs(float(dy)),+ x_sign,+ y_sign,+ )+def plot_vector_field(self,scale: int = 50,@@ -72,23 +100,26 @@ class PIVAnalyzer:def compute_vorticity(self, dx: Optional[float] = None, dy: Optional[float] = None) -> np.ndarray:- """Out-of-plane vorticity, dv/dx - du/dy. Defaults to the inferred grid spacing."""- gx, gy = self.grid_spacing- dx = gx if dx is None else dx- dy = gy if dy is None else dy- return np.gradient(self.v, dx, axis=1) - np.gradient(self.u, dy, axis=0)+ """Out-of-plane vorticity, dv/dx - du/dy. Defaults to the inferred grid spacing.++ dx and dy are spacing magnitudes; the axis orientation comes from the saved+ coordinates (see axis_signs), so a counter-clockwise flow gives positive+ vorticity whichever way the rows run.+ """+ dx, dy, x_sign, y_sign = self._steps(dx, dy)+ dv_dx = x_sign * np.gradient(self.v, dx, axis=1)+ du_dy = y_sign * np.gradient(self.u, dy, axis=0)+ return dv_dx - du_dydef compute_strain(self, dx: Optional[float] = None, dy: Optional[float] = None) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:"""Return (exx, eyy, exy) of the 2D strain-rate tensor."""- gx, gy = self.grid_spacing- dx = gx if dx is None else dx- dy = gy if dy is None else dy- du_dx = np.gradient(self.u, dx, axis=1)- du_dy = np.gradient(self.u, dy, axis=0)- dv_dx = np.gradient(self.v, dx, axis=1)- dv_dy = np.gradient(self.v, dy, axis=0)+ dx, dy, x_sign, y_sign = self._steps(dx, dy)+ du_dx = x_sign * np.gradient(self.u, dx, axis=1)+ du_dy = y_sign * np.gradient(self.u, dy, axis=0)+ dv_dx = x_sign * np.gradient(self.v, dx, axis=1)+ dv_dy = y_sign * np.gradient(self.v, dy, axis=0)return du_dx, dv_dy, 0.5 * (du_dy + dv_dx)def compute_statistics(self) -> Dict[str, float]:diff --git a/skills/phylogenetics/SKILL.md b/skills/phylogenetics/SKILL.mdindex a9415fd3..996bd983 100644--- a/skills/phylogenetics/SKILL.md+++ b/skills/phylogenetics/SKILL.md@@ -3,7 +3,7 @@ name: phylogeneticsdescription: Build and analyze phylogenetic trees using MAFFT (multiple alignment), IQ-TREE 2 (maximum likelihood), and FastTree (fast NJ/ML). Visualize with ETE3 or FigTree. For evolutionary analysis, microbial genomics, viral phylodynamics, protein family analysis, and molecular clock studies.license: Unknownmetadata:- version: "1.0"+ version: "1.1"skill-author: Kuan-lin Huang---@@ -23,6 +23,10 @@ Phylogenetic analysis reconstructs the evolutionary history of biological sequen# Conda (recommended for CLI tools)conda install -c bioconda mafft iqtree fasttreepip install ete3++# ete3's TreeStyle/NodeStyle rendering lives in its Qt backend, so image output+# needs PyQt5 as well; tree parsing and statistics work without it.+pip install PyQt5```## When to Use This Skilldiff --git a/skills/phylogenetics/scripts/phylogenetic_analysis.py b/skills/phylogenetics/scripts/phylogenetic_analysis.pyindex bdf3943f..53a68b3b 100644--- a/skills/phylogenetics/scripts/phylogenetic_analysis.py+++ b/skills/phylogenetics/scripts/phylogenetic_analysis.py@@ -138,9 +138,11 @@ def visualize_tree(tree_file: str, output_png: str, outgroup: str = None) -> Non"""Visualize the phylogenetic tree with ETE3."""try:from ete3 import Tree, TreeStyle, NodeStyle- except ImportError:- print("ETE3 not installed. Skipping visualization.")- print(" Install: pip install ete3")+ except ImportError as exc:+ # TreeStyle and NodeStyle live in ete3's Qt-backed treeview module, so+ # this also fires when ete3 itself imported fine but PyQt5 is missing.+ print(f"ETE3 rendering unavailable ({exc}). Skipping visualization.")+ print(" Install: pip install ete3 PyQt5")returnt = Tree(tree_file)diff --git a/skills/primekg/SKILL.md b/skills/primekg/SKILL.mdindex b2f3d784..df1c0c72 100644--- a/skills/primekg/SKILL.md+++ b/skills/primekg/SKILL.md@@ -3,7 +3,7 @@ name: primekgdescription: Query the Precision Medicine Knowledge Graph (PrimeKG) for multiscale biological data including genes, drugs, diseases, phenotypes, and more.license: Unknownmetadata:- version: "1.0"+ version: "1.1"skill-author: K-Dense Inc. (PrimeKG original from Harvard MIMS)---@@ -92,7 +92,8 @@ The graph contains several key relationship types including:- `scripts/query_primekg.py`: Core functions for searching and querying the knowledge graph.### Data Path-- Data: `/mnt/c/Users/eamon/Documents/Data/PrimeKG/kg.csv`+- Data: `kg.csv`, downloaded from the [PrimeKG Harvard Dataverse](https://dataverse.harvard.edu/dataverse/primekg).+- Point the scripts at it with `export PRIMEKG_DATA=/path/to/kg.csv` (default: `data/PrimeKG/kg.csv`).- Total nodes: ~129,000- Total edges: ~4,000,000- Database: CSV-based, optimized for pandas querying.diff --git a/skills/primekg/scripts/query_primekg.py b/skills/primekg/scripts/query_primekg.pyindex d2379bca..bfc64594 100644--- a/skills/primekg/scripts/query_primekg.py+++ b/skills/primekg/scripts/query_primekg.py@@ -3,13 +3,18 @@ import osimport jsonfrom typing import List, Dict, Optional, Union-# Default data path-DATA_PATH = "/mnt/c/Users/eamon/Documents/Data/PrimeKG/kg.csv"+# Where kg.csv lives. Override with the PRIMEKG_DATA environment variable, or+# by assigning to DATA_PATH before calling any query function.+DATA_PATH = os.environ.get("PRIMEKG_DATA", "data/PrimeKG/kg.csv")def _load_kg():"""Internal helper to load the KG efficiently."""if not os.path.exists(DATA_PATH):- raise FileNotFoundError(f"PrimeKG data not found at {DATA_PATH}. Please ensure the file is downloaded.")+ raise FileNotFoundError(+ f"PrimeKG data not found at {DATA_PATH}. Download kg.csv from "+ "https://dataverse.harvard.edu/dataverse/primekg and set "+ "PRIMEKG_DATA to its path."+ )# For very large files, we might want to use a database or specialized graph library.# For now, we'll use pandas for simplicity but with low_memory=True.return pd.read_csv(DATA_PATH, low_memory=True)diff --git a/skills/pydeseq2/SKILL.md b/skills/pydeseq2/SKILL.mdindex 9864f850..33f6d713 100644--- a/skills/pydeseq2/SKILL.md+++ b/skills/pydeseq2/SKILL.md@@ -5,7 +5,7 @@ allowed-tools: Read Write Edit Bashcompatibility: Requires Python >=3.11 and PyDESeq2 0.5.4-compatible dependencies. Examples target PyDESeq2 0.5.x, formulaic design strings, explicit contrasts, and uv-based installs.license: MIT licensemetadata:- version: "1.2"+ version: "1.3"skill-author: K-Dense Inc.---diff --git a/skills/pydeseq2/scripts/run_deseq2_analysis.py b/skills/pydeseq2/scripts/run_deseq2_analysis.pyindex 96c61f23..c6555340 100644--- a/skills/pydeseq2/scripts/run_deseq2_analysis.py+++ b/skills/pydeseq2/scripts/run_deseq2_analysis.py@@ -47,8 +47,10 @@ def load_and_validate_data(counts_path, metadata_path, transpose_counts=True):print(f" Counts shape: {counts_df.shape} (samples × genes)")print(f" Metadata shape: {metadata.shape} (samples × variables)")- # Validate- if not all(counts_df.index == metadata.index):+ # Validate. `Index.equals` also covers a length mismatch, which element-wise+ # comparison cannot: `index_a == index_b` raises when the two differ in+ # length, so the intersection fallback below would never be reached.+ if not counts_df.index.equals(metadata.index):print("\nWarning: Sample indices don't match perfectly. Taking intersection...")common_samples = counts_df.index.intersection(metadata.index)counts_df = counts_df.loc[common_samples]diff --git a/skills/pymc/SKILL.md b/skills/pymc/SKILL.mdindex 74817d2d..53581d92 100644--- a/skills/pymc/SKILL.md+++ b/skills/pymc/SKILL.md@@ -5,7 +5,7 @@ allowed-tools: Read Write Edit Bashcompatibility: Requires Python 3.12+ and PyMC 6.0.1-compatible dependencies. Install reproducible environments with `uv pip install "pymc[nutpie]==6.0.1"`; optional NumPyro or BlackJAX samplers require separately pinned JAX-compatible dependencies.license: Apache License, Version 2.0metadata:- version: "1.2"+ version: "1.3"skill-author: K-Dense Inc.---@@ -160,7 +160,7 @@ Creates:- Rank plots (mixing check)- Autocorrelation plots- Energy plots-- ESS evolution+- Local ESS plots- Summary statistics CSV### Quick Diagnostic Check@@ -258,7 +258,7 @@ This skill includes:- **`model_diagnostics.py`**: Automated diagnostic checking and report generation. Functions: `check_diagnostics()` for quick checks, `create_diagnostic_report()` for comprehensive analysis with plots.-- **`model_comparison.py`**: Model comparison utilities using LOO/WAIC. Functions: `compare_models()`, `check_loo_reliability()`, `model_averaging()`.+- **`model_comparison.py`**: Model comparison utilities built on PSIS-LOO ELPD, the only criterion ArviZ 1.x `compare()` ranks on. Functions: `compare_models()`, `check_loo_reliability()`, `model_averaging()`.### Templates (`assets/`)diff --git a/skills/pymc/references/model_patterns.md b/skills/pymc/references/model_patterns.mdindex a9461cd9..02664c01 100644--- a/skills/pymc/references/model_patterns.md+++ b/skills/pymc/references/model_patterns.md@@ -109,11 +109,11 @@ comparison = compare_models(models, ic='loo')check_loo_reliability(models)```-**Interpretation:**-- **Δloo < 2**: Models are similar, choose simpler model-- **2 < Δloo < 4**: Weak evidence for better model-- **4 < Δloo < 10**: Moderate evidence-- **Δloo > 10**: Strong evidence for better model+**Interpretation** — ArviZ 1.x reports `elpd_diff` on the ELPD scale (higher is+better, so the best model's `elpd_diff` is 0 and the others are negative):+- **|elpd_diff| < 4**: Models are similar, choose the simpler model+- **|elpd_diff| > 4 but within 2 `dse`**: Moderate evidence for the better model+- **|elpd_diff| > 4 and beyond 2 `dse`**: Strong evidence for the better model**Check Pareto-k values:**- k < 0.7: LOO reliablediff --git a/skills/pymc/scripts/model_comparison.py b/skills/pymc/scripts/model_comparison.pyindex 04a69894..fafd1366 100644--- a/skills/pymc/scripts/model_comparison.py+++ b/skills/pymc/scripts/model_comparison.py@@ -24,12 +24,16 @@ import matplotlib.pyplot as pltfrom typing import Any, Dict+#: ArviZ 1.x compares models on PSIS-LOO ELPD only; there is no `ic=` switch and+#: no deviance scale. WAIC is still available on its own via `az.waic()`.+SUPPORTED_IC = ('loo', 'elpd')++def compare_models(models_dict: Dict[str, Any],ic='loo',- scale='deviance',verbose=True):"""- Compare multiple models using information criteria.+ Compare multiple models by expected log pointwise predictive density.Parameters----------@@ -37,29 +41,38 @@ def compare_models(models_dict: Dict[str, Any],Dictionary mapping model names to PyMC posterior objects.All models must have log_likelihood computed.ic : str- Information criterion to use: 'loo' (default) or 'waic'- scale : str- Scale for IC: 'deviance' (default), 'log', or 'negative_log'+ Information criterion. Only 'loo' (equivalently 'elpd') is supported:+ ArviZ 1.x ranks models on PSIS-LOO ELPD.verbose : boolPrint detailed comparison results (default: True)Returns-------pd.DataFrame- Comparison DataFrame with model rankings and statistics+ Comparison DataFrame with model rankings and statistics, on the ELPD+ scale (higher is better, so `elpd_diff` is 0 for the best model and+ negative for the others).Notes------ Models must be fit with idata_kwargs={'log_likelihood': True} or- log-likelihood computed afterwards with pm.compute_log_likelihood().+ Models must have a log_likelihood group, computed during sampling or+ afterwards with pm.compute_log_likelihood(idata)."""+ if ic.lower() not in SUPPORTED_IC:+ raise ValueError(+ f"unknown information criterion {ic!r}: ArviZ 1.x ranks models on "+ "PSIS-LOO ELPD, so pass ic='loo'. For WAIC, call az.waic() per "+ "model directly."+ )+if verbose:print("="*70)- print(f" " * 25 + f"MODEL COMPARISON ({ic.upper()})")+ print(" " * 25 + "MODEL COMPARISON (LOO)")print("="*70)- # Perform comparison- comparison = az.compare(models_dict, ic=ic, scale=scale)+ # round_to='none' keeps the columns numeric; the default formats them for+ # display, which turns every comparison below into a string comparison.+ comparison = az.compare(models_dict, round_to='none')if verbose:print("\nModel Rankings:")@@ -69,15 +82,15 @@ def compare_models(models_dict: Dict[str, Any],print("\n" + "="*70)print("INTERPRETATION GUIDE")print("="*70)- print(f"• rank: Model ranking (0 = best)")- print(f"• {ic}: {ic.upper()} estimate (lower is better)")- print(f"• p_{ic}: Effective number of parameters")- print(f"• d{ic}: Difference from best model")- print(f"• weight: Model probability (pseudo-BMA)")- print(f"• se: Standard error of {ic.upper()}")- print(f"• dse: Standard error of the difference")- print(f"• warning: True if model has reliability issues")- print(f"• scale: {scale}")+ print("• rank: Model ranking (0 = best)")+ print("• elpd: PSIS-LOO ELPD estimate (higher is better)")+ print("• p: Effective number of parameters")+ print("• elpd_diff: ELPD minus the best model's ELPD (0 for the best)")+ print("• weight: Model probability (stacking weights)")+ print("• se: Standard error of the ELPD estimate")+ print("• dse: Standard error of the difference")+ print("• p_worse: Probability the model is worse than the best one")+ print("• diag_elpd: Reliability diagnostic for the ELPD estimate")print("\n" + "="*70)print("MODEL SELECTION GUIDELINES")@@ -86,33 +99,38 @@ def compare_models(models_dict: Dict[str, Any],best_model = comparison.index[0]print(f"\n✓ Best model: {best_model}")- # Check for clear winner+ # Check for a clear winner. Vehtari et al. recommend treating an ELPD+ # difference below 4 as small, and otherwise judging it against the+ # standard error of the difference.if len(comparison) > 1:- delta = comparison.iloc[1][f'd{ic}']+ delta = abs(comparison.iloc[1]['elpd_diff'])delta_se = comparison.iloc[1]['dse']- if delta > 10:- print(f" → STRONG evidence for {best_model} (Δ{ic} > 10)")- elif delta > 4:- print(f" → MODERATE evidence for {best_model} (4 < Δ{ic} < 10)")- elif delta > 2:- print(f" → WEAK evidence for {best_model} (2 < Δ{ic} < 4)")+ if delta < 4:+ print(f" → Models are SIMILAR (ELPD difference {delta:.1f} < 4)")+ print(" Consider model averaging or choose based on simplicity")+ elif delta > 2 * delta_se:+ print(+ f" → STRONG evidence for {best_model} "+ f"(ELPD difference {delta:.1f} > 2 SE)"+ )else:- print(f" → Models are SIMILAR (Δ{ic} < 2)")- print(f" Consider model averaging or choose based on simplicity")-- # Check if difference is significant relative to SE- if delta > 2 * delta_se:- print(f" → Difference is > 2 SE, likely reliable")- else:- print(f" → Difference is < 2 SE, uncertain distinction")-- # Check for warnings- if comparison['warning'].any():+ print(+ f" → MODERATE evidence for {best_model} "+ f"(ELPD difference {delta:.1f}, within 2 SE)"+ )++ # Reliability. ArviZ 1.x reports this per row as a diagnostic string+ # instead of the old boolean `warning` column.+ flagged = [+ name+ for name, diagnostic in comparison['diag_elpd'].items()+ if isinstance(diagnostic, str) and diagnostic.strip() not in ('', 'ok')+ ]+ if flagged:print("\n⚠️ WARNING: Some models have reliability issues")- warned_models = comparison[comparison['warning']].index.tolist()- print(f" Models with warnings: {', '.join(warned_models)}")- print(f" → Check Pareto-k diagnostics with check_loo_reliability()")+ print(f" Models with warnings: {', '.join(flagged)}")+ print(" → Check Pareto-k diagnostics with check_loo_reliability()")return comparison@@ -210,19 +228,21 @@ def plot_model_comparison(comparison, output_path=None, show=True):matplotlib.figure.FigureThe comparison figure"""- fig = plt.figure(figsize=(10, 6))- az.plot_compare(comparison)- plt.title('Model Comparison', fontsize=14, fontweight='bold')- plt.tight_layout()+ # ArviZ 1.x returns a PlotCollection and does not draw into pyplot's+ # current figure, so the figure has to come back out of the collection --+ # plt.savefig() would write a blank image.+ collection = az.plot_compare(comparison)+ fig = collection.viz['figure'].item()+ fig.suptitle('Model Comparison', fontsize=14, fontweight='bold')if output_path:- plt.savefig(output_path, dpi=300, bbox_inches='tight')+ fig.savefig(output_path, dpi=300, bbox_inches='tight')print(f"Comparison plot saved to {output_path}")if show:plt.show()else:- plt.close()+ plt.close(fig)return fig@@ -239,7 +259,7 @@ def model_averaging(models_dict: Dict[str, Any],models_dict : dictDictionary mapping model names to PyMC posterior objectsweights : array-like, optional- Model weights. If None, computed from IC (pseudo-BMA weights)+ Model weights. If None, taken from `compare_models` (stacking weights)var_name : strName of the predicted variable (default: 'y_obs')ic : str@@ -253,7 +273,7 @@ def model_averaging(models_dict: Dict[str, Any],Model weights used"""if weights is None:- comparison = az.compare(models_dict, ic=ic)+ comparison = compare_models(models_dict, ic=ic, verbose=False)weights = comparison['weight'].valuesmodel_names = comparison.index.tolist()else:diff --git a/skills/pymc/scripts/model_diagnostics.py b/skills/pymc/scripts/model_diagnostics.pyindex 960b57bc..1b79f28a 100644--- a/skills/pymc/scripts/model_diagnostics.py+++ b/skills/pymc/scripts/model_diagnostics.py@@ -15,7 +15,6 @@ Usage:"""import arviz as az-import numpy as npimport matplotlib.pyplot as pltfrom pathlib import Path@@ -44,8 +43,10 @@ def check_diagnostics(idata, var_names=None, ess_threshold=400, rhat_threshold=1print(" " * 20 + "MCMC DIAGNOSTICS REPORT")print("="*70)- # Get summary statistics- summary = az.summary(idata, var_names=var_names)+ # Get summary statistics. round_to="none" is required: ArviZ 1.x formats the+ # default summary for display, returning strings, which makes every numeric+ # comparison below raise TypeError.+ summary = az.summary(idata, var_names=var_names, round_to="none")results = {'summary': summary,@@ -197,60 +198,51 @@ def create_diagnostic_report(idata, var_names=None, output_dir='diagnostics/', sprint(f"\nGenerating diagnostic plots in '{output_dir}'...")+ # ArviZ 1.x plots return a PlotCollection and do not draw into pyplot's+ # current figure, so the figure must be saved through the collection --+ # plt.savefig() would write a blank image.+ def _save(plot_collection, filename, label):+ plot_collection.savefig(+ output_path / filename, dpi=300, bbox_inches='tight'+ )+ print(f" ✓ Saved {label}")+ if show:+ plt.show()+ else:+ plt.close(plot_collection.viz['figure'].item())+# 1. Trace plots- az.plot_trace_dist(idata, var_names=var_names)- plt.tight_layout()- plt.savefig(output_path / 'trace_plots.png', dpi=300, bbox_inches='tight')- print(f" ✓ Saved trace plots")- if show:- plt.show()- else:- plt.close()+ _save(+ az.plot_trace_dist(idata, var_names=var_names),+ 'trace_plots.png',+ 'trace plots',+ )# 2. Rank plots (check mixing)- fig = plt.figure(figsize=(12, 8))- az.plot_rank(idata, var_names=var_names)- plt.tight_layout()- plt.savefig(output_path / 'rank_plots.png', dpi=300, bbox_inches='tight')- print(f" ✓ Saved rank plots")- if show:- plt.show()- else:- plt.close()+ _save(+ az.plot_rank(idata, var_names=var_names),+ 'rank_plots.png',+ 'rank plots',+ )# 3. Autocorrelation plots- fig = plt.figure(figsize=(12, 8))- az.plot_autocorr(idata, var_names=var_names, combined=True)- plt.tight_layout()- plt.savefig(output_path / 'autocorr_plots.png', dpi=300, bbox_inches='tight')- print(f" ✓ Saved autocorrelation plots")- if show:- plt.show()- else:- plt.close()+ _save(+ az.plot_autocorr(idata, var_names=var_names),+ 'autocorr_plots.png',+ 'autocorrelation plots',+ )# 4. Energy plot (if available)if hasattr(idata.sample_stats, 'energy'):- fig = plt.figure(figsize=(10, 6))- az.plot_energy(idata)- plt.tight_layout()- plt.savefig(output_path / 'energy_plot.png', dpi=300, bbox_inches='tight')- print(f" ✓ Saved energy plot")- if show:- plt.show()- else:- plt.close()-- # 5. ESS plot- fig = plt.figure(figsize=(10, 6))- az.plot_ess(idata, var_names=var_names, kind='evolution')- plt.tight_layout()- plt.savefig(output_path / 'ess_evolution.png', dpi=300, bbox_inches='tight')- print(f" ✓ Saved ESS evolution plot")- if show:- plt.show()- else:- plt.close()+ _save(az.plot_energy(idata), 'energy_plot.png', 'energy plot')++ # 5. ESS plot. ArviZ 1.x offers 'local' and 'quantile'; the old+ # 'evolution' kind no longer exists.+ _save(+ az.plot_ess(idata, var_names=var_names, kind='local'),+ 'ess_local.png',+ 'local ESS plot',+ )# Save summary to CSVresults['summary'].to_csv(output_path / 'summary_statistics.csv')@@ -272,53 +264,44 @@ def compare_prior_posterior(idata, prior_idata, var_names=None, output_path=Noneprior_idata : xarray.DataTree or arviz.InferenceDataPrior object with prior samplesvar_names : list, optional- Variables to compare+ Variables to compare. Defaults to the first three posterior variables.output_path : str, optionalIf provided, save plot to this pathReturns-------- None+ arviz_plots.PlotCollection+ The overlaid prior/posterior figure."""- fig, axes = plt.subplots(- len(var_names) if var_names else 3,- 1,- figsize=(10, 8)+ if var_names is None:+ var_names = list(idata.posterior.data_vars)[:3]++ # ArviZ 1.x plot functions take a DataTree and a group name, not a flat+ # array plus an axis. Passing the first call's PlotCollection back into the+ # second is what overlays the two distributions on the same axes.+ collection = az.plot_dist(+ prior_idata,+ group='prior',+ var_names=var_names,+ visuals={'dist': {'color': 'blue'}},+ )+ az.plot_dist(+ idata,+ group='posterior',+ var_names=var_names,+ plot_collection=collection,+ visuals={'dist': {'color': 'green'}},)-- if not isinstance(axes, np.ndarray):- axes = [axes]-- for idx, var in enumerate(var_names if var_names else list(idata.posterior.data_vars)[:3]):- # Plot prior- az.plot_dist(- prior_idata.prior[var].values.flatten(),- label='Prior',- ax=axes[idx],- color='blue',- alpha=0.3- )-- # Plot posterior- az.plot_dist(- idata.posterior[var].values.flatten(),- label='Posterior',- ax=axes[idx],- color='green',- alpha=0.3- )-- axes[idx].set_title(f'{var}: Prior vs Posterior')- axes[idx].legend()-- plt.tight_layout()if output_path:- plt.savefig(output_path, dpi=300, bbox_inches='tight')+ collection.savefig(output_path, dpi=300, bbox_inches='tight')print(f"Prior-posterior comparison saved to {output_path}")+ print("Prior is blue, posterior is green")else:plt.show()+ return collection+# Example usageif __name__ == '__main__':diff --git a/skills/pymoo/SKILL.md b/skills/pymoo/SKILL.mdindex 6d20bcb4..544e50e7 100644--- a/skills/pymoo/SKILL.md+++ b/skills/pymoo/SKILL.md@@ -5,7 +5,7 @@ license: Apache-2.0 licenseallowed-tools: Read Write Edit Bashcompatibility: Requires Python 3.10+ and pymoo (uv pip install). Optional matplotlib for visualization plots; optional autograd for gradient-based features; optional joblib for JoblibParallelization.metadata:- version: "1.2"+ version: "1.3"skill-author: K-Dense Inc.---diff --git a/skills/pymoo/references/algorithms.md b/skills/pymoo/references/algorithms.mdindex ccf50069..90547b2b 100644--- a/skills/pymoo/references/algorithms.md+++ b/skills/pymoo/references/algorithms.md@@ -152,7 +152,7 @@ algorithm = SPEA2(pop_size=100)from pymoo.algorithms.moo.nsga3 import NSGA3from pymoo.util.ref_dirs import get_reference_directions-ref_dirs = get_reference_directions("das-dennis", n_obj=4, n_partitions=12)+ref_dirs = get_reference_directions("das-dennis", 4, n_partitions=12) # n_dim is positionalalgorithm = NSGA3(ref_dirs=ref_dirs)```diff --git a/skills/pymoo/references/quick_start_workflows.md b/skills/pymoo/references/quick_start_workflows.mdindex c809835f..df1bf395 100644--- a/skills/pymoo/references/quick_start_workflows.md+++ b/skills/pymoo/references/quick_start_workflows.md@@ -114,7 +114,7 @@ from pymoo.visualization.pcp import PCPproblem = get_problem("dtlz2", n_obj=5)# Generate reference directions (required for NSGA-III)-ref_dirs = get_reference_directions("das-dennis", n_obj=5, n_partitions=12)+ref_dirs = get_reference_directions("das-dennis", 5, n_partitions=12) # n_dim is positional# Configure NSGA-IIIalgorithm = NSGA3(ref_dirs=ref_dirs)diff --git a/skills/pymoo/scripts/many_objective_example.py b/skills/pymoo/scripts/many_objective_example.pyindex 27499e5c..dd541fce 100644--- a/skills/pymoo/scripts/many_objective_example.py+++ b/skills/pymoo/scripts/many_objective_example.py@@ -21,8 +21,10 @@ def run_many_objective_optimization():problem = get_problem("dtlz2", n_obj=n_obj)# Generate reference directions for NSGA-III- # Das-Dennis method for uniform distribution- ref_dirs = get_reference_directions("das-dennis", n_obj=n_obj, n_partitions=12)+ # Das-Dennis method for uniform distribution.+ # The dimension is positional: the factory's first argument is n_dim, and+ # passing it as n_obj= raises TypeError.+ ref_dirs = get_reference_directions("das-dennis", n_obj, n_partitions=12)print(f"Number of reference directions: {len(ref_dirs)}")diff --git a/skills/pytorch-lightning/SKILL.md b/skills/pytorch-lightning/SKILL.mdindex 8a6c5cfd..cfcbb703 100644--- a/skills/pytorch-lightning/SKILL.md+++ b/skills/pytorch-lightning/SKILL.md@@ -5,7 +5,7 @@ allowed-tools: Read Write Edit Bashlicense: Apache-2.0 licensecompatibility: Requires Python 3.10+ and lightning 2.6+ (or pytorch-lightning 2.6+). GPU training needs CUDA-capable PyTorch. Optional loggers (wandb, mlflow, comet-ml) and DeepSpeed require separate installs.metadata:- version: "1.0"+ version: "1.1"skill-author: K-Dense Inc.---diff --git a/skills/pytorch-lightning/references/distributed_training.md b/skills/pytorch-lightning/references/distributed_training.mdindex 864575b3..14b8ae5b 100644--- a/skills/pytorch-lightning/references/distributed_training.md+++ b/skills/pytorch-lightning/references/distributed_training.md@@ -636,6 +636,7 @@ Save checkpoints to resume from failures:```pythoncheckpoint_callback = ModelCheckpoint(+ monitor="val_loss", # save_top_k > 1 needs a quantity to rank onsave_top_k=3,save_last=True, # Always save last for resumingevery_n_epochs=5diff --git a/skills/pytorch-lightning/scripts/quick_trainer_setup.py b/skills/pytorch-lightning/scripts/quick_trainer_setup.pyindex 89f8bdbc..680f1d30 100644--- a/skills/pytorch-lightning/scripts/quick_trainer_setup.py+++ b/skills/pytorch-lightning/scripts/quick_trainer_setup.py@@ -256,6 +256,8 @@ def deepspeed_trainer(checkpoint_callback = ModelCheckpoint(dirpath=checkpoint_dir,filename="{epoch:02d}-{step:06d}",+ monitor="val_loss", # Required: save_top_k > 1 needs a quantity+ mode="min",save_top_k=3,save_last=True,every_n_train_steps=1000, # Save every N steps@@ -351,6 +353,8 @@ def time_limited_trainer(checkpoint_callback = ModelCheckpoint(dirpath=checkpoint_dir,+ monitor="val_loss", # Required: save_top_k > 1 needs a quantity+ mode="min",save_top_k=3,save_last=True, # Important for resumingevery_n_epochs=5,@@ -410,6 +414,12 @@ def reproducible_trainer(seed=42, max_epochs=100):# =============================================================================if __name__ == "__main__":+ from lightning.pytorch.accelerators import CUDAAccelerator++ # Trainer construction validates the requested hardware, so the GPU-only+ # configurations below can only be built where that hardware exists.+ cuda_devices = CUDAAccelerator.auto_device_count() if CUDAAccelerator.is_available() else 0+print("PyTorch Lightning Trainer Configurations\n")# Example 1: Basic training@@ -423,29 +433,38 @@ if __name__ == "__main__":print("2. Debug Trainer:")trainer = debug_trainer()print(f" - Fast dev run: {trainer.fast_dev_run}")- print(f" - Detect anomaly: {trainer.detect_anomaly}")+ print(f" - Accelerator: {trainer.accelerator}")print()# Example 3: Production single GPUprint("3. Production Single GPU Trainer:")- trainer = production_single_gpu_trainer(max_epochs=100)- print(f" - Max epochs: {trainer.max_epochs}")- print(f" - Precision: {trainer.precision}")- print(f" - Callbacks: {len(trainer.callbacks)}")+ if cuda_devices >= 1:+ trainer = production_single_gpu_trainer(max_epochs=100)+ print(f" - Max epochs: {trainer.max_epochs}")+ print(f" - Precision: {trainer.precision}")+ print(f" - Callbacks: {len(trainer.callbacks)}")+ else:+ print(" - skipped: no CUDA GPU on this machine")print()# Example 4: Multi-GPU DDPprint("4. Multi-GPU DDP Trainer:")- trainer = multi_gpu_ddp_trainer(num_gpus=4)- print(f" - Strategy: {trainer.strategy}")- print(f" - Devices: {trainer.num_devices}")+ if cuda_devices >= 4:+ trainer = multi_gpu_ddp_trainer(num_gpus=4)+ print(f" - Strategy: {trainer.strategy}")+ print(f" - Devices: {trainer.num_devices}")+ else:+ print(f" - skipped: needs 4 CUDA GPUs, found {cuda_devices}")print()# Example 5: FSDP for large modelsprint("5. FSDP Trainer for Large Models:")- trainer = large_model_fsdp_trainer(num_gpus=8)- print(f" - Strategy: {trainer.strategy}")- print(f" - Precision: {trainer.precision}")+ if cuda_devices >= 8:+ trainer = large_model_fsdp_trainer(num_gpus=8)+ print(f" - Strategy: {trainer.strategy}")+ print(f" - Precision: {trainer.precision}")+ else:+ print(f" - skipped: needs 8 CUDA GPUs, found {cuda_devices}")print()print("\nTo use these configurations:")diff --git a/skills/pytorch-lightning/scripts/template_lightning_module.py b/skills/pytorch-lightning/scripts/template_lightning_module.pyindex 01fdc6e2..edcdc478 100644--- a/skills/pytorch-lightning/scripts/template_lightning_module.py+++ b/skills/pytorch-lightning/scripts/template_lightning_module.py@@ -162,13 +162,13 @@ class TemplateLightningModule(L.LightningModule):weight_decay=1e-5,)- # Define scheduler+ # Define scheduler. PyTorch removed the schedulers' `verbose` argument;+ # use LearningRateMonitor or the logged learning_rate metric instead.scheduler = ReduceLROnPlateau(optimizer,mode="min",factor=0.5,patience=5,- verbose=True,)# Return configuration@@ -215,5 +215,6 @@ if __name__ == "__main__":# Train (you need to provide train_dataloader and val_dataloader)# trainer.fit(model, train_dataloader, val_dataloader)- print(f"Model created with {model.num_parameters:,} parameters")+ n_parameters = sum(p.numel() for p in model.parameters())+ print(f"Model created with {n_parameters:,} parameters")print(f"Hyperparameters: {model.hparams}")diff --git a/skills/scanpy/SKILL.md b/skills/scanpy/SKILL.mdindex 92dc9906..c75a5854 100644--- a/skills/scanpy/SKILL.md+++ b/skills/scanpy/SKILL.md@@ -3,7 +3,7 @@ name: scanpydescription: Standard single-cell RNA-seq analysis pipeline. Use for QC, normalization, dimensionality reduction (PCA/UMAP/t-SNE), clustering, differential expression, visualization, and converting R-friendly single-cell formats such as Seurat or SingleCellExperiment RDS files into h5ad for Scanpy. Best for exploratory scRNA-seq analysis with established workflows. For deep learning models use scvi-tools; for data format questions use anndata.license: BSD-3-Clausemetadata:- version: "1.4"+ version: "1.5"skill-author: K-Dense Inc.---diff --git a/skills/scanpy/scripts/_common.py b/skills/scanpy/scripts/_common.pyindex 575fb8e9..e1132fd9 100644--- a/skills/scanpy/scripts/_common.py+++ b/skills/scanpy/scripts/_common.py@@ -104,13 +104,24 @@ def add_io_args(parser, default_output=None):return parser+def _named_keys(mapping):+ """Named keys of an AnnData mapping, in order.++ anndata >= 0.13 reports an unnamed `None` key on `.layers` standing for X+ itself. Joining that into a string raises TypeError, so filter it out.+ """+ return [key for key in mapping.keys() if isinstance(key, str)]++def summarize(adata):"""Return a short human-readable summary string of an AnnData object."""lines = [f"{adata.n_obs} cells x {adata.n_vars} genes"]if len(adata.obs.columns):lines.append("obs: " + ", ".join(adata.obs.columns[:20]))- if list(adata.obsm.keys()):- lines.append("obsm: " + ", ".join(adata.obsm.keys()))- if list(adata.layers.keys()):- lines.append("layers: " + ", ".join(adata.layers.keys()))+ obsm = _named_keys(adata.obsm)+ if obsm:+ lines.append("obsm: " + ", ".join(obsm))+ layers = _named_keys(adata.layers)+ if layers:+ lines.append("layers: " + ", ".join(layers))return "\n".join(lines)diff --git a/skills/scientific-slides/SKILL.md b/skills/scientific-slides/SKILL.mdindex 7826ee34..0d49b98e 100644--- a/skills/scientific-slides/SKILL.md+++ b/skills/scientific-slides/SKILL.md@@ -4,7 +4,7 @@ description: Build slide decks and presentations for research talks. Use this foallowed-tools: Read Write Edit Bashlicense: MIT licensemetadata:- version: "1.3"+ version: "1.4"skill-author: K-Dense Inc.openclaw:primaryEnv: OPENROUTER_API_KEYdiff --git a/skills/scientific-slides/scripts/validate_presentation.py b/skills/scientific-slides/scripts/validate_presentation.pyindex 1e75bb07..c701b7f3 100644--- a/skills/scientific-slides/scripts/validate_presentation.py+++ b/skills/scientific-slides/scripts/validate_presentation.py@@ -16,12 +16,17 @@ import subprocessfrom pathlib import Pathfrom typing import Dict, List, Tuple, Optional-# Try to import PyPDF2 for PDF analysis+# PDF page and geometry analysis. pypdf is the maintained continuation of+# PyPDF2 and exposes the same PdfReader API, so accept whichever is installed.try:- import PyPDF2- HAS_PYPDF2 = True+ from pypdf import PdfReader+ HAS_PDF_READER = Trueexcept ImportError:- HAS_PYPDF2 = False+ try:+ from PyPDF2 import PdfReader+ HAS_PDF_READER = True+ except ImportError:+ HAS_PDF_READER = False# Try to import python-pptx for PowerPoint analysistry:@@ -97,15 +102,15 @@ class PresentationValidator:def _validate_pdf(self):"""Validate PDF presentation."""- if not HAS_PYPDF2:+ if not HAS_PDF_READER:self.warnings.append(- "PyPDF2 not installed. Install with: pip install PyPDF2"+ "pypdf not installed. Install with: pip install pypdf")return-+try:with open(self.filepath, 'rb') as f:- reader = PyPDF2.PdfReader(f)+ reader = PdfReader(f)num_pages = len(reader.pages)self.info.append(f"Number of slides: {num_pages}")diff --git a/skills/scvelo/SKILL.md b/skills/scvelo/SKILL.mdindex b17b339c..47f91cad 100644--- a/skills/scvelo/SKILL.md+++ b/skills/scvelo/SKILL.md@@ -2,8 +2,9 @@name: scvelodescription: RNA velocity analysis with scVelo. Estimate cell state transitions from unspliced/spliced mRNA dynamics, infer trajectory directions, compute latent time, and identify driver genes in single-cell RNA-seq data. Complements Scanpy/scVI-tools for trajectory inference.license: BSD-3-Clause+compatibility: Requires Python 3.10+ with scvelo, scanpy, and anndata. Verified against scvelo 0.3.4, whose dynamical model and pl.scatter need pandas<3 and whose stochastic estimator needs numpy<2; the deterministic estimator works on current releases.metadata:- version: "1.0"+ version: "1.1"skill-author: Kuan-lin Huang---@@ -74,12 +75,15 @@ print(adata)### 2. Preprocessing```python-# Filter and normalize (follows Scanpy conventions)+# Filter and normalize. As of scVelo 0.3, filter_and_normalize() only filters+# genes and normalizes per cell -- it no longer takes n_top_genes and no longer+# log-transforms, so the log step and HVG selection come from Scanpy.scv.pp.filter_and_normalize(adata,- min_shared_counts=20, # Minimum counts in spliced+unspliced- n_top_genes=2000 # Top highly variable genes+ min_shared_counts=20 # Minimum counts in spliced+unspliced)+sc.pp.log1p(adata)+sc.pp.highly_variable_genes(adata, n_top_genes=2000, subset=True)# Compute first and second order moments (means and variances)# knn_connectivities must be computed first@@ -238,8 +242,10 @@ def run_rna_velocity(adata, n_top_genes=2000, mode='dynamical', n_jobs=4):"""scv.settings.verbosity = 2- # 1. Preprocessing- scv.pp.filter_and_normalize(adata, min_shared_counts=20, n_top_genes=n_top_genes)+ # 1. Preprocessing (scVelo 0.3 dropped log/HVG from filter_and_normalize)+ scv.pp.filter_and_normalize(adata, min_shared_counts=20)+ sc.pp.log1p(adata)+ sc.pp.highly_variable_genes(adata, n_top_genes=n_top_genes, subset=True)if 'neighbors' not in adata.uns:sc.pp.neighbors(adata, n_neighbors=30)diff --git a/skills/scvelo/scripts/rna_velocity_workflow.py b/skills/scvelo/scripts/rna_velocity_workflow.pyindex 8ff89c1f..52b88c0d 100644--- a/skills/scvelo/scripts/rna_velocity_workflow.py+++ b/skills/scvelo/scripts/rna_velocity_workflow.py@@ -65,7 +65,15 @@ def run_velocity_analysis(# ── Step 2: Preprocessing ─────────────────────────────────────────────────print("Step 1/5: Preprocessing...")- scv.pp.filter_and_normalize(adata, min_shared_counts=20, n_top_genes=n_top_genes)+ # scVelo 0.3 narrowed filter_and_normalize() to gene filtering plus+ # per-cell normalization: it no longer accepts n_top_genes and no longer+ # log-transforms, so the log step and HVG selection come from Scanpy.+ scv.pp.filter_and_normalize(adata, min_shared_counts=20)+ if "log1p" not in adata.uns:+ sc.pp.log1p(adata)+ sc.pp.highly_variable_genes(+ adata, n_top_genes=min(n_top_genes, adata.n_vars), subset=True+ )if "neighbors" not in adata.uns:sc.pp.neighbors(adata, n_neighbors=n_neighbors, n_pcs=30)diff --git a/tests/_contract/__init__.py b/tests/_contract/__init__.pynew file mode 100644index 00000000..3da55d12--- /dev/null+++ b/tests/_contract/__init__.py@@ -0,0 +1,38 @@+"""Shared test contract for every skill in this repository.++Suites do not import this package by name from `sys.path` -- putting `tests/`+on `sys.path` would turn `tests/simpy/`, `tests/qutip/`, `tests/neurokit2/` and+friends into importable namespace packages that shadow the real libraries (see+the comment on `addopts` in `pyproject.toml`). Instead `tests/conftest.py`+loads this package by file location and registers it as `skill_contract`, so a+suite writes:++ import skill_contract++ CliHelpTests = skill_contract.cli.help_test_case(SKILL_ROOT)++Two halves, split by what they need from the environment:++`structure`+ Never imports skill code -- scripts are parsed with `ast`, not executed --+ so it is safe to run across every skill in one interpreter.+ `tests/_meta` does exactly that.++`cli`+ Runs each script's `--help` in a subprocess. Skips when the skill's+ packages are absent, and runs for real under+ `python tests/run_all.py --isolated`.++`office`+ The OOXML tree that docx, pptx, and xlsx each ship a byte-identical copy of.++`schematic`+ The AI schematic generator that scientific-schematics, latex-posters, and+ literature-review each ship a byte-identical copy of.+"""++from __future__ import annotations++from . import cli, office, schematic, structure++__all__ = ["cli", "office", "schematic", "structure"]diff --git a/tests/_contract/cli.py b/tests/_contract/cli.pynew file mode 100644index 00000000..e482180f--- /dev/null+++ b/tests/_contract/cli.py@@ -0,0 +1,211 @@+"""`--help` contract for a skill's bundled command-line scripts.++Unlike `structure`, this half actually runs the scripts, so what it proves+depends on the environment. In the bare project environment most scientific+packages are absent and the affected scripts skip; under+`python tests/run_all.py --isolated`, where each skill gets the packages it+documents, the same tests run for real. That is the point of the split: one+definition, honest in both places.++Each script runs in its own subprocess -- `--help` must not need this+interpreter's `sys.path`, and a script that hangs must not hang the suite.+"""++from __future__ import annotations++import ast+import os+import re+import subprocess+import sys+import unittest+from pathlib import Path++DEFAULT_TIMEOUT = 120++#: Never invoked directly: shared helpers and package markers, not CLIs.+NON_CLI_NAMES = frozenset({"__init__.py", "__main__.py", "_common.py", "conftest.py"})+++def cli_scripts(skill_root: Path) -> list[Path]:+ """Top-level scripts under `scripts/` that build an argparse parser.++ Only the top level: nested directories such as the `office/` trees under+ docx/pptx/xlsx are importable libraries, not entry points.+ """+ scripts = []+ for path in sorted((skill_root / "scripts").glob("*.py")):+ if path.name in NON_CLI_NAMES:+ continue+ try:+ tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path))+ except SyntaxError:+ continue # structure.compile_problems reports it+ imports_argparse = any(+ (isinstance(node, ast.Import) and any(a.name == "argparse" for a in node.names))+ or (isinstance(node, ast.ImportFrom) and node.module == "argparse")+ for node in ast.walk(tree)+ )+ if imports_argparse:+ scripts.append(path)+ return scripts+++def run_help(script: Path, timeout: int = DEFAULT_TIMEOUT) -> subprocess.CompletedProcess:+ environment = {**os.environ, "PYTHONDONTWRITEBYTECODE": "1"}+ return subprocess.run(+ [sys.executable, str(script), "--help"],+ capture_output=True,+ text=True,+ timeout=timeout,+ env=environment,+ cwd=script.parent,+ )+++#: A script that guards its own imports and prints a friendly install hint --+#: better behaviour than a traceback -- must still be recognised as "package+#: absent" rather than reported as a broken CLI. `exa-search` does exactly this.+_GRACEFUL_IMPORT_GUARD = re.compile(+ r"(?:^|\n)\s*([\w.\-]+) (?:is )?not installed\b"+ r"|No module named ['\"]?([\w.]+)"+ r"|pip install ([\w.\-\[\]]+)",+ re.IGNORECASE,+)+++def _missing_dependency(output: str) -> str | None:+ """The package name, when a failed `--help` was caused by an absent import.++ Deliberately narrow. `ImportError: cannot import name 'PSICQUIC' from+ 'bioservices'` means the package IS installed and the script is calling an+ API that no longer exists -- upstream drift, the most valuable thing this+ contract can catch. Treating that as "package absent" would skip the test+ and hide the breakage, so only a genuinely absent module counts:++ * `ModuleNotFoundError`, or an `ImportError` naming no such module;+ * a script that catches the ImportError itself and prints an install hint.+ """+ for line in reversed(output.strip().splitlines()):+ if line.startswith("ModuleNotFoundError:"):+ return line.split(":", 1)[1].strip()+ if line.startswith("ImportError:"):+ message = line.split(":", 1)[1].strip()+ return message if "No module named" in message else None++ match = _GRACEFUL_IMPORT_GUARD.search(output)+ if match:+ return next(group for group in match.groups() if group)+ return None+++def help_test_case(+ skill_root: Path,+ *,+ skip: frozenset[str] | set[str] | tuple[str, ...] = (),+ timeout: int = DEFAULT_TIMEOUT,+) -> type[unittest.TestCase]:+ """Build the `--help` TestCase for one skill.++ `skip` names scripts (by filename) that legitimately have no working+ `--help` -- pass it sparingly and say why at the call site.+ """+ skipped = frozenset(skip)++ class CliHelpContractTests(unittest.TestCase):+ maxDiff = None++ def test_every_cli_answers_help(self) -> None:+ scripts = [+ path for path in cli_scripts(skill_root) if path.name not in skipped+ ]+ self.assertTrue(+ scripts,+ f"{skill_root.name} ships no argparse CLI -- drop this test case "+ "or fix the discovery",+ )+ for script in scripts:+ with self.subTest(script=script.name):+ try:+ result = run_help(script, timeout=timeout)+ except subprocess.TimeoutExpired:+ self.fail(+ f"{script.name} --help did not return within {timeout}s; "+ "it is doing work before parsing arguments"+ )+ if result.returncode != 0:+ missing = _missing_dependency(result.stderr + result.stdout)+ if missing:+ self.skipTest(+ f"{script.name} needs an uninstalled package ({missing}); "+ "run under `tests/run_all.py --isolated` to exercise it"+ )+ self.fail(+ f"{script.name} --help exited {result.returncode}:\n"+ f"{result.stderr.strip()}"+ )+ self.assertIn(+ "usage:",+ result.stdout.lower(),+ f"{script.name} --help printed no usage line",+ )+ self.assertNotIn("Traceback", result.stderr)++ CliHelpContractTests.__qualname__ = f"CliHelpContractTests[{skill_root.name}]"+ return CliHelpContractTests+++def demo_test_case(+ skill_root: Path,+ scripts: tuple[str, ...],+ *,+ timeout: int = DEFAULT_TIMEOUT,+) -> type[unittest.TestCase]:+ """Build a TestCase that runs a library script's `__main__` demo block.++ Some skills ship importable modules rather than CLIs, with a worked example+ under `if __name__ == "__main__":`. That example is documentation, and+ documentation rots -- so run it and require a clean exit.++ Opt-in and explicit: pass the filenames, because a demo block that writes+ files or takes minutes should not be run by accident.+ """++ class DemoBlockTests(unittest.TestCase):+ maxDiff = None++ def test_every_demo_block_runs_clean(self) -> None:+ for name in scripts:+ script = skill_root / "scripts" / name+ with self.subTest(script=name):+ self.assertTrue(script.is_file(), f"{name} is not shipped")+ environment = {**os.environ, "PYTHONDONTWRITEBYTECODE": "1"}+ # Headless: a demo that plots must not open a window.+ environment.setdefault("MPLBACKEND", "Agg")+ try:+ result = subprocess.run(+ [sys.executable, str(script)],+ capture_output=True,+ text=True,+ timeout=timeout,+ env=environment,+ cwd=script.parent,+ )+ except subprocess.TimeoutExpired:+ self.fail(f"{name} did not finish within {timeout}s")+ if result.returncode != 0:+ missing = _missing_dependency(result.stderr + result.stdout)+ if missing:+ self.skipTest(+ f"{name} needs an uninstalled package ({missing}); "+ "run under `tests/run_all.py --isolated`"+ )+ self.fail(+ f"{name} exited {result.returncode}:\n{result.stderr.strip()}"+ )+ self.assertTrue(+ result.stdout.strip(), f"{name} printed nothing"+ )++ DemoBlockTests.__qualname__ = f"DemoBlockTests[{skill_root.name}]"+ return DemoBlockTestsdiff --git a/tests/_contract/office.py b/tests/_contract/office.pynew file mode 100644index 00000000..2954c0b1--- /dev/null+++ b/tests/_contract/office.py@@ -0,0 +1,296 @@+"""Shared tests for the OOXML `office/` tree bundled by docx, pptx, and xlsx.++Those three skills each ship a byte-identical copy of `scripts/office/` --+`helpers/`, `validators/`, `validate.py`, `soffice.py`, and the vendored+ISO/ECMA schemas. Rather than write the same tests three times, each suite+instantiates `office_test_case()` against its own copy, so a change that lands+in one copy and not the others fails on the copy that was missed as well as on+`identical_tree_problems()` in `tests/_meta`.++The interesting surface is the safety logic: `safe_extract` guards zip-slip and+symlink entries, and `opc_target` refuses relationship targets that escape the+package. Both are reachable with nothing but the standard library.+"""++from __future__ import annotations++import hashlib+import importlib+import stat+import sys+import tempfile+import unittest+import zipfile+from pathlib import Path++REPO_ROOT = Path(__file__).resolve().parents[2]+SKILLS_DIR = REPO_ROOT / "skills"++#: The skills that ship the shared tree. Kept here so adding a fourth is one edit.+OFFICE_SKILLS = ("docx", "pptx", "xlsx")++#: Other files several skills ship byte-identical copies of. A copy that drifts+#: is a skill quietly behaving differently from its siblings, so `tests/_meta`+#: pins them together. Each entry is (path relative to the skill, skills).+SHARED_FILES: tuple[tuple[str, tuple[str, ...]], ...] = (+ (+ "scripts/generate_schematic.py",+ (+ "scientific-schematics",+ "latex-posters",+ "literature-review",+ "citation-management",+ "scientific-slides",+ ),+ ),+ (+ "scripts/generate_schematic_ai.py",+ (+ "scientific-schematics",+ "latex-posters",+ "literature-review",+ "citation-management",+ "scientific-slides",+ ),+ ),+)+++def shared_file_problems(skills_dir: Path = SKILLS_DIR) -> list[str]:+ """Every skill in a `SHARED_FILES` group ships the same bytes."""+ problems = []+ for relative, skills in SHARED_FILES:+ digests = {}+ for name in skills:+ path = skills_dir / name / relative+ if not path.is_file():+ problems.append(f"{name}: {relative} is missing")+ continue+ digests[name] = hashlib.sha256(path.read_bytes()).hexdigest()+ if len(set(digests.values())) > 1:+ reference = skills[0]+ problems.extend(+ f"{name}: {relative} has drifted from {reference}'s copy"+ for name, digest in digests.items()+ if digest != digests.get(reference)+ )+ return problems+++def _tree_digest(office_dir: Path) -> str:+ """A digest over every path and byte under an `office/` tree."""+ digest = hashlib.sha256()+ for path in sorted(office_dir.rglob("*")):+ if not path.is_file():+ continue+ digest.update(str(path.relative_to(office_dir)).encode("utf-8"))+ digest.update(path.read_bytes())+ return digest.hexdigest()+++def identical_tree_problems(skills_dir: Path = SKILLS_DIR) -> list[str]:+ """The shared `office/` trees have not drifted apart."""+ digests = {}+ for name in OFFICE_SKILLS:+ office = skills_dir / name / "scripts" / "office"+ if not office.is_dir():+ return [f"{name}: scripts/office/ is missing"]+ digests[name] = _tree_digest(office)++ reference = digests[OFFICE_SKILLS[0]]+ return [+ f"{name}: scripts/office/ has drifted from {OFFICE_SKILLS[0]}'s copy "+ f"({digests[name][:12]} vs {reference[:12]})"+ for name in OFFICE_SKILLS[1:]+ if digests[name] != reference+ ]+++def office_test_case(skill_root: Path) -> type[unittest.TestCase]:+ """Build the shared `office/` TestCase for one of docx / pptx / xlsx."""+ office_dir = skill_root / "scripts" / "office"++ def load_helpers():+ # `office/` puts `helpers` and `validators` at the top level -- see the+ # `from helpers import ...` in validate.py -- so office/ itself goes on+ # the path. Safe because this repo runs one skill per process.+ if str(office_dir) not in sys.path:+ sys.path.insert(0, str(office_dir))+ return importlib.import_module("helpers")++ class OfficeSharedTreeTests(unittest.TestCase):+ maxDiff = None++ def setUp(self) -> None:+ self.helpers = load_helpers()++ # -- safe_extract ------------------------------------------------++ def test_safe_extract_unpacks_an_ordinary_package(self) -> None:+ with tempfile.TemporaryDirectory() as directory:+ root = Path(directory)+ archive = root / "package.docx"+ with zipfile.ZipFile(archive, "w") as handle:+ handle.writestr("[Content_Types].xml", "<Types/>")+ handle.writestr("word/document.xml", "<document/>")++ destination = root / "unpacked"+ destination.mkdir()+ with zipfile.ZipFile(archive) as handle:+ self.helpers.safe_extract(handle, destination)++ self.assertTrue((destination / "[Content_Types].xml").is_file())+ self.assertEqual(+ (destination / "word" / "document.xml").read_text(), "<document/>"+ )++ def test_safe_extract_refuses_a_traversal_entry(self) -> None:+ with tempfile.TemporaryDirectory() as directory:+ root = Path(directory)+ archive = root / "evil.docx"+ with zipfile.ZipFile(archive, "w") as handle:+ handle.writestr("../escaped.xml", "<pwned/>")++ destination = root / "unpacked"+ destination.mkdir()+ with zipfile.ZipFile(archive) as handle:+ with self.assertRaisesRegex(ValueError, "unsafe archive entry"):+ self.helpers.safe_extract(handle, destination)+ self.assertFalse((root / "escaped.xml").exists())++ def test_safe_extract_refuses_a_symlink_entry(self) -> None:+ with tempfile.TemporaryDirectory() as directory:+ root = Path(directory)+ archive = root / "link.docx"+ info = zipfile.ZipInfo("word/document.xml")+ info.external_attr = (stat.S_IFLNK | 0o777) << 16+ with zipfile.ZipFile(archive, "w") as handle:+ handle.writestr(info, "/etc/passwd")++ destination = root / "unpacked"+ destination.mkdir()+ with zipfile.ZipFile(archive) as handle:+ with self.assertRaisesRegex(ValueError, "symlink archive entry"):+ self.helpers.safe_extract(handle, destination)++ # -- opc_target --------------------------------------------------++ def test_opc_target_resolves_relative_and_absolute_part_names(self) -> None:+ resolve = self.helpers.opc_target+ self.assertEqual(+ resolve("media/image1.png", "word/document.xml"),+ "word/media/image1.png",+ )+ self.assertEqual(+ resolve("/word/styles.xml", "word/document.xml"), "word/styles.xml"+ )+ self.assertEqual(+ resolve("../customXml/item1.xml", "word/document.xml"),+ "customXml/item1.xml",+ )+ # Percent-encoding is decoded before resolution.+ self.assertEqual(+ resolve("media/my%20image.png", "word/document.xml"),+ "word/media/my image.png",+ )++ def test_opc_target_ignores_external_and_scheme_targets(self) -> None:+ resolve = self.helpers.opc_target+ self.assertIsNone(resolve("", "word/document.xml"))+ self.assertIsNone(+ resolve("https://example.invalid/x", "word/document.xml", "External")+ )+ self.assertIsNone(resolve("mailto:[email protected]", "word/document.xml"))++ def test_opc_target_refuses_targets_that_escape_the_package(self) -> None:+ resolve = self.helpers.opc_target+ with self.assertRaisesRegex(ValueError, "escapes the package"):+ resolve("../../outside.xml", "word/document.xml")+ with self.assertRaisesRegex(ValueError, "not a POSIX part name"):+ resolve("word\\styles.xml", "word/document.xml")+ # A bare "/" is absolute and strips to nothing at all.+ with self.assertRaisesRegex(ValueError, "resolves to nothing"):+ resolve("/", "word/document.xml")++ def test_a_dot_target_resolves_to_its_own_directory(self) -> None:+ # normpath collapses it rather than treating it as an error.+ self.assertEqual(+ self.helpers.opc_target(".", "word/document.xml"), "word"+ )++ # -- text rendering ----------------------------------------------++ def test_rendered_text_honours_xml_space_preserve(self) -> None:+ render = self.helpers.rendered_text+ self.assertEqual(render(" spaced ", True), " spaced ")+ self.assertEqual(render(" spaced ", False), "spaced")+ self.assertEqual(render("\t\nmixed\r\n", False), "mixed")++ def test_part_text_survives_undecodable_bytes(self) -> None:+ # surrogateescape, not a crash: a corrupt part must still be+ # reportable rather than taking the whole validation run down.+ self.assertEqual(self.helpers.part_text(b"ok"), "ok")+ self.assertEqual(len(self.helpers.part_text(b"\xff\xfe")), 2)++ # -- rezip -------------------------------------------------------++ def test_rezip_stores_content_types_first_and_uncompressed(self) -> None:+ with tempfile.TemporaryDirectory() as directory:+ root = Path(directory)+ source = root / "unpacked"+ (source / "word").mkdir(parents=True)+ (source / "[Content_Types].xml").write_text("<Types/>")+ (source / "word" / "document.xml").write_text("<document/>")++ output = root / "rebuilt.docx"+ self.helpers.rezip(source, output)++ with zipfile.ZipFile(output) as handle:+ entries = handle.namelist()+ # OOXML readers require [Content_Types].xml first and stored.+ self.assertEqual(entries[0], "[Content_Types].xml")+ self.assertEqual(+ handle.getinfo("[Content_Types].xml").compress_type,+ zipfile.ZIP_STORED,+ )+ self.assertIn("word/document.xml", entries)++ def test_rezip_leaves_no_temporary_file_behind(self) -> None:+ with tempfile.TemporaryDirectory() as directory:+ root = Path(directory)+ source = root / "unpacked"+ source.mkdir()+ (source / "part.xml").write_text("<part/>")++ output = root / "rebuilt.docx"+ self.helpers.rezip(source, output)+ self.assertEqual(+ sorted(path.name for path in root.iterdir()),+ ["rebuilt.docx", "unpacked"],+ )++ # -- packaging ---------------------------------------------------++ def test_ooxml_family_covers_this_skill(self) -> None:+ families = set(self.helpers.OOXML_FAMILY.values())+ self.assertEqual(families, {"docx", "pptx", "xlsx"})+ self.assertIn(f".{skill_root.name}", self.helpers.OOXML_FAMILY)++ def test_every_validator_schema_path_exists(self) -> None:+ schemas = office_dir / "schemas"+ self.assertTrue(schemas.is_dir(), "vendored schemas are missing")+ referenced = set()+ for module in sorted((office_dir / "validators").glob("*.py")):+ for line in module.read_text(encoding="utf-8").splitlines():+ for token in line.split('"'):+ if token.endswith(".xsd"):+ referenced.add(token.lstrip("/"))+ missing = sorted(+ name+ for name in referenced+ if not any(schemas.rglob(Path(name).name))+ )+ self.assertEqual(missing, [], "validators name schemas that are not shipped")++ OfficeSharedTreeTests.__qualname__ = f"OfficeSharedTreeTests[{skill_root.name}]"+ return OfficeSharedTreeTestsdiff --git a/tests/_contract/schematic.py b/tests/_contract/schematic.pynew file mode 100644index 00000000..55b9e8cf--- /dev/null+++ b/tests/_contract/schematic.py@@ -0,0 +1,102 @@+"""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 SchematicContractTestsdiff --git a/tests/_contract/structure.py b/tests/_contract/structure.pynew file mode 100644index 00000000..ebbc8116--- /dev/null+++ b/tests/_contract/structure.py@@ -0,0 +1,432 @@+"""The structural contract every skill in this repository must satisfy.++Nothing here imports skill code. Scripts are read and parsed with `ast`, never+executed, so the whole contract is safe to run against every skill inside a+single interpreter -- which is what `tests/_meta` does. Per-skill suites that+*do* import their scripts still need one process each; see `tests/conftest.py`.++Every check takes a skill directory and returns a list of human-readable+problems, empty when the skill conforms. Returning problems rather than+asserting keeps the checks reusable: `tests/_meta` reports them per rule and+per skill, so one broken link names the file and the line rather than failing+an opaque assertion.+"""++from __future__ import annotations++import ast+import re+import subprocess+import sys+from collections.abc import Callable, Iterable+from functools import lru_cache+from pathlib import Path++REPO_ROOT = Path(__file__).resolve().parents[2]+SKILLS_DIR = REPO_ROOT / "skills"++# The Agent Skills specification defines a closed set of top-level keys. Any+# other key is a validation error, and because strictyaml rejects the whole+# document, it takes `name` and `description` down with it.+ALLOWED_FRONTMATTER_FIELDS = frozenset(+ {"name", "description", "license", "compatibility", "allowed-tools", "metadata"}+)++MAX_SKILL_MD_LINES = 500++# `__import__` is deliberately absent: several skills use it for a legitimate+# availability probe (`try: __import__("torch")`) or to reach pathlib before+# the sys.path insert that makes `_common` importable.+BANNED_BUILTIN_CALLS = frozenset({"eval", "exec"})+BANNED_OS_CALLS = frozenset({"system", "popen"})++# Inline-code and markdown-link references to files the skill ships.+_INLINE_PATH = re.compile(r"`((?:assets|references|scripts)/[A-Za-z0-9_./-]+)`")+_MARKDOWN_LINK = re.compile(r"\]\(((?:assets|references|scripts)/[A-Za-z0-9_./-]+)\)")++# An absolute path under someone's home or drive mount is a leaked local+# environment: it names a person, and it cannot work on any other machine.+_PERSONAL_PATH = re.compile(+ r"/(?:mnt/[a-z]/Users|home|Users)/(?!<|\$|\{)([A-Za-z0-9._-]+)/"+)++# Service and platform accounts that legitimately appear in documentation --+# `/home/dnanexus/` is where a DNAnexus worker runs, not somebody's laptop --+# plus the placeholder spellings skills use for "your username".+_IMPERSONAL_ACCOUNTS = frozenset(+ {+ "dnanexus", "ubuntu", "root", "runner", "ec2-user", "jovyan", "vscode",+ "airflow", "nextflow", "opt", "shared", "linuxbrew",+ "user", "username", "you", "me", "youruser", "your-user", "name",+ }+)+++def script_bearing_skills(skills_dir: Path = SKILLS_DIR) -> list[Path]:+ """Skill directories that ship at least one file under `scripts/`.++ An empty `scripts/` directory does not count. Git cannot track empty+ directories, so one only ever exists as local cruft, and requiring a test+ suite for a skill that ships no scripts would be nonsense.+ """+ return [+ skill+ for skill in sorted(skills_dir.iterdir())+ if skill.is_dir()+ and (skill / "SKILL.md").is_file()+ and any((skill / "scripts").rglob("*"))+ ]+++def all_skill_names(skills_dir: Path = SKILLS_DIR) -> set[str]:+ return {+ skill.name+ for skill in skills_dir.iterdir()+ if skill.is_dir() and (skill / "SKILL.md").is_file()+ }+++def _frontmatter(skill: Path) -> str | None:+ """The raw YAML between the opening and closing `---`, or None."""+ text = (skill / "SKILL.md").read_text(encoding="utf-8")+ if not text.startswith("---\n"):+ return None+ end = text.find("\n---", 3)+ if end == -1:+ return None+ return text[4:end]+++def _top_level_entries(frontmatter: str) -> list[tuple[str, str]]:+ """(key, value) for every unindented `key: value` line."""+ entries = []+ for line in frontmatter.splitlines():+ match = re.match(r"^([A-Za-z][A-Za-z0-9_-]*):(.*)$", line)+ if match:+ entries.append((match.group(1), match.group(2).strip()))+ return entries+++def _metadata_scalars(frontmatter: str) -> list[tuple[str, str]]:+ """(key, value) for scalars nested one level under `metadata:`.++ Host manifest blocks (`openclaw`, `hermes`) nest further; their contents+ are deliberately skipped -- the spec exempts them from the string-only+ rule, and they carry booleans on purpose.+ """+ lines = frontmatter.splitlines()+ try:+ start = next(i for i, line in enumerate(lines) if line.startswith("metadata:"))+ except StopIteration:+ return []+ scalars = []+ for line in lines[start + 1 :]:+ if line.strip() and not line.startswith((" ", "\t")):+ break+ match = re.match(r"^ ([A-Za-z][A-Za-z0-9_-]*):(.*)$", line)+ if match and match.group(2).strip():+ scalars.append((match.group(1), match.group(2).strip()))+ return scalars+++def frontmatter_problems(skill: Path) -> list[str]:+ """Frontmatter parses, uses only spec fields, and is versioned."""+ problems: list[str] = []+ if not (skill / "SKILL.md").is_file():+ return [f"{skill.name}: no SKILL.md"]++ frontmatter = _frontmatter(skill)+ if frontmatter is None:+ return [f"{skill.name}: SKILL.md has no `---` delimited frontmatter"]++ entries = _top_level_entries(frontmatter)+ keys = [key for key, _ in entries]++ for key in keys:+ if key not in ALLOWED_FRONTMATTER_FIELDS:+ problems.append(+ f"{skill.name}: top-level `{key}` is not one of the six spec fields "+ "-- move it under `metadata`"+ )+ for required in ("name", "description", "metadata"):+ if required not in keys:+ problems.append(f"{skill.name}: frontmatter is missing `{required}`")++ values = dict(entries)+ name = values.get("name", "").strip("\"'")+ if name and name != skill.name:+ problems.append(+ f"{skill.name}: frontmatter name is `{name}`, must equal the directory name"+ )++ # strictyaml rejects JSON flow style outright, taking the whole document+ # with it -- so `name` and `description` become unreadable too.+ for key, value in entries:+ if value.startswith(("{", "[")):+ problems.append(+ f"{skill.name}: `{key}` uses JSON flow style; strictyaml rejects it"+ )++ tools = values.get("allowed-tools")+ if tools is not None and ("," in tools or tools.startswith("[")):+ problems.append(+ f"{skill.name}: `allowed-tools` must be a space-separated string"+ )++ scalars = dict(_metadata_scalars(frontmatter))+ if "version" not in scalars:+ problems.append(f"{skill.name}: `metadata.version` is required")+ for key, value in scalars.items():+ # Only values YAML would actually coerce. `1.0.0` has two dots, so it+ # is already a string; `1.0` is a float and must be quoted.+ ambiguous = re.fullmatch(+ r"\d+|\d+\.\d+|true|false|yes|no|on|off|\d{4}-\d{2}-\d{2}", value, re.I+ )+ if ambiguous:+ problems.append(+ f"{skill.name}: `metadata.{key}: {value}` must be quoted to stay a string"+ )+ return problems+++def length_problems(skill: Path) -> list[str]:+ """SKILL.md stays under 500 lines; longer material belongs in references/."""+ lines = len((skill / "SKILL.md").read_text(encoding="utf-8").splitlines())+ if lines > MAX_SKILL_MD_LINES:+ return [+ f"{skill.name}: SKILL.md is {lines} lines, over the {MAX_SKILL_MD_LINES}-line "+ "limit -- move reference material into references/"+ ]+ return []+++def stray_test_problems(skill: Path) -> list[str]:+ """Tests never live under skills/ -- a skill ships only what an agent loads."""+ strays = [+ str(path.relative_to(skill))+ for path in sorted(skill.rglob("*"))+ if (path.is_dir() and path.name == "tests")+ or (path.is_file() and path.name.startswith("test_") and path.suffix == ".py")+ ]+ return [+ f"{skill.name}: ships {stray}; tests belong in tests/{skill.name}/"+ for stray in strays+ ]+++@lru_cache(maxsize=1)+def _tracked_files(skills_dir: Path = SKILLS_DIR) -> frozenset[str] | None:+ """Repo-relative paths git tracks under `skills/`, or None outside a checkout."""+ try:+ listed = subprocess.run(+ ["git", "ls-files", "--", str(skills_dir)],+ capture_output=True,+ text=True,+ timeout=60,+ cwd=REPO_ROOT,+ )+ except (OSError, subprocess.SubprocessError):+ return None+ if listed.returncode != 0:+ return None+ return frozenset(listed.stdout.split())+++def bytecode_problems(skill: Path) -> list[str]:+ """No compiled bytecode ships with a skill.++ "Ships" means committed. Importing a skill's scripts is what creates+ `__pycache__`, and running one by hand outside pytest -- which sets+ `PYTHONDONTWRITEBYTECODE` -- leaves some behind, so scanning the working+ tree would fail on local cruft that is already gitignored. Fall back to a+ filesystem scan only when git cannot answer.+ """+ tracked = _tracked_files()+ candidates = [+ path+ for path in sorted(skill.rglob("*"))+ if path.suffix in {".pyc", ".pyo"} or path.name == "__pycache__"+ ]+ if tracked is not None:+ candidates = [+ path+ for path in candidates+ if str(path.relative_to(REPO_ROOT)) in tracked+ or any(entry.startswith(f"{path.relative_to(REPO_ROOT)}/") for entry in tracked)+ ]+ return [+ f"{skill.name}: ships bytecode artifact {path.relative_to(skill)}"+ for path in candidates+ ]+++def link_problems(skill: Path, known_skills: Iterable[str] | None = None) -> list[str]:+ """Every `assets/`, `references/`, or `scripts/` path in the docs resolves.++ Skills routinely point at each other -- bulk-rnaseq documents+ `pathway-enrichment`'s `scripts/run_enrichment.py`, citation-management+ points at `pyzotero` -> `references/exports.md`. A path that does not+ resolve inside this skill is therefore accepted when another skill is+ named on the same line and owns it.+ """+ names = set(known_skills) if known_skills is not None else all_skill_names()+ documents = [skill / "SKILL.md", *sorted((skill / "references").glob("*.md"))]++ problems = []+ for document in documents:+ if not document.is_file():+ continue+ for number, line in enumerate(document.read_text(encoding="utf-8").splitlines(), 1):+ for relative in set(_INLINE_PATH.findall(line)) | set(+ _MARKDOWN_LINK.findall(line)+ ):+ if (skill / relative).exists():+ continue+ owners = [+ other+ for other in names+ if other != skill.name+ and other in line+ and (SKILLS_DIR / other / relative).exists()+ ]+ if owners:+ continue+ problems.append(+ f"{skill.name}: {document.name}:{number} references "+ f"`{relative}`, which does not exist"+ )+ return problems+++def _script_paths(skill: Path, suffix: str = ".py") -> list[Path]:+ return sorted((skill / "scripts").rglob(f"*{suffix}"))+++def compile_problems(skill: Path) -> list[str]:+ """Every bundled Python script parses -- a syntax error can never ship."""+ problems = []+ for path in _script_paths(skill):+ try:+ ast.parse(path.read_text(encoding="utf-8"), filename=str(path))+ except SyntaxError as error:+ problems.append(+ f"{skill.name}: {path.relative_to(skill)} does not parse: "+ f"line {error.lineno}: {error.msg}"+ )+ return problems+++def dynamic_execution_problems(skill: Path) -> list[str]:+ """No `eval`, `exec`, `os.system`, or `os.popen` in bundled scripts.++ A narrower rule than the Cisco scanner's, and a complementary one: this is+ deterministic and runs on every skill every time, where the scanner is+ LLM-backed and runs only on changed skills.+ """+ problems = []+ for path in _script_paths(skill):+ try:+ tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path))+ except SyntaxError:+ continue # compile_problems already reports it+ for node in ast.walk(tree):+ if not isinstance(node, ast.Call):+ continue+ function = node.func+ if isinstance(function, ast.Name) and function.id in BANNED_BUILTIN_CALLS:+ problems.append(+ f"{skill.name}: {path.relative_to(skill)}:{node.lineno} "+ f"calls {function.id}()"+ )+ if (+ isinstance(function, ast.Attribute)+ and function.attr in BANNED_OS_CALLS+ and isinstance(function.value, ast.Name)+ and function.value.id == "os"+ ):+ problems.append(+ f"{skill.name}: {path.relative_to(skill)}:{node.lineno} "+ f"calls os.{function.attr}()"+ )+ return problems+++def shadow_module_problems(skill: Path) -> list[str]:+ """No script shadows a standard-library module.++ Tests and the scripts themselves put `scripts/` on `sys.path`, so a file+ named `json.py` or `csv.py` there wins over the real module for the rest+ of the process.+ """+ return [+ f"{skill.name}: scripts/{path.name} shadows the standard-library module "+ f"`{path.stem}`"+ for path in sorted((skill / "scripts").glob("*.py"))+ if path.stem in sys.stdlib_module_names+ ]+++def personal_path_problems(skill: Path) -> list[str]:+ """No script or document hardcodes somebody's home directory.++ A path like `/mnt/c/Users/<name>/Data/kg.csv` names a real person and works+ on exactly one machine. Placeholders are fine -- `/home/$USER/`,+ `/Users/<you>/` -- so the pattern skips anything that looks templated.+ """+ documents = [+ skill / "SKILL.md",+ *sorted((skill / "references").glob("*.md")),+ *_script_paths(skill),+ *_script_paths(skill, ".sh"),+ ]+ problems = []+ for document in documents:+ if not document.is_file():+ continue+ for number, line in enumerate(+ document.read_text(encoding="utf-8", errors="replace").splitlines(), 1+ ):+ for match in _PERSONAL_PATH.finditer(line):+ if match.group(1).lower() in _IMPERSONAL_ACCOUNTS:+ continue+ problems.append(+ f"{skill.name}: {document.relative_to(skill)}:{number} hardcodes "+ f"the local path `{match.group(0)}`"+ )+ return problems+++def shell_script_problems(skill: Path) -> list[str]:+ """Bundled shell scripts have a shebang, the executable bit, and parse."""+ problems = []+ for path in _script_paths(skill, ".sh"):+ relative = path.relative_to(skill)+ first_line = path.read_text(encoding="utf-8").splitlines()[:1]+ if not first_line or not first_line[0].startswith("#!"):+ problems.append(f"{skill.name}: {relative} has no shebang")+ if not path.stat().st_mode & 0o111:+ problems.append(f"{skill.name}: {relative} is not executable")+ syntax = subprocess.run(+ ["bash", "-n", str(path)], capture_output=True, text=True, timeout=30+ )+ if syntax.returncode != 0:+ problems.append(+ f"{skill.name}: {relative} fails `bash -n`: {syntax.stderr.strip()}"+ )+ return problems+++#: Rule name -> check. `tests/_meta` iterates this so a new rule is picked up+#: repo-wide by adding one entry.+CHECKS: dict[str, Callable[[Path], list[str]]] = {+ "frontmatter": frontmatter_problems,+ "skill_md_length": length_problems,+ "no_tests_under_skills": stray_test_problems,+ "no_bytecode": bytecode_problems,+ "local_links_resolve": link_problems,+ "scripts_compile": compile_problems,+ "no_dynamic_execution": dynamic_execution_problems,+ "no_stdlib_shadowing": shadow_module_problems,+ "no_personal_paths": personal_path_problems,+ "shell_scripts": shell_script_problems,+}diff --git a/tests/_meta/test_repo_contract.py b/tests/_meta/test_repo_contract.pynew file mode 100644index 00000000..367efb87--- /dev/null+++ b/tests/_meta/test_repo_contract.py@@ -0,0 +1,126 @@+"""Repo-wide guards: every skill conforms, and every skill with scripts is tested.++This suite is deliberately not per-skill. It imports no skill code -- the+structural contract parses scripts with `ast` and never executes them -- so+running it across all skills in one interpreter is safe, and it is the only+place that can see the whole repository at once. That is what lets it enforce+the rule `AGENTS.md` states but nothing previously checked:++ If the skill ships `scripts/`, put their tests in `tests/<name>/`.++It runs in the project environment and needs no scientific packages, so CI can+run it on every pull request in seconds.+"""++from __future__ import annotations++import tomllib+import unittest+from pathlib import Path++import skill_contract++REPO_ROOT = Path(__file__).resolve().parents[2]+SKILLS_DIR = REPO_ROOT / "skills"+TESTS_DIR = REPO_ROOT / "tests"+REQUIREMENTS = TESTS_DIR / "skill-requirements.toml"++structure = skill_contract.structure+office = skill_contract.office++SCRIPT_BEARING = structure.script_bearing_skills(SKILLS_DIR)+KNOWN_SKILLS = structure.all_skill_names(SKILLS_DIR)+++def _suite_names() -> set[str]:+ """Test directories that stand for a skill, excluding infrastructure."""+ return {+ path.name+ for path in TESTS_DIR.iterdir()+ if path.is_dir() and not path.name.startswith((".", "_"))+ }+++class CoverageTests(unittest.TestCase):+ """The rule this whole suite exists to enforce."""++ maxDiff = None++ def test_every_skill_with_scripts_has_a_test_suite(self) -> None:+ suites = _suite_names()+ untested = sorted(+ skill.name for skill in SCRIPT_BEARING if skill.name not in suites+ )+ self.assertEqual(+ untested,+ [],+ "these skills ship scripts/ but have no tests/<name>/ suite; add one "+ "(see AGENTS.md, 'Creating a skill' step 5)",+ )++ def test_every_suite_has_a_test_file(self) -> None:+ empty = sorted(+ name+ for name in _suite_names()+ if not any((TESTS_DIR / name).glob("test_*.py"))+ )+ self.assertEqual(empty, [], "test directories with no test_*.py")++ def test_no_test_suite_is_orphaned(self) -> None:+ orphans = sorted(name for name in _suite_names() if name not in KNOWN_SKILLS)+ self.assertEqual(+ orphans, [], "test directories that do not name a skill under skills/"+ )++ def test_every_skill_with_scripts_has_a_requirements_entry(self) -> None:+ """`--isolated` needs a `[skills.<name>]` entry or it cannot build the env."""+ manifest = tomllib.loads(REQUIREMENTS.read_text(encoding="utf-8"))+ entries = manifest.get("skills", {})+ missing = sorted(+ skill.name for skill in SCRIPT_BEARING if skill.name not in entries+ )+ self.assertEqual(+ missing,+ [],+ f"add a [skills.<name>] block to {REQUIREMENTS.name} "+ "(packages = [] for standard-library-only skills)",+ )++ def test_requirements_entries_name_real_skills(self) -> None:+ manifest = tomllib.loads(REQUIREMENTS.read_text(encoding="utf-8"))+ unknown = sorted(set(manifest.get("skills", {})) - KNOWN_SKILLS)+ self.assertEqual(unknown, [], f"stale entries in {REQUIREMENTS.name}")+++class StructuralContractTests(unittest.TestCase):+ """Every rule in `skill_contract.structure`, against every script-bearing skill."""++ maxDiff = None++ def test_all_skills_satisfy_every_structural_rule(self) -> None:+ self.assertTrue(SCRIPT_BEARING, "no skills found -- the anchor is wrong")+ for rule, check in structure.CHECKS.items():+ for skill in SCRIPT_BEARING:+ with self.subTest(rule=rule, skill=skill.name):+ problems = (+ check(skill, KNOWN_SKILLS)+ if rule == "local_links_resolve"+ else check(skill)+ )+ self.assertEqual(problems, [])+++class SharedCopyTests(unittest.TestCase):+ """Files several skills ship identical copies of must not drift apart."""++ maxDiff = None++ def test_docx_pptx_xlsx_ship_the_same_office_tree(self) -> None:+ self.assertEqual(office.identical_tree_problems(SKILLS_DIR), [])++ def test_shared_scripts_are_identical_across_their_skills(self) -> None:+ self.assertEqual(office.shared_file_problems(SKILLS_DIR), [])+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/analytical-method-validation/test_scripts.py b/tests/analytical-method-validation/test_scripts.pyindex e8ccdf3b..262f8ae9 100644--- a/tests/analytical-method-validation/test_scripts.py+++ b/tests/analytical-method-validation/test_scripts.py@@ -17,6 +17,8 @@ import sysimport unittestfrom pathlib import Path+import skill_contract+SKILL_ROOT = Path(__file__).resolve().parents[2] / "skills" / "analytical-method-validation"SCRIPTS_DIR = SKILL_ROOT / "scripts"FIXTURES = Path(__file__).resolve().parent / "fixtures"@@ -58,7 +60,7 @@ class TestSkillStructure(unittest.TestCase):end = text.index("\n---\n", 4)front = text[4:end]self.assertIn("name: analytical-method-validation", front)- self.assertIn('version: "1.0"', front)+ self.assertRegex(front, r'\n version: "\d+\.\d+"\n')# allowed-tools must be a space-separated string, not a YAML listfor line in front.splitlines():if line.startswith("allowed-tools:"):@@ -945,5 +947,10 @@ class TestInputHandling(unittest.TestCase):self.assertIn("note:", res.stderr)+# 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(SKILL_ROOT)+if __name__ == "__main__":unittest.main()diff --git a/tests/arbor/test_scripts.py b/tests/arbor/test_scripts.pynew file mode 100644index 00000000..5334c01c--- /dev/null+++ b/tests/arbor/test_scripts.py@@ -0,0 +1,461 @@+"""Tests for the Arbor hypothesis-tree state manager.++`tree.py` is the durable state of an Autonomous Optimization run, so the tests+drive it the way a coordinator does -- through the parser, one subcommand at a+time, against a real `.arbor/` directory in a temporary run dir -- and assert+on the JSON that lands on disk. Testing the persisted state rather than return+values is deliberate: the script's contract *is* the file it writes, and a+coordinator resuming a run reads nothing else.++The behaviours worth pinning are the ones a corrupted run would hinge on: the+merge gate honouring `metric_direction`, pruning stopping at merged nodes, and+`validate` catching an inconsistent tree.+"""++from __future__ import annotations++import io+import json+import sys+import tempfile+import unittest+from contextlib import redirect_stdout, redirect_stderr+from pathlib import Path++import skill_contract++SKILL_ROOT = Path(__file__).resolve().parents[2] / "skills" / "arbor"+SCRIPTS = SKILL_ROOT / "scripts"+sys.path.insert(0, str(SCRIPTS))++import tree as arbor_tree # noqa: E402++CliHelpTests = skill_contract.cli.help_test_case(SKILL_ROOT)+++class ArborRunTestCase(unittest.TestCase):+ """A temporary run directory plus helpers for driving the CLI."""++ def setUp(self) -> None:+ self._temporary = tempfile.TemporaryDirectory()+ self.addCleanup(self._temporary.cleanup)+ self.run_dir = Path(self._temporary.name)+ self.parser = arbor_tree.build_parser()++ def run_command(self, *argv: str) -> tuple[str, str]:+ """Invoke one subcommand; return its (stdout, stderr)."""+ args = self.parser.parse_args(["--run-dir", str(self.run_dir), *argv])+ out, err = io.StringIO(), io.StringIO()+ with redirect_stdout(out), redirect_stderr(err):+ args.func(args)+ return out.getvalue(), err.getvalue()++ def init(self, **overrides: str) -> None:+ argv = [+ "init",+ "--objective", overrides.get("objective", "Improve F1 on the dev split"),+ "--dev-eval", "python eval.py --split dev",+ "--test-eval", "python eval.py --split test",+ ]+ for flag in ("metric-direction", "max-depth", "budget", "branching"):+ if flag.replace("-", "_") in overrides:+ argv += [f"--{flag}", str(overrides[flag.replace('-', '_')])]+ self.run_command(*argv)++ @property+ def tree(self) -> dict:+ return json.loads((self.run_dir / ".arbor" / "tree.json").read_text())++ @property+ def run_config(self) -> dict:+ return json.loads((self.run_dir / ".arbor" / "run.json").read_text())+++class InitTests(ArborRunTestCase):+ def test_init_creates_both_state_files_with_a_root_node(self) -> None:+ self.init()+ self.assertTrue((self.run_dir / ".arbor" / "tree.json").is_file())+ self.assertTrue((self.run_dir / ".arbor" / "run.json").is_file())++ tree = self.tree+ self.assertEqual(tree["root"], "n0")+ root = tree["nodes"]["n0"]+ self.assertEqual(root["status"], "root")+ self.assertIsNone(root["parent"])+ self.assertEqual(root["depth"], 0)+ self.assertEqual(root["hypothesis"], "Improve F1 on the dev split")++ def test_run_config_records_the_budget_and_starts_unspent(self) -> None:+ self.init(budget=7, max_depth=3, branching=5)+ run = self.run_config+ self.assertEqual(run["budget_cycles"], 7)+ self.assertEqual(run["max_depth"], 3)+ self.assertEqual(run["branching"], 5)+ self.assertEqual(run["cycles_used"], 0)+ self.assertIsNone(run["best_node"])+ self.assertIsNone(run["best_test_score"])++ def test_init_refuses_to_erase_an_existing_run(self) -> None:+ self.init()+ with self.assertRaises(SystemExit) as raised:+ self.init()+ self.assertIn("--force", str(raised.exception))++ def test_force_overwrites_and_resets_the_counter(self) -> None:+ self.init()+ self.run_command("add-node", "--parent", "n0", "--hypothesis", "h")+ self.assertEqual(len(self.tree["nodes"]), 2)++ args = self.parser.parse_args(+ [+ "--run-dir", str(self.run_dir),+ "init",+ "--objective", "A fresh objective",+ "--dev-eval", "d",+ "--test-eval", "t",+ "--force",+ ]+ )+ with redirect_stdout(io.StringIO()):+ args.func(args)+ self.assertEqual(list(self.tree["nodes"]), ["n0"])+ self.assertEqual(self.tree["_counter"], 0)++ def test_commands_before_init_explain_how_to_start(self) -> None:+ with self.assertRaises(SystemExit) as raised:+ self.run_command("observe")+ self.assertIn("tree.py init", str(raised.exception))+++class NodeTests(ArborRunTestCase):+ def setUp(self) -> None:+ super().setUp()+ self.init(max_depth=2)++ def test_ids_are_sequential_and_depth_is_derived_from_the_parent(self) -> None:+ self.run_command("add-node", "--parent", "n0", "--hypothesis", "direction A")+ self.run_command("add-node", "--parent", "n0", "--hypothesis", "direction B")+ self.run_command("add-node", "--parent", "n1", "--hypothesis", "intervention A1")++ nodes = self.tree["nodes"]+ self.assertEqual(sorted(nodes), ["n0", "n1", "n2", "n3"])+ self.assertEqual(nodes["n1"]["depth"], 1)+ self.assertEqual(nodes["n2"]["depth"], 1)+ self.assertEqual(nodes["n3"]["depth"], 2)+ self.assertEqual(nodes["n3"]["parent"], "n1")++ def test_new_nodes_start_pending_with_empty_evidence(self) -> None:+ self.run_command("add-node", "--parent", "n0", "--hypothesis", "h")+ node = self.tree["nodes"]["n1"]+ self.assertEqual(node["status"], "pending")+ self.assertEqual(node["insight"], "")+ self.assertIsNone(node["metadata"]["dev_score"])+ self.assertIsNone(node["metadata"]["branch_ref"])++ def test_depth_one_is_a_direction_and_deeper_is_an_intervention(self) -> None:+ out, _ = self.run_command("add-node", "--parent", "n0", "--hypothesis", "h")+ self.assertIn("direction node n1", out)+ out, _ = self.run_command("add-node", "--parent", "n1", "--hypothesis", "h")+ self.assertIn("intervention node n2", out)++ def test_exceeding_max_depth_warns_but_still_records(self) -> None:+ self.run_command("add-node", "--parent", "n0", "--hypothesis", "h")+ self.run_command("add-node", "--parent", "n1", "--hypothesis", "h")+ _, err = self.run_command("add-node", "--parent", "n2", "--hypothesis", "too deep")+ self.assertIn("exceeds max_depth", err)+ self.assertIn("n3", self.tree["nodes"])++ def test_an_unknown_parent_is_refused_with_a_pointer_to_status(self) -> None:+ with self.assertRaises(SystemExit) as raised:+ self.run_command("add-node", "--parent", "n99", "--hypothesis", "h")+ self.assertIn("tree.py status", str(raised.exception))++ def test_status_must_come_from_the_documented_set(self) -> None:+ self.run_command("add-node", "--parent", "n0", "--hypothesis", "h")+ self.run_command("set-status", "--node", "n1", "--status", "running")+ self.assertEqual(self.tree["nodes"]["n1"]["status"], "running")++ with self.assertRaises(SystemExit):+ self.run_command("set-status", "--node", "n1", "--status", "abandoned")+ self.assertEqual(self.tree["nodes"]["n1"]["status"], "running")+++class EvidenceTests(ArborRunTestCase):+ def setUp(self) -> None:+ super().setUp()+ self.init()+ self.run_command("add-node", "--parent", "n0", "--hypothesis", "direction")+ self.run_command("add-node", "--parent", "n1", "--hypothesis", "intervention")++ def test_evidence_defaults_the_status_to_executed(self) -> None:+ self.run_command(+ "set-evidence", "--node", "n2", "--dev-score", "0.81", "--result", "ran clean"+ )+ node = self.tree["nodes"]["n2"]+ self.assertEqual(node["status"], "executed")+ self.assertEqual(node["metadata"]["dev_score"], 0.81)+ self.assertEqual(node["metadata"]["result"], "ran clean")++ def test_an_explicit_status_overrides_the_default(self) -> None:+ self.run_command(+ "set-evidence", "--node", "n2", "--dev-score", "0.1", "--status", "pruned"+ )+ self.assertEqual(self.tree["nodes"]["n2"]["status"], "pruned")++ def test_a_partial_update_leaves_untouched_fields_alone(self) -> None:+ self.run_command(+ "set-evidence",+ "--node", "n2",+ "--dev-score", "0.5",+ "--result", "first pass",+ "--branch-ref", "wt/n2",+ )+ self.run_command("set-evidence", "--node", "n2", "--dev-score", "0.6")++ metadata = self.tree["nodes"]["n2"]["metadata"]+ self.assertEqual(metadata["dev_score"], 0.6)+ self.assertEqual(metadata["result"], "first pass")+ self.assertEqual(metadata["branch_ref"], "wt/n2")++ def test_a_leaf_with_ancestors_is_reminded_to_propagate(self) -> None:+ out, _ = self.run_command("set-evidence", "--node", "n2", "--insight", "lr matters")+ self.assertIn("tree.py propagate", out)+ self.assertIn("['n1', 'n0']", out)++ def test_a_zero_dev_score_is_recorded_rather_than_treated_as_absent(self) -> None:+ self.run_command("set-evidence", "--node", "n2", "--dev-score", "0")+ self.assertEqual(self.tree["nodes"]["n2"]["metadata"]["dev_score"], 0.0)+++class PropagateTests(ArborRunTestCase):+ def setUp(self) -> None:+ super().setUp()+ self.init()+ self.run_command("add-node", "--parent", "n0", "--hypothesis", "direction")+ self.run_command("add-node", "--parent", "n1", "--hypothesis", "intervention")++ def test_default_propagation_reaches_only_the_immediate_parent(self) -> None:+ self.run_command("propagate", "--node", "n2", "--insight", "small batches help")+ nodes = self.tree["nodes"]+ self.assertIn("[from n2] small batches help", nodes["n1"]["insight"])+ self.assertEqual(nodes["n0"]["insight"], "")++ def test_to_root_reaches_every_ancestor(self) -> None:+ self.run_command(+ "propagate", "--node", "n2", "--insight", "generalises", "--to-root"+ )+ nodes = self.tree["nodes"]+ self.assertIn("generalises", nodes["n1"]["insight"])+ self.assertIn("generalises", nodes["n0"]["insight"])++ def test_insights_accumulate_rather_than_overwrite(self) -> None:+ self.run_command("propagate", "--node", "n2", "--insight", "first lesson")+ self.run_command("propagate", "--node", "n2", "--insight", "second lesson")+ insight = self.tree["nodes"]["n1"]["insight"]+ self.assertIn("first lesson", insight)+ self.assertIn("second lesson", insight)+ self.assertEqual(len(insight.splitlines()), 2)++ def test_every_line_records_which_node_it_came_from(self) -> None:+ self.run_command("propagate", "--node", "n2", "--insight", "lesson")+ self.assertTrue(self.tree["nodes"]["n1"]["insight"].startswith("[from n2]"))++ def test_the_root_has_no_ancestors_to_propagate_to(self) -> None:+ with self.assertRaises(SystemExit) as raised:+ self.run_command("propagate", "--node", "n0", "--insight", "x")+ self.assertIn("no ancestors", str(raised.exception))+++class PruneTests(ArborRunTestCase):+ def setUp(self) -> None:+ super().setUp()+ self.init(max_depth=4)+ self.run_command("add-node", "--parent", "n0", "--hypothesis", "direction")+ self.run_command("add-node", "--parent", "n1", "--hypothesis", "child")+ self.run_command("add-node", "--parent", "n2", "--hypothesis", "grandchild")++ def test_pruning_takes_the_whole_subtree(self) -> None:+ self.run_command("prune", "--node", "n1", "--reason", "dead end")+ statuses = {nid: n["status"] for nid, n in self.tree["nodes"].items()}+ self.assertEqual(statuses["n1"], "pruned")+ self.assertEqual(statuses["n2"], "pruned")+ self.assertEqual(statuses["n3"], "pruned")+ self.assertEqual(statuses["n0"], "root")++ def test_the_reason_is_recorded_on_the_target_only(self) -> None:+ self.run_command("prune", "--node", "n1", "--reason", "falsified by n3")+ nodes = self.tree["nodes"]+ self.assertEqual(nodes["n1"]["metadata"]["prune_reason"], "falsified by n3")+ self.assertNotIn("prune_reason", nodes["n2"]["metadata"])++ def test_a_merged_node_survives_a_prune_of_its_ancestor(self) -> None:+ # A merged node is already in M_best; pruning its parent must not+ # retroactively mark the promoted work as a dead end.+ self.run_command("set-status", "--node", "n2", "--status", "merged")+ self.run_command("prune", "--node", "n1")+ statuses = {nid: n["status"] for nid, n in self.tree["nodes"].items()}+ self.assertEqual(statuses["n1"], "pruned")+ self.assertEqual(statuses["n2"], "merged")+ # The traversal stops at the merged node, so its child is untouched too.+ self.assertEqual(statuses["n3"], "pending")++ def test_pruning_the_root_is_a_no_op(self) -> None:+ self.run_command("prune", "--node", "n0")+ self.assertEqual(self.tree["nodes"]["n0"]["status"], "root")+++class MergeGateTests(ArborRunTestCase):+ def _prepare(self, direction: str = "max") -> None:+ self.init(metric_direction=direction)+ self.run_command("add-node", "--parent", "n0", "--hypothesis", "direction")+ self.run_command("add-node", "--parent", "n0", "--hypothesis", "rival")++ def test_the_first_candidate_always_passes(self) -> None:+ self._prepare()+ out, _ = self.run_command(+ "merge", "--node", "n1", "--test-score", "0.7", "--branch-ref", "wt/n1"+ )+ self.assertIn("MERGE GATE PASSED", out)+ self.assertEqual(self.run_config["best_node"], "n1")+ self.assertEqual(self.run_config["best_test_score"], 0.7)+ self.assertEqual(self.run_config["best_branch_ref"], "wt/n1")+ self.assertEqual(self.tree["nodes"]["n1"]["status"], "merged")++ def test_a_worse_candidate_is_rejected_and_leaves_m_best_alone(self) -> None:+ self._prepare()+ self.run_command("merge", "--node", "n1", "--test-score", "0.7")+ out, _ = self.run_command("merge", "--node", "n2", "--test-score", "0.6")++ self.assertIn("MERGE GATE REJECTED", out)+ self.assertEqual(self.run_config["best_node"], "n1")+ self.assertEqual(self.run_config["best_test_score"], 0.7)+ self.assertEqual(self.tree["nodes"]["n2"]["status"], "pending")+ # The test score is still recorded -- a rejection is evidence.+ self.assertEqual(self.tree["nodes"]["n2"]["metadata"]["test_score"], 0.6)++ def test_minimisation_runs_invert_the_comparison(self) -> None:+ self._prepare(direction="min")+ self.run_command("merge", "--node", "n1", "--test-score", "0.7")+ out, _ = self.run_command("merge", "--node", "n2", "--test-score", "0.6")+ self.assertIn("MERGE GATE PASSED", out)+ self.assertEqual(self.run_config["best_node"], "n2")+ self.assertEqual(self.run_config["best_test_score"], 0.6)++ def test_an_exact_tie_does_not_displace_the_incumbent(self) -> None:+ self._prepare()+ self.run_command("merge", "--node", "n1", "--test-score", "0.7")+ out, _ = self.run_command("merge", "--node", "n2", "--test-score", "0.7")+ self.assertIn("MERGE GATE REJECTED", out)+ self.assertEqual(self.run_config["best_node"], "n1")++ def test_the_node_branch_ref_is_used_when_none_is_supplied(self) -> None:+ self._prepare()+ self.run_command("set-evidence", "--node", "n1", "--branch-ref", "wt/from-evidence")+ self.run_command("merge", "--node", "n1", "--test-score", "0.7")+ self.assertEqual(self.run_config["best_branch_ref"], "wt/from-evidence")++ def test_a_negative_score_can_still_be_the_first_best(self) -> None:+ # `better()` special-cases only `old is None`, not falsiness.+ self._prepare()+ self.run_command("merge", "--node", "n1", "--test-score", "-3.5")+ self.assertEqual(self.run_config["best_test_score"], -3.5)+++class CycleTests(ArborRunTestCase):+ def test_cycles_count_up_and_report_the_remainder(self) -> None:+ self.init(budget=2)+ out, _ = self.run_command("cycle")+ self.assertIn("Cycle 1/2 (1 remaining)", out)+ out, _ = self.run_command("cycle")+ self.assertIn("Cycle 2/2 (0 remaining)", out)+ self.assertIn("Budget exhausted", out)+ self.assertEqual(self.run_config["cycles_used"], 2)++ def test_the_counter_keeps_going_past_the_budget(self) -> None:+ self.init(budget=1)+ self.run_command("cycle")+ out, _ = self.run_command("cycle")+ self.assertIn("Budget exhausted", out)+ self.assertEqual(self.run_config["cycles_used"], 2)+++class ValidateTests(ArborRunTestCase):+ def setUp(self) -> None:+ super().setUp()+ self.init()+ self.run_command("add-node", "--parent", "n0", "--hypothesis", "direction")++ def _write_tree(self, tree: dict) -> None:+ (self.run_dir / ".arbor" / "tree.json").write_text(json.dumps(tree))++ def test_a_healthy_tree_validates(self) -> None:+ out, _ = self.run_command("validate")+ self.assertIn("OK", out)+ self.assertIn("2 nodes", out)++ def test_a_dangling_parent_is_caught(self) -> None:+ tree = self.tree+ tree["nodes"]["n1"]["parent"] = "n42"+ self._write_tree(tree)+ with self.assertRaises(SystemExit):+ self.run_command("validate")++ def test_an_invalid_status_is_caught(self) -> None:+ tree = self.tree+ tree["nodes"]["n1"]["status"] = "hallucinated"+ self._write_tree(tree)+ with self.assertRaises(SystemExit):+ self.run_command("validate")++ def test_a_best_node_that_was_never_merged_is_caught(self) -> None:+ run = self.run_config+ run["best_node"] = "n1"+ (self.run_dir / ".arbor" / "run.json").write_text(json.dumps(run))+ with self.assertRaises(SystemExit):+ self.run_command("validate")++ def test_a_merged_best_node_validates(self) -> None:+ self.run_command("merge", "--node", "n1", "--test-score", "0.9")+ out, _ = self.run_command("validate")+ self.assertIn("OK", out)+ self.assertIn("best=n1", out)+++class ProjectionTests(ArborRunTestCase):+ def test_observe_reports_the_objective_and_every_node(self) -> None:+ self.init(objective="Reduce inference latency")+ self.run_command("add-node", "--parent", "n0", "--hypothesis", "quantise weights")+ self.run_command("set-evidence", "--node", "n1", "--dev-score", "0.42")++ out, _ = self.run_command("observe")+ self.assertIn("Reduce inference latency", out)+ self.assertIn("quantise weights", out)+ self.assertIn("0.42", out)++ def test_status_renders_the_tree_without_mutating_it(self) -> None:+ self.init()+ self.run_command("add-node", "--parent", "n0", "--hypothesis", "a direction")+ before = self.tree+ out, _ = self.run_command("status")+ self.assertIn("a direction", out)+ self.assertEqual(self.tree, before)+++class PersistenceTests(ArborRunTestCase):+ def test_writes_leave_no_temporary_file_behind(self) -> None:+ # _save writes to a .tmp sibling and replaces, so a crash cannot leave+ # a half-written tree.json -- but it must also clean up on success.+ self.init()+ self.run_command("add-node", "--parent", "n0", "--hypothesis", "h")+ leftovers = sorted(p.name for p in (self.run_dir / ".arbor").iterdir())+ self.assertEqual(leftovers, ["run.json", "tree.json"])++ def test_state_survives_a_fresh_read(self) -> None:+ self.init()+ self.run_command("add-node", "--parent", "n0", "--hypothesis", "persisted")+ reloaded = json.loads((self.run_dir / ".arbor" / "tree.json").read_text())+ self.assertEqual(reloaded["nodes"]["n1"]["hypothesis"], "persisted")+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/arboreto/test_scripts.py b/tests/arboreto/test_scripts.pynew file mode 100644index 00000000..90cf8135--- /dev/null+++ b/tests/arboreto/test_scripts.py@@ -0,0 +1,127 @@+"""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()diff --git a/tests/autoskill/test_cli.py b/tests/autoskill/test_cli.pyindex 6b620f24..97d68699 100644--- a/tests/autoskill/test_cli.py+++ b/tests/autoskill/test_cli.py@@ -1,7 +1,11 @@+from pathlib import Path+import pytestimport autoskill+import skill_contract+def test_dispatches_to_run_subcommand(monkeypatch):calls = {}@@ -59,3 +63,8 @@ def test_missing_subcommand_errors_out():def test_unknown_subcommand_errors_out():with pytest.raises(SystemExit):autoskill.main(["nope"])++# 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(Path(__file__).resolve().parents[2] / "skills" / "autoskill")diff --git a/tests/bids/test_scripts.py b/tests/bids/test_scripts.pynew file mode 100644index 00000000..8bfecfb4--- /dev/null+++ b/tests/bids/test_scripts.py@@ -0,0 +1,147 @@+"""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()diff --git a/tests/bioservices/test_scripts.py b/tests/bioservices/test_scripts.pynew file mode 100644index 00000000..8631686e--- /dev/null+++ b/tests/bioservices/test_scripts.py@@ -0,0 +1,938 @@+"""Tests for the BioServices cross-database workflow scripts.++BioServices *is* the network, so every service class is replaced here and the+tests assert on the request that would have been issued and on the parsing of a+canned response. Nothing in this file opens a connection.++The parsers are where these scripts can be quietly wrong, so the fixtures are+real records with published values: the KEGG flat file for ATP (C00002) carries+formula C10H16N5O13P3, exact mass 506.9957 and ChEBI 15422, and the parser must+pull exactly those out -- and must not mistake the indented DBLINKS lines that+follow the PATHWAY block for pathways.++The rest of the coverage is the batch machinery: chunking a large identifier+list into requests of the requested size, retrying a failed chunk one identifier+at a time, marking everything that never came back as failed, and writing a CSV+whose "Failed" rows really are the unmapped ones. Alias normalisation is tested+in both directions -- an alias must resolve and an already-official code must+survive untouched.+"""++from __future__ import annotations++import csv+import io+import sys+import tempfile+import unittest+from contextlib import redirect_stdout+from pathlib import Path+from unittest.mock import patch++import pytest++import skill_contract++SKILL_ROOT = Path(__file__).resolve().parents[2] / "skills" / "bioservices"+SCRIPTS = SKILL_ROOT / "scripts"+sys.path.insert(0, str(SCRIPTS))++pytest.importorskip("bioservices", reason="bioservices skill needs bioservices")++import batch_id_converter as converter # noqa: E402+import compound_cross_reference as compound # noqa: E402+import pathway_analysis as pathways # noqa: E402+import protein_analysis_workflow as workflow # noqa: E402++CliHelpTests = skill_contract.cli.help_test_case(SKILL_ROOT)++# KEGG's flat file for ATP, trimmed to the fields the parser reads. Field names+# start in column 1; continuation lines are indented 12 spaces.+ATP_ENTRY = """\+ENTRY C00002 Compound+NAME ATP;+ Adenosine 5'-triphosphate+FORMULA C10H16N5O13P3+EXACT_MASS 506.9957+MOL_WEIGHT 507.181+REACTION R00002 R00076+PATHWAY map00190 Oxidative phosphorylation+ map00230 Purine metabolism+ map00730 Thiamine metabolism+ENZYME 1.1.98.6 1.2.1.101+DBLINKS CAS: 56-65-5+ PubChem: 3304+ ChEBI: 15422+ KNApSAcK: C00001491+ PDB-CCD: ATP+ATOM 31+///+"""+++def quietly(function, *args, **kwargs):+ """Run one of these very chatty functions without its progress output."""+ with redirect_stdout(io.StringIO()):+ return function(*args, **kwargs)+++class DatabaseCodeTests(unittest.TestCase):+ """Aliases must resolve, and official codes must pass through untouched."""++ def test_lowercase_aliases_resolve_to_the_official_code(self) -> None:+ self.assertEqual(converter.normalize_database_code("uniprot"), "UniProtKB_AC-ID")+ self.assertEqual(converter.normalize_database_code("entrez"), "GeneID")+ self.assertEqual(converter.normalize_database_code("refseq"), "RefSeq_Protein")++ def test_aliases_are_matched_case_insensitively(self) -> None:+ self.assertEqual(converter.normalize_database_code("UniProt"), "UniProtKB_AC-ID")+ self.assertEqual(converter.normalize_database_code("ENSEMBL"), "Ensembl")++ def test_an_official_code_survives_normalisation(self) -> None:+ # Rewriting a valid code would break the mapping request.+ for code in ("UniProtKB_AC-ID", "Ensembl_Protein", "RefSeq_Protein", "GO"):+ with self.subTest(code=code):+ self.assertEqual(converter.normalize_database_code(code), code)++ def test_every_alias_maps_to_a_code_that_is_itself_stable(self) -> None:+ # Normalisation must be idempotent, or a second pass would corrupt it.+ for alias, code in converter.DATABASE_CODES.items():+ with self.subTest(alias=alias):+ self.assertEqual(converter.normalize_database_code(code), code)++ def test_an_unknown_code_is_passed_through_rather_than_rejected(self) -> None:+ # UniProt supports far more codes than the alias table lists.+ self.assertEqual(converter.normalize_database_code("Ensembl_Genomes"),+ "Ensembl_Genomes")+++class IdentifierFileTests(unittest.TestCase):+ def setUp(self) -> None:+ self._temporary = tempfile.TemporaryDirectory()+ self.addCleanup(self._temporary.cleanup)+ self.root = Path(self._temporary.name)++ def read(self, text: str):+ path = self.root / "ids.txt"+ path.write_text(text, encoding="utf-8")+ return quietly(converter.read_ids_from_file, path)++ def test_identifiers_are_read_one_per_line_and_trimmed(self) -> None:+ self.assertEqual(self.read("P43403\n P04637 \n"), ["P43403", "P04637"])++ def test_comments_and_blank_lines_are_ignored(self) -> None:+ self.assertEqual(+ self.read("# kinases\nP43403\n\n#P00000\nP04637\n"),+ ["P43403", "P04637"],+ )++ def test_an_empty_file_yields_no_identifiers(self) -> None:+ self.assertEqual(self.read("\n\n"), [])++ def test_a_missing_file_raises(self) -> None:+ with self.assertRaises(OSError):+ converter.read_ids_from_file(self.root / "absent.txt")+++class RecordingUniProt:+ """Stands in for `bioservices.UniProt`, recording every mapping request."""++ def __init__(self, verbose: bool = True) -> None:+ self.requests: list[dict] = []+ RecordingUniProt.instances.append(self)++ instances: list["RecordingUniProt"] = []++ def mapping(self, fr: str, to: str, query: str):+ self.requests.append({"fr": fr, "to": to, "query": query})+ return RecordingUniProt.responder(query)+++class BatchConversionTests(unittest.TestCase):+ def setUp(self) -> None:+ RecordingUniProt.instances = []+ RecordingUniProt.responder = lambda query: {+ identifier: [f"hsa:{identifier}"] for identifier in query.split(",")+ }+ patcher = patch.object(converter, "UniProt", RecordingUniProt)+ patcher.start()+ self.addCleanup(patcher.stop)+ # Rate limiting is real behaviour, but the suite must not sleep for it.+ sleeper = patch.object(converter.time, "sleep")+ self.sleep = sleeper.start()+ self.addCleanup(sleeper.stop)++ @property+ def requests(self) -> list[dict]:+ self.assertEqual(len(RecordingUniProt.instances), 1)+ return RecordingUniProt.instances[0].requests++ def convert(self, ids, **kwargs):+ return quietly(+ converter.batch_convert, ids, "UniProtKB_AC-ID", "KEGG", **kwargs+ )++ def test_a_short_list_is_one_comma_separated_request(self) -> None:+ mapping, failed = self.convert(["P43403", "P04637"])+ self.assertEqual(len(self.requests), 1)+ self.assertEqual(self.requests[0]["query"], "P43403,P04637")+ self.assertEqual(self.requests[0]["fr"], "UniProtKB_AC-ID")+ self.assertEqual(self.requests[0]["to"], "KEGG")+ self.assertEqual(mapping["P43403"], ["hsa:P43403"])+ self.assertEqual(failed, [])++ def test_a_long_list_is_split_into_chunks_of_the_requested_size(self) -> None:+ # 250 identifiers at 100 per request is 3 requests: 100, 100, 50.+ identifiers = [f"P{index:05d}" for index in range(250)]+ mapping, failed = self.convert(identifiers, chunk_size=100, delay=0)+ self.assertEqual(len(self.requests), 3)+ self.assertEqual(+ [len(request["query"].split(",")) for request in self.requests],+ [100, 100, 50],+ )+ # Every identifier appears exactly once across the chunks.+ sent = [+ identifier+ for request in self.requests+ for identifier in request["query"].split(",")+ ]+ self.assertEqual(sent, identifiers)+ self.assertEqual(len(mapping), 250)+ self.assertEqual(failed, [])++ def test_a_chunk_size_larger_than_the_list_still_sends_one_request(self) -> None:+ self.convert(["P43403"], chunk_size=500)+ self.assertEqual(len(self.requests), 1)++ def test_identifiers_that_never_map_are_reported_as_failed(self) -> None:+ RecordingUniProt.responder = lambda query: {"P43403": ["hsa:7535"]}+ mapping, failed = self.convert(["P43403", "P99999"], delay=0)+ self.assertEqual(mapping["P43403"], ["hsa:7535"])+ # Absent from the response, so present in the result with no target --+ # a silently dropped identifier would inflate the mapping rate.+ self.assertIsNone(mapping["P99999"])+ self.assertEqual(len(mapping), 2)++ def test_an_empty_response_marks_the_whole_chunk_failed(self) -> None:+ RecordingUniProt.responder = lambda query: {}+ mapping, failed = self.convert(["P43403", "P04637"], delay=0)+ self.assertEqual(sorted(failed), ["P04637", "P43403"])+ self.assertTrue(all(value is None for value in mapping.values()))++ def test_a_failed_chunk_is_retried_one_identifier_at_a_time(self) -> None:+ # UniProt rejects a whole batch when one identifier in it is malformed,+ # so the per-identifier retry is what rescues the rest.+ def responder(query: str):+ if "," in query:+ raise RuntimeError("400 Bad Request")+ if query == "BROKEN":+ return {}+ return {query: [f"hsa:{query}"]}++ RecordingUniProt.responder = staticmethod(responder)+ mapping, failed = self.convert(["P43403", "BROKEN", "P04637"], delay=0)+ queries = [request["query"] for request in self.requests]+ self.assertEqual(queries[0], "P43403,BROKEN,P04637") # the failed batch+ self.assertEqual(queries[1:], ["P43403", "BROKEN", "P04637"])+ self.assertEqual(mapping["P43403"], ["hsa:P43403"])+ self.assertEqual(failed, ["BROKEN"])++ def test_a_retry_that_also_fails_records_the_identifier_once(self) -> None:+ def responder(query: str):+ raise RuntimeError("service unavailable")++ RecordingUniProt.responder = staticmethod(responder)+ mapping, failed = self.convert(["P43403"], delay=0)+ self.assertEqual(failed, ["P43403"])+ self.assertIsNone(mapping["P43403"])++ def test_the_delay_is_only_taken_between_chunks(self) -> None:+ self.convert([f"P{index}" for index in range(3)], chunk_size=1, delay=0.5)+ # Three chunks, two gaps.+ self.assertEqual(+ [call.args[0] for call in self.sleep.call_args_list], [0.5, 0.5]+ )++ def test_no_delay_is_taken_when_it_is_switched_off(self) -> None:+ self.convert([f"P{index}" for index in range(3)], chunk_size=1, delay=0)+ self.sleep.assert_not_called()+++class MappingCsvTests(unittest.TestCase):+ def setUp(self) -> None:+ self._temporary = tempfile.TemporaryDirectory()+ self.addCleanup(self._temporary.cleanup)+ self.root = Path(self._temporary.name)+ self.path = self.root / "mapping.csv"+ quietly(+ converter.save_mapping_csv,+ {"P43403": ["hsa:7535", "mmu:22637"], "P99999": None, "P04637": ["hsa:7157"]},+ self.path,+ "UniProtKB_AC-ID",+ "KEGG",+ )+ with self.path.open(newline="", encoding="utf-8") as handle:+ self.rows = list(csv.reader(handle))++ def test_the_header_is_the_documented_five_columns(self) -> None:+ self.assertEqual(+ self.rows[0],+ ["Source_ID", "Source_DB", "Target_IDs", "Target_DB", "Mapping_Status"],+ )++ def test_rows_are_sorted_by_source_identifier(self) -> None:+ self.assertEqual(+ [row[0] for row in self.rows[1:]], ["P04637", "P43403", "P99999"]+ )++ def test_multiple_targets_are_joined_with_semicolons(self) -> None:+ # A comma would collide with the CSV delimiter.+ row = next(row for row in self.rows if row[0] == "P43403")+ self.assertEqual(row[2], "hsa:7535;mmu:22637")+ self.assertEqual(row[4], "Success")++ def test_an_unmapped_identifier_is_written_as_an_empty_failed_row(self) -> None:+ row = next(row for row in self.rows if row[0] == "P99999")+ self.assertEqual(row[2], "")+ self.assertEqual(row[4], "Failed")++ def test_the_source_and_target_databases_are_recorded_on_every_row(self) -> None:+ for row in self.rows[1:]:+ self.assertEqual((row[1], row[3]), ("UniProtKB_AC-ID", "KEGG"))++ def test_failed_identifiers_are_saved_only_when_there_are_some(self) -> None:+ target = self.root / "failed.txt"+ quietly(converter.save_failed_ids, [], target)+ self.assertFalse(target.exists())+ quietly(converter.save_failed_ids, ["P99999", "P88888"], target)+ self.assertEqual(+ target.read_text(encoding="utf-8").split(), ["P99999", "P88888"]+ )+++class FakeKegg:+ """Records KEGG requests and replays canned flat-file responses."""++ def __init__(self, find_result: str = "", entries: dict | None = None) -> None:+ self.find_result = find_result+ self.entries = entries or {}+ self.requests: list[tuple[str, tuple]] = []++ def find(self, database: str, query: str):+ self.requests.append(("find", (database, query)))+ return self.find_result++ def get(self, identifier: str):+ self.requests.append(("get", (identifier,)))+ return self.entries.get(identifier, "")+++class KeggCompoundSearchTests(unittest.TestCase):+ def search(self, find_result: str):+ fake = FakeKegg(find_result=find_result)+ with patch.object(compound, "KEGG", lambda *a, **k: fake):+ _, identifier = quietly(compound.search_kegg_compound, "ATP")+ return fake, identifier++ def test_the_compound_database_is_searched_by_name(self) -> None:+ fake, _ = self.search("cpd:C00002\tATP; Adenosine 5'-triphosphate\n")+ self.assertEqual(fake.requests[0], ("find", ("compound", "ATP")))++ def test_the_cpd_prefix_is_stripped_from_the_first_hit(self) -> None:+ # Downstream calls rebuild "cpd:<id>", so keeping the prefix here would+ # produce "cpd:cpd:C00002".+ _, identifier = self.search("cpd:C00002\tATP\ncpd:C00008\tADP\n")+ self.assertEqual(identifier, "C00002")++ def test_no_results_returns_no_identifier(self) -> None:+ for empty in ("", "\n", " "):+ with self.subTest(response=repr(empty)):+ _, identifier = self.search(empty)+ self.assertIsNone(identifier)++ def test_a_service_error_returns_no_identifier_rather_than_raising(self) -> None:+ class Broken:+ def find(self, *args):+ raise RuntimeError("KEGG is down")++ with patch.object(compound, "KEGG", lambda *a, **k: Broken()):+ _, identifier = quietly(compound.search_kegg_compound, "ATP")+ self.assertIsNone(identifier)+++class KeggEntryParsingTests(unittest.TestCase):+ """Parsed against the published values in the ATP entry above."""++ def setUp(self) -> None:+ self.kegg = FakeKegg(entries={"cpd:C00002": ATP_ENTRY})+ self.info = quietly(compound.get_kegg_info, self.kegg, "C00002")++ def test_the_entry_is_requested_with_the_cpd_prefix(self) -> None:+ self.assertEqual(self.kegg.requests, [("get", ("cpd:C00002",))])++ def test_the_published_formula_and_masses_are_extracted(self) -> None:+ self.assertEqual(self.info["formula"], "C10H16N5O13P3")+ self.assertEqual(self.info["exact_mass"], "506.9957")+ self.assertEqual(self.info["mol_weight"], "507.181")++ def test_the_name_loses_its_trailing_semicolon(self) -> None:+ # KEGG separates synonyms with ";"; keeping it would corrupt the label.+ self.assertEqual(self.info["name"], "ATP")++ def test_the_chebi_identifier_is_pulled_out_of_dblinks(self) -> None:+ # ATP is CHEBI:15422.+ self.assertEqual(self.info["chebi_id"], "15422")++ def test_only_the_pathway_block_becomes_pathways(self) -> None:+ # Three PATHWAY lines. The indented DBLINKS lines that follow must not+ # be collected, or the pathway count is inflated by database links.+ self.assertEqual(len(self.info["pathways"]), 3)+ self.assertEqual(self.info["pathways"][0], "map00190 Oxidative phosphorylation")+ self.assertTrue(+ all("PubChem" not in pathway for pathway in self.info["pathways"])+ )+ self.assertTrue(+ all("KNApSAcK" not in pathway for pathway in self.info["pathways"])+ )++ def test_an_entry_without_a_pathway_block_has_no_pathways(self) -> None:+ entry = "ENTRY C99999\nNAME Nothing\nFORMULA CH4\n///\n"+ info = quietly(+ compound.get_kegg_info, FakeKegg(entries={"cpd:C99999": entry}), "C99999"+ )+ self.assertEqual(info["pathways"], [])+ self.assertIsNone(info["chebi_id"])+ self.assertEqual(info["formula"], "CH4")++ def test_an_empty_response_is_reported_as_no_information(self) -> None:+ self.assertIsNone(quietly(compound.get_kegg_info, FakeKegg(), "C00002"))+++class ChebiAndChemblTests(unittest.TestCase):+ def test_a_bare_chebi_number_is_prefixed_before_the_request(self) -> None:+ # The ChEBI service requires the "CHEBI:" namespace.+ requested: list[str] = []++ class FakeChebi:+ def getCompleteEntity(self, identifier):+ requested.append(identifier)+ return type(+ "Entity",+ (),+ {+ "chebiId": "CHEBI:15422",+ "chebiAsciiName": "ATP",+ "Formulae": "C10H16N5O13P3",+ "mass": "507.18100",+ },+ )()++ with patch.object(compound, "ChEBI", lambda *a, **k: FakeChebi()):+ info = quietly(compound.get_chebi_info, "15422")+ self.assertEqual(requested, ["CHEBI:15422"])+ self.assertEqual(info["chebi_id"], "CHEBI:15422")+ self.assertEqual(info["name"], "ATP")++ def test_an_already_prefixed_identifier_is_not_prefixed_twice(self) -> None:+ requested: list[str] = []++ class FakeChebi:+ def getCompleteEntity(self, identifier):+ requested.append(identifier)+ return None++ with patch.object(compound, "ChEBI", lambda *a, **k: FakeChebi()):+ quietly(compound.get_chebi_info, "CHEBI:15422")+ self.assertEqual(requested, ["CHEBI:15422"])++ def test_no_chebi_identifier_means_no_request_at_all(self) -> None:+ with patch.object(compound, "ChEBI") as chebi:+ self.assertIsNone(quietly(compound.get_chebi_info, None))+ chebi.assert_not_called()++ def test_the_chembl_lookup_uses_the_current_method_name(self) -> None:+ # `get_compound_by_chemblId` was removed after bioservices 1.6; the+ # current release exposes `get_molecule`, and the installed class must+ # actually have whatever the script calls.+ from bioservices import ChEMBL++ self.assertTrue(hasattr(ChEMBL, "get_molecule"))++ requested: list[str] = []++ class FakeChembl:+ def get_molecule(self, identifier):+ requested.append(identifier)+ return {+ "pref_name": "ASPIRIN",+ "molecule_properties": {"full_mwt": "180.16", "alogp": "1.31"},+ "molecule_structures": {"canonical_smiles": "CC(=O)Oc1ccccc1C(=O)O"},+ }++ with patch.object(compound, "ChEMBL", lambda *a, **k: FakeChembl()):+ result = quietly(compound.get_chembl_info, "CHEMBL25")+ self.assertEqual(requested, ["CHEMBL25"])+ self.assertEqual(result["pref_name"], "ASPIRIN")++ def test_no_chembl_identifier_means_no_request(self) -> None:+ with patch.object(compound, "ChEMBL") as chembl:+ self.assertIsNone(quietly(compound.get_chembl_info, None))+ chembl.assert_not_called()++ def test_a_chembl_error_is_swallowed_into_a_none_result(self) -> None:+ class Broken:+ def get_molecule(self, identifier):+ raise RuntimeError("ChEMBL is down")++ with patch.object(compound, "ChEMBL", lambda *a, **k: Broken()):+ self.assertIsNone(quietly(compound.get_chembl_info, "CHEMBL25"))+++class CompoundReportTests(unittest.TestCase):+ def test_the_report_records_every_identifier_that_was_resolved(self) -> None:+ with tempfile.TemporaryDirectory() as directory:+ path = Path(directory) / "report.txt"+ quietly(+ compound.save_results,+ "ATP",+ {+ "kegg_id": "C00002",+ "name": "ATP",+ "formula": "C10H16N5O13P3",+ "exact_mass": "506.9957",+ "mol_weight": "507.181",+ "chebi_id": "15422",+ "pathways": ["map00190", "map00230"],+ },+ "CHEMBL14249",+ path,+ )+ text = path.read_text(encoding="utf-8")+ self.assertIn("ATP", text)+ self.assertIn("C10H16N5O13P3", text)+ self.assertIn("KEGG: C00002", text)+ self.assertIn("ChEBI: 15422", text)+ self.assertIn("CHEMBL14249", text)+ self.assertIn("Pathways: 2 found", text)++ def test_a_report_without_kegg_information_still_writes(self) -> None:+ # The compound may resolve in ChEMBL but not in KEGG.+ with tempfile.TemporaryDirectory() as directory:+ path = Path(directory) / "report.txt"+ quietly(compound.save_results, "Mystery", None, "CHEMBL1", path)+ text = path.read_text(encoding="utf-8")+ self.assertIn("Mystery", text)+ self.assertIn("CHEMBL1", text)+ self.assertNotIn("KEGG Compound\n", text)+++class FakeKgmlKegg:+ """A KEGG stand-in for the KGML pathway walk."""++ def __init__(self, parsed: dict | None = None, entry: str = "") -> None:+ self.parsed = parsed+ self.entry = entry+ self.parsed_ids: list[str] = []++ def parse_kgml_pathway(self, pathway_id: str):+ self.parsed_ids.append(pathway_id)+ if self.parsed is None:+ raise RuntimeError("no KGML for this pathway")+ return self.parsed++ def get(self, pathway_id: str):+ return self.entry+++KGML = {+ "entries": [{"id": "1", "gene_names": "TP53"}, {"id": "2", "gene_names": "MDM2"}],+ "relations": [+ {"entry1": "1", "entry2": "2", "name": "activation", "link": "PPrel"},+ {"entry1": "2", "entry2": "1", "name": "inhibition", "link": "PPrel"},+ {"entry1": "1", "entry2": "2", "name": "binding/association", "link": "PPrel"},+ {"entry1": "1", "entry2": "2", "name": "activation", "link": "PPrel"},+ {"entry1": "2", "entry2": "2", "name": "methylation", "link": "PPrel"},+ ],+}+++class PathwayAnalysisTests(unittest.TestCase):+ def setUp(self) -> None:+ self._temporary = tempfile.TemporaryDirectory()+ self.addCleanup(self._temporary.cleanup)+ self.root = Path(self._temporary.name)++ def analyse(self, kegg, pathway_id: str = "hsa04115"):+ return quietly(pathways.analyze_pathway, kegg, pathway_id)++ def test_entries_and_relations_are_counted_and_typed(self) -> None:+ kegg = FakeKgmlKegg(parsed=KGML, entry="NAME p53 signaling pathway\n")+ result = self.analyse(kegg)+ self.assertEqual(result["num_entries"], 2)+ self.assertEqual(result["num_relations"], 5)+ # Hand-counted from KGML above.+ self.assertEqual(+ result["relation_types"],+ {"activation": 2, "inhibition": 1, "binding/association": 1,+ "methylation": 1},+ )+ self.assertEqual(result["pathway_name"], "p53 signaling pathway")++ def test_a_pathway_without_kgml_is_skipped_not_fatal(self) -> None:+ # Many KEGG pathways have no KGML; one of them must not end the run.+ self.assertIsNone(self.analyse(FakeKgmlKegg(parsed=None)))++ def test_a_missing_name_falls_back_to_unknown(self) -> None:+ result = self.analyse(FakeKgmlKegg(parsed=KGML, entry="ENTRY hsa04115\n"))+ self.assertEqual(result["pathway_name"], "Unknown")++ def test_an_empty_pathway_reports_zero_rather_than_failing(self) -> None:+ result = self.analyse(FakeKgmlKegg(parsed={}, entry=""))+ self.assertEqual((result["num_entries"], result["num_relations"]), (0, 0))+ self.assertEqual(result["relation_types"], {})++ def test_failed_pathways_are_dropped_from_the_batch(self) -> None:+ class Flaky(FakeKgmlKegg):+ def parse_kgml_pathway(self, pathway_id):+ if pathway_id == "bad":+ raise RuntimeError("no KGML")+ return KGML++ results = quietly(+ pathways.analyze_all_pathways, Flaky(entry=""), ["good", "bad", "good2"]+ )+ self.assertEqual([r["pathway_id"] for r in results], ["good", "good2"])++ def test_the_limit_truncates_the_pathway_list(self) -> None:+ kegg = FakeKgmlKegg(parsed=KGML, entry="")+ results = quietly(+ pathways.analyze_all_pathways, kegg, ["a", "b", "c", "d"], 2+ )+ self.assertEqual(len(results), 2)+ self.assertEqual(kegg.parsed_ids, ["a", "b"])++ def test_the_summary_buckets_the_four_named_interaction_types(self) -> None:+ result = self.analyse(FakeKgmlKegg(parsed=KGML, entry="NAME p53\n"))+ path = self.root / "summary.csv"+ quietly(pathways.save_pathway_summary, [result], path)+ with path.open(newline="", encoding="utf-8") as handle:+ header, row = list(csv.reader(handle))+ self.assertEqual(+ header,+ ["Pathway_ID", "Pathway_Name", "Num_Genes", "Num_Interactions",+ "Activation", "Inhibition", "Phosphorylation", "Binding", "Other"],+ )+ columns = dict(zip(header, row))+ self.assertEqual(columns["Activation"], "2")+ self.assertEqual(columns["Inhibition"], "1")+ self.assertEqual(columns["Phosphorylation"], "0")+ self.assertEqual(columns["Binding"], "1")+ # methylation is not one of the four named buckets.+ self.assertEqual(columns["Other"], "1")+ # Every relation is accounted for exactly once.+ self.assertEqual(+ sum(int(columns[name]) for name in+ ("Activation", "Inhibition", "Phosphorylation", "Binding", "Other")),+ int(columns["Num_Interactions"]),+ )++ def test_interactions_are_written_as_three_column_sif(self) -> None:+ result = self.analyse(FakeKgmlKegg(parsed=KGML, entry=""))+ path = self.root / "network.sif"+ quietly(pathways.save_interactions_sif, [result], path)+ lines = path.read_text(encoding="utf-8").splitlines()+ self.assertEqual(len(lines), 5)+ # SIF is source<TAB>interaction<TAB>target; Cytoscape reads nothing else.+ self.assertEqual(lines[0].split("\t"), ["1", "activation", "2"])+ for line in lines:+ self.assertEqual(len(line.split("\t")), 3)++ def test_per_pathway_files_are_named_without_a_colon(self) -> None:+ # "path:hsa04115" would be an illegal filename on some systems.+ result = self.analyse(FakeKgmlKegg(parsed=KGML, entry=""), "path:hsa04115")+ quietly(pathways.save_detailed_pathway_info, [result], str(self.root))+ written = [p.name for p in (self.root / "pathways").iterdir()]+ self.assertEqual(written, ["path_hsa04115_interactions.csv"])++ def test_the_organism_is_set_on_the_client_before_listing_pathways(self) -> None:+ class FakeKeggOrganism:+ organism = None+ pathwayIds = ["path:hsa00010", "path:hsa04115"]++ kegg = FakeKeggOrganism()+ ids = quietly(pathways.get_all_pathways, kegg, "hsa")+ self.assertEqual(kegg.organism, "hsa")+ self.assertEqual(ids, ["path:hsa00010", "path:hsa04115"])+++class NcbiEmailTests(unittest.TestCase):+ """BLAST submissions need a contact address; a bad one gets rejected."""++ def test_a_valid_address_on_the_command_line_wins(self) -> None:+ with patch.dict("os.environ", {"NCBI_EMAIL": "[email protected]"}):+ self.assertEqual(+ workflow.resolve_ncbi_email("[email protected]"), "[email protected]"+ )++ def test_the_environment_is_the_fallback(self) -> None:+ with patch.dict("os.environ", {"NCBI_EMAIL": "[email protected]"}):+ self.assertEqual(workflow.resolve_ncbi_email(None), "[email protected]")++ def test_surrounding_whitespace_is_stripped(self) -> None:+ self.assertEqual(workflow.resolve_ncbi_email(" [email protected] "), "[email protected]")++ def test_no_address_anywhere_yields_none(self) -> None:+ with patch.dict("os.environ", {}, clear=True):+ self.assertIsNone(workflow.resolve_ncbi_email(None))+ self.assertIsNone(workflow.resolve_ncbi_email(""))++ def test_malformed_addresses_are_refused(self) -> None:+ for candidate in ("not-an-email", "a@b", "a [email protected]", "@b.org", "[email protected]"):+ with self.subTest(candidate=candidate):+ with patch.dict("os.environ", {}, clear=True):+ self.assertIsNone(workflow.resolve_ncbi_email(candidate))+++class ProteinSearchTests(unittest.TestCase):+ TABLE = (+ "Entry\tGene names\tOrganism\tLength\tProtein names\n"+ "P43403\tZAP70 SRK\tHomo sapiens\t619\tTyrosine-protein kinase ZAP-70\n"+ "P04637\tTP53\tHomo sapiens\t393\tCellular tumor antigen p53\n"+ )++ class FakeUniProt:+ def __init__(self, verbose: bool = True, retrieve=None, search="") -> None:+ self.retrieve_result = retrieve+ self.search_result = search+ self.calls: list[tuple[str, tuple, dict]] = []++ def retrieve(self, *args, **kwargs):+ self.calls.append(("retrieve", args, kwargs))+ if self.retrieve_result is None:+ raise RuntimeError("not an accession")+ return self.retrieve_result++ def search(self, *args, **kwargs):+ self.calls.append(("search", args, kwargs))+ return self.search_result++ def run_search(self, query: str, **kwargs):+ fake = self.FakeUniProt(**kwargs)+ with patch.object(workflow, "UniProt", lambda **k: fake):+ _, identifier = quietly(workflow.search_protein, query)+ return fake, identifier++ def test_an_accession_shaped_query_is_retrieved_directly(self) -> None:+ # P43403 is six characters starting with P, so it is fetched rather+ # than searched -- one request instead of a full-text query.+ fake, identifier = self.run_search("P43403", retrieve="Entry\tP43403\n")+ self.assertEqual(identifier, "P43403")+ self.assertEqual([call[0] for call in fake.calls], ["retrieve"])++ def test_a_name_query_falls_through_to_search(self) -> None:+ fake, identifier = self.run_search("ZAP70_HUMAN", search=self.TABLE)+ self.assertEqual([call[0] for call in fake.calls], ["search"])+ self.assertEqual(identifier, "P43403") # the first data row++ def test_a_failed_direct_retrieval_falls_back_to_search(self) -> None:+ fake, identifier = self.run_search("P43403", retrieve=None, search=self.TABLE)+ self.assertEqual([call[0] for call in fake.calls], ["retrieve", "search"])+ self.assertEqual(identifier, "P43403")++ def test_a_header_only_response_finds_nothing(self) -> None:+ # One line means the table had no data rows; indexing lines[1] would+ # raise instead of reporting "not found".+ _, identifier = self.run_search("NOSUCHPROTEIN", search="Entry\tGene names\n")+ self.assertIsNone(identifier)++ def test_an_empty_response_finds_nothing(self) -> None:+ _, identifier = self.run_search("NOSUCHPROTEIN", search="")+ self.assertIsNone(identifier)+++class SequenceRetrievalTests(unittest.TestCase):+ class FakeUniProt:+ def __init__(self, fasta) -> None:+ self.fasta = fasta+ self.formats: list[str] = []++ def retrieve(self, identifier, frmt=None):+ self.formats.append(frmt)+ return self.fasta++ def test_the_fasta_header_is_dropped_and_the_lines_joined(self) -> None:+ fake = self.FakeUniProt(">sp|P43403|ZAP70_HUMAN\nMPDPAAHL\nPFFYGSIS\n")+ sequence = quietly(workflow.retrieve_sequence, fake, "P43403")+ # 16 residues across two wrapped lines; a header left in would corrupt+ # the BLAST submission that follows.+ self.assertEqual(sequence, "MPDPAAHLPFFYGSIS")+ self.assertEqual(fake.formats, ["fasta"])++ def test_an_empty_response_yields_no_sequence(self) -> None:+ self.assertIsNone(+ quietly(workflow.retrieve_sequence, self.FakeUniProt(""), "P43403")+ )++ def test_a_service_error_yields_no_sequence(self) -> None:+ class Broken:+ def retrieve(self, *args, **kwargs):+ raise RuntimeError("UniProt is down")++ self.assertIsNone(quietly(workflow.retrieve_sequence, Broken(), "P43403"))+++class BlastGuardTests(unittest.TestCase):+ def test_blast_is_not_submitted_without_a_contact_address(self) -> None:+ # EBI rejects anonymous submissions; sending one wastes a job slot.+ with patch.object(workflow, "NCBIblast") as blast:+ self.assertIsNone(quietly(workflow.run_blast, "MPDPAAHL", None))+ blast.assert_not_called()++ def test_blast_is_not_submitted_when_explicitly_skipped(self) -> None:+ with patch.object(workflow, "NCBIblast") as blast:+ self.assertIsNone(+ quietly(workflow.run_blast, "MPDPAAHL", "[email protected]", skip=True)+ )+ blast.assert_not_called()++ def test_a_finished_job_returns_its_result(self) -> None:+ class FakeBlast:+ def __init__(self, verbose: bool = True) -> None:+ self.submitted: dict = {}++ def run(self, **kwargs):+ self.submitted = kwargs+ return "ncbiblast-1"++ def getStatus(self, jobid):+ return "FINISHED"++ def getResult(self, jobid, kind):+ return "BLAST report\nhit 1\n"++ fake = FakeBlast()+ with patch.object(workflow, "NCBIblast", lambda **k: fake):+ result = quietly(workflow.run_blast, "MPDPAAHL", "[email protected]")+ self.assertIn("BLAST report", result)+ self.assertEqual(fake.submitted["program"], "blastp")+ self.assertEqual(fake.submitted["stype"], "protein")+ self.assertEqual(fake.submitted["database"], "uniprotkb")+ self.assertEqual(fake.submitted["email"], "[email protected]")++ def test_a_failed_job_returns_nothing_rather_than_polling_forever(self) -> None:+ class FailingBlast:+ def __init__(self, verbose: bool = True) -> None:+ pass++ def run(self, **kwargs):+ return "ncbiblast-2"++ def getStatus(self, jobid):+ return "ERROR"++ with patch.object(workflow, "NCBIblast", lambda **k: FailingBlast()):+ with patch.object(workflow.time, "sleep"):+ self.assertIsNone(quietly(workflow.run_blast, "MPDPAAHL", "[email protected]"))+++class InteractionTests(unittest.TestCase):+ #: A PSI-MI TAB record: the first 12 columns are what the parser reads.+ LINE = "\t".join(+ [+ "uniprotkb:P43403", "uniprotkb:P07948",+ "intact:EBI-1", "intact:EBI-2",+ "uniprotkb:ZAP70", "uniprotkb:LYN",+ "psi-mi:\"MI:0018\"(two hybrid)", "Smith et al.",+ "pubmed:12345", "taxid:9606", "taxid:9606",+ "psi-mi:\"MI:0407\"(direct interaction)",+ ]+ )++ def test_the_query_is_scoped_to_human_and_parsed_by_column(self) -> None:+ recorded: list[tuple] = []+ payload = self.LINE++ class FakePsicquic:+ def query(self, database, query):+ recorded.append((database, query))+ return payload++ with patch.object(workflow, "PSICQUIC", lambda *a, **k: FakePsicquic()):+ interactions = quietly(workflow.find_interactions, "ZAP70")+ self.assertEqual(recorded, [("mint", "ZAP70 AND species:9606")])+ # Columns 5 and 6 hold the aliases; column 12 the interaction type.+ self.assertEqual(interactions[0][0], "ZAP70")+ self.assertEqual(interactions[0][1], "LYN")+ self.assertIn("direct interaction", interactions[0][2])++ def test_a_truncated_record_is_ignored_rather_than_indexed(self) -> None:+ class FakePsicquic:+ def query(self, database, query):+ return "uniprotkb:P43403\tuniprotkb:P07948\n"++ with patch.object(workflow, "PSICQUIC", lambda *a, **k: FakePsicquic()):+ self.assertEqual(quietly(workflow.find_interactions, "ZAP70"), [])++ def test_no_interactions_returns_an_empty_list(self) -> None:+ class FakePsicquic:+ def query(self, database, query):+ return ""++ with patch.object(workflow, "PSICQUIC", lambda *a, **k: FakePsicquic()):+ self.assertEqual(quietly(workflow.find_interactions, "ZAP70"), [])++ def test_a_release_without_psicquic_skips_the_step(self) -> None:+ # bioservices 1.16.0 does not ship PSICQUIC; the workflow must degrade+ # rather than fail, and must not try to construct it.+ with patch.object(workflow, "PSICQUIC", None):+ self.assertEqual(quietly(workflow.find_interactions, "ZAP70"), [])+++class GoAnnotationTests(unittest.TestCase):+ ANNOTATIONS = (+ "DB\tID\tSymbol\tQualifier\tRef\tEvidence\tGO_ID\tGO_NAME\tASPECT\n"+ "UniProtKB\tP43403\tZAP70\t\tPMID:1\tIDA\tGO:0004713\tprotein tyrosine kinase activity\tF\n"+ "UniProtKB\tP43403\tZAP70\t\tPMID:2\tIDA\tGO:0002250\tadaptive immune response\tP\n"+ "UniProtKB\tP43403\tZAP70\t\tPMID:3\tIDA\tGO:0005886\tplasma membrane\tC\n"+ "UniProtKB\tP43403\tZAP70\t\tPMID:4\tIDA\tGO:0046777\tprotein autophosphorylation\tP\n"+ )++ def annotations(self, payload: str):+ recorded: list[dict] = []++ class FakeQuickGo:+ def Annotation(self, **kwargs):+ recorded.append(kwargs)+ return payload++ with patch.object(workflow, "QuickGO", lambda *a, **k: FakeQuickGo()):+ result = quietly(workflow.get_go_annotations, "P43403")+ return recorded, result++ def test_terms_are_grouped_by_the_three_go_aspects(self) -> None:+ recorded, aspects = self.annotations(self.ANNOTATIONS)+ self.assertEqual(recorded, [{"protein": "P43403", "format": "tsv"}])+ self.assertEqual(len(aspects["P"]), 2) # two biological processes+ self.assertEqual(len(aspects["F"]), 1)+ self.assertEqual(len(aspects["C"]), 1)+ self.assertEqual(aspects["F"][0], ("GO:0004713", "protein tyrosine kinase activity"))++ def test_an_unknown_aspect_letter_is_discarded(self) -> None:+ payload = self.ANNOTATIONS + (+ "UniProtKB\tP43403\tZAP70\t\tPMID:5\tIDA\tGO:0000001\tmystery\tX\n"+ )+ _, aspects = self.annotations(payload)+ self.assertEqual(set(aspects), {"P", "F", "C"})+ self.assertEqual(sum(len(terms) for terms in aspects.values()), 4)++ def test_no_annotations_yields_an_empty_list(self) -> None:+ _, result = self.annotations("")+ self.assertEqual(result, [])++ def test_a_header_only_response_yields_empty_aspects(self) -> None:+ _, aspects = self.annotations("DB\tID\tSymbol\n")+ self.assertEqual(aspects, {"P": [], "F": [], "C": []})+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/bulk-rnaseq/test_scripts.py b/tests/bulk-rnaseq/test_scripts.pynew file mode 100644index 00000000..5fa3d035--- /dev/null+++ b/tests/bulk-rnaseq/test_scripts.py@@ -0,0 +1,384 @@+"""Tests for the bulk RNA-seq samplesheet validator and counts-matrix builder.++`validate_samplesheet` is the gate in front of an expensive pipeline run, and+the distinction it draws between an error and a warning is the whole product:+a duplicated FASTQ is fatal, the same sample across lanes is not. Every test+here asserts on that split, not merely that "something was reported".++The design checks matter just as much. A group with one replicate cannot+estimate variance, and a batch nested inside condition cannot be separated+from the biology -- both are silent disasters downstream, so both are pinned.+"""++from __future__ import annotations++import sys+import tempfile+import unittest+from pathlib import Path++import pytest++import skill_contract++SKILL_ROOT = Path(__file__).resolve().parents[2] / "skills" / "bulk-rnaseq"+SCRIPTS = SKILL_ROOT / "scripts"+sys.path.insert(0, str(SCRIPTS))++pd = pytest.importorskip("pandas", reason="bulk-rnaseq needs pandas")++import build_counts_matrix # noqa: E402+import validate_samplesheet # noqa: E402++CliHelpTests = skill_contract.cli.help_test_case(SKILL_ROOT)++GOOD_SHEET = """\+sample,fastq_1,fastq_2,strandedness+ctrl_1,ctrl_1_R1.fastq.gz,ctrl_1_R2.fastq.gz,auto+ctrl_2,ctrl_2_R1.fastq.gz,ctrl_2_R2.fastq.gz,auto+treat_1,treat_1_R1.fastq.gz,treat_1_R2.fastq.gz,auto+treat_2,treat_2_R1.fastq.gz,treat_2_R2.fastq.gz,auto+"""++GOOD_METADATA = """\+sample,condition,batch+ctrl_1,control,b1+ctrl_2,control,b2+treat_1,treated,b1+treat_2,treated,b2+"""+++class SamplesheetTestCase(unittest.TestCase):+ def setUp(self) -> None:+ self._temporary = tempfile.TemporaryDirectory()+ self.addCleanup(self._temporary.cleanup)+ self.root = Path(self._temporary.name)+ self.report = validate_samplesheet.Report()++ def write(self, name: str, text: str) -> Path:+ path = self.root / name+ path.write_text(text, encoding="utf-8")+ return path++ def validate(self, text: str, check_files: bool = False):+ return validate_samplesheet.validate_samplesheet(+ self.write("samplesheet.csv", text), check_files, self.report+ )+++class SamplesheetShapeTests(SamplesheetTestCase):+ def test_a_well_formed_sheet_passes_cleanly(self) -> None:+ sheet = self.validate(GOOD_SHEET)+ self.assertIsNotNone(sheet)+ self.assertEqual(self.report.errors, [])+ self.assertEqual(self.report.warnings, [])+ self.assertEqual(len(sheet), 4)++ def test_a_missing_file_is_an_error_not_a_crash(self) -> None:+ result = validate_samplesheet.validate_samplesheet(+ self.root / "absent.csv", False, self.report+ )+ self.assertIsNone(result)+ self.assertTrue(any("not found" in e for e in self.report.errors))++ def test_the_required_columns_are_sample_and_fastq_1(self) -> None:+ self.validate("sample,reads\nctrl_1,x.fastq.gz\n")+ self.assertTrue(+ any("must have at least" in e for e in self.report.errors)+ )++ def test_whitespace_around_headers_and_values_is_stripped(self) -> None:+ sheet = self.validate(+ " sample , fastq_1 \n ctrl_1 , ctrl_1_R1.fastq.gz \n"+ )+ self.assertEqual(list(sheet.columns), ["sample", "fastq_1"])+ self.assertEqual(sheet.loc[0, "sample"], "ctrl_1")+ self.assertEqual(self.report.errors, [])++ def test_a_missing_strandedness_column_is_only_advisory(self) -> None:+ self.validate("sample,fastq_1\nctrl_1,a.fastq.gz\n")+ self.assertEqual(self.report.errors, [])+ self.assertTrue(any("strandedness" in w for w in self.report.warnings))+++class SamplesheetContentTests(SamplesheetTestCase):+ def test_empty_sample_or_read_cells_are_errors_with_a_row_number(self) -> None:+ self.validate("sample,fastq_1\n,a.fastq.gz\nctrl_2,\n")+ self.assertTrue(any("row 2" in e and "'sample'" in e for e in self.report.errors))+ self.assertTrue(any("row 3" in e and "'fastq_1'" in e for e in self.report.errors))++ def test_the_same_file_in_both_read_columns_is_an_error(self) -> None:+ # A copy-paste that would silently halve the library.+ self.validate("sample,fastq_1,fastq_2\nctrl_1,same.fastq.gz,same.fastq.gz\n")+ self.assertTrue(any("the same file" in e for e in self.report.errors))++ def test_a_reused_read_one_file_is_an_error(self) -> None:+ self.validate(+ "sample,fastq_1\nctrl_1,shared.fastq.gz\nctrl_2,shared.fastq.gz\n"+ )+ self.assertTrue(any("appears 2 times" in e for e in self.report.errors))++ def test_unknown_strandedness_values_are_rejected(self) -> None:+ self.validate("sample,fastq_1,strandedness\nctrl_1,a.fastq.gz,sideways\n")+ self.assertTrue(any("strandedness 'sideways'" in e for e in self.report.errors))++ def test_every_documented_strandedness_value_is_accepted(self) -> None:+ rows = "\n".join(+ f"s{i},r{i}.fastq.gz,{value}"+ for i, value in enumerate(sorted(validate_samplesheet.VALID_STRANDEDNESS))+ )+ self.validate(f"sample,fastq_1,strandedness\n{rows}\n")+ self.assertEqual(self.report.errors, [])++ def test_strandedness_is_matched_case_insensitively(self) -> None:+ self.validate("sample,fastq_1,strandedness\nctrl_1,a.fastq.gz,REVERSE\n")+ self.assertEqual(self.report.errors, [])++ def test_one_sample_across_lanes_warns_but_does_not_fail(self) -> None:+ # nf-core merges lanes, so this is normal -- it must stay a warning.+ self.validate(+ "sample,fastq_1,fastq_2\n"+ "ctrl_1,L1_R1.fastq.gz,L1_R2.fastq.gz\n"+ "ctrl_1,L2_R1.fastq.gz,L2_R2.fastq.gz\n"+ )+ self.assertEqual(self.report.errors, [])+ self.assertTrue(any("lane-merged" in w for w in self.report.warnings))++ def test_mixing_paired_and_single_rows_for_one_sample_is_an_error(self) -> None:+ self.validate(+ "sample,fastq_1,fastq_2\n"+ "ctrl_1,L1_R1.fastq.gz,L1_R2.fastq.gz\n"+ "ctrl_1,L2_R1.fastq.gz,\n"+ )+ self.assertTrue(+ any("mixes paired-end and single-end" in e for e in self.report.errors)+ )+++class FileExistenceTests(SamplesheetTestCase):+ def test_absent_local_reads_are_errors_when_checking_is_on(self) -> None:+ self.validate("sample,fastq_1\nctrl_1,missing.fastq.gz\n", check_files=True)+ self.assertTrue(any("fastq_1 not found" in e for e in self.report.errors))++ def test_present_local_reads_pass(self) -> None:+ (self.root / "real.fastq.gz").write_bytes(b"")+ self.validate(+ f"sample,fastq_1\nctrl_1,{self.root / 'real.fastq.gz'}\n", check_files=True+ )+ self.assertEqual(self.report.errors, [])++ def test_an_unusual_extension_on_an_existing_file_is_only_a_warning(self) -> None:+ (self.root / "reads.txt").write_bytes(b"")+ self.validate(+ f"sample,fastq_1\nctrl_1,{self.root / 'reads.txt'}\n", check_files=True+ )+ self.assertEqual(self.report.errors, [])+ self.assertTrue(any("unusual extension" in w for w in self.report.warnings))++ def test_remote_urls_are_skipped_rather_than_reported_missing(self) -> None:+ for prefix in validate_samplesheet.REMOTE_PREFIXES:+ with self.subTest(prefix=prefix):+ report = validate_samplesheet.Report()+ path = self.write(+ "remote.csv", f"sample,fastq_1\nctrl_1,{prefix}bucket/r1.fastq.gz\n"+ )+ validate_samplesheet.validate_samplesheet(path, True, report)+ self.assertEqual(report.errors, [])+ self.assertTrue(any("remote" in w for w in report.warnings))++ def test_nothing_is_checked_when_file_checking_is_off(self) -> None:+ self.validate("sample,fastq_1\nctrl_1,missing.fastq.gz\n", check_files=False)+ self.assertEqual(self.report.errors, [])+++class MetadataTests(SamplesheetTestCase):+ def _validate_metadata(self, metadata: str, sheet_text: str = GOOD_SHEET,+ condition_col: str = "condition", min_rep: int = 3):+ sheet = validate_samplesheet.validate_samplesheet(+ self.write("sheet.csv", sheet_text), False, validate_samplesheet.Report()+ )+ validate_samplesheet.validate_metadata(+ self.write("meta.csv", metadata), sheet, condition_col, min_rep, self.report+ )+ return sheet++ def test_a_matching_design_passes_apart_from_the_replicate_advisory(self) -> None:+ self._validate_metadata(GOOD_METADATA)+ self.assertEqual(self.report.errors, [])++ def test_a_missing_condition_column_names_the_columns_it_found(self) -> None:+ self._validate_metadata("sample,group\nctrl_1,control\n")+ self.assertTrue(any("no 'condition' column" in e for e in self.report.errors))+ self.assertTrue(any("group" in e for e in self.report.errors))++ def test_samples_missing_from_the_metadata_are_an_error(self) -> None:+ self._validate_metadata("sample,condition\nctrl_1,control\nctrl_2,control\n")+ self.assertTrue(+ any("missing from metadata" in e for e in self.report.errors)+ )++ def test_extra_metadata_samples_are_only_a_warning(self) -> None:+ self._validate_metadata(GOOD_METADATA + "spare,control,b3\n")+ self.assertEqual(self.report.errors, [])+ self.assertTrue(+ any("not in samplesheet" in w for w in self.report.warnings)+ )++ def test_a_singleton_group_cannot_estimate_variance_and_is_fatal(self) -> None:+ sheet_text = (+ "sample,fastq_1\n"+ "ctrl_1,c1.fastq.gz\nctrl_2,c2.fastq.gz\ntreat_1,t1.fastq.gz\n"+ )+ self._validate_metadata(+ "sample,condition\nctrl_1,control\nctrl_2,control\ntreat_1,treated\n",+ sheet_text=sheet_text,+ )+ self.assertTrue(+ any("need >=2 to estimate variance" in e for e in self.report.errors)+ )++ def test_two_replicates_pass_but_warn_below_the_recommended_minimum(self) -> None:+ self._validate_metadata(GOOD_METADATA, min_rep=3)+ self.assertEqual(self.report.errors, [])+ self.assertTrue(any("recommended" in w for w in self.report.warnings))++ def test_an_entirely_empty_condition_column_is_fatal(self) -> None:+ self._validate_metadata(+ "sample,condition\nctrl_1,\nctrl_2,\ntreat_1,\ntreat_2,\n"+ )+ self.assertTrue(any("is empty for all samples" in e for e in self.report.errors))++ def test_batch_fully_nested_in_condition_is_flagged_as_confounded(self) -> None:+ # Each batch holding a single condition means the batch effect and the+ # biology cannot be told apart -- the most expensive silent mistake here.+ self._validate_metadata(+ "sample,condition,batch\n"+ "ctrl_1,control,b1\nctrl_2,control,b1\n"+ "treat_1,treated,b2\ntreat_2,treated,b2\n"+ )+ self.assertTrue(any("confounded" in w for w in self.report.warnings))++ def test_a_crossed_batch_design_is_not_flagged(self) -> None:+ self._validate_metadata(GOOD_METADATA)+ self.assertFalse(any("confounded" in w for w in self.report.warnings))+++class ReportTests(unittest.TestCase):+ def test_errors_fail_the_run_and_warnings_do_not(self) -> None:+ clean = validate_samplesheet.Report()+ self.assertEqual(clean.summarize(), 0)++ warned = validate_samplesheet.Report()+ warned.warn("advisory")+ self.assertEqual(warned.summarize(), 0)++ failed = validate_samplesheet.Report()+ failed.error("fatal")+ self.assertEqual(failed.summarize(), 1)+++class SampleNameTests(unittest.TestCase):+ def test_common_quantifier_suffixes_are_stripped(self) -> None:+ clean = build_counts_matrix._clean_sample_name+ for raw in ("ctrl_1", "ctrl_1.bam", "ctrl_1_S1_L001"):+ with self.subTest(raw=raw):+ self.assertTrue(clean(raw).startswith("ctrl_1"))++ def test_cleaning_is_idempotent(self) -> None:+ clean = build_counts_matrix._clean_sample_name+ once = clean("ctrl_1.bam")+ self.assertEqual(clean(once), once)++ def test_the_star_strand_columns_match_the_documented_layout(self) -> None:+ # STAR's ReadsPerGene.out.tab puts unstranded/forward/reverse in+ # columns 1-3; picking the wrong one silently halves the counts.+ self.assertEqual(+ build_counts_matrix.STAR_STRAND_COL,+ {"unstranded": 1, "forward": 2, "reverse": 3},+ )+++class CountsMatrixTests(unittest.TestCase):+ def setUp(self) -> None:+ self._temporary = tempfile.TemporaryDirectory()+ self.addCleanup(self._temporary.cleanup)+ self.root = Path(self._temporary.name)++ def _star_table(self, sample: str, rows: str) -> None:+ # STAR tables sit flat in the directory, named <sample>.ReadsPerGene.out.tab.+ (self.root / f"{sample}.ReadsPerGene.out.tab").write_text(+ "N_unmapped\t1\t1\t1\n"+ "N_multimapping\t2\t2\t2\n"+ "N_noFeature\t3\t3\t3\n"+ "N_ambiguous\t4\t4\t4\n" + rows,+ encoding="utf-8",+ )++ def test_star_counts_are_assembled_from_per_sample_tables(self) -> None:+ self._star_table("ctrl_1", "GENE1\t10\t0\t0\nGENE2\t20\t0\t0\n")+ self._star_table("treat_1", "GENE1\t30\t0\t0\nGENE2\t40\t0\t0\n")++ counts = build_counts_matrix.build_from_star(self.root, "unstranded")+ self.assertEqual(sorted(counts.index), ["GENE1", "GENE2"])+ self.assertEqual(set(counts.columns), {"ctrl_1", "treat_1"})+ self.assertEqual(counts.loc["GENE1", "ctrl_1"], 10)+ self.assertEqual(counts.loc["GENE2", "treat_1"], 40)++ def test_star_summary_rows_are_excluded_from_the_gene_matrix(self) -> None:+ # The first four rows are alignment statistics, not genes; counting+ # them would inflate the library size for every sample.+ self._star_table("s1", "GENE1\t5\t0\t0\n")+ counts = build_counts_matrix.build_from_star(self.root, "unstranded")+ self.assertEqual(list(counts.index), ["GENE1"])++ def test_genes_absent_from_one_sample_become_zero_not_nan(self) -> None:+ self._star_table("s1", "GENE1\t5\t0\t0\nGENE2\t7\t0\t0\n")+ self._star_table("s2", "GENE1\t9\t0\t0\n")+ counts = build_counts_matrix.build_from_star(self.root, "unstranded")+ self.assertEqual(counts.loc["GENE2", "s2"], 0)+ self.assertEqual(str(counts.dtypes.unique()[0]), "int64")++ def test_the_strand_choice_selects_a_different_column(self) -> None:+ self._star_table("s1", "GENE1\t100\t60\t40\n")+ for strand, expected in (("unstranded", 100), ("forward", 60), ("reverse", 40)):+ with self.subTest(strand=strand):+ counts = build_counts_matrix.build_from_star(self.root, strand)+ self.assertEqual(counts.loc["GENE1", "s1"], expected)++ def test_an_empty_directory_exits_with_a_message(self) -> None:+ with self.assertRaises(SystemExit) as raised:+ build_counts_matrix.build_from_star(self.root, "unstranded")+ self.assertIn("ReadsPerGene.out.tab", str(raised.exception))++ def test_featurecounts_output_is_reduced_to_genes_by_samples(self) -> None:+ path = self.root / "counts.txt"+ path.write_text(+ "# Program:featureCounts\n"+ "Geneid\tChr\tStart\tEnd\tStrand\tLength\tctrl_1.bam\ttreat_1.bam\n"+ "GENE1\tchr1\t1\t100\t+\t100\t10\t30\n"+ "GENE2\tchr1\t200\t300\t+\t100\t20\t40\n",+ encoding="utf-8",+ )+ counts = build_counts_matrix.build_from_featurecounts(path)+ self.assertEqual(list(counts.index), ["GENE1", "GENE2"])+ self.assertEqual(len(counts.columns), 2)+ self.assertEqual(counts.iloc[0, 0], 10)+ # The annotation columns must not survive as samples.+ self.assertFalse({"Chr", "Start", "End", "Strand", "Length"} & set(counts.columns))++ def test_outputs_are_written_where_downstream_steps_expect_them(self) -> None:+ counts = pd.DataFrame(+ {"ctrl_1": [10, 20], "treat_1": [30, 40]}, index=["GENE1", "GENE2"]+ )+ output = self.root / "out"+ build_counts_matrix.write_outputs(counts, output)+ written = sorted(path.name for path in output.iterdir())+ self.assertTrue(written, "write_outputs produced nothing")+ for name in written:+ with self.subTest(file=name):+ self.assertGreater((output / name).stat().st_size, 0)+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/citation-management/test_scripts.py b/tests/citation-management/test_scripts.pynew file mode 100644index 00000000..81e8b3a7--- /dev/null+++ b/tests/citation-management/test_scripts.py@@ -0,0 +1,348 @@+"""Tests for the citation-management BibTeX tooling.++Two of this skill's scripts reach the network (Crossref, PubMed, Scholar) and+two are pure text processing. The pure half is where citation errors are+actually introduced -- a page range silently rewritten, a DOI left with its URL+prefix so lookups fail, two distinct papers merged because they share a key --+so that is what the suite drives, end to end through real `.bib` files.++The schematic scripts this skill also ships come from the shared contract;+five skills carry byte-identical copies.+"""++from __future__ import annotations++import sys+import tempfile+import unittest+from pathlib import Path++import skill_contract++SKILL_ROOT = Path(__file__).resolve().parents[2] / "skills" / "citation-management"+SCRIPTS = SKILL_ROOT / "scripts"+sys.path.insert(0, str(SCRIPTS))++import format_bibtex # noqa: E402+import validate_citations # noqa: E402++SchematicTests = skill_contract.schematic.schematic_test_case(SKILL_ROOT)++BIBLIOGRAPHY = """\+@article{jumper2021,+ author = {Jumper, John and Evans, Richard},+ title = {Highly accurate protein structure prediction},+ journal = {Nature},+ year = {2021},+ volume = {596},+ pages = {583-589},+ doi = {https://doi.org/10.1038/s41586-021-03819-2}+}++@inproceedings{vaswani2017,+ author = {Vaswani, Ashish; Shazeer, Noam},+ title = {Attention Is All You Need},+ booktitle = {NeurIPS},+ year = {2017},+ pages = {pp. 5998--6008}+}+"""+++class BibTeXTestCase(unittest.TestCase):+ def setUp(self) -> None:+ self._temporary = tempfile.TemporaryDirectory()+ self.addCleanup(self._temporary.cleanup)+ self.root = Path(self._temporary.name)+ self.formatter = format_bibtex.BibTeXFormatter()++ def bib(self, text: str = BIBLIOGRAPHY) -> str:+ path = self.root / "refs.bib"+ path.write_text(text, encoding="utf-8")+ return str(path)+++class ParsingTests(BibTeXTestCase):+ def test_entries_are_parsed_with_type_key_and_fields(self) -> None:+ entries = self.formatter.parse_bibtex_file(self.bib())+ self.assertEqual(len(entries), 2)+ self.assertEqual(entries[0]["key"], "jumper2021")+ self.assertEqual(entries[0]["type"], "article")+ self.assertEqual(entries[0]["fields"]["journal"], "Nature")+ self.assertEqual(entries[1]["type"], "inproceedings")++ def test_an_empty_file_parses_to_no_entries(self) -> None:+ self.assertEqual(self.formatter.parse_bibtex_file(self.bib("")), [])++ def test_comments_outside_entries_are_ignored(self) -> None:+ entries = self.formatter.parse_bibtex_file(+ self.bib(+ "% a leading comment\n"+ "@article{a,\n title = {T},\n year = {2020}\n}\n"+ "% a trailing comment\n"+ )+ )+ self.assertEqual(len(entries), 1)+ self.assertEqual(entries[0]["key"], "a")++ def test_an_entry_closed_on_the_same_line_is_not_recognised(self) -> None:+ # The entry pattern anchors on `\n}`, so the closing brace must start a+ # line. Single-line entries are legal BibTeX but are skipped silently --+ # pinned here so the limitation is visible rather than surprising.+ self.assertEqual(+ self.formatter.parse_bibtex_file(+ self.bib("@article{a, title = {T}, year = {2020}}\n")+ ),+ [],+ )++ def test_quoted_field_values_are_read_as_well_as_braced_ones(self) -> None:+ entries = self.formatter.parse_bibtex_file(+ self.bib('@article{a,\n title = "Quoted Title",\n year = {2020}\n}\n')+ )+ self.assertEqual(entries[0]["fields"]["title"], "Quoted Title")++ def test_an_unreadable_file_returns_no_entries_rather_than_raising(self) -> None:+ self.assertEqual(+ self.formatter.parse_bibtex_file(str(self.root / "absent.bib")), []+ )+++class FixTests(BibTeXTestCase):+ def _fixed_fields(self, **fields) -> dict:+ entry = {"key": "k", "type": "article", "fields": fields}+ return self.formatter.fix_common_issues(entry)["fields"]++ def test_a_single_hyphen_page_range_becomes_an_en_dash_range(self) -> None:+ # BibTeX renders `583-589` as a hyphen, not an en dash.+ self.assertEqual(self._fixed_fields(pages="583-589")["pages"], "583--589")++ def test_an_already_correct_range_is_left_alone(self) -> None:+ self.assertEqual(self._fixed_fields(pages="583--589")["pages"], "583--589")++ def test_a_pp_prefix_is_stripped(self) -> None:+ for raw in ("pp. 5998--6008", "PP.5998--6008"):+ with self.subTest(raw=raw):+ self.assertEqual(self._fixed_fields(pages=raw)["pages"], "5998--6008")++ def test_a_doi_loses_its_url_prefix(self) -> None:+ # A DOI stored as a URL fails every downstream Crossref lookup.+ for raw in (+ "https://doi.org/10.1038/x",+ "http://doi.org/10.1038/x",+ "doi:10.1038/x",+ ):+ with self.subTest(raw=raw):+ self.assertEqual(self._fixed_fields(doi=raw)["doi"], "10.1038/x")++ def test_a_bare_doi_is_untouched(self) -> None:+ self.assertEqual(self._fixed_fields(doi="10.1038/x")["doi"], "10.1038/x")++ def test_author_separators_are_normalised_to_and(self) -> None:+ self.assertEqual(+ self._fixed_fields(author="Vaswani, A.; Shazeer, N.")["author"],+ "Vaswani, A. and Shazeer, N.",+ )+ self.assertEqual(+ self._fixed_fields(author="Smith, J. & Jones, K.")["author"],+ "Smith, J. and Jones, K.",+ )++ def test_a_doubled_and_is_collapsed(self) -> None:+ self.assertEqual(+ self._fixed_fields(author="A and and B")["author"], "A and B"+ )++ def test_fixing_does_not_mutate_the_original_entry(self) -> None:+ entry = {"key": "k", "type": "article", "fields": {"pages": "1-2"}}+ self.formatter.fix_common_issues(entry)+ self.assertEqual(entry["fields"]["pages"], "1-2")++ def test_absent_fields_are_not_invented(self) -> None:+ self.assertEqual(self._fixed_fields(title="T"), {"title": "T"})+++class DeduplicationTests(BibTeXTestCase):+ def _entries(self, *specs) -> list:+ return [+ {"key": key, "type": "article", "fields": fields} for key, fields in specs+ ]++ def test_entries_sharing_a_doi_collapse_to_one(self) -> None:+ entries = self._entries(+ ("a2021", {"doi": "10.1/x"}), ("b2021", {"doi": "10.1/x"})+ )+ self.assertEqual(len(self.formatter.deduplicate_entries(entries)), 1)++ def test_entries_sharing_a_citation_key_collapse_to_one(self) -> None:+ entries = self._entries(("same", {"doi": "10.1/a"}), ("same", {"doi": "10.1/b"}))+ self.assertEqual(len(self.formatter.deduplicate_entries(entries)), 1)++ def test_distinct_entries_all_survive(self) -> None:+ entries = self._entries(+ ("a", {"doi": "10.1/a"}), ("b", {"doi": "10.1/b"}), ("c", {})+ )+ self.assertEqual(len(self.formatter.deduplicate_entries(entries)), 3)++ def test_the_first_occurrence_is_kept(self) -> None:+ entries = self._entries(+ ("first", {"doi": "10.1/x", "title": "T1"}),+ ("second", {"doi": "10.1/x", "title": "T2"}),+ )+ kept = self.formatter.deduplicate_entries(entries)+ self.assertEqual(kept[0]["key"], "first")++ def test_entries_without_a_doi_are_deduplicated_by_key_alone(self) -> None:+ entries = self._entries(("a", {}), ("a", {}), ("b", {}))+ self.assertEqual(len(self.formatter.deduplicate_entries(entries)), 2)+++class SortTests(BibTeXTestCase):+ def setUp(self) -> None:+ super().setUp()+ self.entries = [+ {"key": "zeta", "type": "article", "fields": {"year": "2019", "author": "Young, A.", "title": "Beta"}},+ {"key": "alpha", "type": "article", "fields": {"year": "2021", "author": "Adams, B.", "title": "Alpha"}},+ ]++ def test_the_default_sort_is_by_citation_key(self) -> None:+ self.assertEqual(+ [e["key"] for e in self.formatter.sort_entries(self.entries)],+ ["alpha", "zeta"],+ )++ def test_sorting_by_year_author_and_title(self) -> None:+ expected = {+ "year": ["zeta", "alpha"],+ "author": ["alpha", "zeta"],+ "title": ["alpha", "zeta"],+ }+ for field, order in expected.items():+ with self.subTest(sort_by=field):+ self.assertEqual(+ [e["key"] for e in self.formatter.sort_entries(self.entries, field)],+ order,+ )++ def test_descending_reverses_the_order(self) -> None:+ self.assertEqual(+ [e["key"] for e in self.formatter.sort_entries(self.entries, "key", True)],+ ["zeta", "alpha"],+ )++ def test_entries_missing_the_sort_field_go_last(self) -> None:+ entries = self.entries + [{"key": "omega", "type": "article", "fields": {}}]+ ordered = self.formatter.sort_entries(entries, "year")+ self.assertEqual(ordered[-1]["key"], "omega")++ def test_an_unknown_sort_field_falls_back_to_the_key(self) -> None:+ self.assertEqual(+ [e["key"] for e in self.formatter.sort_entries(self.entries, "nonsense")],+ ["alpha", "zeta"],+ )+++class RenderTests(BibTeXTestCase):+ def test_a_formatted_entry_reparses_to_the_same_fields(self) -> None:+ original = self.formatter.parse_bibtex_file(self.bib())[0]+ rendered = self.formatter.format_entry(original)++ path = self.root / "round-trip.bib"+ path.write_text(rendered, encoding="utf-8")+ reparsed = self.formatter.parse_bibtex_file(str(path))[0]++ self.assertEqual(reparsed["key"], original["key"])+ self.assertEqual(reparsed["type"], original["type"])+ self.assertEqual(reparsed["fields"], original["fields"])++ def test_fields_are_emitted_in_the_documented_order(self) -> None:+ entry = {+ "key": "k",+ "type": "article",+ "fields": {"year": "2021", "title": "T", "author": "A"},+ }+ rendered = self.formatter.format_entry(entry)+ self.assertLess(rendered.index("author"), rendered.index("title"))+ self.assertLess(rendered.index("title"), rendered.index("year"))++ def test_braces_are_balanced(self) -> None:+ rendered = self.formatter.format_entry(+ self.formatter.parse_bibtex_file(self.bib())[0]+ )+ self.assertEqual(rendered.count("{"), rendered.count("}"))+++class EndToEndTests(BibTeXTestCase):+ def test_formatting_a_file_applies_every_fix(self) -> None:+ output = self.root / "clean.bib"+ self.formatter.format_file(self.bib(), output=str(output))+ text = output.read_text(encoding="utf-8")++ self.assertIn("583--589", text)+ self.assertIn("10.1038/s41586-021-03819-2", text)+ self.assertNotIn("https://doi.org/", text)+ self.assertNotIn("pp. ", text)+ self.assertIn("Vaswani, Ashish and Shazeer, Noam", text)++ def test_the_result_still_parses(self) -> None:+ output = self.root / "clean.bib"+ self.formatter.format_file(self.bib(), output=str(output))+ self.assertEqual(len(self.formatter.parse_bibtex_file(str(output))), 2)+++class ValidationTests(BibTeXTestCase):+ def setUp(self) -> None:+ super().setUp()+ self.validator = validate_citations.CitationValidator()++ def test_a_complete_article_raises_no_errors(self) -> None:+ entry = {+ "key": "jumper2021",+ "type": "article",+ "fields": {+ "author": "Jumper, John",+ "title": "A title",+ "journal": "Nature",+ "year": "2021",+ },+ }+ errors, _ = self.validator.validate_entry(entry)+ self.assertEqual(errors, [])++ def test_a_missing_required_field_is_reported(self) -> None:+ entry = {+ "key": "incomplete",+ "type": "article",+ "fields": {"title": "A title", "year": "2021"},+ }+ errors, _ = self.validator.validate_entry(entry)+ self.assertTrue(errors)+ self.assertIn("author", " ".join(str(error) for error in errors).lower())++ def test_duplicate_detection_finds_repeated_entries(self) -> None:+ entries = self.formatter.parse_bibtex_file(self.bib(BIBLIOGRAPHY + BIBLIOGRAPHY))+ self.assertTrue(self.validator.detect_duplicates(entries))++ def test_distinct_entries_are_not_reported_as_duplicates(self) -> None:+ entries = self.formatter.parse_bibtex_file(self.bib())+ self.assertEqual(self.validator.detect_duplicates(entries), [])++ def test_manuscript_citation_keys_are_extracted(self) -> None:+ manuscript = self.root / "paper.tex"+ manuscript.write_text(+ "As shown \\cite{jumper2021} and \\citep{vaswani2017,smith2020}.\n",+ encoding="utf-8",+ )+ keys = self.validator.parse_manuscript_citations(str(manuscript))+ self.assertIn("jumper2021", keys)+ self.assertIn("vaswani2017", keys)+ self.assertIn("smith2020", keys)++ def test_a_manuscript_with_no_citations_yields_none(self) -> None:+ manuscript = self.root / "paper.tex"+ manuscript.write_text("No citations here.\n", encoding="utf-8")+ self.assertEqual(self.validator.parse_manuscript_citations(str(manuscript)), [])+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/clinical-decision-support/test_scripts.py b/tests/clinical-decision-support/test_scripts.pyindex 65592966..1e7f610a 100644--- a/tests/clinical-decision-support/test_scripts.py+++ b/tests/clinical-decision-support/test_scripts.py@@ -5,7 +5,6 @@ from __future__ import annotationsimport astimport copyimport json-import reimport sysimport unittestfrom pathlib import Path@@ -26,6 +25,8 @@ import model_biomarker_evaluation # noqa: E402import survival_plan_validator # noqa: E402import validate_cds_artifact # noqa: E402+import skill_contract+def load_asset(filename: str) -> dict:return json.loads((ASSETS / filename).read_text(encoding="utf-8"))@@ -94,28 +95,10 @@ class StaticSafetyTests(unittest.TestCase):with self.assertRaises(_common.InputError):_common.local_input_path("https://example.invalid/data.json")- def test_documented_local_paths_exist(self) -> None:- pattern = re.compile(r"\b(?:assets|references|scripts)/[A-Za-z0-9_.-]+")- documents = [ROOT / "SKILL.md", *sorted((ROOT / "references").glob("*.md"))]- missing: list[str] = []- for document in documents:- for relative in pattern.findall(document.read_text(encoding="utf-8")):- if not (ROOT / relative).is_file():- missing.append(f"{document.name}: {relative}")- self.assertEqual(missing, [])-- def test_no_bytecode_artifacts(self) -> None:- artifacts = [- str(path.relative_to(ROOT))- for path in ROOT.rglob("*")- if path.suffix in {".pyc", ".pyo"}- ]- self.assertEqual(artifacts, [])-def test_skill_is_progressively_disclosed_and_versioned(self) -> None:text = (ROOT / "SKILL.md").read_text(encoding="utf-8")self.assertLess(len(text.splitlines()), 500)- self.assertIn('version: "2.1"', text)+ self.assertRegex(text, r'\n version: "\d+\.\d+"\n')self.assertIn("license: MIT", text)self.assertIn("metadata:\n version:", text)@@ -264,5 +247,10 @@ class PrivacyChecklistTests(unittest.TestCase):self.assertFalse(summary["hipaa_compliance_determined"])+# 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()diff --git a/tests/clinical-reports/test_scripts.py b/tests/clinical-reports/test_scripts.pyindex 2335f342..89404f07 100644--- a/tests/clinical-reports/test_scripts.py+++ b/tests/clinical-reports/test_scripts.py@@ -31,6 +31,8 @@ from terminology_validator import validate_terminology_manifest # noqa: E402from validate_case_report import CARE_ITEMS, validate_case_manifest # noqa: E402from validate_trial_report import E3_SECTIONS, validate_trial_manifest # noqa: E402+import skill_contract+def valid_case_manifest() -> dict:return {@@ -486,5 +488,10 @@ class AssetAndGeneratorTests(unittest.TestCase):self.assertFalse(data["authorization_verified"])+# 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(SKILL_ROOT)+if __name__ == "__main__":unittest.main()diff --git a/tests/conftest.py b/tests/conftest.pyindex ca47f17d..3df1d39b 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -11,10 +11,16 @@ Each skill therefore gets its own process:pytest tests/<skill> # one skillpython tests/run_all.py # every skill, one process each++This module also installs `tests/_contract/` as the importable module+`skill_contract` -- the assertions every skill shares, factored out of the+per-skill suites. See `_install_contract` for why it is loaded by file+location rather than by putting `tests/` on `sys.path`."""from __future__ import annotations+import importlib.utilimport osimport sysfrom pathlib import Path@@ -30,12 +36,46 @@ os.environ["PYTHONDONTWRITEBYTECODE"] = "1"TESTS_DIR = Path(__file__).resolve().parent+def _install_contract() -> None:+ """Make the shared contract importable as `skill_contract`.++ `tests/` must never go on `sys.path`: in prepend/append import mode that+ turns every `tests/<skill>/` directory into an importable namespace+ package, so `tests/simpy/`, `tests/qutip/` and `tests/neurokit2/` would+ shadow the real libraries (see `addopts` in pyproject.toml). Loading the+ package by file location and registering it under a name no skill uses+ gives suites `import skill_contract` without that hazard.+ """+ if "skill_contract" in sys.modules:+ return+ package = TESTS_DIR / "_contract"+ spec = importlib.util.spec_from_file_location(+ "skill_contract",+ package / "__init__.py",+ submodule_search_locations=[str(package)],+ )+ module = importlib.util.module_from_spec(spec)+ # Registered before exec_module so the package's own `from . import cli`+ # resolves against the name suites will use.+ sys.modules["skill_contract"] = module+ spec.loader.exec_module(module)+++_install_contract()++def _skill_dirs(config: pytest.Config) -> set[str]:- """Return the names of the skill directories this session would collect."""+ """Return the names of the skill directories this session would collect.++ Underscore-prefixed directories are infrastructure, not skills:+ `_contract/` is a library and `_meta/` runs the repo-wide contract without+ importing any skill code, so neither participates in the one-skill-per-+ process rule.+ """everything = {path.namefor path in TESTS_DIR.iterdir()- if path.is_dir() and not path.name.startswith((".", "__"))+ if path.is_dir() and not path.name.startswith((".", "_"))}selected: set[str] = set()for argument in config.args:diff --git a/tests/deepchem/test_scripts.py b/tests/deepchem/test_scripts.pynew file mode 100644index 00000000..2bd402d1--- /dev/null+++ b/tests/deepchem/test_scripts.py@@ -0,0 +1,448 @@+"""Tests for the DeepChem training scripts.++All three scripts end in a `model.fit(...)` that needs a GPU-scale budget and a+deep-learning backend, so none of them can be run to completion here. What can+be checked is everything that decides *what* gets trained, and that is where+these scripts can go wrong in ways a user only discovers minutes into a run:++* the MoleculeNet table -- `train_on_molnet` resolves a dataset name to+ `dc.molnet.load_<name>` by attribute lookup, so a name with no matching+ loader raises `AttributeError` only after the CLI has accepted it. BACE is+ exactly that case: DeepChem ships `load_bace_classification` and+ `load_bace_regression` but no `load_bace`.+* the model factory -- every `--model` choice must reach a real branch of+ `create_model`, not the fall-through `ValueError`.+* featurizer selection in the transfer-learning script -- ChemBERTa and+ MolFormer consume raw SMILES while GROVER needs graph features, and handing a+ model the wrong representation fails deep inside the fit.+* the fingerprint width, which is declared twice in `predict_solubility.py`:+ once as the regressor's `n_features` and once as the featurizer's `size`. A+ mismatch is a shape error at prediction time, after training has finished.++MoleculeNet loaders are stubbed rather than called, so no test downloads a+benchmark. The custom-CSV path is driven for real on twenty molecules, where the+80/10/10 scaffold split has a known answer.+"""++from __future__ import annotations++import ast+import os+import subprocess+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" / "deepchem"+SCRIPTS = SKILL_ROOT / "scripts"+sys.path.insert(0, str(SCRIPTS))++deepchem = pytest.importorskip("deepchem", reason="deepchem skill needs deepchem")+pytest.importorskip("numpy", reason="deepchem skill needs numpy")++import graph_neural_network # noqa: E402+import predict_solubility # noqa: E402+import transfer_learning # noqa: E402++CliHelpTests = skill_contract.cli.help_test_case(SKILL_ROOT)++#: Published MoleculeNet task types. Delaney (ESOL), FreeSolv and Lipophilicity+#: are regression benchmarks; Tox21, BBBP, BACE and HIV are classification.+PUBLISHED_TASK_TYPES = {+ "tox21": "classification",+ "bbbp": "classification",+ "bace": "classification",+ "hiv": "classification",+ "delaney": "regression",+ "freesolv": "regression",+ "lipo": "regression",+}++#: Tox21 comprises 12 toxicity assays; the other benchmarks here are single-task.+PUBLISHED_TASK_COUNTS = {+ "tox21": 12,+ "bbbp": 1,+ "bace": 1,+ "hiv": 1,+ "delaney": 1,+ "freesolv": 1,+ "lipo": 1,+}++#: Twenty distinct molecules -- enough scaffolds for an 80/10/10 split to give+#: whole numbers, and small enough to featurize in milliseconds.+SAMPLE_SMILES = [+ "CCO", "CCC", "CCCC", "c1ccccc1", "CC(=O)O",+ "CN1C=NC2=C1C(=O)N(C(=O)N2C)C", "CCN", "CCCN", "c1ccncc1", "CC(C)O",+ "CCOC", "CCCl", "CCBr", "c1ccc(O)cc1", "CC(N)=O",+ "CCS", "CC#N", "CCC=O", "c1ccc2ccccc2c1", "CC(C)(C)O",+]+++def parser_choices(module, destination: str) -> list[str]:+ """The choices argparse offers for one option of a script's parser.++ The parsers are built inside `main`, so they cannot be obtained without+ running it; the choice lists are read off the module source instead.+ """+ tree = ast.parse((SCRIPTS / f"{module.__name__}.py").read_text(encoding="utf-8"))+ flag = "--" + destination.replace("_", "-")+ for node in ast.walk(tree):+ if not isinstance(node, ast.Call):+ continue+ if not (node.args and isinstance(node.args[0], ast.Constant)):+ continue+ if node.args[0].value != flag:+ continue+ for keyword in node.keywords:+ if keyword.arg != "choices":+ continue+ source = ast.unparse(keyword.value)+ if source.startswith("list("):+ # `choices=list(SOME_DICT)` or `choices=list(SOME_DICT.keys())`+ name = source[len("list(") : -1].removesuffix(".keys()")+ return list(getattr(module, name))+ return list(ast.literal_eval(keyword.value))+ raise AssertionError(f"{module.__name__} has no {flag} with choices")+++def dotted_name(node: ast.AST) -> str:+ return ast.unparse(node)+++def keyword_constants(source: str, callee: str, keyword: str) -> list[object]:+ """Every constant passed as `keyword` to calls of `callee` in `source`."""+ found = []+ for node in ast.walk(ast.parse(source)):+ if isinstance(node, ast.Call) and dotted_name(node.func) == callee:+ for argument in node.keywords:+ if argument.arg == keyword and isinstance(argument.value, ast.Constant):+ found.append(argument.value.value)+ return found+++def run_script(name: str, *arguments: str, cwd: Path) -> subprocess.CompletedProcess:+ environment = {**os.environ, "PYTHONDONTWRITEBYTECODE": "1", "MPLBACKEND": "Agg"}+ return subprocess.run(+ [sys.executable, str(SCRIPTS / name), *arguments],+ capture_output=True,+ text=True,+ timeout=300,+ env=environment,+ cwd=str(cwd),+ )+++class MolnetCatalogueTests(unittest.TestCase):+ """The dataset table in graph_neural_network.py."""++ def test_every_dataset_name_resolves_to_a_real_molnet_loader(self) -> None:+ # The regression this guards: `getattr(dc.molnet, f"load_{name}")` for a+ # dataset DeepChem exposes only under a suffixed loader name.+ for name in graph_neural_network.MOLNET_DATASETS:+ with self.subTest(dataset=name):+ loader = graph_neural_network.molnet_loader(name)+ self.assertTrue(callable(loader))++ def test_bace_resolves_to_the_classification_loader(self) -> None:+ # DeepChem has no `load_bace`; the table declares BACE a classification+ # benchmark, so the classification loader is the matching one.+ self.assertIs(+ graph_neural_network.molnet_loader("bace"),+ deepchem.molnet.load_bace_classification,+ )+ self.assertFalse(hasattr(deepchem.molnet, "load_bace"))++ def test_the_declared_task_types_match_the_published_benchmarks(self) -> None:+ # The task type selects the metric set (ROC-AUC vs R²) and the model+ # mode, so calling a regression benchmark "classification" produces+ # numbers that look plausible and mean nothing.+ self.assertEqual(+ {+ name: task_type+ for name, (task_type, _) in graph_neural_network.MOLNET_DATASETS.items()+ },+ PUBLISHED_TASK_TYPES,+ )++ def test_the_declared_task_counts_match_the_published_benchmarks(self) -> None:+ self.assertEqual(+ {+ name: count+ for name, (_, count) in graph_neural_network.MOLNET_DATASETS.items()+ },+ PUBLISHED_TASK_COUNTS,+ )++ def test_the_dataset_flag_offers_exactly_the_table(self) -> None:+ self.assertEqual(+ parser_choices(graph_neural_network, "dataset"),+ list(graph_neural_network.MOLNET_DATASETS),+ )++ def test_the_model_flag_offers_exactly_the_model_table(self) -> None:+ self.assertEqual(+ parser_choices(graph_neural_network, "model"),+ list(graph_neural_network.AVAILABLE_MODELS),+ )+++class ModelFactoryTests(unittest.TestCase):+ """`create_model` must cover every `--model` choice."""++ def test_an_unknown_model_is_refused_by_name(self) -> None:+ with self.assertRaisesRegex(ValueError, "Unknown model type: transformer"):+ graph_neural_network.create_model("transformer", 1)++ def test_every_advertised_model_reaches_a_branch(self) -> None:+ # Constructing these needs a torch backend, which the documented install+ # does not always provide, so the assertion is narrower than "it works":+ # whatever happens, it must not be the unknown-model fall-through.+ for name in graph_neural_network.AVAILABLE_MODELS:+ with self.subTest(model=name):+ try:+ graph_neural_network.create_model(name, 1)+ except ValueError as error: # pragma: no cover - backend dependent+ self.fail(f"{name} is advertised but unreachable: {error}")+ except Exception:+ # A missing deep-learning backend is an environment problem,+ # not a wiring problem.+ pass++ def test_every_advertised_model_has_a_human_readable_description(self) -> None:+ # The descriptions are printed as the run banner, so an empty one leaves+ # the log ambiguous about what was trained.+ for name, description in graph_neural_network.AVAILABLE_MODELS.items():+ with self.subTest(model=name):+ self.assertTrue(description.strip())+ self.assertNotEqual(description, name)+++class PretrainedCatalogueTests(unittest.TestCase):+ """The pretrained-model table in transfer_learning.py."""++ def test_the_model_flag_offers_exactly_the_pretrained_table(self) -> None:+ self.assertEqual(+ parser_choices(transfer_learning, "model"),+ list(transfer_learning.PRETRAINED_MODELS),+ )++ def test_each_entry_carries_a_name_and_a_description(self) -> None:+ for key, entry in transfer_learning.PRETRAINED_MODELS.items():+ with self.subTest(model=key):+ self.assertEqual(set(entry), {"name", "description", "model_id"})+ self.assertTrue(entry["name"].strip())+ self.assertTrue(entry["description"].strip())++ def test_the_hub_backed_models_name_a_hugging_face_repository(self) -> None:+ # These strings are passed straight to HuggingFaceModel; a bare model+ # name without the owner prefix cannot be resolved.+ for key in ("chemberta", "molformer"):+ with self.subTest(model=key):+ model_id = transfer_learning.PRETRAINED_MODELS[key]["model_id"]+ self.assertRegex(model_id, r"^[\w.-]+/[\w.-]+$")++ def test_grover_declares_no_hub_id_because_it_loads_itself(self) -> None:+ # GroverModel takes a model_dir, not a hub id; a placeholder string here+ # would be passed to a loader that ignores it.+ self.assertIsNone(transfer_learning.PRETRAINED_MODELS["grover"]["model_id"])++ def test_every_pretrained_model_has_a_fine_tuning_entry_point(self) -> None:+ # main() dispatches on the key; an unhandled one falls through to a+ # "not yet implemented" message after the dataset has been loaded.+ for key in transfer_learning.PRETRAINED_MODELS:+ with self.subTest(model=key):+ self.assertTrue(callable(getattr(transfer_learning, f"train_{key}")))+++class MolnetFeaturizerSelectionTests(unittest.TestCase):+ """`load_molnet_dataset` picks the representation each model can consume."""++ def load(self, dataset: str, model: str, loader: str | None = None) -> dict:+ """Call `load_molnet_dataset` with the real MoleculeNet loader stubbed."""+ captured: dict = {}++ def stub(**keywords):+ captured.update(keywords)+ return (["task"], ("train", "valid", "test"), [])++ with mock.patch.object(deepchem.molnet, loader or f"load_{dataset}", stub):+ transfer_learning.load_molnet_dataset(dataset, model)+ return captured++ def test_smiles_models_get_raw_strings_and_grover_gets_graphs(self) -> None:+ # ChemBERTa and MolFormer tokenise SMILES themselves; GROVER is a graph+ # transformer and cannot read a string.+ self.assertEqual(self.load("bbbp", "chemberta")["featurizer"], "Raw")+ self.assertEqual(self.load("bbbp", "molformer")["featurizer"], "Raw")+ self.assertEqual(self.load("bbbp", "grover")["featurizer"], "GraphConv")++ def test_an_unrecognised_model_falls_back_to_fingerprints(self) -> None:+ self.assertEqual(self.load("bbbp", "random-forest")["featurizer"], "ECFP")++ def test_every_dataset_is_loaded_with_a_scaffold_split(self) -> None:+ # A random split shares scaffolds between train and test and inflates+ # every reported score, so the split must not depend on the model.+ for model in ("chemberta", "grover", "molformer"):+ with self.subTest(model=model):+ self.assertEqual(self.load("delaney", model)["splitter"], "scaffold")++ def test_every_offered_dataset_is_in_the_loader_table(self) -> None:+ # `--dataset` and the dict inside load_molnet_dataset are written out+ # separately, so a name in one and not the other is a live failure --+ # the CLI accepts the run and it dies on "Unknown dataset".+ loaders = (+ "load_tox21",+ "load_bbbp",+ "load_bace_classification",+ "load_hiv",+ "load_delaney",+ "load_freesolv",+ "load_lipo",+ )++ def stub(**keywords):+ return (["task"], ("train", "valid", "test"), [])++ with mock.patch.multiple(+ deepchem.molnet, **{name: stub for name in loaders}+ ):+ for name in parser_choices(transfer_learning, "dataset"):+ with self.subTest(dataset=name):+ tasks, datasets, _ = transfer_learning.load_molnet_dataset(+ name, "chemberta"+ )+ self.assertEqual(len(datasets), 3)+ self.assertEqual(tasks, ["task"])++ def test_an_unknown_dataset_is_refused_before_anything_downloads(self) -> None:+ with self.assertRaisesRegex(ValueError, "Unknown dataset: not-a-benchmark"):+ transfer_learning.load_molnet_dataset("not-a-benchmark", "chemberta")+++class CustomDatasetTests(unittest.TestCase):+ """`load_custom_dataset` on a real CSV, where the split sizes are known."""++ def setUp(self) -> None:+ self._temporary = tempfile.TemporaryDirectory()+ self.addCleanup(self._temporary.cleanup)+ self.root = Path(self._temporary.name)+ self.csv = self.root / "molecules.csv"+ rows = "\n".join(+ f"{smiles},{index % 2}" for index, smiles in enumerate(SAMPLE_SMILES)+ )+ self.csv.write_text(f"smiles,target\n{rows}\n", encoding="utf-8")++ def test_the_split_is_eighty_ten_ten(self) -> None:+ train, valid, test = transfer_learning.load_custom_dataset(+ str(self.csv), ["target"], "smiles", "chemberta"+ )+ self.assertEqual((len(train), len(valid), len(test)), (16, 2, 2))+ # Nothing is lost or duplicated by the split.+ self.assertEqual(len(train) + len(valid) + len(test), len(SAMPLE_SMILES))++ def test_a_smiles_model_keeps_the_strings_unfeaturized(self) -> None:+ # DummyFeaturizer is deliberate: the tokenizer inside the model does the+ # featurizing, so turning the SMILES into a fingerprint here would+ # destroy the input it needs.+ train, _, _ = transfer_learning.load_custom_dataset(+ str(self.csv), ["target"], "smiles", "chemberta"+ )+ self.assertEqual(train.X[0], "CCO")++ def test_a_fingerprint_model_gets_a_2048_bit_vector(self) -> None:+ train, _, _ = transfer_learning.load_custom_dataset(+ str(self.csv), ["target"], "smiles", "random-forest"+ )+ # CircularFingerprint's documented default width.+ self.assertEqual(train.X.shape, (16, 2048))++ def test_the_named_smiles_column_is_the_one_featurized(self) -> None:+ path = self.root / "renamed.csv"+ rows = "\n".join(+ f"{index % 2},{smiles}" for index, smiles in enumerate(SAMPLE_SMILES)+ )+ path.write_text(f"target,structure\n{rows}\n", encoding="utf-8")+ train, _, _ = transfer_learning.load_custom_dataset(+ str(path), ["target"], "structure", "chemberta"+ )+ self.assertEqual(train.X[0], "CCO")+++class SolubilityScriptTests(unittest.TestCase):+ """Static consistency in predict_solubility.py."""++ def test_the_fingerprint_width_matches_the_regressor_input_size(self) -> None:+ # `n_features` is fixed when the model is built and `size` when new+ # molecules are featurized. A mismatch is a shape error at predict+ # time -- after the training run has already been paid for.+ source = (SCRIPTS / "predict_solubility.py").read_text(encoding="utf-8")+ declared = keyword_constants(source, "dc.models.MultitaskRegressor", "n_features")+ featurized = keyword_constants(source, "dc.feat.CircularFingerprint", "size")+ self.assertEqual(len(set(declared)), 1, declared)+ self.assertEqual(set(declared), set(featurized))++ def test_the_fingerprint_radius_is_the_same_everywhere(self) -> None:+ # Training on ECFP4 and predicting with ECFP6 silently produces garbage+ # rather than an error, because the vector width is unchanged.+ source = (SCRIPTS / "predict_solubility.py").read_text(encoding="utf-8")+ radii = keyword_constants(source, "dc.feat.CircularFingerprint", "radius")+ self.assertEqual(len(set(radii)), 1, radii)++ def test_the_default_target_column_is_the_delaney_column_name(self) -> None:+ # The function's default has to match the column in the published+ # Delaney (ESOL) CSV, or the benchmark path finds no target.+ import inspect++ default = inspect.signature(+ predict_solubility.train_solubility_model+ ).parameters["target_col"].default+ self.assertEqual(default, "measured log solubility in mols per litre")+++class ArgumentValidationTests(unittest.TestCase):+ """Both scripts refuse an ambiguous invocation before loading anything."""++ def setUp(self) -> None:+ self._temporary = tempfile.TemporaryDirectory()+ self.addCleanup(self._temporary.cleanup)+ self.root = Path(self._temporary.name)++ def test_a_gnn_run_needs_a_dataset_or_a_csv(self) -> None:+ result = run_script("graph_neural_network.py", cwd=self.root)+ self.assertEqual(result.returncode, 1)+ self.assertIn("Must specify either", result.stderr)++ def test_a_gnn_run_refuses_both_a_dataset_and_a_csv(self) -> None:+ # Silently preferring one would train on data the user did not ask for.+ result = run_script(+ "graph_neural_network.py", "--dataset", "bbbp", "--data", "custom.csv",+ cwd=self.root,+ )+ self.assertEqual(result.returncode, 1)+ self.assertIn("Cannot specify both", result.stderr)++ def test_transfer_learning_requires_a_pretrained_model(self) -> None:+ result = run_script("transfer_learning.py", "--dataset", "bbbp", cwd=self.root)+ # argparse's own exit code for a missing required option.+ self.assertEqual(result.returncode, 2)+ self.assertIn("--model", result.stderr)++ def test_transfer_learning_refuses_both_input_sources(self) -> None:+ result = run_script(+ "transfer_learning.py", "--model", "chemberta",+ "--dataset", "bbbp", "--data", "custom.csv",+ cwd=self.root,+ )+ self.assertEqual(result.returncode, 1)+ self.assertIn("Cannot specify both", result.stderr)+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/deeptools/test_scripts.py b/tests/deeptools/test_scripts.pynew file mode 100644index 00000000..557a66e0--- /dev/null+++ b/tests/deeptools/test_scripts.py@@ -0,0 +1,319 @@+"""Tests for the deepTools helper scripts.++`workflow_generator` writes bash that a user is expected to run, so its input+sanitising is the security boundary of this skill: every path that reaches a+generated script passes `sanitize_path`, and every interpolation goes through+`shlex.quote`. Those tests come first, and the generated scripts are checked+with `bash -n` so a template that stops parsing cannot ship.++`validate_files` inspects real files, so the tests build genuine BED fixtures+in a temporary directory rather than mocking `open`.+"""++from __future__ import annotations++import subprocess+import sys+import tempfile+import unittest+from pathlib import Path++import skill_contract++SKILL_ROOT = Path(__file__).resolve().parents[2] / "skills" / "deeptools"+SCRIPTS = SKILL_ROOT / "scripts"+sys.path.insert(0, str(SCRIPTS))++import validate_files # noqa: E402+import workflow_generator # noqa: E402++CliHelpTests = skill_contract.cli.help_test_case(SKILL_ROOT)++# Every generator's required parameters, so the templates can be driven+# uniformly and a new workflow shows up here as a KeyError rather than silently+# going untested.+WORKFLOW_PARAMS = {+ "chipseq_qc": {+ "input_bam": "data/input.bam",+ "chip_bams": ["data/chip1.bam", "data/chip2.bam"],+ "output_dir": "results/qc",+ },+ "chipseq_analysis": {+ "input_bam": "data/input.bam",+ "chip_bam": "data/chip.bam",+ "genes_bed": "annotation/genes.bed",+ "peaks_bed": "peaks/macs2.bed",+ "output_dir": "results/analysis",+ },+ "rnaseq_coverage": {+ "rnaseq_bam": "data/rnaseq.bam",+ "output_dir": "results/coverage",+ },+ "atacseq": {+ "atac_bam": "data/atac.bam",+ "peaks_bed": "peaks/atac.bed",+ "output_dir": "results/atac",+ },+}++GENERATORS = {+ "chipseq_qc": workflow_generator.generate_chipseq_qc_workflow,+ "chipseq_analysis": workflow_generator.generate_chipseq_analysis_workflow,+ "rnaseq_coverage": workflow_generator.generate_rnaseq_coverage_workflow,+ "atacseq": workflow_generator.generate_atacseq_workflow,+}+++class PathSanitisingTests(unittest.TestCase):+ def test_ordinary_paths_pass_through_unchanged(self) -> None:+ for path in ("sample.bam", "data/sub-01_run-1.bam", "./x.bed", "a-b_c.2.bw"):+ with self.subTest(path=path):+ self.assertEqual(+ workflow_generator.sanitize_path(path, "default", "--bam"), path+ )++ def test_empty_and_none_fall_back_to_the_default(self) -> None:+ for value in (None, ""):+ with self.subTest(value=value):+ self.assertEqual(+ workflow_generator.sanitize_path(value, "fallback.bam", "--bam"),+ "fallback.bam",+ )++ def test_shell_metacharacters_are_refused(self) -> None:+ injections = (+ "sample.bam; rm -rf /",+ "$(whoami).bam",+ "`id`.bam",+ "a|b.bam",+ "file name.bam",+ "x.bam\nrm -rf /",+ "~/secret.bam",+ "a&b.bam",+ "x>out.bam",+ )+ for value in injections:+ with self.subTest(value=value):+ with self.assertRaisesRegex(ValueError, "unsupported characters"):+ workflow_generator.sanitize_path(value, "d", "--bam")++ def test_parent_directory_segments_are_refused(self) -> None:+ for value in ("../escape.bam", "data/../../etc/passwd", "..", "a/../b"):+ with self.subTest(value=value):+ with self.assertRaisesRegex(ValueError, r"'\.\.' path segments"):+ workflow_generator.sanitize_path(value, "d", "--bam")++ def test_a_dotdot_substring_inside_a_name_is_allowed(self) -> None:+ # Only whole segments are parent references; `a..b.bam` is a filename.+ self.assertEqual(+ workflow_generator.sanitize_path("a..b.bam", "d", "--bam"), "a..b.bam"+ )+++class PathListTests(unittest.TestCase):+ def test_space_separated_values_are_split_and_validated(self) -> None:+ self.assertEqual(+ workflow_generator.sanitize_path_list("a.bam b.bam", [], "--chip"),+ ["a.bam", "b.bam"],+ )++ def test_an_empty_list_is_refused(self) -> None:+ with self.assertRaisesRegex(ValueError, "at least one file path"):+ workflow_generator.sanitize_path_list(None, [], "--chip")++ def test_one_bad_entry_rejects_the_whole_list(self) -> None:+ with self.assertRaisesRegex(ValueError, "unsupported characters"):+ workflow_generator.sanitize_path_list("good.bam bad;rm.bam", [], "--chip")++ def test_quoting_cannot_smuggle_a_space_into_a_single_path(self) -> None:+ # shlex.split honours the quotes, but sanitize_path then rejects the+ # space -- the two layers have to agree, not just the first.+ with self.assertRaisesRegex(ValueError, "unsupported characters"):+ workflow_generator.sanitize_path_list("'my file.bam'", [], "--chip")+++class PositiveIntTests(unittest.TestCase):+ def test_integers_and_integer_strings_are_accepted(self) -> None:+ self.assertEqual(workflow_generator.sanitize_positive_int(8, "--threads"), 8)+ self.assertEqual(workflow_generator.sanitize_positive_int("16", "--threads"), 16)++ def test_zero_negative_and_non_numeric_are_refused(self) -> None:+ with self.assertRaisesRegex(ValueError, ">= 1"):+ workflow_generator.sanitize_positive_int(0, "--threads")+ with self.assertRaisesRegex(ValueError, ">= 1"):+ workflow_generator.sanitize_positive_int(-4, "--threads")+ for value in ("eight", None, "8.5"):+ with self.subTest(value=value):+ with self.assertRaisesRegex(ValueError, "must be an integer"):+ workflow_generator.sanitize_positive_int(value, "--threads")+++class ShellQuotingTests(unittest.TestCase):+ def test_values_are_quoted_for_bash(self) -> None:+ self.assertEqual(workflow_generator.shell_literal("plain.bam"), "plain.bam")+ self.assertIn("'", workflow_generator.shell_literal("has space.bam"))++ def test_arrays_quote_each_element(self) -> None:+ rendered = workflow_generator.shell_array(["a.bam", "b c.bam"])+ self.assertEqual(rendered.split()[0], "a.bam")+ self.assertIn("'b c.bam'", rendered)++ def test_relative_run_hints_are_prefixed_so_bash_finds_them(self) -> None:+ self.assertEqual(+ workflow_generator.runnable_script_path("run.sh"), "./run.sh"+ )+ self.assertEqual(+ workflow_generator.runnable_script_path("/tmp/run.sh"), "/tmp/run.sh"+ )+++class GeneratedScriptTests(unittest.TestCase):+ """Every generated workflow is valid bash and carries safe defaults."""++ def _generate(self, workflow: str) -> str:+ with tempfile.TemporaryDirectory() as directory:+ output = Path(directory) / "workflow.sh"+ GENERATORS[workflow](str(output), WORKFLOW_PARAMS[workflow])+ return output.read_text(encoding="utf-8")++ def test_every_advertised_workflow_has_a_generator(self) -> None:+ self.assertEqual(set(workflow_generator.WORKFLOWS), set(GENERATORS))++ def test_generated_scripts_parse_as_bash(self) -> None:+ for workflow in GENERATORS:+ with self.subTest(workflow=workflow):+ script = self._generate(workflow)+ with tempfile.TemporaryDirectory() as directory:+ path = Path(directory) / "generated.sh"+ path.write_text(script, encoding="utf-8")+ result = subprocess.run(+ ["bash", "-n", str(path)],+ capture_output=True,+ text=True,+ timeout=30,+ )+ self.assertEqual(result.returncode, 0, result.stderr)++ def test_generated_scripts_fail_fast(self) -> None:+ for workflow in GENERATORS:+ with self.subTest(workflow=workflow):+ script = self._generate(workflow)+ self.assertTrue(script.startswith("#!/bin/bash"))+ self.assertIn("set -euo pipefail", script)++ def test_parameters_reach_the_script_quoted(self) -> None:+ script = self._generate("chipseq_qc")+ self.assertIn("data/input.bam", script)+ self.assertIn("data/chip1.bam", script)+ self.assertIn("data/chip2.bam", script)+ self.assertIn("results/qc", script)+++class FileValidationTests(unittest.TestCase):+ def test_missing_file_is_reported_not_raised(self) -> None:+ ok, message = validate_files.check_file_exists("/no/such/file.bam")+ self.assertFalse(ok)+ self.assertIn("File not found", message)++ def test_bam_index_is_found_under_either_naming_convention(self) -> None:+ with tempfile.TemporaryDirectory() as directory:+ root = Path(directory)+ bam = root / "sample.bam"+ bam.write_bytes(b"BAM\1")++ ok, message = validate_files.check_bam_index(str(bam))+ self.assertFalse(ok)+ self.assertIn("samtools index", message)++ # sample.bam.bai+ (root / "sample.bam.bai").write_bytes(b"BAI\1")+ ok, _ = validate_files.check_bam_index(str(bam))+ self.assertTrue(ok)++ (root / "sample.bam.bai").unlink()+ # sample.bai+ (root / "sample.bai").write_bytes(b"BAI\1")+ ok, _ = validate_files.check_bam_index(str(bam))+ self.assertTrue(ok)++ def test_tiny_bigwig_is_flagged_as_suspicious(self) -> None:+ with tempfile.TemporaryDirectory() as directory:+ small = Path(directory) / "small.bw"+ small.write_bytes(b"x" * 10)+ ok, message = validate_files.check_bigwig_file(str(small))+ self.assertFalse(ok)+ self.assertIn("suspiciously small", message)++ big = Path(directory) / "big.bw"+ big.write_bytes(b"x" * 1024)+ ok, _ = validate_files.check_bigwig_file(str(big))+ self.assertTrue(ok)++ def test_well_formed_bed_passes_and_counts_regions(self) -> None:+ with tempfile.TemporaryDirectory() as directory:+ bed = Path(directory) / "peaks.bed"+ bed.write_text(+ "# a comment\n"+ "chr1\t100\t200\tpeak1\n"+ "chr1\t300\t400\tpeak2\n"+ "\n",+ encoding="utf-8",+ )+ ok, message = validate_files.check_bed_file(str(bed))+ self.assertTrue(ok, message)+ self.assertIn("2 regions", message)++ def test_bed_rejects_too_few_columns_bad_types_and_inverted_ranges(self) -> None:+ cases = {+ "chr1\t100\n": "at least 3 columns",+ "chr1\tstart\tend\n": "must be integers",+ "chr1\t500\t100\n": "start >= end",+ "chr1\t100\t100\n": "start >= end",+ }+ with tempfile.TemporaryDirectory() as directory:+ for index, (content, expected) in enumerate(cases.items()):+ with self.subTest(content=content.strip()):+ bed = Path(directory) / f"bad{index}.bed"+ bed.write_text(content, encoding="utf-8")+ ok, message = validate_files.check_bed_file(str(bed))+ self.assertFalse(ok)+ self.assertIn(expected, message)++ def test_comment_only_bed_is_treated_as_empty(self) -> None:+ with tempfile.TemporaryDirectory() as directory:+ bed = Path(directory) / "comments.bed"+ bed.write_text("# header\n\n# more\n", encoding="utf-8")+ ok, message = validate_files.check_bed_file(str(bed))+ self.assertFalse(ok)+ self.assertIn("empty", message)++ def test_validate_files_aggregates_across_types(self) -> None:+ with tempfile.TemporaryDirectory() as directory:+ root = Path(directory)+ bam = root / "s.bam"+ bam.write_bytes(b"BAM\1")+ (root / "s.bam.bai").write_bytes(b"BAI\1")+ bed = root / "p.bed"+ bed.write_text("chr1\t1\t2\n", encoding="utf-8")++ ok, messages = validate_files.validate_files(+ bam_files=[str(bam)], bed_files=[str(bed)]+ )+ self.assertTrue(ok, messages)+ self.assertTrue(any("BAM Files" in line for line in messages))+ self.assertTrue(any("BED Files" in line for line in messages))++ # One bad file fails the whole run.+ ok, _ = validate_files.validate_files(+ bam_files=[str(bam), "/no/such.bam"], bed_files=[str(bed)]+ )+ self.assertFalse(ok)++ def test_no_files_means_nothing_to_report(self) -> None:+ ok, messages = validate_files.validate_files()+ self.assertTrue(ok)+ self.assertEqual(messages, [])+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/diffdock/test_scripts.py b/tests/diffdock/test_scripts.pynew file mode 100644index 00000000..fb4b6171--- /dev/null+++ b/tests/diffdock/test_scripts.py@@ -0,0 +1,657 @@+"""Tests for the DiffDock helper scripts.++Docking itself needs a GPU, the upstream repository, and downloaded+checkpoints, so nothing here runs inference. What these scripts do around a run+is what the tests cover, and each group guards a specific way the surrounding+work goes wrong:++* `analyze_results` turns a directory of pose files into a ranked table. Get the+ confidence bands wrong and a low-confidence pose is reported as trustworthy;+ parse `rank10_...sdf` before `rank2_...sdf` and the "top" pose is not the top+ one. The published bands (> 0 high, -1.5 to 0 moderate, < -1.5 low, from+ DiffDock's README and `references/confidence_and_limitations.md`) are asserted+ literally, including their boundaries.+* `prepare_batch_csv` is a validator, so both directions matter: a usable CSV+ must pass silently, and each malformed row must be named. A CSV missing a+ required column used to raise KeyError instead of reporting it.+* `setup_check` only reports; the tests stub the interpreter, the import+ machinery, and the working directory so its verdicts are checked against a+ known environment rather than this machine's.+"""++from __future__ import annotations++import contextlib+import csv+import io+import os+import sys+import tempfile+import types+import unittest+from pathlib import Path+from unittest import mock++import pytest++import skill_contract++SKILL_ROOT = Path(__file__).resolve().parents[2] / "skills" / "diffdock"+SCRIPTS = SKILL_ROOT / "scripts"+sys.path.insert(0, str(SCRIPTS))++# Only prepare_batch_csv needs a third-party package; the other two scripts are+# standard library, but a module-scope skip keeps the guard in one place.+pytest.importorskip("pandas", reason="diffdock's prepare_batch_csv needs pandas")++import analyze_results # noqa: E402+import prepare_batch_csv # noqa: E402+import setup_check # noqa: E402++CliHelpTests = skill_contract.cli.help_test_case(SKILL_ROOT)++#: Aspirin, the SMILES the bundled template ships as its first example.+ASPIRIN = "CC(=O)Oc1ccccc1C(=O)O"+++def quietly(function, *args, **kwargs):+ """Call `function`, returning (result, everything it printed)."""+ stream = io.StringIO()+ with contextlib.redirect_stdout(stream):+ result = function(*args, **kwargs)+ return result, stream.getvalue()+++class TemporaryDirectoryTestCase(unittest.TestCase):+ def setUp(self) -> None:+ self._temporary = tempfile.TemporaryDirectory()+ self.addCleanup(self._temporary.cleanup)+ self.root = Path(self._temporary.name)+++class ConfidenceClassificationTests(unittest.TestCase):+ """The bands come from DiffDock upstream, so they are asserted literally."""++ def test_the_three_published_bands(self) -> None:+ self.assertEqual(analyze_results.classify_confidence(1.2), "High")+ self.assertEqual(analyze_results.classify_confidence(-0.7), "Moderate")+ self.assertEqual(analyze_results.classify_confidence(-3.0), "Low")++ def test_the_band_boundaries_fall_on_the_documented_side(self) -> None:+ # Exactly 0 is not "High" -- the high band is strictly above zero -- and+ # exactly -1.5 is "Low", so the moderate band is (-1.5, 0].+ self.assertEqual(analyze_results.classify_confidence(0.0), "Moderate")+ self.assertEqual(analyze_results.classify_confidence(-1.5), "Low")+ self.assertEqual(analyze_results.classify_confidence(-1.4999), "Moderate")++ def test_a_missing_score_is_unknown_rather_than_low(self) -> None:+ # A pose whose score could not be parsed must not be reported as bad.+ self.assertEqual(analyze_results.classify_confidence(None), "Unknown")+++class ConfidenceExtractionTests(TemporaryDirectoryTestCase):+ def test_the_score_is_read_from_the_current_filename_format(self) -> None:+ path = self.root / "rank1_confidence0.87.sdf"+ path.write_text("")+ self.assertEqual(+ analyze_results.extract_confidence_score(path, self.root), 0.87+ )++ def test_a_negative_score_keeps_its_sign(self) -> None:+ # Most real poses score below zero; dropping the minus sign would turn+ # every low-confidence pose into a high-confidence one.+ path = self.root / "rank3_confidence-2.35.sdf"+ path.write_text("")+ self.assertEqual(+ analyze_results.extract_confidence_score(path, self.root), -2.35+ )++ def test_a_legacy_run_falls_back_to_confidence_scores_txt(self) -> None:+ # Older DiffDock wrote rank_1.sdf plus one score per line, in rank order.+ (self.root / "confidence_scores.txt").write_text("0.5\n-0.25\n-2.0\n")+ path = self.root / "rank_2.sdf"+ path.write_text("")+ self.assertEqual(+ analyze_results.extract_confidence_score(path, self.root), -0.25+ )++ def test_a_rank_past_the_end_of_the_legacy_file_is_not_invented(self) -> None:+ (self.root / "confidence_scores.txt").write_text("0.5\n")+ path = self.root / "rank_4.sdf"+ path.write_text("")+ self.assertIsNone(analyze_results.extract_confidence_score(path, self.root))++ def test_an_sdf_data_item_is_the_last_resort(self) -> None:+ # The SDF data-item spelling: a `> <tag>` line, then the value.+ path = self.root / "rank_1.sdf"+ path.write_text(" 1 0 0\nM END\n> <confidence>\n-1.75\n\n$$$$\n")+ self.assertEqual(+ analyze_results.extract_confidence_score(path, self.root), -1.75+ )++ def test_an_inline_confidence_property_is_also_read(self) -> None:+ path = self.root / "rank_1.sdf"+ path.write_text("M END\nconfidence: 0.31\n$$$$\n")+ self.assertEqual(+ analyze_results.extract_confidence_score(path, self.root), 0.31+ )++ def test_a_file_with_no_score_anywhere_yields_none(self) -> None:+ path = self.root / "rank_1.sdf"+ path.write_text("no properties here\n")+ self.assertIsNone(analyze_results.extract_confidence_score(path, self.root))+++class ComplexParsingTests(TemporaryDirectoryTestCase):+ @staticmethod+ def write(directory: Path, *names: str) -> None:+ directory.mkdir(parents=True, exist_ok=True)+ for name in names:+ (directory / name).write_text("")++ def test_ranks_are_ordered_numerically_not_lexicographically(self) -> None:+ # "rank10" sorts before "rank2" as text; the top pose would be wrong.+ self.write(+ self.root,+ "rank1_confidence0.90.sdf",+ "rank2_confidence0.10.sdf",+ "rank10_confidence-2.00.sdf",+ )+ parsed = analyze_results.parse_single_complex(self.root)+ self.assertEqual([p["rank"] for p in parsed["predictions"]], [1, 2, 10])++ def test_the_scored_filename_wins_over_the_bare_one_for_the_same_rank(self) -> None:+ # A run can leave both spellings behind; keeping the unscored one would+ # silently drop the confidence for that rank.+ self.write(self.root, "rank_1.sdf", "rank1_confidence0.42.sdf")+ parsed = analyze_results.parse_single_complex(self.root)+ self.assertEqual(len(parsed["predictions"]), 1)+ self.assertEqual(parsed["predictions"][0]["confidence"], 0.42)++ def test_a_directory_without_pose_files_parses_to_nothing(self) -> None:+ self.write(self.root, "log.txt")+ self.assertIsNone(analyze_results.parse_single_complex(self.root))++ def test_a_single_complex_directory_is_reported_under_one_key(self) -> None:+ self.write(self.root, "rank1_confidence0.5.sdf")+ results = analyze_results.parse_confidence_scores(self.root)+ self.assertEqual(list(results), ["single_complex"])++ def test_a_batch_directory_is_keyed_by_subdirectory_name(self) -> None:+ self.write(self.root / "complex_a", "rank1_confidence0.5.sdf")+ self.write(self.root / "complex_b", "rank1_confidence-1.0.sdf")+ self.write(self.root / "failed_run", "log.txt")+ results = analyze_results.parse_confidence_scores(self.root)+ # The subdirectory with no poses is omitted rather than listed empty.+ self.assertEqual(sorted(results), ["complex_a", "complex_b"])+++class TopPredictionTests(unittest.TestCase):+ @staticmethod+ def results(*entries):+ """Build the {complex: {'predictions': [...]}} shape the parsers return."""+ built = {}+ for name, predictions in entries:+ built[name] = {+ "predictions": [+ {"rank": rank, "file": f"rank{rank}.sdf", "path": f"{name}/rank{rank}.sdf",+ "confidence": confidence}+ for rank, confidence in predictions+ ]+ }+ return built++ def test_the_best_poses_are_ranked_across_every_complex(self) -> None:+ results = self.results(+ ("a", [(1, -0.5), (2, -2.0)]),+ ("b", [(1, 0.9), (2, 0.2)]),+ )+ top = analyze_results.get_top_predictions(results, n=3)+ self.assertEqual(+ [(entry["complex"], entry["confidence"]) for entry in top],+ [("b", 0.9), ("b", 0.2), ("a", -0.5)],+ )++ def test_unscored_poses_are_excluded_rather_than_sorted_as_zero(self) -> None:+ results = self.results(("a", [(1, None), (2, -1.0)]))+ top = analyze_results.get_top_predictions(results, n=10)+ self.assertEqual([entry["rank"] for entry in top], [2])++ def test_asking_for_more_than_exists_returns_what_exists(self) -> None:+ results = self.results(("a", [(1, 0.5)]))+ self.assertEqual(len(analyze_results.get_top_predictions(results, n=50)), 1)+++class CsvExportTests(TemporaryDirectoryTestCase):+ def test_every_pose_becomes_one_row_with_its_band(self) -> None:+ results = {+ "kinase_1": {+ "predictions": [+ {"rank": 1, "file": "r1.sdf", "path": "/x/r1.sdf", "confidence": 0.8},+ {"rank": 2, "file": "r2.sdf", "path": "/x/r2.sdf", "confidence": -2.5},+ {"rank": 3, "file": "r3.sdf", "path": "/x/r3.sdf", "confidence": None},+ ]+ }+ }+ destination = self.root / "summary.csv"+ quietly(analyze_results.export_to_csv, results, destination)++ with destination.open(newline="") as handle:+ rows = list(csv.DictReader(handle))+ self.assertEqual(+ [row["confidence_class"] for row in rows], ["High", "Low", "Unknown"]+ )+ # An unscored pose must leave the numeric column empty, not write "None",+ # which would parse as a string and break any downstream aggregation.+ self.assertEqual(rows[2]["confidence"], "")+ self.assertEqual(rows[0]["complex_name"], "kinase_1")+ self.assertEqual(rows[0]["file_path"], "/x/r1.sdf")+++class SummaryFilterTests(unittest.TestCase):+ RESULTS = {+ "a": {+ "predictions": [+ {"rank": 1, "file": "r1.sdf", "path": "a/r1.sdf", "confidence": 0.5},+ {"rank": 2, "file": "r2.sdf", "path": "a/r2.sdf", "confidence": -1.0},+ {"rank": 3, "file": "r3.sdf", "path": "a/r3.sdf", "confidence": None},+ ]+ }+ }++ def test_without_a_threshold_every_pose_is_listed(self) -> None:+ _, output = quietly(analyze_results.print_summary, self.RESULTS)+ for rank in ("Rank 1", "Rank 2", "Rank 3"):+ self.assertIn(rank, output)++ def test_a_threshold_keeps_the_poses_at_or_above_it(self) -> None:+ # Inclusive at the boundary: -1.0 survives a threshold of -1.0.+ _, output = quietly(+ analyze_results.print_summary, self.RESULTS, None, -1.0+ )+ self.assertIn("Rank 1", output)+ self.assertIn("Rank 2", output)++ def test_a_threshold_drops_lower_and_unscored_poses(self) -> None:+ _, output = quietly(analyze_results.print_summary, self.RESULTS, None, 0.0)+ self.assertIn("Rank 1", output)+ self.assertNotIn("Rank 2", output)+ # An unscored pose cannot be shown to clear a threshold.+ self.assertNotIn("Rank 3", output)++ def test_top_n_truncates_the_listing(self) -> None:+ _, output = quietly(analyze_results.print_summary, self.RESULTS, 1)+ self.assertIn("Rank 1", output)+ self.assertNotIn("Rank 2", output)++ def test_an_empty_complex_is_reported_rather_than_skipped(self) -> None:+ _, output = quietly(analyze_results.print_summary, {"a": {"predictions": []}})+ self.assertIn("No predictions found", output)+++class SmilesValidationTests(unittest.TestCase):+ def setUp(self) -> None:+ if not prepare_batch_csv.RDKIT_AVAILABLE:+ self.skipTest("RDKit is not installed; SMILES validation is a no-op")++ def test_a_real_drug_smiles_is_accepted(self) -> None:+ valid, message = prepare_batch_csv.validate_smiles(ASPIRIN)+ self.assertTrue(valid, message)++ def test_a_malformed_smiles_is_rejected(self) -> None:+ # An unclosed ring bond: RDKit returns None rather than raising.+ valid, message = prepare_batch_csv.validate_smiles("C1CCCC")+ self.assertFalse(valid)+ self.assertIn("Invalid SMILES", message)++ def test_an_impossible_valence_is_rejected(self) -> None:+ valid, _ = prepare_batch_csv.validate_smiles("C(C)(C)(C)(C)C")+ self.assertFalse(valid)+++class FilePathValidationTests(TemporaryDirectoryTestCase):+ def test_an_existing_file_passes(self) -> None:+ (self.root / "protein.pdb").write_text("")+ valid, _ = prepare_batch_csv.validate_file_path("protein.pdb", self.root)+ self.assertTrue(valid)++ def test_a_missing_file_is_named_in_the_message(self) -> None:+ valid, message = prepare_batch_csv.validate_file_path("absent.pdb", self.root)+ self.assertFalse(valid)+ self.assertIn("absent.pdb", message)++ def test_a_relative_path_resolves_against_the_base_directory(self) -> None:+ # Without the base directory the same path is looked up in the process+ # working directory, where it does not exist.+ (self.root / "sub").mkdir()+ (self.root / "sub" / "protein.pdb").write_text("")+ self.assertTrue(+ prepare_batch_csv.validate_file_path("sub/protein.pdb", self.root)[0]+ )+ self.assertFalse(prepare_batch_csv.validate_file_path("sub/protein.pdb")[0])++ def test_an_empty_path_is_allowed_because_a_sequence_may_replace_it(self) -> None:+ for value in ("", float("nan")):+ with self.subTest(value=value):+ valid, message = prepare_batch_csv.validate_file_path(value, self.root)+ self.assertTrue(valid)+ self.assertIn("protein_sequence", message)+++class BatchCsvValidationTests(TemporaryDirectoryTestCase):+ HEADER = "complex_name,protein_path,ligand_description,protein_sequence"++ def write_csv(self, *rows: str) -> Path:+ path = self.root / "batch.csv"+ path.write_text("\n".join([self.HEADER, *rows]) + "\n")+ return path++ def test_a_usable_csv_passes_without_complaint(self) -> None:+ (self.root / "protein.pdb").write_text("")+ path = self.write_csv(f"target_1,protein.pdb,{ASPIRIN},")+ valid, messages = prepare_batch_csv.validate_csv(path)+ self.assertTrue(valid, "\n".join(messages))+ joined = "\n".join(messages)+ self.assertIn("All required columns present", joined)+ self.assertIn("PASSED", joined)+ # A clean CSV must not accumulate per-row complaints.+ self.assertNotIn("Row 1", joined)++ def test_a_sequence_only_row_needs_no_protein_file(self) -> None:+ path = self.write_csv(f"target_1,,{ASPIRIN},MSKGEELFTG")+ valid, messages = prepare_batch_csv.validate_csv(path)+ self.assertTrue(valid, "\n".join(messages))++ def test_a_row_with_neither_protein_input_is_rejected(self) -> None:+ path = self.write_csv(f"target_1,,{ASPIRIN},")+ valid, messages = prepare_batch_csv.validate_csv(path)+ self.assertFalse(valid)+ self.assertIn("Must provide either protein_path or protein_sequence",+ "\n".join(messages))++ def test_a_missing_complex_name_is_reported(self) -> None:+ path = self.write_csv(f",protein.pdb,{ASPIRIN},")+ (self.root / "protein.pdb").write_text("")+ valid, messages = prepare_batch_csv.validate_csv(path)+ self.assertFalse(valid)+ self.assertIn("Missing complex_name", "\n".join(messages))++ def test_a_missing_protein_file_is_reported_with_its_row(self) -> None:+ path = self.write_csv(f"target_1,gone.pdb,{ASPIRIN},")+ valid, messages = prepare_batch_csv.validate_csv(path)+ self.assertFalse(valid)+ joined = "\n".join(messages)+ self.assertIn("Row 1", joined)+ self.assertIn("Protein file issue", joined)++ def test_a_missing_ligand_description_is_reported(self) -> None:+ (self.root / "protein.pdb").write_text("")+ path = self.write_csv("target_1,protein.pdb,,")+ valid, messages = prepare_batch_csv.validate_csv(path)+ self.assertFalse(valid)+ self.assertIn("Missing ligand_description", "\n".join(messages))++ def test_a_ligand_path_is_checked_as_a_file_not_as_smiles(self) -> None:+ # Anything containing a separator is treated as a path, so a missing+ # SDF must be reported as a file problem rather than as bad chemistry.+ (self.root / "protein.pdb").write_text("")+ path = self.write_csv("target_1,protein.pdb,ligands/gone.sdf,")+ valid, messages = prepare_batch_csv.validate_csv(path)+ self.assertFalse(valid)+ self.assertIn("Ligand file issue", "\n".join(messages))++ def test_both_protein_inputs_together_warn_but_still_validate(self) -> None:+ (self.root / "protein.pdb").write_text("")+ path = self.write_csv(f"target_1,protein.pdb,{ASPIRIN},MSKGEELFTG")+ valid, messages = prepare_batch_csv.validate_csv(path)+ self.assertTrue(valid, "\n".join(messages))+ self.assertIn("will use protein_path", "\n".join(messages))++ def test_a_missing_column_is_reported_instead_of_raising(self) -> None:+ # Regression: the per-row checks index protein_path directly, so a CSV+ # without that column used to abort with KeyError.+ path = self.root / "partial.csv"+ path.write_text(f"complex_name,ligand_description\ntarget_1,{ASPIRIN}\n")+ valid, messages = prepare_batch_csv.validate_csv(path)+ self.assertFalse(valid)+ joined = "\n".join(messages)+ self.assertIn("Missing required columns", joined)+ self.assertIn("protein_path", joined)+ self.assertIn("protein_sequence", joined)++ def test_an_unreadable_csv_is_reported_not_raised(self) -> None:+ valid, messages = prepare_batch_csv.validate_csv(self.root / "absent.csv")+ self.assertFalse(valid)+ self.assertIn("Error reading CSV", messages[0])++ def test_a_header_only_csv_is_vacuously_valid(self) -> None:+ path = self.write_csv()+ valid, messages = prepare_batch_csv.validate_csv(path)+ self.assertTrue(valid, "\n".join(messages))+ self.assertIn("0 rows", messages[0])++ def test_an_invalid_smiles_row_fails_validation(self) -> None:+ if not prepare_batch_csv.RDKIT_AVAILABLE:+ self.skipTest("RDKit is not installed; SMILES validation is a no-op")+ (self.root / "protein.pdb").write_text("")+ path = self.write_csv("target_1,protein.pdb,C1CCCC,")+ valid, messages = prepare_batch_csv.validate_csv(path)+ self.assertFalse(valid)+ self.assertIn("SMILES issue", "\n".join(messages))+++class TemplateCsvTests(TemporaryDirectoryTestCase):+ def test_the_template_carries_the_four_columns_diffdock_requires(self) -> None:+ destination = self.root / "template.csv"+ frame = prepare_batch_csv.create_template_csv(destination)+ self.assertEqual(+ list(frame.columns),+ ["complex_name", "protein_path", "ligand_description", "protein_sequence"],+ )+ self.assertTrue(destination.is_file())++ def test_the_requested_number_of_example_rows_is_written(self) -> None:+ frame = prepare_batch_csv.create_template_csv(self.root / "t.csv", 2)+ self.assertEqual(len(frame), 2)++ def test_only_three_examples_exist_so_larger_requests_are_capped(self) -> None:+ # The CLI advertises 1-3; asking for more must not produce empty rows.+ frame = prepare_batch_csv.create_template_csv(self.root / "t.csv", 9)+ self.assertEqual(len(frame), 3)+ self.assertFalse(frame["complex_name"].isna().any())++ def test_the_first_example_ligand_is_a_parseable_molecule(self) -> None:+ frame = prepare_batch_csv.create_template_csv(self.root / "t.csv", 1)+ self.assertEqual(frame["ligand_description"][0], ASPIRIN)+ if prepare_batch_csv.RDKIT_AVAILABLE:+ self.assertTrue(prepare_batch_csv.validate_smiles(ASPIRIN)[0])+++class ShippedTemplateAssetTests(unittest.TestCase):+ """`assets/batch_template.csv` is what a user copies, so it must be valid."""++ def setUp(self) -> None:+ with (SKILL_ROOT / "assets" / "batch_template.csv").open(newline="") as handle:+ self.rows = list(csv.DictReader(handle))++ def test_it_declares_the_columns_the_validator_requires(self) -> None:+ self.assertEqual(+ set(self.rows[0]),+ {"complex_name", "protein_path", "ligand_description", "protein_sequence"},+ )++ def test_every_row_supplies_a_protein_by_path_or_by_sequence(self) -> None:+ for row in self.rows:+ with self.subTest(complex_name=row["complex_name"]):+ self.assertTrue(+ row["protein_path"] or row["protein_sequence"],+ "row has neither protein_path nor protein_sequence",+ )++ def test_every_smiles_in_the_asset_parses(self) -> None:+ if not prepare_batch_csv.RDKIT_AVAILABLE:+ self.skipTest("RDKit is not installed; SMILES validation is a no-op")+ for row in self.rows:+ ligand = row["ligand_description"]+ if "/" in ligand or ligand.endswith((".sdf", ".mol2")):+ continue # a file reference, not a molecule+ with self.subTest(ligand=ligand):+ self.assertTrue(prepare_batch_csv.validate_smiles(ligand)[0])+++class PythonVersionCheckTests(unittest.TestCase):+ @staticmethod+ def version(major: int, minor: int, micro: int = 0):+ return mock.patch.object(+ sys, "version_info", types.SimpleNamespace(major=major, minor=minor, micro=micro)+ )++ def test_the_upstream_minimum_of_three_nine_passes(self) -> None:+ # DiffDock's environment.yml pins Python 3.9.18, so 3.9 is the floor.+ with self.version(3, 9, 18):+ passed, output = quietly(setup_check.check_python_version)+ self.assertTrue(passed)+ self.assertIn("3.9.18", output)++ def test_anything_older_fails_and_says_what_is_required(self) -> None:+ with self.version(3, 8, 10):+ passed, output = quietly(setup_check.check_python_version)+ self.assertFalse(passed)+ self.assertIn("3.9", output)++ def test_a_newer_interpreter_is_accepted(self) -> None:+ with self.version(3, 13, 1):+ passed, _ = quietly(setup_check.check_python_version)+ self.assertTrue(passed)+++class PackageProbeTests(unittest.TestCase):+ def test_a_present_package_reports_its_version(self) -> None:+ module = types.ModuleType("diffdock_probe_present")+ module.__version__ = "1.2.3"+ with mock.patch.dict(sys.modules, {"diffdock_probe_present": module}):+ found, output = quietly(+ setup_check.check_package, "probe", "diffdock_probe_present"+ )+ self.assertTrue(found)+ self.assertIn("1.2.3", output)++ def test_a_nested_version_attribute_is_followed(self) -> None:+ # RDKit's version lives at rdkit.rdBase.__version__, not on the package.+ module = types.ModuleType("diffdock_probe_nested")+ module.rdBase = types.SimpleNamespace(__version__="2024.03.1")+ with mock.patch.dict(sys.modules, {"diffdock_probe_nested": module}):+ found, output = quietly(+ setup_check.check_package,+ "rdkit",+ "diffdock_probe_nested",+ "rdBase.__version__",+ )+ self.assertTrue(found)+ self.assertIn("2024.03.1", output)++ def test_a_package_without_a_version_still_counts_as_installed(self) -> None:+ module = types.ModuleType("diffdock_probe_bare")+ with mock.patch.dict(sys.modules, {"diffdock_probe_bare": module}):+ found, output = quietly(+ setup_check.check_package, "probe", "diffdock_probe_bare"+ )+ self.assertTrue(found)+ self.assertIn("unknown", output)++ def test_an_absent_package_is_reported_as_not_installed(self) -> None:+ found, output = quietly(+ setup_check.check_package, "probe", "diffdock_probe_absent_xyz"+ )+ self.assertFalse(found)+ self.assertIn("not installed", output)++ def test_torch_reports_cuda_separately_from_the_import(self) -> None:+ torch = types.ModuleType("torch")+ torch.__version__ = "2.4.0"+ torch.cuda = types.SimpleNamespace(is_available=lambda: False)+ with mock.patch.dict(sys.modules, {"torch": torch}):+ (installed, has_cuda), output = quietly(setup_check.check_pytorch)+ # Present but CPU-only: the check must pass while flagging no GPU.+ self.assertEqual((installed, has_cuda), (True, False))+ self.assertIn("CUDA not available", output)++ def test_a_visible_gpu_is_named_in_the_report(self) -> None:+ torch = types.ModuleType("torch")+ torch.__version__ = "2.4.0"+ torch.cuda = types.SimpleNamespace(+ is_available=lambda: True,+ get_device_name=lambda index: "NVIDIA A100",+ device_count=lambda: 2,+ )+ torch.version = types.SimpleNamespace(cuda="12.1")+ with mock.patch.dict(sys.modules, {"torch": torch}):+ (installed, has_cuda), output = quietly(setup_check.check_pytorch)+ self.assertEqual((installed, has_cuda), (True, True))+ self.assertIn("NVIDIA A100", output)+ self.assertIn("12.1", output)++ def test_missing_torch_reports_no_gpu_rather_than_raising(self) -> None:+ # None in sys.modules makes `import torch` raise ImportError.+ with mock.patch.dict(sys.modules, {"torch": None}):+ (installed, has_cuda), output = quietly(setup_check.check_pytorch)+ self.assertEqual((installed, has_cuda), (False, False))+ self.assertIn("not installed", output)++ def test_missing_esm_is_reported_as_optional(self) -> None:+ with mock.patch.dict(sys.modules, {"esm": None}):+ found, output = quietly(setup_check.check_esm)+ self.assertFalse(found)+ # ESM is only needed to fold a sequence, so the message must say so+ # rather than reading as a hard failure.+ self.assertIn("protein sequence folding", output)+ self.assertIn("fair-esm", output)+++class InstallationProbeTests(TemporaryDirectoryTestCase):+ def setUp(self) -> None:+ super().setUp()+ origin = os.getcwd()+ self.addCleanup(os.chdir, origin)+ os.chdir(self.root)++ def test_an_unrelated_directory_is_not_a_diffdock_checkout(self) -> None:+ found, output = quietly(setup_check.check_diffdock_installation)+ self.assertFalse(found)+ self.assertIn("repository root", output)++ def test_the_upstream_entry_points_are_what_it_looks_for(self) -> None:+ for name in ("inference.py", "default_inference_args.yaml", "environment.yml"):+ (self.root / name).write_text("")+ found, output = quietly(setup_check.check_diffdock_installation)+ self.assertTrue(found)+ self.assertIn("inference.py", output)++ def test_absent_checkpoints_are_a_note_not_a_failure(self) -> None:+ (self.root / "inference.py").write_text("")+ found, output = quietly(setup_check.check_diffdock_installation)+ # Weights download on first run, so their absence must not fail setup.+ self.assertTrue(found)+ self.assertIn("downloaded on first run", output)++ def test_present_checkpoints_are_recognised_at_the_documented_path(self) -> None:+ (self.root / "inference.py").write_text("")+ for name in ("score_model", "confidence_model"):+ (self.root / "workdir" / "v1.1" / name).mkdir(parents=True)+ _, output = quietly(setup_check.check_diffdock_installation)+ self.assertIn("Model checkpoints found", output)+++class PerformanceNoteTests(unittest.TestCase):+ def test_the_gpu_and_cpu_guidance_do_not_swap(self) -> None:+ _, with_gpu = quietly(setup_check.print_performance_notes, True)+ _, without = quietly(setup_check.print_performance_notes, False)+ self.assertIn("GPU detected", with_gpu)+ self.assertNotIn("No GPU detected", with_gpu)+ # CPU docking is hours per complex; the warning is the point of the note.+ self.assertIn("No GPU detected", without)+ self.assertIn("SIGNIFICANTLY slower", without)+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/dnanexus-integration/test_scripts.py b/tests/dnanexus-integration/test_scripts.pynew file mode 100644index 00000000..c4c45470--- /dev/null+++ b/tests/dnanexus-integration/test_scripts.py@@ -0,0 +1,582 @@+"""Tests for the DNAnexus integration scripts.++`validate_dxapp` is an offline linter for `dxapp.json`, so the tests start from+one manifest that must be clean and mutate a single field per test. That shape+matters: a validator is only useful if a valid manifest stays silent, and a+suite built only from broken inputs never proves that.++`inspect_dxpy` introspects the installed `dxpy` SDK. Its report-shaping and+version-comparison logic is pure and tested here; anything needing the SDK+itself skips unless `dxpy` is installed, which it is under+`tests/run_all.py --isolated`.+"""++from __future__ import annotations++import copy+import importlib+import json+import subprocess+import sys+import tempfile+import unittest+from pathlib import Path++import skill_contract++SKILL_ROOT = Path(__file__).resolve().parents[2] / "skills" / "dnanexus-integration"+SCRIPTS = SKILL_ROOT / "scripts"+sys.path.insert(0, str(SCRIPTS))++import inspect_dxpy # noqa: E402+import validate_dxapp # noqa: E402++CliHelpTests = skill_contract.cli.help_test_case(SKILL_ROOT)+++def valid_app_manifest() -> dict:+ """A minimal dxapp.json that must produce no errors and no warnings."""+ return {+ "name": "my-analysis-app",+ "title": "My Analysis App",+ "version": "1.2.3",+ "inputSpec": [+ {"name": "reads", "class": "file"},+ {"name": "threads", "class": "int", "optional": True},+ ],+ "outputSpec": [{"name": "report", "class": "file"}],+ "runSpec": {+ "file": "src/code.sh",+ "interpreter": "bash",+ "distribution": "Ubuntu",+ "release": "24.04",+ "version": "0",+ },+ }+++def issue_codes(manifest: dict, kind: str = "auto") -> set[str]:+ _, issues = validate_dxapp.Validator(manifest, kind).validate()+ return {issue.code for issue in issues}+++class ValidBaselineTests(unittest.TestCase):+ def test_a_correct_app_manifest_produces_nothing(self) -> None:+ kind, issues = validate_dxapp.Validator(valid_app_manifest(), "auto").validate()+ self.assertEqual(kind, "app")+ self.assertEqual([f"{i.code} at {i.path}" for i in issues], [])++ def test_kind_is_inferred_from_the_presence_of_version(self) -> None:+ manifest = valid_app_manifest()+ del manifest["version"]+ kind, _ = validate_dxapp.Validator(manifest, "auto").validate()+ self.assertEqual(kind, "applet")++ kind, _ = validate_dxapp.Validator(manifest, "app").validate()+ self.assertEqual(kind, "app")++ def test_an_applet_only_gets_a_warning_for_missing_specs(self) -> None:+ applet = {+ "name": "my-applet",+ "runSpec": {+ "file": "src/code.sh",+ "interpreter": "bash",+ "distribution": "Ubuntu",+ "release": "24.04",+ "version": "0",+ },+ }+ _, issues = validate_dxapp.Validator(applet, "applet").validate()+ severities = {issue.code: issue.severity for issue in issues}+ self.assertEqual(severities.get("missing-spec"), "warning")++ # The same omission is an error for an app.+ _, issues = validate_dxapp.Validator(applet, "app").validate()+ severities = {issue.code: issue.severity for issue in issues}+ self.assertEqual(severities.get("missing-spec"), "error")++ def test_a_non_object_root_is_rejected_without_further_checks(self) -> None:+ kind, issues = validate_dxapp.Validator(["not", "an", "object"], "auto").validate()+ self.assertEqual(kind, "unknown")+ self.assertEqual([issue.code for issue in issues], ["root-type"])+++class MetadataTests(unittest.TestCase):+ def test_name_is_required_and_character_restricted(self) -> None:+ manifest = valid_app_manifest()+ del manifest["name"]+ self.assertIn("missing-name", issue_codes(manifest))++ for bad in ("has space", "slash/name", "quote'name"):+ with self.subTest(name=bad):+ manifest = valid_app_manifest()+ manifest["name"] = bad+ self.assertIn("invalid-name", issue_codes(manifest))++ def test_app_versions_must_be_semantic(self) -> None:+ for bad in ("1.2", "v1.2.3", "1.02.3", "1.2.3.4", ""):+ with self.subTest(version=bad):+ manifest = valid_app_manifest()+ manifest["version"] = bad+ self.assertIn("invalid-version", issue_codes(manifest))++ for good in ("0.0.1", "1.2.3-beta.1", "1.2.3+build5", "10.20.30"):+ with self.subTest(version=good):+ manifest = valid_app_manifest()+ manifest["version"] = good+ self.assertNotIn("invalid-version", issue_codes(manifest))++ def test_top_level_resources_is_flagged_as_deprecated(self) -> None:+ manifest = valid_app_manifest()+ manifest["resources"] = ["project-xxxx:/assets"]+ self.assertIn("deprecated-resources", issue_codes(manifest))+++class ParameterSpecTests(unittest.TestCase):+ def test_parameter_names_follow_the_identifier_rule(self) -> None:+ for bad in ("2reads", "has-dash", "has space", ""):+ with self.subTest(name=bad):+ manifest = valid_app_manifest()+ manifest["inputSpec"][0]["name"] = bad+ self.assertIn("parameter-name", issue_codes(manifest))++ def test_duplicate_parameter_names_are_rejected(self) -> None:+ manifest = valid_app_manifest()+ manifest["inputSpec"][1]["name"] = "reads"+ self.assertIn("duplicate-parameter", issue_codes(manifest))++ def test_unknown_and_array_classes(self) -> None:+ manifest = valid_app_manifest()+ manifest["inputSpec"][0]["class"] = "array:file"+ self.assertNotIn("parameter-class", issue_codes(manifest))++ manifest["inputSpec"][0]["class"] = "array:blob"+ self.assertIn("parameter-class", issue_codes(manifest))++ def test_optional_must_be_a_boolean(self) -> None:+ manifest = valid_app_manifest()+ manifest["inputSpec"][1]["optional"] = "yes"+ self.assertIn("optional-type", issue_codes(manifest))++ def test_input_only_fields_are_rejected_in_the_output_spec(self) -> None:+ for field in ("default", "suggestions", "choices"):+ with self.subTest(field=field):+ manifest = valid_app_manifest()+ manifest["outputSpec"][0][field] = "x"+ self.assertIn("output-only-field", issue_codes(manifest))++ # ...and accepted in the input spec.+ manifest = valid_app_manifest()+ manifest["inputSpec"][1]["default"] = 4+ self.assertNotIn("output-only-field", issue_codes(manifest))++ def test_a_spec_that_is_not_a_list_is_reported_once(self) -> None:+ manifest = valid_app_manifest()+ manifest["inputSpec"] = {"reads": "file"}+ self.assertIn("spec-type", issue_codes(manifest))+++class RunSpecTests(unittest.TestCase):+ def test_runspec_is_required(self) -> None:+ manifest = valid_app_manifest()+ del manifest["runSpec"]+ self.assertIn("missing-runspec", issue_codes(manifest))++ def test_an_entry_source_is_required_and_should_not_be_doubled(self) -> None:+ manifest = valid_app_manifest()+ del manifest["runSpec"]["file"]+ self.assertIn("missing-entry-source", issue_codes(manifest))++ manifest = valid_app_manifest()+ manifest["runSpec"]["code"] = "echo hi"+ self.assertIn("multiple-entry-sources", issue_codes(manifest))++ def test_interpreter_distribution_release_and_aee_version_are_pinned(self) -> None:+ checks = {+ "interpreter": ("perl", "interpreter"),+ "distribution": ("Debian", "distribution"),+ "release": ("22.04", "release"),+ "version": ("1", "aee-version"),+ }+ for field, (value, code) in checks.items():+ with self.subTest(field=field):+ manifest = valid_app_manifest()+ manifest["runSpec"][field] = value+ self.assertIn(code, issue_codes(manifest))++ def test_ubuntu_2004_is_supported_but_flagged_as_legacy(self) -> None:+ manifest = valid_app_manifest()+ manifest["runSpec"]["release"] = "20.04"+ codes = issue_codes(manifest)+ self.assertNotIn("release", codes)+ self.assertIn("legacy-release", codes)++ def test_deprecated_system_requirements_location_is_flagged(self) -> None:+ manifest = valid_app_manifest()+ manifest["runSpec"]["systemRequirements"] = {"*": {"instanceType": "mem1_ssd1_v2_x4"}}+ self.assertIn("deprecated-system-requirements", issue_codes(manifest))++ def test_restartable_entry_points_are_constrained_and_warned_about(self) -> None:+ manifest = valid_app_manifest()+ manifest["runSpec"]["restartableEntryPoints"] = "some"+ self.assertIn("restartable-entry-points", issue_codes(manifest))++ manifest = valid_app_manifest()+ manifest["runSpec"]["restartableEntryPoints"] = "all"+ codes = issue_codes(manifest)+ self.assertNotIn("restartable-entry-points", codes)+ self.assertIn("restart-idempotency", codes)+++class PolicyTests(unittest.TestCase):+ def test_unpinned_dependencies_are_warned_about(self) -> None:+ manifest = valid_app_manifest()+ manifest["runSpec"]["execDepends"] = [{"name": "samtools"}]+ self.assertIn("floating-dependency", issue_codes(manifest))++ manifest["runSpec"]["execDepends"] = [{"name": "samtools", "version": "1.19"}]+ self.assertNotIn("floating-dependency", issue_codes(manifest))++ def test_dependency_entries_must_be_named_objects(self) -> None:+ manifest = valid_app_manifest()+ manifest["runSpec"]["execDepends"] = ["samtools"]+ self.assertIn("dependency-type", issue_codes(manifest))++ manifest["runSpec"]["execDepends"] = [{"version": "1.19"}]+ self.assertIn("dependency-name", issue_codes(manifest))++ def test_max_restarts_is_bounded_and_rejects_booleans(self) -> None:+ for bad in (-1, 10, 99, True, "3"):+ with self.subTest(value=bad):+ manifest = valid_app_manifest()+ manifest["runSpec"]["executionPolicy"] = {"maxRestarts": bad}+ self.assertIn("max-restarts", issue_codes(manifest))++ manifest = valid_app_manifest()+ manifest["runSpec"]["executionPolicy"] = {"maxRestarts": 0}+ self.assertNotIn("max-restarts", issue_codes(manifest))++ def test_restart_reasons_are_checked_against_the_documented_set(self) -> None:+ manifest = valid_app_manifest()+ manifest["runSpec"]["executionPolicy"] = {"restartOn": {"MadeUpError": 2}}+ self.assertIn("unknown-restart-reason", issue_codes(manifest))++ manifest["runSpec"]["executionPolicy"] = {"restartOn": {"ExecutionError": 2}}+ self.assertNotIn("unknown-restart-reason", issue_codes(manifest))++ manifest["runSpec"]["executionPolicy"] = {"restartOn": {"ExecutionError": -1}}+ self.assertIn("restart-count", issue_codes(manifest))++ def test_timeout_units_and_values_are_constrained(self) -> None:+ manifest = valid_app_manifest()+ manifest["runSpec"]["timeoutPolicy"] = {"*": {"hours": 12}}+ self.assertEqual(issue_codes(manifest), set())++ manifest["runSpec"]["timeoutPolicy"] = {"*": {"weeks": 1}}+ self.assertIn("timeout-unit", issue_codes(manifest))++ manifest["runSpec"]["timeoutPolicy"] = {"*": {"hours": -1}}+ self.assertIn("timeout-value", issue_codes(manifest))++ manifest["runSpec"]["timeoutPolicy"] = {"*": {}}+ self.assertIn("timeout-duration", issue_codes(manifest))+++class RegionalOptionTests(unittest.TestCase):+ def test_region_identifiers_should_be_provider_qualified(self) -> None:+ manifest = valid_app_manifest()+ manifest["regionalOptions"] = {"us-east-1": {}}+ self.assertIn("region-name", issue_codes(manifest))++ manifest["regionalOptions"] = {"aws:us-east-1": {}}+ self.assertNotIn("region-name", issue_codes(manifest))++ def test_system_requirements_must_cover_every_region_or_none(self) -> None:+ manifest = valid_app_manifest()+ manifest["regionalOptions"] = {+ "aws:us-east-1": {"systemRequirements": {"*": {"instanceType": "mem1_ssd1_v2_x4"}}},+ "azure:westus": {},+ }+ self.assertIn("inconsistent-regional-requirements", issue_codes(manifest))++ manifest["regionalOptions"]["azure:westus"] = {+ "systemRequirements": {"*": {"instanceType": "azure:mem1_ssd1_x4"}}+ }+ self.assertNotIn("inconsistent-regional-requirements", issue_codes(manifest))++ def test_resource_selectors_are_mutually_exclusive(self) -> None:+ manifest = valid_app_manifest()+ manifest["regionalOptions"] = {+ "aws:us-east-1": {+ "systemRequirements": {+ "*": {+ "instanceType": "mem1_ssd1_v2_x4",+ "clusterSpec": {"type": "spark"},+ }+ }+ }+ }+ self.assertIn("resource-selector-conflict", issue_codes(manifest))++ def test_instance_type_selector_needs_a_non_empty_string_list(self) -> None:+ def with_selector(selector):+ manifest = valid_app_manifest()+ manifest["regionalOptions"] = {+ "aws:us-east-1": {+ "systemRequirements": {"*": {"instanceTypeSelector": selector}}+ }+ }+ return issue_codes(manifest)++ self.assertIn("allowed-instance-types", with_selector({"allowedInstanceTypes": []}))+ self.assertIn("allowed-instance-types", with_selector({"allowedInstanceTypes": [1]}))+ self.assertIn(+ "duplicate-instance-type",+ with_selector({"allowedInstanceTypes": ["a", "a"]}),+ )+ self.assertNotIn(+ "allowed-instance-types",+ with_selector({"allowedInstanceTypes": ["mem1_ssd1_v2_x4"]}),+ )+++class AccessAndSecretTests(unittest.TestCase):+ def test_broad_and_privileged_access_is_warned_about(self) -> None:+ manifest = valid_app_manifest()+ manifest["access"] = {"network": ["*"]}+ self.assertIn("broad-network", issue_codes(manifest))++ manifest["access"] = {"network": ["api.example.invalid"]}+ self.assertNotIn("broad-network", issue_codes(manifest))++ manifest["access"] = {"project": "ADMINISTER"}+ self.assertIn("admin-project-access", issue_codes(manifest))++ manifest["access"] = {"allProjects": "VIEW"}+ self.assertIn("all-projects-access", issue_codes(manifest))++ manifest["access"] = {"developer": True}+ self.assertIn("developer-access", issue_codes(manifest))++ def test_access_levels_are_checked_against_the_documented_set(self) -> None:+ manifest = valid_app_manifest()+ manifest["access"] = {"project": "READWRITE"}+ self.assertIn("access-level", issue_codes(manifest))++ def test_embedded_credentials_are_found_at_any_depth(self) -> None:+ manifest = valid_app_manifest()+ manifest["runSpec"]["assetDepends"] = [{"api_token": "sk-live-abc123"}]+ self.assertIn("embedded-secret", issue_codes(manifest))++ manifest = valid_app_manifest()+ manifest["details"] = {"nested": {"private-key": "-----BEGIN..."}}+ self.assertIn("embedded-secret", issue_codes(manifest))++ def test_placeholder_credentials_are_not_flagged(self) -> None:+ for placeholder in ("", "changeme", "PLACEHOLDER", "<token>", " redacted "):+ with self.subTest(value=placeholder):+ manifest = valid_app_manifest()+ manifest["details"] = {"password": placeholder}+ self.assertNotIn("embedded-secret", issue_codes(manifest))++ def test_a_secret_key_holding_false_is_a_setting_not_a_credential(self) -> None:+ manifest = valid_app_manifest()+ manifest["details"] = {"use_token": False}+ self.assertNotIn("embedded-secret", issue_codes(manifest))++ def test_secret_detection_matches_whole_words_only(self) -> None:+ # SECRET_KEY_RE anchors on word boundaries so `tokenizer` is not a token.+ manifest = valid_app_manifest()+ manifest["details"] = {"tokenizer": "bpe"}+ self.assertNotIn("embedded-secret", issue_codes(manifest))++ def test_https_ports_are_restricted(self) -> None:+ manifest = valid_app_manifest()+ manifest["httpsApp"] = {"ports": [443]}+ self.assertNotIn("https-ports", issue_codes(manifest))++ for bad in ([], [22], [443, 9000], "443"):+ with self.subTest(ports=bad):+ manifest["httpsApp"] = {"ports": bad}+ self.assertIn("https-ports", issue_codes(manifest))+++class CommandLineTests(unittest.TestCase):+ def _run(self, manifest, *flags) -> subprocess.CompletedProcess:+ with tempfile.TemporaryDirectory() as directory:+ path = Path(directory) / "dxapp.json"+ path.write_text(json.dumps(manifest), encoding="utf-8")+ return subprocess.run(+ [sys.executable, str(SCRIPTS / "validate_dxapp.py"), str(path), *flags],+ capture_output=True,+ text=True,+ timeout=60,+ )++ def test_a_clean_manifest_exits_zero(self) -> None:+ result = self._run(valid_app_manifest())+ self.assertEqual(result.returncode, 0, result.stderr)+ self.assertIn("Errors: 0", result.stdout)++ def test_errors_exit_one(self) -> None:+ manifest = valid_app_manifest()+ del manifest["name"]+ self.assertEqual(self._run(manifest).returncode, 1)++ def test_strict_promotes_warnings_to_a_failure(self) -> None:+ manifest = valid_app_manifest()+ manifest["runSpec"]["release"] = "20.04" # warning only+ self.assertEqual(self._run(manifest).returncode, 0)+ self.assertEqual(self._run(manifest, "--strict").returncode, 1)++ def test_json_output_is_machine_readable(self) -> None:+ manifest = valid_app_manifest()+ manifest["access"] = {"network": ["*"]}+ result = self._run(manifest, "--json")+ report = json.loads(result.stdout)+ self.assertTrue(report["valid"])+ self.assertEqual(report["kind"], "app")+ self.assertEqual(report["warnings"], 1)+ self.assertEqual(report["issues"][0]["code"], "broad-network")++ def test_unreadable_manifest_exits_two_with_a_parse_issue(self) -> None:+ with tempfile.TemporaryDirectory() as directory:+ path = Path(directory) / "dxapp.json"+ path.write_text("{not json", encoding="utf-8")+ result = subprocess.run(+ [+ sys.executable,+ str(SCRIPTS / "validate_dxapp.py"),+ str(path),+ "--json",+ ],+ capture_output=True,+ text=True,+ timeout=60,+ )+ self.assertEqual(result.returncode, 2)+ report = json.loads(result.stdout)+ self.assertFalse(report["valid"])+ self.assertEqual(report["issues"][0]["code"], "parse")+++class SummaryTests(unittest.TestCase):+ def test_summarize_counts_both_severities(self) -> None:+ issues = [+ validate_dxapp.Issue("error", "a", "$", "m"),+ validate_dxapp.Issue("warning", "b", "$", "m"),+ validate_dxapp.Issue("warning", "c", "$", "m"),+ ]+ self.assertEqual(validate_dxapp.summarize(issues), {"error": 1, "warning": 2})++ def test_summarize_of_nothing_is_zeroed_not_empty(self) -> None:+ self.assertEqual(validate_dxapp.summarize([]), {"error": 0, "warning": 0})+++class SdkInspectionTests(unittest.TestCase):+ """`inspect_dxpy`'s pure helpers; the SDK-dependent report needs dxpy."""++ def test_version_comparison_is_numeric_not_lexicographic(self) -> None:+ parse = inspect_dxpy.numeric_version+ self.assertEqual(parse("0.410.0"), (0, 410, 0))+ # The bug this guards: "0.99" > "0.410" as strings, but not as versions.+ self.assertLess(parse("0.99.0"), parse("0.410.0"))+ self.assertGreater(parse("1.0.0"), parse("0.410.0"))++ def test_version_comparison_tolerates_non_numeric_segments(self) -> None:+ # Never raise on an unexpected version string -- the script's job is to+ # report, not to crash on a pre-release tag.+ self.assertIsInstance(inspect_dxpy.numeric_version("0.410.0rc1"), tuple)+ self.assertIsInstance(inspect_dxpy.numeric_version(""), tuple)++ def test_documented_baseline_is_a_parseable_version(self) -> None:+ self.assertRegex(inspect_dxpy.DOCUMENTED_BASELINE, r"^\d+\.\d+\.\d+$")+ self.assertTrue(inspect_dxpy.numeric_version(inspect_dxpy.DOCUMENTED_BASELINE))++ def test_required_symbols_are_dxpy_qualified_names(self) -> None:+ self.assertTrue(inspect_dxpy.REQUIRED_SYMBOLS)+ for name in inspect_dxpy.REQUIRED_SYMBOLS:+ with self.subTest(symbol=name):+ self.assertTrue(name.startswith("dxpy."))++ def test_missing_symbol_detection_reads_the_report_not_the_sdk(self) -> None:+ symbol = "dxpy.upload_local_file"+ self.assertIn(symbol, inspect_dxpy.REQUIRED_SYMBOLS)++ # An empty report means nothing was observed, so everything is missing.+ self.assertEqual(+ inspect_dxpy.missing_required_symbols({}),+ sorted(inspect_dxpy.REQUIRED_SYMBOLS),+ )++ report = {+ "symbols": {+ "dxpy": [{"qualified_name": symbol, "available": False}],+ }+ }+ self.assertIn(symbol, inspect_dxpy.missing_required_symbols(report))++ report["symbols"]["dxpy"][0]["available"] = True+ self.assertNotIn(symbol, inspect_dxpy.missing_required_symbols(report))++ def test_missing_method_detection_reads_the_report(self) -> None:+ missing = inspect_dxpy.missing_required_methods({})+ self.assertIn("DXFile.describe", missing)+ self.assertEqual(missing, sorted(missing))++ report = {"methods": {"DXFile": {"describe": {"available": True}}}}+ self.assertNotIn("DXFile.describe", inspect_dxpy.missing_required_methods(report))++ def test_report_generation_needs_the_sdk(self) -> None:+ try:+ importlib.import_module("dxpy")+ except ImportError:+ self.skipTest("dxpy is not installed; run under --isolated")++ report = inspect_dxpy.build_report()+ self.assertEqual(+ set(report),+ {+ "schema_version",+ "python",+ "platform",+ "documented_baseline",+ "dxpy_version",+ "version_meets_baseline",+ "symbols",+ "methods",+ "known_legacy_checks",+ },+ )+ self.assertEqual(+ report["documented_baseline"], inspect_dxpy.DOCUMENTED_BASELINE+ )+ # The report must be usable by the two consumers below.+ self.assertEqual(inspect_dxpy.missing_required_symbols(report), [])+ self.assertEqual(inspect_dxpy.missing_required_methods(report), [])++ def test_the_installed_sdk_meets_the_documented_baseline(self) -> None:+ try:+ importlib.import_module("dxpy")+ except ImportError:+ self.skipTest("dxpy is not installed; run under --isolated")++ report = inspect_dxpy.build_report()+ # Recomputed independently of the script's own comparison.+ self.assertEqual(+ report["version_meets_baseline"],+ inspect_dxpy.numeric_version(report["dxpy_version"])+ >= inspect_dxpy.numeric_version(inspect_dxpy.DOCUMENTED_BASELINE),+ )++ def test_the_report_is_json_serialisable(self) -> None:+ try:+ importlib.import_module("dxpy")+ except ImportError:+ self.skipTest("dxpy is not installed; run under --isolated")+ # --json is the documented machine-readable path.+ json.dumps(inspect_dxpy.build_report())+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/docx/test_scripts.py b/tests/docx/test_scripts.pynew file mode 100644index 00000000..ed936258--- /dev/null+++ b/tests/docx/test_scripts.py@@ -0,0 +1,226 @@+"""Tests for the docx skill's OOXML editors.++The shared `office/` tree -- zip safety, relationship resolution, repacking --+is covered by the contract, since pptx and xlsx ship byte-identical copies.+What is specific to docx is the run merger and the comment writer, and both+edit `word/document.xml` in place, so the tests build a real unpacked package+in a temporary directory and assert on the XML that comes back out.++`merge_runs` is the one with a genuine correctness risk: Word splits a single+sentence across many `<w:r>` runs, and merging them must preserve the visible+text exactly, including whitespace held by `xml:space="preserve"`.+"""++from __future__ import annotations++import sys+import tempfile+import unittest+from pathlib import Path++import pytest++import skill_contract++SKILL_ROOT = Path(__file__).resolve().parents[2] / "skills" / "docx"+SCRIPTS = SKILL_ROOT / "scripts"+sys.path.insert(0, str(SCRIPTS))++pytest.importorskip("defusedxml", reason="docx scripts need defusedxml")++import merge_runs # noqa: E402++OfficeTests = skill_contract.office.office_test_case(SKILL_ROOT)+CliHelpTests = skill_contract.cli.help_test_case(SKILL_ROOT)++WORDML = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"+++def document(body: str) -> str:+ return (+ '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n'+ f'<w:document xmlns:w="{WORDML}"><w:body>{body}</w:body></w:document>'+ )+++def run(text: str, *, preserve: bool = False, properties: str = "") -> str:+ space = ' xml:space="preserve"' if preserve else ""+ return f"<w:r>{properties}<w:t{space}>{text}</w:t></w:r>"+++class UnpackedPackage:+ """A minimal unpacked .docx directory."""++ def __init__(self, root: Path, body: str) -> None:+ self.root = root+ (root / "word").mkdir(parents=True, exist_ok=True)+ (root / "word" / "document.xml").write_text(document(body), encoding="utf-8")+ (root / "[Content_Types].xml").write_text("<Types/>", encoding="utf-8")++ @property+ def xml(self) -> str:+ return (self.root / "word" / "document.xml").read_text(encoding="utf-8")++ def visible_text(self) -> str:+ import re++ return "".join(re.findall(r"<w:t[^>]*>(.*?)</w:t>", self.xml, re.DOTALL))+++class MergeRunsTestCase(unittest.TestCase):+ def setUp(self) -> None:+ self._temporary = tempfile.TemporaryDirectory()+ self.addCleanup(self._temporary.cleanup)+ self.root = Path(self._temporary.name)++ def package(self, body: str) -> UnpackedPackage:+ return UnpackedPackage(self.root, body)+++class TextPreservationTests(MergeRunsTestCase):+ def test_adjacent_identical_runs_merge_without_changing_the_text(self) -> None:+ # The trailing space needs xml:space="preserve" to be significant --+ # without it OOXML says the space is not part of the text, which is+ # what `office/helpers.rendered_text` implements.+ package = self.package(+ "<w:p>" + run("Hello ", preserve=True) + run("world") + run("!") + "</w:p>"+ )+ before = package.visible_text()+ merge_runs.merge_runs(str(self.root))+ self.assertEqual(package.visible_text(), before)+ self.assertEqual(package.visible_text(), "Hello world!")++ def test_unpreserved_trailing_whitespace_is_insignificant(self) -> None:+ # The counterpart: without xml:space="preserve" the space is dropped,+ # matching how Word itself reads the part.+ package = self.package("<w:p>" + run("Hello ") + run("world") + "</w:p>")+ merge_runs.merge_runs(str(self.root))+ self.assertEqual(package.visible_text(), "Helloworld")++ def test_merging_reduces_the_run_count(self) -> None:+ package = self.package(+ "<w:p>" + run("a") + run("b") + run("c") + "</w:p>"+ )+ merged, _ = merge_runs.merge_runs(str(self.root))+ self.assertGreater(merged, 0)+ self.assertEqual(package.xml.count("<w:r>"), 1)++ def test_runs_with_different_formatting_are_not_merged(self) -> None:+ bold = "<w:rPr><w:b/></w:rPr>"+ package = self.package(+ "<w:p>" + run("plain") + run("bold", properties=bold) + "</w:p>"+ )+ merge_runs.merge_runs(str(self.root))+ self.assertEqual(package.xml.count("<w:r>"), 2)+ self.assertEqual(package.visible_text(), "plainbold")++ def test_preserved_whitespace_survives_a_merge(self) -> None:+ # Losing xml:space="preserve" silently deletes the space between words.+ package = self.package(+ "<w:p>" + run("one ", preserve=True) + run("two", preserve=True) + "</w:p>"+ )+ merge_runs.merge_runs(str(self.root))+ self.assertEqual(package.visible_text(), "one two")++ def test_runs_in_different_paragraphs_are_not_merged_across(self) -> None:+ package = self.package(+ "<w:p>" + run("first") + "</w:p><w:p>" + run("second") + "</w:p>"+ )+ merge_runs.merge_runs(str(self.root))+ self.assertEqual(package.xml.count("<w:p>"), 2)+ self.assertEqual(package.visible_text(), "firstsecond")++ def test_a_document_with_nothing_to_merge_keeps_its_content(self) -> None:+ # The XML declaration is rewritten by minidom's serializer, so compare+ # the document element rather than the whole byte stream.+ package = self.package("<w:p>" + run("only one run") + "</w:p>")+ merged, _ = merge_runs.merge_runs(str(self.root))+ self.assertEqual(merged, 0)+ self.assertEqual(package.visible_text(), "only one run")+ self.assertEqual(package.xml.count("<w:r>"), 1)++ def test_an_empty_document_does_not_raise(self) -> None:+ self.package("")+ merged, _ = merge_runs.merge_runs(str(self.root))+ self.assertEqual(merged, 0)++ def test_the_result_is_still_well_formed_xml(self) -> None:+ import defusedxml.ElementTree as ElementTree++ package = self.package(+ "<w:p>" + "".join(run(str(index)) for index in range(20)) + "</w:p>"+ )+ merge_runs.merge_runs(str(self.root))+ ElementTree.fromstring(package.xml)+ self.assertEqual(package.visible_text(), "".join(str(i) for i in range(20)))++ def test_merging_is_idempotent(self) -> None:+ package = self.package("<w:p>" + run("a") + run("b") + "</w:p>")+ merge_runs.merge_runs(str(self.root))+ once = package.xml+ merged, _ = merge_runs.merge_runs(str(self.root))+ self.assertEqual(merged, 0)+ self.assertEqual(package.xml, once)+++class HelperTests(unittest.TestCase):+ """`merge_runs` walks a minidom tree, so the helpers take minidom nodes."""++ def _runs(self, body: str) -> list:+ import defusedxml.minidom++ dom = defusedxml.minidom.parseString(document(body))+ root = dom.documentElement+ return merge_runs._find_runs(root, merge_runs._run_tag_names(root))++ def test_adjacency_requires_the_elements_to_be_siblings_in_order(self) -> None:+ runs = self._runs("<w:p>" + run("a") + run("b") + "</w:p>")+ self.assertEqual(len(runs), 2)+ self.assertTrue(merge_runs._is_adjacent(runs[0], runs[1]))+ self.assertFalse(merge_runs._is_adjacent(runs[1], runs[0]))++ def test_an_intervening_element_breaks_adjacency(self) -> None:+ runs = self._runs(+ "<w:p>" + run("a") + "<w:bookmarkStart/>" + run("b") + "</w:p>"+ )+ self.assertFalse(merge_runs._is_adjacent(runs[0], runs[1]))++ def test_element_matching_is_namespace_aware(self) -> None:+ runs = self._runs("<w:p>" + run("a") + "</w:p>")+ self.assertTrue(merge_runs._is_element(runs[0], "r"))+ self.assertFalse(merge_runs._is_element(runs[0], "p"))++ def test_run_tag_names_are_discovered_from_the_document(self) -> None:+ names = merge_runs._run_tag_names(+ __import__("defusedxml.minidom", fromlist=["parseString"])+ .parseString(document("<w:p>" + run("a") + "</w:p>"))+ .documentElement+ )+ self.assertTrue(names)+++class TemplateTests(unittest.TestCase):+ def test_the_comment_templates_are_shipped_and_parse(self) -> None:+ import defusedxml.ElementTree as ElementTree++ templates = sorted((SCRIPTS / "templates").glob("*.xml"))+ self.assertTrue(templates, "no comment templates shipped")+ for template in templates:+ with self.subTest(template=template.name):+ ElementTree.fromstring(template.read_text(encoding="utf-8"))++ def test_the_documented_comment_parts_are_all_present(self) -> None:+ # Word needs every one of these to open a commented document.+ shipped = {path.name for path in (SCRIPTS / "templates").glob("*.xml")}+ for required in (+ "comments.xml",+ "commentsExtended.xml",+ "commentsIds.xml",+ "people.xml",+ ):+ with self.subTest(part=required):+ self.assertIn(required, shipped)+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/etetoolkit/test_scripts.py b/tests/etetoolkit/test_scripts.pynew file mode 100644index 00000000..551fe388--- /dev/null+++ b/tests/etetoolkit/test_scripts.py@@ -0,0 +1,912 @@+"""Tests for the ETE 4 tree helpers.++Three things in these scripts can be wrong in ways a user would not notice.+The diagnostics in `tree_stats` are numbers people quote in papers, so they are+checked against a Newick string whose leaf count, branch lengths, farthest-leaf+distance, and support values are all known by construction -- including the+detail that the Newick *parser number* decides whether an internal label is a+name or a support value. The validators in both scripts are proved in both+directions: acceptable input passes silently, and each rejection names the+argument at fault. And `validate_bind_address` is a security boundary --+SmartView serves an unauthenticated interactive viewer, so binding it past+loopback must require the explicit `--allow-remote-bind` opt-in -- so every+loopback spelling and every remote spelling is exercised.++Everything here needs ete4 itself; there is no pure-Python half worth testing+separately, because the interesting logic is about what ETE returns.+"""++from __future__ import annotations++import argparse+import contextlib+import io+import json+import sys+import tempfile+import unittest+from pathlib import Path++import pytest++import skill_contract++SKILL_ROOT = Path(__file__).resolve().parents[2] / "skills" / "etetoolkit"+SCRIPTS = SKILL_ROOT / "scripts"+sys.path.insert(0, str(SCRIPTS))++pytest.importorskip("ete4", reason="etetoolkit skill needs ete4")++import quick_visualize # noqa: E402+import tree_operations # noqa: E402++CliHelpTests = skill_contract.cli.help_test_case(SKILL_ROOT)++#: Four taxa, two clades, *named* internal nodes -- so it needs parser 1, which+#: reads internal labels as names. Total branch length 8 (1+1+1+1+2+2); the+#: farthest leaf sits 3 from the root.+BALANCED = "((A:1,B:1)AB:1,(C:2,D:2)CD:1)root;"++#: The same shape with unlabelled internal nodes, so the default parser 0 reads+#: it. Total branch length 6, and every leaf is 2 from the root.+PLAIN = "((A:1,B:1):1,(C:1,D:1):1);"+++class TreeFixtureCase(unittest.TestCase):+ """Base class giving each test a scratch directory and a `newick` helper."""++ def setUp(self) -> None:+ self._temporary = tempfile.TemporaryDirectory()+ self.addCleanup(self._temporary.cleanup)+ self.root = Path(self._temporary.name)++ def newick(self, text: str, name: str = "tree.nwk") -> Path:+ path = self.root / name+ path.write_text(text + "\n", encoding="utf-8")+ return path+++class ParserSpecTests(unittest.TestCase):+ """`--parser` accepts both ETE's numeric ids and its named aliases."""++ def test_a_numeric_parser_id_stays_an_integer(self) -> None:+ # ETE looks parsers up by int; passing "0" as a string selects nothing.+ for text, expected in (("0", 0), ("1", 1), (" 5 ", 5), ("-1", -1)):+ with self.subTest(text=text):+ self.assertEqual(tree_operations.parser_spec(text), expected)++ def test_a_named_parser_stays_a_string(self) -> None:+ self.assertEqual(tree_operations.parser_spec("newick"), "newick")++ def test_an_empty_parser_is_rejected(self) -> None:+ for text in ("", " "):+ with self.subTest(text=text):+ with self.assertRaises(argparse.ArgumentTypeError):+ tree_operations.parser_spec(text)++ def test_both_scripts_agree_on_the_parser_type(self) -> None:+ # The two CLIs define the converter separately; a divergence would make+ # `--parser 1` mean different things in `stats` and in `quick_visualize`.+ self.assertEqual(quick_visualize.parser_spec("1"), tree_operations.parser_spec("1"))+ self.assertEqual(+ quick_visualize.parser_spec("newick"), tree_operations.parser_spec("newick")+ )+++class CommaSeparatedTests(unittest.TestCase):+ def test_whitespace_and_empty_fields_are_dropped(self) -> None:+ self.assertEqual(+ tree_operations.comma_separated("name, dist ,,support,"),+ ["name", "dist", "support"],+ )++ def test_an_empty_string_selects_no_properties(self) -> None:+ # `--props ""` must mean "none", not a single empty property name, or+ # tree.write() is asked for a property no node has.+ self.assertEqual(tree_operations.comma_separated(""), [])+++class ModeSpecTests(unittest.TestCase):+ def test_short_and_long_layout_names_normalise_to_the_long_form(self) -> None:+ for text in ("r", "R", "rectangular", "RECTANGULAR"):+ with self.subTest(text=text):+ self.assertEqual(quick_visualize.mode_spec(text), "rectangular")+ for text in ("c", "C", "circular"):+ with self.subTest(text=text):+ self.assertEqual(quick_visualize.mode_spec(text), "circular")++ def test_an_unknown_layout_is_rejected(self) -> None:+ for text in ("radial", "", "rect"):+ with self.subTest(text=text):+ with self.assertRaisesRegex(+ argparse.ArgumentTypeError, "rectangular/r or circular/c"+ ):+ quick_visualize.mode_spec(text)+++class TreeLoadingTests(TreeFixtureCase):+ def test_a_valid_newick_file_loads_with_its_leaves(self) -> None:+ tree = tree_operations.load_tree(self.newick(BALANCED), 1)+ self.assertEqual(sorted(tree.leaf_names()), ["A", "B", "C", "D"])++ def test_a_missing_file_is_reported_as_user_error(self) -> None:+ with self.assertRaisesRegex(tree_operations.UserInputError, "does not exist"):+ tree_operations.load_tree(self.root / "absent.nwk", 0)++ def test_a_directory_is_not_a_tree(self) -> None:+ with self.assertRaises(tree_operations.UserInputError):+ tree_operations.load_tree(self.root, 0)++ def test_malformed_newick_becomes_a_user_error_not_a_traceback(self) -> None:+ # A truncated tree is the commonest real failure; the CLI must name the+ # file and the parser rather than surfacing NewickError.+ path = self.newick("((A:1,B:1)")+ with self.assertRaisesRegex(tree_operations.UserInputError, "could not parse"):+ tree_operations.load_tree(path, 0)++ def test_both_scripts_load_trees_identically(self) -> None:+ path = self.newick(BALANCED)+ self.assertEqual(+ sorted(quick_visualize.load_tree(path, 1).leaf_names()),+ sorted(tree_operations.load_tree(path, 1).leaf_names()),+ )+++class NumericSummaryTests(unittest.TestCase):+ def test_an_empty_list_summarises_to_none_rather_than_raising(self) -> None:+ # A tree with no branch lengths at all must report "none", not crash in+ # statistics.fmean on an empty sequence.+ self.assertIsNone(tree_operations.numeric_summary([]))++ def test_the_four_statistics_are_the_textbook_ones(self) -> None:+ summary = tree_operations.numeric_summary([1.0, 2.0, 3.0, 6.0])+ self.assertEqual(summary["minimum"], 1.0)+ self.assertEqual(summary["maximum"], 6.0)+ self.assertEqual(summary["mean"], 3.0)+ self.assertEqual(summary["median"], 2.5)++ def test_a_single_value_is_its_own_summary(self) -> None:+ self.assertEqual(+ tree_operations.numeric_summary([4.0]),+ {"minimum": 4.0, "maximum": 4.0, "mean": 4.0, "median": 4.0},+ )+++class TreeStatsTests(TreeFixtureCase):+ """Every number below is read off the Newick string, not off the code."""++ def stats(self, text: str, parser: int = 1) -> dict:+ path = self.newick(text)+ return tree_operations.tree_stats(tree_operations.load_tree(path, parser), path)++ def test_the_node_counts_match_the_newick_string(self) -> None:+ stats = self.stats(BALANCED)+ self.assertEqual(stats["leaf_count"], 4)+ # root, AB, CD.+ self.assertEqual(stats["internal_node_count"], 3)+ self.assertEqual(stats["total_node_count"], 7)+ self.assertEqual(stats["root_child_count"], 2)+ self.assertEqual(stats["polytomy_count"], 0)+ self.assertEqual(stats["unary_node_count"], 0)++ def test_branch_length_statistics_exclude_the_root(self) -> None:+ # Six non-root branches: AB=1, A=1, B=1, CD=1, C=2, D=2.+ summary = self.stats(BALANCED)["branch_lengths"]+ self.assertEqual(summary["minimum"], 1.0)+ self.assertEqual(summary["maximum"], 2.0)+ self.assertEqual(summary["median"], 1.0)+ self.assertAlmostEqual(summary["mean"], 8 / 6)++ def test_the_farthest_leaf_distance_is_the_root_to_tip_path(self) -> None:+ stats = self.stats(BALANCED)+ # root -> CD (1) -> C or D (2). C and D tie, so accept either name.+ self.assertEqual(stats["farthest_leaf_distance"], 3.0)+ self.assertIn(stats["farthest_leaf"], {"C", "D"})++ def test_a_polytomy_is_counted_and_a_bifurcating_tree_reports_none(self) -> None:+ self.assertEqual(self.stats("((A,B,C),D);")["polytomy_count"], 1)+ self.assertEqual(self.stats("((A,B),(C,D));")["polytomy_count"], 0)++ def test_a_unary_node_is_counted(self) -> None:+ # Single-child nodes survive some pruning routines and break downstream+ # tools, so they get their own counter.+ stats = self.stats("((A),(B,C));")+ self.assertEqual(stats["unary_node_count"], 1)+ self.assertEqual(stats["leaf_count"], 3)++ def test_duplicate_leaf_names_are_listed_once_each(self) -> None:+ self.assertEqual(self.stats("((A,A),(B,C));")["duplicate_leaf_names"], ["A"])+ self.assertEqual(self.stats("((A,B),(C,D));")["duplicate_leaf_names"], [])++ def test_unnamed_leaves_are_reported_by_position(self) -> None:+ # An unnamed leaf has no name to report, so the node id (the path of+ # child indices from the root) identifies it instead.+ self.assertEqual(self.stats("((A,),(B,C));")["unnamed_leaf_ids"], [[0, 1]])++ def test_the_parser_number_decides_whether_a_label_is_a_name_or_support(self) -> None:+ # Parser 1 reads "AB"/"CD" as internal *names*, so no support exists;+ # parser 0 reads the same position as a support value. Getting this+ # backwards silently reports support statistics for a tree that has+ # none, or none for a tree that has them.+ self.assertIsNone(self.stats(BALANCED, parser=1)["internal_support"])++ supported = self.stats("((A:1,B:1)0.95:1,(C:1,D:1)0.80:1);", parser=0)+ summary = supported["internal_support"]+ self.assertEqual(summary["minimum"], 0.80)+ self.assertEqual(summary["maximum"], 0.95)+ self.assertAlmostEqual(summary["mean"], 0.875)++ def test_the_reported_source_and_version_identify_the_run(self) -> None:+ path = self.newick(BALANCED)+ stats = tree_operations.tree_stats(tree_operations.load_tree(path, 1), path)+ self.assertEqual(stats["source"], str(path))+ # The statistics depend on ETE's traversal, so the version is recorded.+ self.assertTrue(stats["ete_version"])+++class PrintStatsTests(TreeFixtureCase):+ def test_json_output_is_machine_readable_and_complete(self) -> None:+ path = self.newick(BALANCED)+ stats = tree_operations.tree_stats(tree_operations.load_tree(path, 1), path)+ buffer = io.StringIO()+ with contextlib.redirect_stdout(buffer):+ tree_operations.print_stats(stats, as_json=True)+ self.assertEqual(json.loads(buffer.getvalue()), stats)++ def test_text_output_says_none_where_a_summary_is_missing(self) -> None:+ # Parser 1 leaves support unset; the text report must say so rather+ # than crash formatting None.+ path = self.newick(BALANCED)+ stats = tree_operations.tree_stats(tree_operations.load_tree(path, 1), path)+ buffer = io.StringIO()+ with contextlib.redirect_stdout(buffer):+ tree_operations.print_stats(stats, as_json=False)+ text = buffer.getvalue()+ self.assertIn("Internal support: none", text)+ self.assertIn("Leaves: 4", text)+ self.assertIn("Duplicate leaf names: none", text)+++class NodeResolutionTests(TreeFixtureCase):+ def test_a_unique_name_resolves_to_that_node(self) -> None:+ tree = tree_operations.load_tree(self.newick(BALANCED), 1)+ node = tree_operations.resolve_unique_node(tree, "AB")+ self.assertEqual(sorted(node.leaf_names()), ["A", "B"])++ def test_an_absent_name_is_refused(self) -> None:+ tree = tree_operations.load_tree(self.newick(BALANCED), 1)+ with self.assertRaisesRegex(tree_operations.UserInputError, "node not found"):+ tree_operations.resolve_unique_node(tree, "Z")++ def test_an_ambiguous_name_is_refused_rather_than_silently_taking_the_first(self) -> None:+ # Rooting on "whichever A ETE traversed first" would give a different+ # tree run to run, so a duplicate name has to be an error.+ tree = tree_operations.load_tree(self.newick("((A,A),(B,C));"), 1)+ with self.assertRaisesRegex(tree_operations.UserInputError, "ambiguous"):+ tree_operations.resolve_unique_node(tree, "A")+++class KeepNameTests(TreeFixtureCase):+ def test_names_passed_on_the_command_line_are_returned_in_order(self) -> None:+ self.assertEqual(tree_operations.read_keep_names(["A", "B"], None), ["A", "B"])++ def test_a_taxon_file_skips_blank_lines_and_comments(self) -> None:+ path = self.root / "keep.txt"+ path.write_text("# keep these\nA\n\n B \n#C\n", encoding="utf-8")+ self.assertEqual(tree_operations.read_keep_names(None, path), ["A", "B"])++ def test_an_empty_request_is_refused(self) -> None:+ for values, file_path in ((None, None), ([], None)):+ with self.subTest(values=values):+ with self.assertRaisesRegex(+ tree_operations.UserInputError, "at least one taxon"+ ):+ tree_operations.read_keep_names(values, file_path)++ def test_a_taxon_file_of_only_comments_is_refused(self) -> None:+ path = self.root / "keep.txt"+ path.write_text("# nothing here\n\n", encoding="utf-8")+ with self.assertRaisesRegex(tree_operations.UserInputError, "at least one taxon"):+ tree_operations.read_keep_names(None, path)++ def test_duplicate_requests_are_refused(self) -> None:+ # `prune --keep A A` would silently retain one leaf while reporting two.+ with self.assertRaisesRegex(tree_operations.UserInputError, "duplicate"):+ tree_operations.read_keep_names(["A", "B", "A"], None)++ def test_a_missing_taxon_file_is_refused(self) -> None:+ with self.assertRaisesRegex(tree_operations.UserInputError, "taxon file"):+ tree_operations.read_keep_names(None, self.root / "absent.txt")+++class RequestedNameValidationTests(TreeFixtureCase):+ def test_names_that_all_resolve_pass_silently(self) -> None:+ tree = tree_operations.load_tree(self.newick(BALANCED), 1)+ self.assertIsNone(tree_operations.validate_requested_names(tree, ["A", "D"]))++ def test_an_internal_node_name_is_not_a_leaf(self) -> None:+ # `prune` works on leaf names; "AB" exists in the tree but is not one.+ tree = tree_operations.load_tree(self.newick(BALANCED), 1)+ with self.assertRaisesRegex(tree_operations.UserInputError, "absent"):+ tree_operations.validate_requested_names(tree, ["AB"])++ def test_a_leaf_name_duplicated_in_the_tree_is_refused(self) -> None:+ tree = tree_operations.load_tree(self.newick("((A,A),(B,C));"), 1)+ with self.assertRaisesRegex(tree_operations.UserInputError, "duplicated"):+ tree_operations.validate_requested_names(tree, ["A"])+++class SaveTreeTests(TreeFixtureCase):+ def test_a_saved_tree_reloads_with_the_same_topology(self) -> None:+ tree = tree_operations.load_tree(self.newick(BALANCED), 1)+ output = self.root / "out.nwk"+ tree_operations.save_tree(tree, output, 1, [])+ reloaded = tree_operations.load_tree(output, 1)+ self.assertEqual(sorted(reloaded.leaf_names()), ["A", "B", "C", "D"])+ # Branch lengths survive the round trip, so the total is unchanged.+ self.assertEqual(+ sum(float(node.dist) for node in reloaded.traverse() if not node.is_root),+ 8.0,+ )++ def test_the_file_ends_in_exactly_one_newline(self) -> None:+ tree = tree_operations.load_tree(self.newick(BALANCED), 1)+ output = self.root / "out.nwk"+ tree_operations.save_tree(tree, output, 1, [])+ text = output.read_text(encoding="utf-8")+ self.assertTrue(text.endswith(";\n"))+ self.assertFalse(text.endswith("\n\n"))++ def test_a_missing_output_directory_is_refused_before_writing(self) -> None:+ tree = tree_operations.load_tree(self.newick(BALANCED), 1)+ with self.assertRaisesRegex(tree_operations.UserInputError, "output directory"):+ tree_operations.save_tree(tree, self.root / "nope" / "out.nwk", 1, [])+++class CommandLineTests(TreeFixtureCase):+ """`main` end to end: the exit codes and the numbers it prints."""++ def run_main(self, argv: list[str]) -> tuple[int, str, str]:+ out, err = io.StringIO(), io.StringIO()+ with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):+ code = tree_operations.main(argv)+ return code, out.getvalue(), err.getvalue()++ def test_a_missing_input_exits_two_with_a_message_on_stderr(self) -> None:+ code, _, err = self.run_main(["stats", str(self.root / "absent.nwk")])+ self.assertEqual(code, 2)+ self.assertIn("error:", err)++ def test_stats_json_round_trips_through_the_cli(self) -> None:+ code, out, _ = self.run_main(+ ["stats", str(self.newick(BALANCED)), "--parser", "1", "--json"]+ )+ self.assertEqual(code, 0)+ self.assertEqual(json.loads(out)["leaf_count"], 4)++ def test_the_wrong_parser_number_is_reported_rather_than_guessed(self) -> None:+ # BALANCED labels its internal nodes, so parser 0 -- which reads that+ # position as a support value -- cannot convert "AB" to a float. Falling+ # back to another parser would silently reinterpret the tree.+ code, _, err = self.run_main(["stats", str(self.newick(BALANCED))])+ self.assertEqual(code, 2)+ self.assertIn("could not parse", err)++ def test_leaves_prints_one_name_per_line(self) -> None:+ code, out, _ = self.run_main(["leaves", str(self.newick(PLAIN))])+ self.assertEqual(code, 0)+ self.assertEqual(sorted(out.split()), ["A", "B", "C", "D"])++ def test_an_unnamed_leaf_still_occupies_a_line(self) -> None:+ # Otherwise the leaf count and the line count disagree downstream.+ code, out, _ = self.run_main(["leaves", str(self.newick("((A,),(B,C));"))])+ self.assertEqual(code, 0)+ self.assertEqual(len(out.splitlines()), 4)++ def test_the_ascii_drawing_contains_every_leaf(self) -> None:+ code, out, _ = self.run_main(["ascii", str(self.newick(PLAIN))])+ self.assertEqual(code, 0)+ for name in ("A", "B", "C", "D"):+ self.assertIn(name, out)++ def test_identical_trees_have_a_robinson_foulds_distance_of_zero(self) -> None:+ path = self.newick("((A:1,B:1):1,(C:1,D:1):1);")+ code, out, _ = self.run_main(["compare", str(path), str(path), "--unrooted"])+ self.assertEqual(code, 0)+ result = json.loads(out)+ self.assertEqual(result["rf"], 0)+ self.assertEqual(result["normalized_rf"], 0.0)+ self.assertEqual(result["common_leaf_count"], 4)++ def test_the_two_distinct_four_taxon_topologies_are_maximally_apart(self) -> None:+ # Unrooted, ((A,B),(C,D)) and ((A,C),(B,D)) each have exactly one+ # non-trivial split and the splits differ, so RF = 1 + 1 = 2 and the+ # maximum possible RF for four taxa is also 2.+ first = self.newick("((A:1,B:1):1,(C:1,D:1):1);", "a.nwk")+ second = self.newick("((A:1,C:1):1,(B:1,D:1):1);", "b.nwk")+ code, out, _ = self.run_main(["compare", str(first), str(second), "--unrooted"])+ self.assertEqual(code, 0)+ result = json.loads(out)+ self.assertEqual(result["rf"], 2)+ self.assertEqual(result["max_rf"], 2)+ self.assertEqual(result["normalized_rf"], 1.0)+ self.assertEqual(result["common_leaves"], ["A", "B", "C", "D"])++ def test_comparing_a_tree_with_duplicate_names_is_refused(self) -> None:+ # Robinson-Foulds is defined over sets of leaf labels; duplicates make+ # the split sets meaningless, so the comparison must not run.+ good = self.newick("((A,B),(C,D));", "good.nwk")+ bad = self.newick("((A,A),(C,D));", "bad.nwk")+ code, _, err = self.run_main(["compare", str(good), str(bad)])+ self.assertEqual(code, 2)+ self.assertIn("duplicate leaf names", err)++ def test_comparing_a_tree_with_unnamed_leaves_is_refused(self) -> None:+ good = self.newick("((A,B),(C,D));", "good.nwk")+ bad = self.newick("((A,),(C,D));", "bad.nwk")+ code, _, err = self.run_main(["compare", str(good), str(bad)])+ self.assertEqual(code, 2)+ self.assertIn("unnamed leaves", err)++ def test_pruning_keeps_only_the_requested_leaves(self) -> None:+ output = self.root / "pruned.nwk"+ code, out, _ = self.run_main(+ [+ "prune",+ str(self.newick("((A:1,B:1):1,(C:1,D:1):1);")),+ str(output),+ "--keep",+ "A",+ "B",+ "--output-parser",+ "1",+ ]+ )+ self.assertEqual(code, 0)+ self.assertIn("Retained 2 leaves", out)+ self.assertEqual(+ sorted(tree_operations.load_tree(output, 1).leaf_names()), ["A", "B"]+ )++ def test_pruning_preserves_the_path_length_between_retained_leaves(self) -> None:+ # A--B is 1+1 = 2 in the input; with --preserve-branch-length the+ # collapsed internal node's length must be folded in, not discarded.+ output = self.root / "pruned.nwk"+ code, _, _ = self.run_main(+ [+ "prune",+ str(self.newick("((A:1,B:1):5,(C:1,D:1):1);")),+ str(output),+ "--keep",+ "A",+ "B",+ "--output-parser",+ "1",+ ]+ )+ self.assertEqual(code, 0)+ pruned = tree_operations.load_tree(output, 1)+ leaves = {leaf.name: leaf for leaf in pruned.leaves()}+ self.assertEqual(pruned.get_distance(leaves["A"], leaves["B"]), 2.0)++ def test_pruning_to_an_absent_leaf_is_refused(self) -> None:+ code, _, err = self.run_main(+ [+ "prune",+ str(self.newick(PLAIN)),+ str(self.root / "pruned.nwk"),+ "--keep",+ "Z",+ ]+ )+ self.assertEqual(code, 2)+ self.assertIn("absent", err)++ def test_rerooting_on_an_outgroup_preserves_the_leaves_and_total_length(self) -> None:+ # Rerooting relocates the root along an existing branch; it must not+ # create, destroy, or rescale any evolutionary distance.+ output = self.root / "rerooted.nwk"+ code, out, _ = self.run_main(+ [+ "reroot",+ str(self.newick("((A:1,B:1):1,(C:1,D:1):1);")),+ str(output),+ "--outgroup",+ "A",+ "--output-parser",+ "1",+ ]+ )+ self.assertEqual(code, 0)+ self.assertIn("outgroup 'A'", out)+ rerooted = tree_operations.load_tree(output, 1)+ self.assertEqual(sorted(rerooted.leaf_names()), ["A", "B", "C", "D"])+ self.assertAlmostEqual(+ sum(float(node.dist) for node in rerooted.traverse() if not node.is_root),+ 6.0,+ )++ def test_midpoint_rooting_reports_which_midpoint_it_used(self) -> None:+ source = self.newick("((A:1,B:1):1,(C:1,D:1):1);")+ code, out, _ = self.run_main(+ ["reroot", str(source), str(self.root / "m.nwk"), "--midpoint"]+ )+ self.assertEqual(code, 0)+ self.assertIn("branch-length midpoint", out)++ code, out, _ = self.run_main(+ [+ "reroot",+ str(source),+ str(self.root / "t.nwk"),+ "--midpoint",+ "--topological",+ ]+ )+ self.assertEqual(code, 0)+ self.assertIn("topological midpoint", out)++ def test_topological_without_midpoint_is_refused(self) -> None:+ # --topological only changes how the midpoint is found, so pairing it+ # with --outgroup would silently do nothing.+ code, _, err = self.run_main(+ [+ "reroot",+ str(self.newick(PLAIN)),+ str(self.root / "out.nwk"),+ "--outgroup",+ "A",+ "--topological",+ ]+ )+ self.assertEqual(code, 2)+ self.assertIn("--topological applies only to --midpoint", err)++ def test_converting_between_parsers_keeps_the_leaf_set(self) -> None:+ output = self.root / "converted.nwk"+ code, _, _ = self.run_main(+ [+ "convert",+ str(self.newick(BALANCED)),+ str(output),+ "--input-parser",+ "1",+ "--output-parser",+ "1",+ ]+ )+ self.assertEqual(code, 0)+ self.assertEqual(+ sorted(tree_operations.load_tree(output, 1).leaf_names()),+ ["A", "B", "C", "D"],+ )+++class BindAddressTests(unittest.TestCase):+ """SmartView serves an unauthenticated viewer, so the bind host is a gate."""++ def test_every_loopback_spelling_is_allowed_without_the_opt_in(self) -> None:+ # A validator that rejected these would make the default `--host+ # 127.0.0.1` unusable, so the permissive direction matters as much as+ # the restrictive one.+ for host in ("127.0.0.1", "127.0.0.2", "::1", "localhost", "LocalHost"):+ with self.subTest(host=host):+ self.assertIsNone(quick_visualize.validate_bind_address(host, False))++ def test_the_wildcard_address_is_refused_without_the_opt_in(self) -> None:+ # 0.0.0.0 is not loopback: it publishes the viewer on every interface.+ with self.assertRaisesRegex(quick_visualize.UserInputError, "non-loopback"):+ quick_visualize.validate_bind_address("0.0.0.0", False)++ def test_routable_addresses_are_refused_without_the_opt_in(self) -> None:+ for host in ("192.168.1.10", "10.0.0.5", "8.8.8.8", "::", "2001:db8::1"):+ with self.subTest(host=host):+ with self.assertRaises(quick_visualize.UserInputError):+ quick_visualize.validate_bind_address(host, False)++ def test_a_host_name_that_merely_starts_with_localhost_is_refused(self) -> None:+ # "localhost.example.com" resolves wherever its DNS says; only the+ # exact name is treated as loopback.+ for host in ("localhost.example.com", "notlocalhost", "example.com"):+ with self.subTest(host=host):+ with self.assertRaisesRegex(+ quick_visualize.UserInputError, "--allow-remote-bind"+ ):+ quick_visualize.validate_bind_address(host, False)++ def test_the_opt_in_permits_exactly_what_it_says(self) -> None:+ for host in ("0.0.0.0", "192.168.1.10", "example.com", "::"):+ with self.subTest(host=host):+ self.assertIsNone(quick_visualize.validate_bind_address(host, True))+++class SupportFractionTests(unittest.TestCase):+ def test_percentages_are_normalised_and_fractions_left_alone(self) -> None:+ # Bootstrap support is written both as 0-1 and as 0-100; colouring by+ # support has to mean the same thing either way.+ self.assertEqual(quick_visualize.support_fraction(95), 0.95)+ self.assertEqual(quick_visualize.support_fraction(0.95), 0.95)+ self.assertEqual(quick_visualize.support_fraction(100), 1.0)++ def test_the_boundary_value_one_is_treated_as_a_fraction(self) -> None:+ # `numeric > 1` -- a support of exactly 1 is full support, not 1%.+ self.assertEqual(quick_visualize.support_fraction(1), 1.0)++ def test_zero_support_stays_zero_and_missing_support_stays_none(self) -> None:+ self.assertEqual(quick_visualize.support_fraction(0), 0.0)+ self.assertIsNone(quick_visualize.support_fraction(None))+++class SupportColorTests(TreeFixtureCase):+ def args(self, extra: list[str] | None = None) -> argparse.Namespace:+ return quick_visualize.build_parser().parse_args(+ ["tree.nwk", *(extra or [])]+ )++ def test_each_support_band_gets_its_own_colour(self) -> None:+ path = self.newick("((A:1,B:1)95:1,((C:1,D:1)70:1,(E:1,F:1)50:1)80:1)100;")+ tree = quick_visualize.load_tree(path, 0)+ args = self.args()+ by_support = {+ float(node.support): quick_visualize.support_color(node, args)+ for node in tree.traverse()+ if not node.is_leaf+ }+ self.assertEqual(by_support[95.0], args.high_support_color)+ # 70 normalises to exactly the moderate threshold, which is inclusive.+ self.assertEqual(by_support[70.0], args.moderate_support_color)+ self.assertEqual(by_support[80.0], args.moderate_support_color)+ self.assertEqual(by_support[50.0], args.low_support_color)++ def test_a_node_with_no_support_gets_the_missing_colour(self) -> None:+ tree = quick_visualize.load_tree(self.newick("((A:1,B:1):1,(C:1,D:1):1);"), 0)+ args = self.args()+ internal = next(node for node in tree.traverse() if not node.is_leaf)+ self.assertIsNone(internal.support)+ self.assertEqual(+ quick_visualize.support_color(internal, args), args.missing_support_color+ )++ def test_custom_thresholds_move_the_bands(self) -> None:+ tree = quick_visualize.load_tree(self.newick("((A:1,B:1)80:1,(C:1,D:1)80:1);"), 0)+ # The root itself carries no support here, so pick a labelled clade.+ node = next(+ node+ for node in tree.traverse()+ if not node.is_leaf and node.support is not None+ )+ strict = self.args(["--high-support", "0.99", "--moderate-support", "0.9"])+ lenient = self.args(["--high-support", "0.8", "--moderate-support", "0.5"])+ self.assertEqual(+ quick_visualize.support_color(node, strict), strict.low_support_color+ )+ self.assertEqual(+ quick_visualize.support_color(node, lenient), lenient.high_support_color+ )+++class ValidateArgsTests(unittest.TestCase):+ def args(self, extra: list[str] | None = None) -> argparse.Namespace:+ return quick_visualize.build_parser().parse_args(["tree.nwk", *(extra or [])])++ def test_the_shipped_defaults_validate(self) -> None:+ # If the defaults failed their own validator the CLI would be unusable+ # with no arguments at all.+ self.assertIsNone(quick_visualize.validate_args(self.args()))++ def test_support_thresholds_must_be_ordered_and_within_zero_to_one(self) -> None:+ for extra in (+ ["--moderate-support", "0.95", "--high-support", "0.9"],+ ["--high-support", "1.5"],+ ["--moderate-support", "-0.1"],+ ):+ with self.subTest(extra=extra):+ with self.assertRaisesRegex(+ quick_visualize.UserInputError, "support thresholds"+ ):+ quick_visualize.validate_args(self.args(extra))++ def test_equal_thresholds_are_allowed(self) -> None:+ # The comparison chain is <=, so a single cut-off between "high" and+ # "low" is a legitimate configuration.+ quick_visualize.validate_args(+ self.args(["--moderate-support", "0.9", "--high-support", "0.9"])+ )++ def test_negative_sizes_are_refused_and_zero_is_allowed(self) -> None:+ for flag in ("--label-size", "--leaf-size", "--internal-size"):+ with self.subTest(flag=flag):+ with self.assertRaisesRegex(+ quick_visualize.UserInputError, "cannot be negative"+ ):+ quick_visualize.validate_args(self.args([flag, "-1"]))+ # Zero is how a user hides a marker, so it must be accepted.+ quick_visualize.validate_args(self.args([flag, "0"]))++ def test_dimensions_must_be_positive_when_given(self) -> None:+ for flag in ("--width", "--height", "--dpi"):+ with self.subTest(flag=flag):+ with self.assertRaisesRegex(+ quick_visualize.UserInputError, "must be positive"+ ):+ quick_visualize.validate_args(self.args([flag, "0"]))+ quick_visualize.validate_args(self.args([flag, "1"]))++ def test_the_port_range_is_the_tcp_range(self) -> None:+ for port in ("0", "65536", "-1"):+ with self.subTest(port=port):+ with self.assertRaisesRegex(quick_visualize.UserInputError, "port"):+ quick_visualize.validate_args(self.args(["--port", port]))+ for port in ("1", "8080", "65535"):+ with self.subTest(port=port):+ quick_visualize.validate_args(self.args(["--port", port]))++ def test_the_arc_bounds_are_degrees(self) -> None:+ for extra in (["--arc-start", "361"], ["--arc-start", "-361"]):+ with self.subTest(extra=extra):+ with self.assertRaisesRegex(quick_visualize.UserInputError, "arc-start"):+ quick_visualize.validate_args(self.args(extra))+ for extra in (["--arc-span", "0"], ["--arc-span", "361"], ["--arc-span", "-90"]):+ with self.subTest(extra=extra):+ with self.assertRaisesRegex(quick_visualize.UserInputError, "arc-span"):+ quick_visualize.validate_args(self.args(extra))+ # A full circle and a negative start are both legitimate.+ quick_visualize.validate_args(+ self.args(["--arc-start", "-360", "--arc-span", "360"])+ )+++class EngineChoiceTests(unittest.TestCase):+ def args(self, extra: list[str]) -> argparse.Namespace:+ return quick_visualize.build_parser().parse_args(["tree.nwk", *extra])++ def test_no_output_means_the_interactive_engine(self) -> None:+ self.assertEqual(quick_visualize.choose_engine(self.args([])), "smartview")++ def test_the_suffix_picks_the_engine_that_can_write_it(self) -> None:+ # SmartView only screenshots PNG; vector output needs Qt treeview.+ cases = {"out.png": "smartview", "out.pdf": "treeview", "out.svg": "treeview"}+ for name, expected in cases.items():+ with self.subTest(name=name):+ self.assertEqual(+ quick_visualize.choose_engine(self.args([name])), expected+ )++ def test_suffix_matching_is_case_insensitive(self) -> None:+ self.assertEqual(quick_visualize.choose_engine(self.args(["OUT.PDF"])), "treeview")++ def test_an_unwritable_suffix_is_refused_rather_than_guessed(self) -> None:+ for name in ("out.tiff", "out.eps", "out"):+ with self.subTest(name=name):+ with self.assertRaisesRegex(+ quick_visualize.UserInputError, "cannot infer renderer"+ ):+ quick_visualize.choose_engine(self.args([name]))++ def test_an_explicit_engine_overrides_the_suffix(self) -> None:+ self.assertEqual(+ quick_visualize.choose_engine(self.args(["out.tiff", "--engine", "treeview"])),+ "treeview",+ )+ self.assertEqual(+ quick_visualize.choose_engine(self.args(["out.pdf", "--engine", "smartview"])),+ "smartview",+ )+++class RenderDestinationTests(TreeFixtureCase):+ """Destination checks run before any renderer is loaded or invoked."""++ def args(self, extra: list[str] | None = None) -> argparse.Namespace:+ return quick_visualize.build_parser().parse_args(["tree.nwk", *(extra or [])])++ def setUp(self) -> None:+ super().setUp()+ self.tree = quick_visualize.load_tree(self.newick(BALANCED), 1)++ def test_smartview_refuses_a_non_png_destination(self) -> None:+ with self.assertRaisesRegex(quick_visualize.UserInputError, "PNG"):+ quick_visualize.render_smartview(+ self.tree, None, self.root / "out.pdf", self.args()+ )++ def test_smartview_refuses_a_missing_output_directory(self) -> None:+ with self.assertRaisesRegex(quick_visualize.UserInputError, "output directory"):+ quick_visualize.render_smartview(+ self.tree, None, self.root / "nope" / "out.png", self.args()+ )++ def test_treeview_refuses_a_suffix_it_cannot_write(self) -> None:+ with self.assertRaisesRegex(quick_visualize.UserInputError, r"\.png, \.pdf, or \.svg"):+ quick_visualize.render_treeview(self.tree, self.root / "out.txt", self.args())++ def test_treeview_refuses_a_missing_output_directory(self) -> None:+ with self.assertRaisesRegex(quick_visualize.UserInputError, "output directory"):+ quick_visualize.render_treeview(+ self.tree, self.root / "nope" / "out.pdf", self.args()+ )++ def test_the_missing_qt_extra_is_reported_as_an_install_hint(self) -> None:+ try:+ import ete4.treeview # noqa: F401+ except ImportError:+ pass+ else:+ self.skipTest("ete4[treeview] is installed, so the hint cannot be triggered")+ with self.assertRaisesRegex(quick_visualize.UserInputError, r"ete4\[treeview\]"):+ quick_visualize.create_treeview_style(self.tree, self.args())+++class SmartViewLayoutTests(TreeFixtureCase):+ """The CLI's display options have to reach the SmartView style dictionary."""++ def args(self, extra: list[str] | None = None) -> argparse.Namespace:+ return quick_visualize.build_parser().parse_args(["tree.nwk", *(extra or [])])++ def elements(self, args: argparse.Namespace) -> list:+ return list(quick_visualize.create_smartview_layout(args).draw_tree(None))++ def style(self, args: argparse.Namespace) -> dict:+ # ete4's Layout prepends its own DEFAULT_TREE_STYLE, so the style the+ # script yields is the second element.+ return self.elements(args)[1]++ def test_the_layout_mode_becomes_the_smartview_shape(self) -> None:+ self.assertEqual(self.style(self.args())["shape"], "rectangular")+ self.assertEqual(self.style(self.args(["--mode", "c"]))["shape"], "circular")++ def test_arc_options_are_only_emitted_for_the_circular_layout(self) -> None:+ # A rectangular tree has no arc; passing angle keys would be ignored at+ # best and misread at worst.+ rectangular = self.style(self.args())+ self.assertNotIn("angle-start", rectangular)+ circular = self.style(self.args(["--mode", "c", "--arc-span", "180"]))+ self.assertEqual(circular["angle-span"], 180)+ self.assertEqual(circular["angle-start"], 0)++ def test_collapse_thresholds_are_passed_through_unchanged(self) -> None:+ style = self.style(self.args(["--collapse-pixels", "20", "--content-pixels", "6"]))+ self.assertEqual(style["node-height-min"], 20)+ self.assertEqual(style["content-height-min"], 6)++ def dots(self, args: argparse.Namespace, newick: str, parser: int = 0) -> dict:+ """{leaf-or-support key: dot spec} for every node of `newick`."""+ layout = quick_visualize.create_smartview_layout(args)+ tree = quick_visualize.load_tree(self.newick(newick), parser)+ found = {}+ for node in tree.traverse():+ elements = [+ element+ for element in layout.draw_node(node, ())+ if isinstance(element, dict) and "dot" in element+ ]+ self.assertEqual(len(elements), 1, "every node gets exactly one dot")+ found[node.name if node.is_leaf else node.support] = elements[0]["dot"]+ return found++ def test_leaves_and_internal_nodes_get_their_own_colour_and_size(self) -> None:+ args = self.args()+ dots = self.dots(args, "((A:1,B:1)80:1,(C:1,D:1)80:1);")+ self.assertEqual(dots["A"]["fill"], args.leaf_color)+ self.assertEqual(dots["A"]["radius"], args.leaf_size)+ self.assertEqual(dots[80.0]["fill"], args.internal_color)+ self.assertEqual(dots[80.0]["radius"], args.internal_size)++ def test_colour_by_support_repaints_internal_nodes_only(self) -> None:+ # Leaves have no bootstrap support, so they must keep the leaf colour+ # even when --color-by-support is on.+ args = self.args(["--color-by-support"])+ dots = self.dots(args, "((A:1,B:1)95:1,(C:1,D:1)50:1);")+ self.assertEqual(dots["A"]["fill"], args.leaf_color)+ self.assertEqual(dots[95.0]["fill"], args.high_support_color)+ self.assertEqual(dots[50.0]["fill"], args.low_support_color)++ def test_a_title_adds_a_header_face_and_no_title_adds_nothing(self) -> None:+ # An empty --title must not yield a blank face that reserves header space.+ self.assertEqual(len(self.elements(self.args())), 2)+ self.assertEqual(len(self.elements(self.args(["--title", ""]))), 2)+ self.assertEqual(len(self.elements(self.args(["--title", "Fig 1"]))), 3)+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/exa-search/test_exa_search.py b/tests/exa-search/test_exa_search.pyindex 22d5b211..4ac55b5f 100644--- a/tests/exa-search/test_exa_search.py+++ b/tests/exa-search/test_exa_search.py@@ -17,10 +17,18 @@ import osimport sysimport tempfileimport unittest++import pytestfrom pathlib import Pathfrom types import SimpleNamespacefrom unittest.mock import MagicMock, patch+import skill_contract++# Guarded so a bare project-environment run skips cleanly instead of failing;+# the real run is `tests/run_all.py --isolated exa-search`.+pytest.importorskip("exa_py", reason="exa-search needs exa-py")+SKILL_ROOT = Path(__file__).resolve().parents[2] / "skills" / "exa-search"SCRIPTS_DIR = SKILL_ROOT / "scripts"@@ -213,5 +221,10 @@ class IntegrationHeaderAndFlowTests(unittest.TestCase):self.assertEqual(payload["results"][0]["title"], "Attention Is All You Need")+# 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(SKILL_ROOT)+if __name__ == "__main__":unittest.main()diff --git a/tests/experimental-design/test_scripts.py b/tests/experimental-design/test_scripts.pynew file mode 100644index 00000000..15fcccbd--- /dev/null+++ b/tests/experimental-design/test_scripts.py@@ -0,0 +1,322 @@+"""Tests for the experimental-design generators.++Randomisation and DOE code is easy to get subtly wrong in ways that no error+message reveals -- a block that does not actually balance, an allocation ratio+applied to the wrong arm, a design matrix decoded to the wrong real units. So+the assertions here are about the statistical properties the docstrings+promise, not just about shapes: every permuted block is exactly balanced, a+2:1 ratio produces twice as many treatment units, and a two-level design+decodes to the factor's own low/high values.++Determinism matters as much as correctness: every generator takes a seed, and+an experimental design that cannot be reproduced from its seed is not a design.+"""++from __future__ import annotations++import sys+import unittest+from pathlib import Path++import pytest++import skill_contract++SKILL_ROOT = Path(__file__).resolve().parents[2] / "skills" / "experimental-design"+SCRIPTS = SKILL_ROOT / "scripts"+sys.path.insert(0, str(SCRIPTS))++np = pytest.importorskip("numpy", reason="experimental-design needs numpy")+pd = pytest.importorskip("pandas", reason="experimental-design needs pandas")++import randomization # noqa: E402++# Both scripts are importable libraries with a worked example under+# `if __name__ == "__main__":` rather than argparse CLIs, so the contract's+# demo-block case applies instead of its `--help` case.+DemoBlockTests = skill_contract.cli.demo_test_case(+ SKILL_ROOT, ("doe_designs.py", "randomization.py")+)+++def doe():+ """Import the DOE module, skipping when pyDOE3 is absent."""+ pytest.importorskip("pyDOE3", reason="doe_designs needs pyDOE3")+ import doe_designs++ return doe_designs+++class RatioTests(unittest.TestCase):+ def test_no_ratio_means_one_of_each_arm(self) -> None:+ self.assertEqual(+ randomization._normalize_ratio(["a", "b", "c"], None), ["a", "b", "c"]+ )++ def test_a_ratio_repeats_each_arm(self) -> None:+ self.assertEqual(+ randomization._normalize_ratio(["treatment", "control"], (2, 1)),+ ["treatment", "treatment", "control"],+ )++ def test_a_mismatched_ratio_length_is_refused(self) -> None:+ with self.assertRaisesRegex(ValueError, "one entry per arm"):+ randomization._normalize_ratio(["a", "b"], (1, 1, 1))++ def test_non_positive_ratio_entries_are_refused(self) -> None:+ # A zero-weight arm would silently vanish from the allocation.+ for ratio in ((1, 0), (-1, 1), (0, 0)):+ with self.subTest(ratio=ratio):+ with self.assertRaisesRegex(ValueError, "positive integers"):+ randomization._normalize_ratio(["a", "b"], ratio)+++class SimpleRandomizationTests(unittest.TestCase):+ def test_every_unit_is_assigned_exactly_once(self) -> None:+ frame = randomization.simple_randomization(25, seed=1)+ self.assertEqual(len(frame), 25)+ self.assertEqual(list(frame["unit_id"]), list(range(1, 26)))+ self.assertTrue(set(frame["arm"]) <= {"treatment", "control"})++ def test_the_same_seed_reproduces_the_same_allocation(self) -> None:+ first = randomization.simple_randomization(40, seed=7)+ second = randomization.simple_randomization(40, seed=7)+ pd.testing.assert_frame_equal(first, second)++ def test_different_seeds_generally_differ(self) -> None:+ first = randomization.simple_randomization(60, seed=1)+ second = randomization.simple_randomization(60, seed=2)+ self.assertFalse(first["arm"].equals(second["arm"]))++ def test_an_allocation_ratio_shifts_the_expected_split(self) -> None:+ # Simple randomisation only balances in expectation, so assert the+ # direction over a large sample rather than an exact count.+ frame = randomization.simple_randomization(+ 4000, arms=("treatment", "control"), ratio=(3, 1), seed=3+ )+ share = (frame["arm"] == "treatment").mean()+ self.assertAlmostEqual(share, 0.75, delta=0.03)++ def test_three_arms_are_supported(self) -> None:+ frame = randomization.simple_randomization(+ 300, arms=("a", "b", "c"), seed=5+ )+ self.assertEqual(set(frame["arm"]), {"a", "b", "c"})+++class BlockRandomizationTests(unittest.TestCase):+ def test_each_complete_block_is_exactly_balanced(self) -> None:+ # This is the entire point of permuted blocks: balance holds throughout+ # enrollment, not only at the end.+ frame = randomization.block_randomization(24, block_size=4, seed=1)+ for block, rows in frame.groupby("block"):+ with self.subTest(block=block):+ counts = rows["arm"].value_counts().to_dict()+ self.assertEqual(counts, {"treatment": 2, "control": 2})++ def test_the_allocation_ratio_holds_within_every_block(self) -> None:+ frame = randomization.block_randomization(+ 18, arms=["treatment", "control"], ratio=(2, 1), block_size=6, seed=1+ )+ for block, rows in frame.groupby("block"):+ with self.subTest(block=block):+ counts = rows["arm"].value_counts().to_dict()+ self.assertEqual(counts, {"treatment": 4, "control": 2})++ def test_a_block_size_incompatible_with_the_ratio_is_refused(self) -> None:+ with self.assertRaisesRegex(ValueError, "must be a multiple of"):+ randomization.block_randomization(12, ratio=(2, 1), block_size=4)++ def test_the_default_block_size_is_valid_for_the_ratio(self) -> None:+ frame = randomization.block_randomization(12, ratio=(2, 1), seed=1)+ sizes = frame.groupby("block").size().unique()+ self.assertEqual(list(sizes), [6])++ def test_a_partial_final_block_is_truncated_not_padded(self) -> None:+ frame = randomization.block_randomization(10, block_size=4, seed=1)+ self.assertEqual(len(frame), 10)+ self.assertEqual(list(frame["unit_id"]), list(range(1, 11)))++ def test_the_same_seed_reproduces_the_same_blocks(self) -> None:+ pd.testing.assert_frame_equal(+ randomization.block_randomization(20, seed=11),+ randomization.block_randomization(20, seed=11),+ )+++class StratifiedTests(unittest.TestCase):+ def test_every_stratum_is_balanced_independently(self) -> None:+ frame = randomization.stratified_block_randomization(+ {"siteA": 8, "siteB": 12}, block_size=4, seed=1+ )+ self.assertEqual(len(frame), 20)+ balance = randomization.arm_balance(frame, by="stratum")+ self.assertEqual(balance.loc["siteA", "treatment"], 4)+ self.assertEqual(balance.loc["siteA", "control"], 4)+ self.assertEqual(balance.loc["siteB", "treatment"], 6)+ self.assertEqual(balance.loc["siteB", "control"], 6)++ def test_unit_ids_are_renumbered_across_the_whole_cohort(self) -> None:+ frame = randomization.stratified_block_randomization(+ {"a": 4, "b": 4}, block_size=4, seed=1+ )+ self.assertEqual(list(frame["unit_id"]), list(range(1, 9)))++ def test_a_label_sequence_is_accepted_as_well_as_a_count_map(self) -> None:+ labels = ["north"] * 4 + ["south"] * 8+ frame = randomization.stratified_block_randomization(+ labels, block_size=4, seed=1+ )+ self.assertEqual(len(frame), 12)+ self.assertEqual(+ frame["stratum"].value_counts().to_dict(), {"south": 8, "north": 4}+ )++ def test_strata_are_seeded_apart_so_they_do_not_share_a_pattern(self) -> None:+ # Every stratum getting the same permutation would defeat stratification.+ frame = randomization.stratified_block_randomization(+ {"a": 8, "b": 8}, block_size=4, seed=1+ )+ first = list(frame[frame["stratum"] == "a"]["arm"])+ second = list(frame[frame["stratum"] == "b"]["arm"])+ self.assertNotEqual(first, second)+++class ClusterTests(unittest.TestCase):+ def test_one_row_per_cluster_keyed_by_cluster_id(self) -> None:+ frame = randomization.cluster_randomization(+ ["clinic-1", "clinic-2", "clinic-3", "clinic-4"], seed=1+ )+ self.assertEqual(len(frame), 4)+ self.assertEqual(+ list(frame["cluster_id"]),+ ["clinic-1", "clinic-2", "clinic-3", "clinic-4"],+ )+ self.assertNotIn("unit_id", frame.columns)++ def test_an_integer_count_generates_cluster_labels(self) -> None:+ frame = randomization.cluster_randomization(3, seed=1)+ self.assertEqual(+ list(frame["cluster_id"]), ["cluster_1", "cluster_2", "cluster_3"]+ )++ def test_clusters_are_blocked_so_arms_stay_balanced(self) -> None:+ frame = randomization.cluster_randomization(8, block_size=4, seed=1)+ counts = frame["arm"].value_counts().to_dict()+ self.assertEqual(counts, {"treatment": 4, "control": 4})+++class RunOrderTests(unittest.TestCase):+ def test_run_order_is_a_permutation_of_every_row(self) -> None:+ design = pd.DataFrame({"temp": [20, 20, 60, 60], "ph": [6, 8, 6, 8]})+ randomized = randomization.assign_factorial_runs(design, seed=1)+ self.assertEqual(sorted(randomized["run_order"]), [1, 2, 3, 4])+ self.assertEqual(len(randomized), len(design))++ def test_rows_are_returned_sorted_by_run_order(self) -> None:+ design = pd.DataFrame({"x": range(10)})+ randomized = randomization.assign_factorial_runs(design, seed=2)+ self.assertEqual(list(randomized["run_order"]), list(range(1, 11)))++ def test_the_original_design_is_not_mutated(self) -> None:+ design = pd.DataFrame({"x": range(5)})+ before = design.copy()+ randomization.assign_factorial_runs(design, seed=1)+ pd.testing.assert_frame_equal(design, before)++ def test_randomising_actually_reorders_the_runs(self) -> None:+ # A systematic order confounds factors with drift, which is the whole+ # reason this function exists.+ design = pd.DataFrame({"x": range(12)})+ randomized = randomization.assign_factorial_runs(design, seed=1)+ self.assertNotEqual(list(randomized["x"]), list(range(12)))+++class BalanceReportTests(unittest.TestCase):+ def test_counts_are_reported_per_arm(self) -> None:+ frame = pd.DataFrame({"arm": ["a", "a", "b"]})+ self.assertEqual(randomization.arm_balance(frame).to_dict(), {"a": 2, "b": 1})++ def test_grouping_produces_a_stratum_by_arm_table(self) -> None:+ frame = pd.DataFrame(+ {"arm": ["a", "b", "a", "a"], "stratum": ["x", "x", "y", "y"]}+ )+ table = randomization.arm_balance(frame, by="stratum")+ self.assertEqual(table.loc["x", "a"], 1)+ self.assertEqual(table.loc["y", "a"], 2)+ # unstack(fill_value=0) -- an absent combination is 0, not NaN.+ self.assertEqual(table.loc["y", "b"], 0)+++class DesignMatrixTests(unittest.TestCase):+ def test_full_factorial_covers_every_combination(self) -> None:+ design = doe().full_factorial(+ {"temp": [20, 40, 60], "catalyst": ["A", "B"]}, randomize=False+ )+ self.assertEqual(len(design), 6)+ combinations = set(zip(design["temp"], design["catalyst"]))+ self.assertEqual(len(combinations), 6)++ def test_two_level_factorial_decodes_to_the_stated_low_and_high(self) -> None:+ design = doe().two_level_factorial(+ {"temp": (20, 60), "ph": (6.0, 8.0)}, randomize=False+ )+ self.assertEqual(len(design), 4)+ self.assertEqual(set(design["temp"]), {20.0, 60.0})+ self.assertEqual(set(design["ph"]), {6.0, 8.0})++ def test_a_generator_that_names_the_wrong_factor_count_is_refused(self) -> None:+ with self.assertRaisesRegex(ValueError, "generator defines"):+ doe().fractional_factorial({"a": (0, 1), "b": (0, 1)}, "a b c")++ def test_a_valid_fraction_halves_the_full_factorial(self) -> None:+ factors = {f: (0, 1) for f in ("a", "b", "c", "d")}+ design = doe().fractional_factorial(factors, "a b c abc", randomize=False)+ self.assertEqual(len(design), 8) # 2^(4-1), not 2^4+ self.assertEqual(list(design.columns), list(factors))++ def test_plackett_burman_drops_the_dummy_columns(self) -> None:+ factors = {f: (0, 1) for f in ("a", "b", "c", "d", "e")}+ design = doe().plackett_burman(factors, randomize=False)+ self.assertEqual(list(design.columns), list(factors))++ def test_box_behnken_needs_three_factors(self) -> None:+ with self.assertRaisesRegex(ValueError, "at least 3 factors"):+ doe().box_behnken({"a": (0, 1), "b": (0, 1)})++ def test_box_behnken_avoids_the_extreme_corners(self) -> None:+ # Never using the all-low / all-high corner is the design's reason for+ # existing -- those runs are the unsafe or infeasible ones.+ factors = {"a": (0, 10), "b": (0, 10), "c": (0, 10)}+ design = doe().box_behnken(factors, randomize=False)+ corners = {(0.0, 0.0, 0.0), (10.0, 10.0, 10.0)}+ rows = set(zip(design["a"], design["b"], design["c"]))+ self.assertFalse(rows & corners)++ def test_latin_hypercube_stays_inside_every_factor_range(self) -> None:+ design = doe().latin_hypercube({"x": (2.0, 5.0), "y": (-1.0, 1.0)}, 20, seed=3)+ self.assertEqual(len(design), 20)+ self.assertTrue((design["x"] >= 2.0).all() and (design["x"] <= 5.0).all())+ self.assertTrue((design["y"] >= -1.0).all() and (design["y"] <= 1.0).all())++ def test_latin_hypercube_is_reproducible_from_its_seed(self) -> None:+ factors = {"x": (0.0, 1.0), "y": (0.0, 1.0)}+ pd.testing.assert_frame_equal(+ doe().latin_hypercube(factors, 15, seed=9),+ doe().latin_hypercube(factors, 15, seed=9),+ )++ def test_randomize_adds_a_run_order_column_and_sorts_by_it(self) -> None:+ factors = {"a": (0, 1), "b": (0, 1)}+ design = doe().two_level_factorial(factors, randomize=True, seed=4)+ self.assertEqual(design.columns[0], "run_order")+ self.assertEqual(list(design["run_order"]), [1, 2, 3, 4])++ def test_not_randomizing_leaves_the_design_in_canonical_order(self) -> None:+ factors = {"a": (0, 1), "b": (0, 1)}+ design = doe().two_level_factorial(factors, randomize=False)+ self.assertNotIn("run_order", design.columns)+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/exploratory-data-analysis/test_static.py b/tests/exploratory-data-analysis/test_static.pyindex f0b3258a..5d164df2 100644--- a/tests/exploratory-data-analysis/test_static.py+++ b/tests/exploratory-data-analysis/test_static.py@@ -86,7 +86,7 @@ class StaticSafetyTests(unittest.TestCase):skill = (SKILL_ROOT / "SKILL.md").read_text(encoding="utf-8")self.assertIn("license: MIT", skill)self.assertIn("compatibility:", skill)- self.assertIn('metadata:\n version: "1.1"', skill)+ self.assertRegex(skill, r'\nmetadata:\n version: "\d+\.\d+"\n')self.assertNotIn("200+", skill)self.assertLess(len(skill.splitlines()), 500)diff --git a/tests/flowio/test_scripts.py b/tests/flowio/test_scripts.pynew file mode 100644index 00000000..e91edc9a--- /dev/null+++ b/tests/flowio/test_scripts.py@@ -0,0 +1,458 @@+"""Tests for the FlowIO inspection helper.++`inspect_fcs` exists to read an untrusted FCS file without letting it decide how+much memory to allocate, so the guards are the product: the byte-size ceiling,+the estimated-array ceiling that is enforced *before* DATA is loaded, and the+multi-dataset offset walk that refuses a negative, non-increasing, or+out-of-file `$NEXTDATA` chain. Those tests build the pathological offsets by+stubbing `FlowData`, because a well-formed FCS file cannot express them.++The rest of the suite pins the reported numbers against a file this test wrote:+channel classification (a scatter channel silently reported as fluorescence+misleads every downstream gate), and the per-channel statistics, which must+ignore NaN and +/-inf rather than propagate them -- the values below are+hand-computed from the events written, not read back from the code.+"""++from __future__ import annotations++import argparse+import hashlib+import io+import json+import sys+import tempfile+import unittest+from contextlib import redirect_stderr, redirect_stdout+from pathlib import Path+from unittest.mock import patch++import pytest++import skill_contract++SKILL_ROOT = Path(__file__).resolve().parents[2] / "skills" / "flowio"+SCRIPTS = SKILL_ROOT / "scripts"+sys.path.insert(0, str(SCRIPTS))++flowio = pytest.importorskip("flowio", reason="flowio skill needs flowio")+np = pytest.importorskip("numpy", reason="inspect_fcs computes statistics with numpy")++import inspect_fcs # noqa: E402++CliHelpTests = skill_contract.cli.help_test_case(SKILL_ROOT)++NAN = float("nan")+INF = float("inf")+++def write_fcs(+ path: Path,+ events: list[float],+ channels: list[str],+ optional: list[str] | None = None,+) -> Path:+ """Write a real FCS 3.1 file; `events` is the flattened row-major matrix."""+ with path.open("wb") as handle:+ flowio.create_fcs(+ handle, events, channel_names=channels, opt_channel_names=optional+ )+ return path+++def namespace(**overrides) -> argparse.Namespace:+ """The parsed-argument defaults `inspect_file` reads, overridable per test."""+ defaults = dict(+ input=Path("unused.fcs"),+ output=None,+ include_text=False,+ include_analysis=False,+ stats=False,+ raw=False,+ sha256=False,+ max_bytes=inspect_fcs.DEFAULT_MAX_BYTES,+ max_array_bytes=inspect_fcs.DEFAULT_MAX_ARRAY_BYTES,+ max_datasets=inspect_fcs.DEFAULT_MAX_DATASETS,+ null_channel=[],+ ignore_offset_error=False,+ ignore_offset_discrepancy=False,+ use_header_offsets=False,+ )+ defaults.update(overrides)+ return argparse.Namespace(**defaults)+++class ArgumentValidatorTests(unittest.TestCase):+ def test_nonnegative_int_admits_zero_because_zero_disables_a_limit(self) -> None:+ # --max-bytes 0 is documented as "no ceiling", so zero must parse.+ self.assertEqual(inspect_fcs.nonnegative_int("0"), 0)+ self.assertEqual(inspect_fcs.nonnegative_int("512"), 512)++ def test_nonnegative_int_refuses_a_negative_ceiling(self) -> None:+ with self.assertRaises(argparse.ArgumentTypeError):+ inspect_fcs.nonnegative_int("-1")++ def test_positive_int_refuses_zero_and_below(self) -> None:+ # --max-datasets 0 would make the dataset walk yield nothing at all.+ self.assertEqual(inspect_fcs.positive_int("1"), 1)+ for value in ("0", "-3"):+ with self.subTest(value=value):+ with self.assertRaises(argparse.ArgumentTypeError):+ inspect_fcs.positive_int(value)++ def test_non_numeric_limits_raise(self) -> None:+ for validator in (inspect_fcs.nonnegative_int, inspect_fcs.positive_int):+ with self.subTest(validator=validator.__name__):+ with self.assertRaises(ValueError):+ validator("lots")+++class FcsFileTestCase(unittest.TestCase):+ def setUp(self) -> None:+ self._temporary = tempfile.TemporaryDirectory()+ self.addCleanup(self._temporary.cleanup)+ self.root = Path(self._temporary.name)+++class ChannelClassificationTests(FcsFileTestCase):+ """`channel_kind` decides what each column *means* to a downstream gate."""++ CHANNELS = ["FSC-A", "SSC-A", "FL1-A", "Time"]++ def flow(self, null: list[str] | None = None):+ path = write_fcs(+ self.root / "kinds.fcs",+ [1.0, 2.0, 3.0, 4.0],+ self.CHANNELS,+ optional=["fsc", "ssc", "CD3", "time"],+ )+ return flowio.FlowData(str(path), null_channel_list=null or [])++ def test_scatter_time_and_fluorescence_are_told_apart(self) -> None:+ flow = self.flow()+ kinds = [inspect_fcs.channel_kind(flow, i) for i in range(len(self.CHANNELS))]+ self.assertEqual(kinds, ["scatter", "scatter", "fluorescence", "time"])++ def test_a_declared_null_channel_outranks_its_detected_kind(self) -> None:+ # --null-channel exists to retire a channel; if the kind still said+ # "fluorescence" the column would keep being analysed.+ flow = self.flow(null=["FL1-A"])+ self.assertEqual(inspect_fcs.channel_kind(flow, 2), "null")+ # Nulling one channel must not reclassify the others.+ self.assertEqual(inspect_fcs.channel_kind(flow, 0), "scatter")+ self.assertEqual(inspect_fcs.channel_kind(flow, 3), "time")++ def test_channel_records_number_parameters_from_one(self) -> None:+ # FCS $PnN keywords are 1-based; the numpy column index is 0-based.+ # Conflating them shifts every reported gain and range by one channel.+ records = inspect_fcs.channel_records(self.flow())+ self.assertEqual([r["array_index"] for r in records], [0, 1, 2, 3])+ self.assertEqual([r["parameter_number"] for r in records], [1, 2, 3, 4])+ self.assertEqual([r["pnn"] for r in records], self.CHANNELS)+ self.assertEqual([r["pns"] for r in records], ["fsc", "ssc", "CD3", "time"])++ def test_channel_records_carry_the_scaling_keywords_as_json_types(self) -> None:+ # $PnE is a tuple in FlowIO; JSON cannot hold a tuple, so the record+ # must convert it -- otherwise `write_report` fails on real files.+ record = inspect_fcs.channel_records(self.flow())[0]+ self.assertIsInstance(record["pne"], list)+ self.assertEqual(record["pne"], [0.0, 0.0]) # linear scaling+ self.assertEqual(record["png"], 1.0) # unity gain+ json.dumps(record) # would raise if a tuple survived+++class FiniteStatisticsTests(unittest.TestCase):+ """Every value here is computed by hand from the array below."""++ EVENTS = np.array(+ [+ [1.0, NAN, 10.0],+ [3.0, INF, 20.0],+ [5.0, -INF, 30.0],+ [NAN, NAN, 40.0],+ ]+ )+ LABELS = ["mixed", "unusable", "clean"]++ def setUp(self) -> None:+ self.records = inspect_fcs.finite_statistics(self.EVENTS, self.LABELS)++ def test_one_record_is_emitted_per_channel_in_order(self) -> None:+ self.assertEqual([r["pnn"] for r in self.records], self.LABELS)+ self.assertEqual([r["array_index"] for r in self.records], [0, 1, 2])++ def test_statistics_are_computed_over_the_finite_values_only(self) -> None:+ mixed = self.records[0]+ # Finite values are 1, 3, 5: mean 3, min 1, max 5, one NaN dropped.+ self.assertEqual(mixed["finite_count"], 3)+ self.assertEqual(mixed["nan_count"], 1)+ self.assertEqual(mixed["minimum"], 1.0)+ self.assertEqual(mixed["maximum"], 5.0)+ self.assertEqual(mixed["mean"], 3.0)++ def test_infinities_are_counted_by_sign_and_excluded_from_the_range(self) -> None:+ unusable = self.records[1]+ self.assertEqual(unusable["positive_infinity_count"], 1)+ self.assertEqual(unusable["negative_infinity_count"], 1)+ self.assertEqual(unusable["nan_count"], 2)+ self.assertEqual(unusable["finite_count"], 0)++ def test_a_channel_with_no_finite_value_reports_none_not_nan(self) -> None:+ # json.dumps(..., allow_nan=False) in write_report rejects NaN, so the+ # statistics must degrade to null rather than to a NaN float.+ unusable = self.records[1]+ for key in ("minimum", "maximum", "mean"):+ with self.subTest(key=key):+ self.assertIsNone(unusable[key])+ json.dumps(self.records, allow_nan=False)++ def test_a_fully_finite_channel_keeps_every_event(self) -> None:+ clean = self.records[2]+ self.assertEqual(clean["finite_count"], 4)+ self.assertEqual(clean["nan_count"], 0)+ self.assertEqual(clean["mean"], 25.0) # (10+20+30+40)/4+++class FakeText(dict):+ """A `FlowData.text` stand-in exposing only what `iter_datasets` reads."""+++class FakeFlow:+ def __init__(self, nextdata: str) -> None:+ self.text = FakeText(nextdata=nextdata)+++class DatasetWalkTests(FcsFileTestCase):+ """The `$NEXTDATA` chain is attacker-controlled; the walk must bound it."""++ def setUp(self) -> None:+ super().setUp()+ self.path = self.root / "chain.fcs"+ self.path.write_bytes(b"x" * 1000)++ def walk(self, nextdata_values: list[str], max_datasets: int = 8):+ """Run `iter_datasets` with FlowData replaced by a scripted stub."""+ seen: list[int] = []+ remaining = list(nextdata_values)++ def fake_flow_data(path, **kwargs):+ seen.append(kwargs["nextdata_offset"])+ return FakeFlow(remaining.pop(0) if remaining else "0")++ with patch.object(inspect_fcs, "FlowData", fake_flow_data):+ datasets = list(+ inspect_fcs.iter_datasets(+ self.path,+ max_datasets=max_datasets,+ null_channel_list=[],+ ignore_offset_error=False,+ ignore_offset_discrepancy=False,+ use_header_offsets=False,+ )+ )+ return datasets, seen++ def test_a_single_dataset_file_stops_after_one(self) -> None:+ datasets, offsets = self.walk(["0"])+ self.assertEqual(len(datasets), 1)+ self.assertEqual(offsets, [0])+ self.assertEqual(datasets[0][0], 0) # dataset_index+ self.assertEqual(datasets[0][1], 0) # byte offset++ def test_nextdata_is_relative_so_offsets_accumulate(self) -> None:+ # FCS $NEXTDATA is relative to the start of the current dataset. Two+ # hops of 100 must land at 100 then 200, not 100 twice.+ datasets, offsets = self.walk(["100", "100", "0"])+ self.assertEqual(offsets, [0, 100, 200])+ self.assertEqual([index for index, _, _ in datasets], [0, 1, 2])+ self.assertEqual([offset for _, offset, _ in datasets], [0, 100, 200])++ def test_a_negative_relative_offset_is_refused(self) -> None:+ with self.assertRaisesRegex(+ flowio.exceptions.MultipleDataSetsError, "negative relative offset"+ ):+ self.walk(["-8", "0"])++ def test_an_offset_past_the_end_of_the_file_is_refused(self) -> None:+ # The file is 1000 bytes; seeking to 5000 would read foreign memory.+ with self.assertRaisesRegex(+ flowio.exceptions.MultipleDataSetsError, "outside the input file"+ ):+ self.walk(["5000", "0"])++ def test_the_dataset_count_ceiling_is_enforced(self) -> None:+ # A chain of 10-byte hops never terminates on its own; --max-datasets+ # is the only thing that stops it.+ with self.assertRaisesRegex(+ flowio.exceptions.MultipleDataSetsError, r"--max-datasets limit \(3\)"+ ):+ self.walk(["10"] * 20, max_datasets=3)+++class InspectFileTests(FcsFileTestCase):+ """`inspect_file` is the whole report; its guards run before DATA loads."""++ def setUp(self) -> None:+ super().setUp()+ # 3 events x 2 channels of known values.+ self.path = write_fcs(+ self.root / "sample.fcs",+ [1.0, 10.0, 2.0, 20.0, 3.0, 30.0],+ ["FSC-A", "FL1-A"],+ )++ def test_the_report_describes_the_file_that_was_written(self) -> None:+ report = inspect_fcs.inspect_file(namespace(input=self.path))+ self.assertEqual(report["dataset_count"], 1)+ self.assertEqual(report["file_name"], "sample.fcs")+ self.assertEqual(report["size_bytes"], self.path.stat().st_size)+ dataset = report["datasets"][0]+ self.assertEqual(dataset["event_count"], 3)+ self.assertEqual(dataset["channel_count"], 2)+ self.assertEqual(dataset["fcs_version"], "3.1")++ def test_the_array_estimate_is_events_times_channels_times_eight(self) -> None:+ # float64 is 8 bytes; this estimate is what --max-array-bytes compares+ # against, so an understated one defeats the ceiling.+ report = inspect_fcs.inspect_file(namespace(input=self.path))+ self.assertEqual(report["datasets"][0]["estimated_array_bytes"], 3 * 2 * 8)++ def test_metadata_only_is_the_default_and_says_so(self) -> None:+ report = inspect_fcs.inspect_file(namespace(input=self.path))+ self.assertTrue(report["parse_options"]["metadata_only"])+ dataset = report["datasets"][0]+ self.assertNotIn("statistics", dataset)+ self.assertEqual(dataset["event_semantics"], "not loaded; metadata-only inspection")++ def test_stats_loads_events_and_reports_the_array_shape(self) -> None:+ report = inspect_fcs.inspect_file(namespace(input=self.path, stats=True))+ dataset = report["datasets"][0]+ self.assertEqual(dataset["array_shape"], [3, 2])+ self.assertFalse(report["parse_options"]["metadata_only"])+ first, second = dataset["statistics"]+ self.assertEqual((first["minimum"], first["maximum"]), (1.0, 3.0))+ self.assertEqual((second["minimum"], second["maximum"]), (10.0, 30.0))++ def test_raw_stats_are_labelled_as_encoded_values(self) -> None:+ # The semantics string is how a reader knows whether gain/log scaling+ # was applied; mislabelling it invalidates every downstream comparison.+ report = inspect_fcs.inspect_file(namespace(input=self.path, stats=True, raw=True))+ self.assertIn("preprocess=False", report["datasets"][0]["event_semantics"])+ scaled = inspect_fcs.inspect_file(namespace(input=self.path, stats=True))+ self.assertIn("uncompensated", scaled["datasets"][0]["event_semantics"])++ def test_text_and_analysis_are_withheld_unless_requested(self) -> None:+ # TEXT can carry patient identifiers, so it is opt-in.+ default = inspect_fcs.inspect_file(namespace(input=self.path))+ self.assertNotIn("text", default["datasets"][0])+ self.assertGreater(default["datasets"][0]["metadata_summary"]["text_key_count"], 0)++ # FlowIO normalises TEXT keywords to lowercase without the `$`.+ included = inspect_fcs.inspect_file(namespace(input=self.path, include_text=True))+ self.assertEqual(included["datasets"][0]["text"]["p1n"], "FSC-A")++ def test_a_file_over_the_byte_ceiling_is_refused_before_parsing(self) -> None:+ with self.assertRaisesRegex(ValueError, "--max-bytes"):+ inspect_fcs.inspect_file(namespace(input=self.path, max_bytes=10))++ def test_a_zero_byte_ceiling_disables_the_check(self) -> None:+ report = inspect_fcs.inspect_file(namespace(input=self.path, max_bytes=0))+ self.assertEqual(report["parse_options"]["max_bytes"], 0)++ def test_the_array_ceiling_only_applies_with_stats(self) -> None:+ # Metadata-only inspection allocates no array, so a tiny ceiling must+ # not block it -- and must block --stats.+ tiny = namespace(input=self.path, max_array_bytes=8)+ inspect_fcs.inspect_file(tiny)+ with self.assertRaisesRegex(ValueError, "--max-array-bytes"):+ inspect_fcs.inspect_file(namespace(input=self.path, stats=True, max_array_bytes=8))++ def test_a_ceiling_equal_to_the_estimate_is_accepted(self) -> None:+ # The comparison is strictly-greater, so the boundary must pass.+ report = inspect_fcs.inspect_file(+ namespace(input=self.path, stats=True, max_array_bytes=48)+ )+ self.assertEqual(report["datasets"][0]["array_shape"], [3, 2])++ def test_a_missing_input_raises_file_not_found(self) -> None:+ with self.assertRaises(FileNotFoundError):+ inspect_fcs.inspect_file(namespace(input=self.root / "absent.fcs"))++ def test_a_directory_is_not_a_regular_file(self) -> None:+ with self.assertRaisesRegex(ValueError, "not a regular file"):+ inspect_fcs.inspect_file(namespace(input=self.root))++ def test_the_checksum_is_opt_in_and_matches_the_streaming_helper(self) -> None:+ without = inspect_fcs.inspect_file(namespace(input=self.path))+ self.assertNotIn("sha256", without)+ with_sum = inspect_fcs.inspect_file(namespace(input=self.path, sha256=True))+ self.assertEqual(with_sum["sha256"], inspect_fcs.sha256_file(self.path))++ def test_the_checksum_matches_hashlib_on_the_same_bytes(self) -> None:+ expected = hashlib.sha256(self.path.read_bytes()).hexdigest()+ self.assertEqual(inspect_fcs.sha256_file(self.path), expected)+++class ReportWritingTests(FcsFileTestCase):+ def test_stdout_receives_parseable_json(self) -> None:+ buffer = io.StringIO()+ with redirect_stdout(buffer):+ inspect_fcs.write_report({"schema_version": "1.0"}, None)+ self.assertEqual(json.loads(buffer.getvalue()), {"schema_version": "1.0"})++ def test_an_existing_output_file_is_never_overwritten(self) -> None:+ output = self.root / "report.json"+ output.write_text("keep me", encoding="utf-8")+ with self.assertRaises(FileExistsError):+ inspect_fcs.write_report({"a": 1}, output)+ self.assertEqual(output.read_text(encoding="utf-8"), "keep me")++ def test_a_non_finite_number_is_refused_rather_than_written_as_nan(self) -> None:+ # Bare NaN is not valid JSON; writing it would produce a file that+ # every conforming parser rejects.+ with self.assertRaises(ValueError):+ inspect_fcs.write_report({"mean": NAN}, self.root / "nan.json")+++class MainTests(FcsFileTestCase):+ def setUp(self) -> None:+ super().setUp()+ self.path = write_fcs(self.root / "main.fcs", [1.0, 2.0], ["FSC-A", "FL1-A"])++ def test_a_clean_run_exits_zero_and_writes_the_requested_file(self) -> None:+ output = self.root / "out.json"+ self.assertEqual(inspect_fcs.main([str(self.path), "--output", str(output)]), 0)+ report = json.loads(output.read_text(encoding="utf-8"))+ self.assertEqual(report["datasets"][0]["event_count"], 1)++ def test_raw_without_stats_is_rejected_by_the_parser(self) -> None:+ # --raw only changes how events are decoded, so it is meaningless+ # without --stats; accepting it would silently do nothing.+ with self.assertRaises(SystemExit) as raised:+ inspect_fcs.main([str(self.path), "--raw"])+ self.assertEqual(raised.exception.code, 2)++ def test_writing_the_report_over_the_input_fcs_is_rejected(self) -> None:+ with self.assertRaises(SystemExit) as raised:+ inspect_fcs.main([str(self.path), "--output", str(self.path)])+ self.assertEqual(raised.exception.code, 2)+ # The input must survive intact.+ self.assertGreater(self.path.stat().st_size, 0)++ def test_a_missing_input_exits_two_with_a_message_not_a_traceback(self) -> None:+ errors = io.StringIO()+ with redirect_stderr(errors):+ status = inspect_fcs.main([str(self.root / "absent.fcs")])+ self.assertEqual(status, 2)+ self.assertIn("inspect_fcs:", errors.getvalue())+ self.assertNotIn("Traceback", errors.getvalue())++ def test_a_file_that_is_not_fcs_at_all_exits_two(self) -> None:+ junk = self.root / "notes.txt"+ junk.write_text("this is not an FCS file", encoding="utf-8")+ with redirect_stderr(io.StringIO()):+ self.assertEqual(inspect_fcs.main([str(junk)]), 2)+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/fluidsim/test_static.py b/tests/fluidsim/test_static.pyindex d6241c25..158a84dd 100644--- a/tests/fluidsim/test_static.py+++ b/tests/fluidsim/test_static.py@@ -20,7 +20,7 @@ class SkillStructureTests(unittest.TestCase):self.assertIn("\nlicense: MIT\n", text)self.assertRegex(text,- r"\nmetadata:\n version: \"1\.1\"\n skill-author:",+ r"\nmetadata:\n version: \"\d+\.\d+\"\n skill-author:",)self.assertNotIn('metadata: {"version"', text)self.assertIn('last-reviewed: "2026-07-23"', text)diff --git a/tests/generate-image/test_scripts.py b/tests/generate-image/test_scripts.pyindex ccf361b6..3b35c208 100644--- a/tests/generate-image/test_scripts.py+++ b/tests/generate-image/test_scripts.py@@ -229,7 +229,7 @@ class SaveImageTests(unittest.TestCase):class SkillDocumentTests(unittest.TestCase):def test_frontmatter_version_matches_expected(self):text = (SKILL_ROOT / "SKILL.md").read_text(encoding="utf-8")- self.assertIn('version: "2.0"', text)+ self.assertRegex(text, r'\n version: "\d+\.\d+"\n')def test_documented_default_model_matches_the_script(self):text = (SKILL_ROOT / "SKILL.md").read_text(encoding="utf-8")diff --git a/tests/genomic-coordinates/test_scripts.py b/tests/genomic-coordinates/test_scripts.pyindex 8c6dccbf..2f475247 100644--- a/tests/genomic-coordinates/test_scripts.py+++ b/tests/genomic-coordinates/test_scripts.py@@ -19,6 +19,8 @@ import unittestfrom contextlib import redirect_stdout, redirect_stderrfrom pathlib import Path+import skill_contract+SKILL_ROOT = Path(__file__).resolve().parents[2] / "skills" / "genomic-coordinates"SCRIPTS_DIR = SKILL_ROOT / "scripts"FIXTURES = Path(__file__).resolve().parent / "fixtures"@@ -607,7 +609,7 @@ class SkillStructureTests(unittest.TestCase):def test_version_is_a_quoted_string(self):text = (SKILL_ROOT / "SKILL.md").read_text(encoding="utf-8")- self.assertIn('version: "1.0"', text)+ self.assertRegex(text, r'\n version: "\d+\.\d+"\n')def test_skill_md_is_within_the_line_budget(self):lines = (SKILL_ROOT / "SKILL.md").read_text(encoding="utf-8").splitlines()@@ -650,5 +652,10 @@ class SkillStructureTests(unittest.TestCase):self.assertNotIn(module.split(".")[0], third_party)+# 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(SKILL_ROOT)+if __name__ == "__main__":unittest.main()diff --git a/tests/geopandas/test_static.py b/tests/geopandas/test_static.pyindex c2bc03fd..28e51ffa 100644--- a/tests/geopandas/test_static.py+++ b/tests/geopandas/test_static.py@@ -30,7 +30,7 @@ class SkillStructureTests(unittest.TestCase):self.assertIn("\nallowed-tools: Read Write Bash Glob Grep\n", text)self.assertRegex(text,- r'\nmetadata:\n version: "1\.1"\n skill-author:'+ r'\nmetadata:\n version: "\d+\.\d+"\n skill-author:'r'.*\n last-reviewed: "2026-07-23"',)self.assertNotIn('metadata: {"version"', text)diff --git a/tests/get-available-resources/test_scripts.py b/tests/get-available-resources/test_scripts.pyindex 8a9956fa..353b22f3 100644--- a/tests/get-available-resources/test_scripts.py+++ b/tests/get-available-resources/test_scripts.py@@ -25,6 +25,8 @@ import detect_resources # noqa: E402import plan_workload # noqa: E402import snapshot_tools # noqa: E402+import skill_contract+CASES = json.loads(FIXTURES.read_text(encoding="utf-8"))GIB = 1024**3@@ -510,5 +512,10 @@ class PlannerTests(unittest.TestCase):self.assertIn("stress tests or large allocations", plan["prohibited_actions"])+# 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(SKILL_ROOT)+if __name__ == "__main__":unittest.main()diff --git a/tests/gget/test_scripts.py b/tests/gget/test_scripts.pynew file mode 100644index 00000000..6d627469--- /dev/null+++ b/tests/gget/test_scripts.py@@ -0,0 +1,555 @@+"""Tests for the gget workflow scripts.++Every gget module in these scripts is a network call, so all three suites patch+the gget function with `autospec=True` and assert on the call that *would* have+gone out. `autospec` is load-bearing rather than decoration: it binds each+recorded call against the installed gget signature, so a script that passes an+argument gget no longer accepts fails here instead of failing in the field --+which is how `f.write(gget.muscle(...))` (muscle returns None) and+`f.write(gget.seq(...))` (seq returns a list) were caught.++The rest is the logic the scripts own: FASTA and gene-list parsing, the+per-database enrichment sweep, the deliberate five-gene cap on expression+lookups, and the resilience contract -- one service failing must not abort the+run, but an empty gene search must stop it before any further request is made.+"""++from __future__ import annotations++import io+import os+import sys+import tempfile+import unittest+from contextlib import redirect_stdout+from pathlib import Path+from unittest.mock import patch++import pytest++import skill_contract++SKILL_ROOT = Path(__file__).resolve().parents[2] / "skills" / "gget"+SCRIPTS = SKILL_ROOT / "scripts"+sys.path.insert(0, str(SCRIPTS))++pd = pytest.importorskip("pandas", reason="gget scripts need pandas")+gget = pytest.importorskip("gget", reason="gget skill needs gget")++import batch_sequence_analysis as batch # noqa: E402+import enrichment_pipeline as pipeline # noqa: E402+import gene_analysis # noqa: E402++CliHelpTests = skill_contract.cli.help_test_case(SKILL_ROOT)+++#: Every gget module these scripts reach for. All of them are network calls.+GGET_MODULES = (+ "blast", "muscle", "enrichr", "archs4", "search", "info", "seq",+ "opentargets", "alphafold",+)+++class WorkingDirectoryTestCase(unittest.TestCase):+ """The scripts write output relative to the working directory."""++ def setUp(self) -> None:+ self._temporary = tempfile.TemporaryDirectory()+ self.addCleanup(self._temporary.cleanup)+ self.root = Path(self._temporary.name)+ previous = Path.cwd()+ os.chdir(self.root)+ self.addCleanup(os.chdir, previous)++ # Every gget module is replaced up front, with `autospec` so each+ # recorded call is bound against the installed gget signature. The+ # default side effect is a blanket guard: a module a test forgot to+ # arrange raises instead of quietly querying Ensembl, NCBI, Enrichr or+ # ARCHS4 for real.+ self._modules = {}+ for name in GGET_MODULES:+ patcher = patch.object(gget, name, autospec=True)+ mock = patcher.start()+ self.addCleanup(patcher.stop)+ mock.side_effect = AssertionError(+ f"gget.{name} was called without being stubbed"+ )+ self._modules[name] = mock++ def stub(self, name: str, **kwargs):+ """Arrange the already-installed mock for one gget module."""+ mock = self._modules[name]+ # Clears the blanket guard installed in setUp. Call history needs no+ # reset: every test gets its own patchers.+ mock.side_effect = kwargs.pop("side_effect", None)+ if "return_value" in kwargs:+ mock.return_value = kwargs.pop("return_value")+ self.assertEqual(kwargs, {}, "unsupported stub arguments")+ return mock++ def quietly(self, function, *args, **kwargs):+ """Run a chatty workflow function, swallowing its progress output."""+ with redirect_stdout(io.StringIO()):+ return function(*args, **kwargs)+++def blast_frame(description: str = "hypothetical protein") -> pd.DataFrame:+ """A BLAST result shaped like gget.blast returns."""+ return pd.DataFrame(+ [{"Description": description, "Max Score": 300, "Query Coverage": "98%"}]+ )+++class FastaReadingTests(unittest.TestCase):+ def setUp(self) -> None:+ self._temporary = tempfile.TemporaryDirectory()+ self.addCleanup(self._temporary.cleanup)+ self.root = Path(self._temporary.name)++ def read(self, text: str):+ path = self.root / "sequences.fasta"+ path.write_text(text, encoding="utf-8")+ return batch.read_fasta(path)++ def test_wrapped_sequence_lines_are_joined(self) -> None:+ # FASTA wraps at 60-80 columns; keeping the newlines would corrupt+ # every downstream BLAST query.+ records = self.read(">seq1\nMKVL\nAAPG\n")+ self.assertEqual(records, [{"id": "seq1", "seq": "MKVLAAPG"}])++ def test_the_final_record_is_not_dropped(self) -> None:+ # The loop flushes on the next '>', so the last record needs the+ # explicit flush after the file ends.+ records = self.read(">a\nMK\n>b\nVL\n>c\nAA\n")+ self.assertEqual([r["id"] for r in records], ["a", "b", "c"])+ self.assertEqual(records[-1]["seq"], "AA")++ def test_the_identifier_excludes_the_angle_bracket(self) -> None:+ records = self.read(">sp|P12345| my protein\nMK\n")+ self.assertEqual(records[0]["id"], "sp|P12345| my protein")++ def test_an_empty_file_yields_no_records(self) -> None:+ self.assertEqual(self.read(""), [])++ def test_a_header_with_no_sequence_is_still_a_record(self) -> None:+ # Dropping it would silently renumber every later sequence.+ records = self.read(">empty\n>next\nMK\n")+ self.assertEqual(records[0], {"id": "empty", "seq": ""})+ self.assertEqual(len(records), 2)++ def test_a_missing_trailing_newline_is_tolerated(self) -> None:+ self.assertEqual(self.read(">a\nMK")[0]["seq"], "MK")+++class BatchSequenceAnalysisTests(WorkingDirectoryTestCase):+ def fasta(self, records: int = 2) -> Path:+ path = self.root / "input.fasta"+ path.write_text(+ "".join(f">seq{i}\nMKVL{i}\n" for i in range(records)), encoding="utf-8"+ )+ return path++ def test_each_sequence_is_blasted_once_with_the_documented_parameters(self) -> None:+ blast = self.stub("blast", return_value=blast_frame())+ self.stub("muscle")+ self.quietly(+ batch.analyze_sequences,+ self.fasta(2),+ blast_db="swissprot",+ output_dir=str(self.root / "out"),+ )+ self.assertEqual(blast.call_count, 2)+ sequences = [call.args[0] for call in blast.call_args_list]+ self.assertEqual(sequences, ["MKVL0", "MKVL1"])+ for call in blast.call_args_list:+ # save=False keeps gget from writing files of its own next to the+ # script; limit=10 is what the reported "top hit" assumes.+ self.assertEqual(call.kwargs["database"], "swissprot")+ self.assertEqual(call.kwargs["limit"], 10)+ self.assertIs(call.kwargs["save"], False)++ def test_one_csv_is_written_per_sequence_named_after_it(self) -> None:+ self.stub("blast", return_value=blast_frame("kinase domain"))+ self.stub("muscle")+ output = self.root / "out"+ self.quietly(batch.analyze_sequences, self.fasta(2), output_dir=str(output))+ written = sorted(path.name for path in output.glob("*_blast.csv"))+ self.assertEqual(written, ["seq0_blast.csv", "seq1_blast.csv"])+ table = pd.read_csv(output / "seq0_blast.csv")+ self.assertEqual(table.loc[0, "Description"], "kinase domain")++ def test_a_failed_blast_does_not_abort_the_remaining_sequences(self) -> None:+ # A batch run that dies on sequence 1 of 50 is useless.+ blast = self.stub(+ "blast",+ side_effect=[RuntimeError("NCBI timed out"), blast_frame()],+ )+ self.stub("muscle")+ output = self.root / "out"+ self.quietly(batch.analyze_sequences, self.fasta(2), output_dir=str(output))+ self.assertEqual(blast.call_count, 2)+ self.assertFalse((output / "seq0_blast.csv").exists())+ self.assertTrue((output / "seq1_blast.csv").exists())++ def test_alignment_asks_gget_to_write_the_file(self) -> None:+ # gget.muscle returns None, so the alignment must be requested via+ # `out=`; writing the return value would raise TypeError.+ self.stub("blast", return_value=blast_frame())+ muscle = self.stub("muscle")+ output = self.root / "out"+ self.quietly(batch.analyze_sequences, self.fasta(2), output_dir=str(output))+ muscle.assert_called_once()+ self.assertEqual(+ muscle.call_args.kwargs["out"], str(output / "alignment.afa")+ )++ def test_a_single_sequence_is_not_aligned(self) -> None:+ # An alignment of one sequence is meaningless and wastes a request.+ self.stub("blast", return_value=blast_frame())+ muscle = self.stub("muscle")+ self.quietly(+ batch.analyze_sequences, self.fasta(1), output_dir=str(self.root / "out")+ )+ muscle.assert_not_called()++ def test_alignment_can_be_switched_off(self) -> None:+ self.stub("blast", return_value=blast_frame())+ muscle = self.stub("muscle")+ self.quietly(+ batch.analyze_sequences,+ self.fasta(3),+ align=False,+ output_dir=str(self.root / "out"),+ )+ muscle.assert_not_called()++ def test_structure_prediction_stays_a_no_op_even_when_requested(self) -> None:+ # The AlphaFold call is commented out on purpose (it needs `gget setup+ # alphafold` and hours of compute); the flag must not silently start it.+ self.stub("blast", return_value=blast_frame())+ self.stub("muscle")+ alphafold = self.stub("alphafold")+ self.quietly(+ batch.analyze_sequences,+ self.fasta(2),+ predict_structure=True,+ output_dir=str(self.root / "out"),+ )+ alphafold.assert_not_called()++ def test_an_empty_fasta_file_runs_no_queries(self) -> None:+ (self.root / "empty.fasta").write_text("", encoding="utf-8")+ blast = self.stub("blast")+ muscle = self.stub("muscle")+ self.quietly(+ batch.analyze_sequences,+ self.root / "empty.fasta",+ output_dir=str(self.root / "out"),+ )+ blast.assert_not_called()+ muscle.assert_not_called()+++class GeneListReadingTests(unittest.TestCase):+ def setUp(self) -> None:+ self._temporary = tempfile.TemporaryDirectory()+ self.addCleanup(self._temporary.cleanup)+ self.root = Path(self._temporary.name)++ def write(self, name: str, text: str) -> Path:+ path = self.root / name+ path.write_text(text, encoding="utf-8")+ return path++ def test_a_plain_list_drops_blank_lines_and_whitespace(self) -> None:+ path = self.write("genes.txt", "TP53\n\n BRCA1 \n\n")+ self.assertEqual(pipeline.read_gene_list(path), ["TP53", "BRCA1"])++ def test_a_csv_takes_the_first_column_and_skips_the_header(self) -> None:+ # The header row must not become a gene symbol.+ path = self.write("genes.csv", "gene,logFC\nTP53,2.1\nBRCA1,-1.4\n")+ self.assertEqual(pipeline.read_gene_list(path), ["TP53", "BRCA1"])++ def test_a_csv_read_as_text_would_keep_the_commas(self) -> None:+ # Guards the suffix check: the same content named .txt is not a CSV.+ path = self.write("genes.txt", "gene,logFC\nTP53,2.1\n")+ self.assertEqual(pipeline.read_gene_list(path), ["gene,logFC", "TP53,2.1"])++ def test_an_empty_list_file_yields_no_genes(self) -> None:+ self.assertEqual(pipeline.read_gene_list(self.write("none.txt", "\n\n")), [])+++def enrichr_frame(term: str = "p53 signaling pathway") -> pd.DataFrame:+ """An enrichment table shaped like gget.enrichr returns."""+ return pd.DataFrame(+ [+ {"name": term, "adjusted_p_value": 1e-8},+ {"name": "apoptosis", "adjusted_p_value": 0.002},+ ]+ )+++def archs4_frame() -> pd.DataFrame:+ """A tissue-expression table; 'lung' is the clear maximum."""+ return pd.DataFrame(+ [+ {"tissue": "liver", "median": 3.5},+ {"tissue": "lung", "median": 9.25},+ {"tissue": "kidney", "median": 1.0},+ ]+ )+++class EnrichmentPipelineTests(WorkingDirectoryTestCase):+ #: The five Enrichr categories the script sweeps, in order.+ DATABASES = ["pathway", "ontology", "transcription", "diseases_drugs", "celltypes"]++ def test_every_documented_database_is_queried_once_in_order(self) -> None:+ enrichr = self.stub("enrichr", return_value=enrichr_frame())+ self.stub("archs4", return_value=archs4_frame())+ self.quietly(pipeline.enrichment_pipeline, ["TP53"], output_prefix="run")+ self.assertEqual(+ [call.kwargs["database"] for call in enrichr.call_args_list],+ self.DATABASES,+ )++ def test_species_background_and_plotting_are_forwarded(self) -> None:+ enrichr = self.stub("enrichr", return_value=enrichr_frame())+ self.stub("archs4", return_value=archs4_frame())+ self.quietly(+ pipeline.enrichment_pipeline,+ ["TP53", "BRCA1"],+ species="mouse",+ background=["ACTB"],+ output_prefix="run",+ plot=False,+ )+ for call in enrichr.call_args_list:+ self.assertEqual(call.args[0], ["TP53", "BRCA1"])+ self.assertEqual(call.kwargs["species"], "mouse")+ self.assertEqual(call.kwargs["background_list"], ["ACTB"])+ self.assertIs(call.kwargs["plot"], False)++ def test_one_csv_per_database_plus_a_summary_is_written(self) -> None:+ self.stub("enrichr", return_value=enrichr_frame())+ self.stub("archs4", return_value=archs4_frame())+ self.quietly(pipeline.enrichment_pipeline, ["TP53"], output_prefix="run")+ for database in self.DATABASES:+ with self.subTest(database=database):+ self.assertTrue((self.root / f"run_{database}.csv").is_file())+ summary = pd.read_csv(self.root / "run_summary.csv")+ self.assertEqual(len(summary), len(self.DATABASES))+ self.assertEqual(summary.loc[0, "Top Term"], "p53 signaling pathway")+ self.assertEqual(summary.loc[0, "Total Terms"], 2)++ def test_a_database_with_no_hits_is_left_out_of_the_summary(self) -> None:+ # Reporting an empty category as a result would overstate the analysis.+ self.stub(+ "enrichr",+ side_effect=[enrichr_frame(), pd.DataFrame(), None,+ enrichr_frame(), enrichr_frame()],+ )+ self.stub("archs4", return_value=archs4_frame())+ self.quietly(pipeline.enrichment_pipeline, ["TP53"], output_prefix="run")+ summary = pd.read_csv(self.root / "run_summary.csv")+ self.assertEqual(len(summary), 3)+ self.assertFalse((self.root / "run_ontology.csv").exists())++ def test_a_failing_database_does_not_stop_the_sweep(self) -> None:+ enrichr = self.stub(+ "enrichr",+ side_effect=[+ RuntimeError("Enrichr is down"),+ enrichr_frame(),+ enrichr_frame(),+ enrichr_frame(),+ enrichr_frame(),+ ],+ )+ self.stub("archs4", return_value=archs4_frame())+ self.quietly(pipeline.enrichment_pipeline, ["TP53"], output_prefix="run")+ self.assertEqual(enrichr.call_count, 5)+ summary = pd.read_csv(self.root / "run_summary.csv")+ self.assertEqual(len(summary), 4)++ def test_expression_lookups_are_capped_at_five_genes(self) -> None:+ # One ARCHS4 request per gene would make a 2,000-gene list unusable.+ self.stub("enrichr", return_value=enrichr_frame())+ archs4 = self.stub("archs4", return_value=archs4_frame())+ genes = [f"GENE{i}" for i in range(9)]+ self.quietly(pipeline.enrichment_pipeline, genes, output_prefix="run")+ self.assertEqual(archs4.call_count, 5)+ self.assertEqual(+ [call.args[0] for call in archs4.call_args_list], genes[:5]+ )+ for call in archs4.call_args_list:+ self.assertEqual(call.kwargs["which"], "tissue")++ def test_the_top_tissue_is_the_one_with_the_highest_median(self) -> None:+ self.stub("enrichr", return_value=enrichr_frame())+ self.stub("archs4", return_value=archs4_frame())+ self.quietly(pipeline.enrichment_pipeline, ["TP53"], output_prefix="run")+ expression = pd.read_csv(self.root / "run_expression.csv")+ self.assertEqual(expression.loc[0, "Gene"], "TP53")+ self.assertEqual(expression.loc[0, "Top Tissue"], "lung")+ self.assertEqual(expression.loc[0, "Median Expression"], 9.25)++ def test_an_expression_failure_leaves_the_enrichment_results_intact(self) -> None:+ self.stub("enrichr", return_value=enrichr_frame())+ self.stub("archs4", side_effect=RuntimeError("ARCHS4 is down"))+ self.assertTrue(+ self.quietly(pipeline.enrichment_pipeline, ["TP53"], output_prefix="run")+ )+ self.assertTrue((self.root / "run_summary.csv").is_file())+ self.assertFalse((self.root / "run_expression.csv").exists())+++def search_frame(ensembl_id: str = "ENSG00000141510") -> pd.DataFrame:+ """A gget.search result for TP53."""+ return pd.DataFrame(+ [+ {+ "ensembl_id": ensembl_id,+ "ensembl_description": "tumor protein p53",+ "gene_name": "TP53",+ }+ ]+ )+++def info_frame() -> pd.DataFrame:+ return pd.DataFrame(+ [{"uniprot_id": "P04637", "pdb_id": "1TUP", "gene_name": "TP53"}]+ )+++def correlation_frame() -> pd.DataFrame:+ return pd.DataFrame(+ [{"gene_symbol": "MDM2", "correlation": 0.81}]+ )+++def diseases_frame() -> pd.DataFrame:+ return pd.DataFrame(+ [{"disease_name": "Li-Fraumeni syndrome", "overall_score": 0.9}]+ )+++class GeneAnalysisTests(WorkingDirectoryTestCase):+ def stub_everything(self) -> dict:+ return {+ "search": self.stub("search", return_value=search_frame()),+ "info": self.stub("info", return_value=info_frame()),+ "seq": self.stub("seq", return_value=[">ENSG00000141510", "ATGGAG"]),+ "archs4": self.stub(+ "archs4", side_effect=[archs4_frame(), correlation_frame()]+ ),+ "opentargets": self.stub(+ "opentargets", side_effect=[diseases_frame(), pd.DataFrame()]+ ),+ }++ def test_the_search_is_scoped_to_the_species_and_a_single_hit(self) -> None:+ stubs = self.stub_everything()+ self.assertTrue(+ self.quietly(gene_analysis.analyze_gene, "TP53", "homo_sapiens")+ )+ stubs["search"].assert_called_once()+ call = stubs["search"].call_args+ self.assertEqual(call.args[0], ["TP53"])+ self.assertEqual(call.kwargs["species"], "homo_sapiens")+ self.assertEqual(call.kwargs["limit"], 1)++ def test_a_gene_that_does_not_exist_stops_before_any_other_request(self) -> None:+ # Without the early return the Ensembl ID lookup would index an empty+ # frame and raise instead of reporting "not found".+ search = self.stub("search", return_value=pd.DataFrame())+ info = self.stub("info")+ self.assertFalse(+ self.quietly(gene_analysis.analyze_gene, "NOT_A_GENE", "homo_sapiens")+ )+ search.assert_called_once()+ info.assert_not_called()++ def test_the_ensembl_identifier_from_the_search_drives_every_lookup(self) -> None:+ stubs = self.stub_everything()+ self.quietly(gene_analysis.analyze_gene, "TP53")+ self.assertEqual(stubs["info"].call_args.args[0], ["ENSG00000141510"])+ self.assertIs(stubs["info"].call_args.kwargs["pdb"], True)+ for call in stubs["opentargets"].call_args_list:+ self.assertEqual(call.args[0], "ENSG00000141510")++ def test_both_sequence_forms_are_requested(self) -> None:+ stubs = self.stub_everything()+ self.quietly(gene_analysis.analyze_gene, "TP53")+ self.assertEqual(stubs["seq"].call_count, 2)+ translated = [+ call.kwargs.get("translate", False) for call in stubs["seq"].call_args_list+ ]+ self.assertEqual(translated, [False, True])++ def test_the_fasta_files_hold_the_lines_gget_returned(self) -> None:+ # gget.seq returns a list of FASTA lines; writing the list itself+ # raises TypeError, so the join is what makes the file valid.+ self.stub_everything()+ self.quietly(gene_analysis.analyze_gene, "TP53")+ text = (self.root / "tp53_nucleotide.fasta").read_text(encoding="utf-8")+ self.assertEqual(text, ">ENSG00000141510\nATGGAG\n")++ def test_an_already_joined_string_is_written_unchanged(self) -> None:+ # Older gget releases returned one string; both shapes must work.+ self.assertEqual(+ gene_analysis.fasta_text(">x\nATG\n"), ">x\nATG\n"+ )+ self.assertEqual(gene_analysis.fasta_text(">x\nATG"), ">x\nATG\n")+ self.assertEqual(gene_analysis.fasta_text(None), "")++ def test_the_output_prefix_defaults_to_the_lowercased_gene(self) -> None:+ self.stub_everything()+ self.quietly(gene_analysis.analyze_gene, "TP53")+ self.assertTrue((self.root / "tp53_info.csv").is_file())++ def test_an_explicit_prefix_is_used_verbatim(self) -> None:+ self.stub_everything()+ self.quietly(gene_analysis.analyze_gene, "TP53", output_prefix="run1")+ self.assertTrue((self.root / "run1_info.csv").is_file())++ def test_expression_and_correlation_are_separate_archs4_queries(self) -> None:+ stubs = self.stub_everything()+ self.quietly(gene_analysis.analyze_gene, "TP53")+ self.assertEqual(+ [call.kwargs["which"] for call in stubs["archs4"].call_args_list],+ ["tissue", "correlation"],+ )++ def test_both_opentargets_resources_are_requested_with_a_limit(self) -> None:+ stubs = self.stub_everything()+ self.quietly(gene_analysis.analyze_gene, "TP53")+ self.assertEqual(+ [call.kwargs["resource"] for call in stubs["opentargets"].call_args_list],+ ["diseases", "drugs"],+ )+ for call in stubs["opentargets"].call_args_list:+ self.assertEqual(call.kwargs["limit"], 10)++ def test_an_empty_drug_table_is_not_written(self) -> None:+ self.stub_everything() # drugs is an empty frame+ self.quietly(gene_analysis.analyze_gene, "TP53")+ self.assertTrue((self.root / "tp53_diseases.csv").is_file())+ self.assertFalse((self.root / "tp53_drugs.csv").exists())++ def test_optional_lookups_may_fail_without_failing_the_run(self) -> None:+ # Steps 4-7 are wrapped in warnings on purpose: the sequences and+ # annotations already retrieved are worth keeping.+ self.stub("search", return_value=search_frame())+ self.stub("info", return_value=info_frame())+ self.stub("seq", return_value=[">x", "ATG"])+ self.stub("archs4", side_effect=RuntimeError("ARCHS4 is down"))+ self.stub("opentargets", side_effect=RuntimeError("Open Targets is down"))+ self.assertTrue(self.quietly(gene_analysis.analyze_gene, "TP53"))+ self.assertTrue((self.root / "tp53_nucleotide.fasta").is_file())+ self.assertFalse((self.root / "tp53_tissue_expression.csv").exists())+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/hugging-science/test_scripts.py b/tests/hugging-science/test_scripts.pynew file mode 100644index 00000000..e9a26570--- /dev/null+++ b/tests/hugging-science/test_scripts.py@@ -0,0 +1,267 @@+"""Tests for the Hugging Science catalogue fetcher.++The whole script is a markdown parser wrapped in a network call, so the tests+feed `parse_markdown` fixture documents directly and never fetch anything. The+parser is a small state machine over headings and bullets, and its edge cases+-- a section suffix like `## Datasets (12)`, an H3 before any H2, a bullet key+it does not recognise -- are where a catalogue silently loses entries.+"""++from __future__ import annotations++import sys+import unittest+from unittest import mock++from pathlib import Path++import skill_contract++SKILL_ROOT = Path(__file__).resolve().parents[2] / "skills" / "hugging-science"+SCRIPTS = SKILL_ROOT / "scripts"+sys.path.insert(0, str(SCRIPTS))++import fetch_catalog # noqa: E402++CliHelpTests = skill_contract.cli.help_test_case(SKILL_ROOT)++CATALOGUE = """\+# Hugging Science++## Datasets (2)++### Protein Folding Benchmark+- **type**: dataset+- **tags**: biology, benchmark+- **huggingface**: https://huggingface.co/datasets/example/folding+- **author**: Example Lab+- **date**: 2026-01-15++A held-out set of folded structures.+Spanning two lines of prose.++### Climate Reanalysis Grid+- **type**: dataset+- **tags**: climate, earth-science+- **link**: https://huggingface.co/datasets/example/climate++## Models++### Genomics Encoder+- **type**: model+- **tags**: genomics+- **url**: https://huggingface.co/example/genomics-encoder++## Blog Posts++### Why Open Science Needs Open Weights+- **author**: A. Writer+- **date**: 2026-02-02++An argument.+"""+++class ParserTests(unittest.TestCase):+ def setUp(self) -> None:+ self.entries = fetch_catalog.parse_markdown(CATALOGUE)++ def test_every_entry_is_found(self) -> None:+ self.assertEqual(+ [entry.title for entry in self.entries],+ [+ "Protein Folding Benchmark",+ "Climate Reanalysis Grid",+ "Genomics Encoder",+ "Why Open Science Needs Open Weights",+ ],+ )++ def test_the_count_suffix_is_stripped_from_the_section_label(self) -> None:+ # "## Datasets (2)" must land in the same bucket as "## Datasets".+ self.assertEqual(self.entries[0].section, "datasets")+ self.assertEqual(self.entries[1].section, "datasets")+ self.assertEqual(self.entries[2].section, "models")+ self.assertEqual(self.entries[3].section, "blog posts")++ def test_metadata_bullets_populate_the_record(self) -> None:+ entry = self.entries[0]+ self.assertEqual(entry.type, "dataset")+ self.assertEqual(entry.tags, ["biology", "benchmark"])+ self.assertEqual(entry.url, "https://huggingface.co/datasets/example/folding")+ self.assertEqual(entry.author, "Example Lab")+ self.assertEqual(entry.date, "2026-01-15")++ def test_huggingface_link_and_url_keys_all_fill_the_url(self) -> None:+ self.assertTrue(self.entries[0].url) # **huggingface**+ self.assertTrue(self.entries[1].url) # **link**+ self.assertTrue(self.entries[2].url) # **url**++ def test_prose_after_the_bullets_becomes_the_description(self) -> None:+ self.assertEqual(+ self.entries[0].description,+ "A held-out set of folded structures. Spanning two lines of prose.",+ )++ def test_an_entry_without_prose_has_an_empty_description(self) -> None:+ self.assertEqual(self.entries[1].description, "")++ def test_content_before_the_first_entry_is_ignored(self) -> None:+ entries = fetch_catalog.parse_markdown(+ "# Title\n\nSome preamble prose.\n\n### First\n- **type**: model\n"+ )+ self.assertEqual(len(entries), 1)+ self.assertEqual(entries[0].title, "First")++ def test_an_entry_before_any_section_is_labelled_unknown(self) -> None:+ entries = fetch_catalog.parse_markdown("### Orphan\n- **type**: model\n")+ self.assertEqual(entries[0].section, "unknown")++ def test_unrecognised_bullet_keys_are_dropped_not_misfiled(self) -> None:+ entries = fetch_catalog.parse_markdown(+ "## Models\n\n### X\n- **license**: mit\n- **type**: model\n"+ )+ self.assertEqual(entries[0].type, "model")+ self.assertEqual(entries[0].tags, [])++ def test_empty_input_yields_no_entries(self) -> None:+ self.assertEqual(fetch_catalog.parse_markdown(""), [])+ self.assertEqual(fetch_catalog.parse_markdown("## Datasets\n"), [])++ def test_tags_are_split_and_blank_entries_discarded(self) -> None:+ entries = fetch_catalog.parse_markdown(+ "### X\n- **tags**: a, , b ,\n"+ )+ self.assertEqual(entries[0].tags, ["a", "b"])+++class FilterTests(unittest.TestCase):+ def setUp(self) -> None:+ self.entries = fetch_catalog.parse_markdown(CATALOGUE)++ def test_no_filter_matches_everything(self) -> None:+ self.assertTrue(all(e.matches_filter(None, None) for e in self.entries))++ def test_each_cli_filter_value_selects_its_section(self) -> None:+ expected = {"datasets": 2, "models": 1, "blogs": 1}+ for kind, count in expected.items():+ with self.subTest(kind=kind):+ matched = [e for e in self.entries if e.matches_filter(kind, None)]+ self.assertEqual(len(matched), count)++ def test_the_aliases_absorb_singular_section_headings_upstream(self) -> None:+ # The alias sets map one CLI value onto the section spellings the+ # source markdown may use, so `--filter datasets` still works when a+ # topic file writes `## Dataset`.+ singular = fetch_catalog.parse_markdown("## Dataset\n\n### X\n- **type**: dataset\n")+ self.assertTrue(singular[0].matches_filter("datasets", None))++ blog = fetch_catalog.parse_markdown("## Blog\n\n### Y\n")+ self.assertTrue(blog[0].matches_filter("blogs", None))++ def test_the_cli_only_offers_the_aliased_filter_values(self) -> None:+ # matches_filter falls back to an exact section match for anything that+ # is not an alias key, so the CLI must not offer values outside them.+ source = (SCRIPTS / "fetch_catalog.py").read_text(encoding="utf-8")+ self.assertIn('choices=["datasets", "models", "blogs"]', source)++ def test_kind_matching_is_case_insensitive(self) -> None:+ matched = [e for e in self.entries if e.matches_filter("MODELS", None)]+ self.assertEqual(len(matched), 1)++ def test_tag_matching_is_a_case_insensitive_substring(self) -> None:+ matched = [e.title for e in self.entries if e.matches_filter(None, "GENOM")]+ self.assertEqual(matched, ["Genomics Encoder"])++ def test_a_tag_also_matches_the_type_field(self) -> None:+ # `matches_filter` falls back to `type` so `--tag model` still works+ # on entries that carry no explicit tags.+ entry = fetch_catalog.Entry(title="X", section="models", type="model")+ self.assertTrue(entry.matches_filter(None, "model"))++ def test_kind_and_tag_must_both_match(self) -> None:+ matched = [e for e in self.entries if e.matches_filter("datasets", "genomics")]+ self.assertEqual(matched, [])++ def test_an_unknown_kind_matches_nothing_rather_than_everything(self) -> None:+ matched = [e for e in self.entries if e.matches_filter("posters", None)]+ self.assertEqual(matched, [])+++class RenderTests(unittest.TestCase):+ def setUp(self) -> None:+ self.entries = fetch_catalog.parse_markdown(CATALOGUE)++ def test_an_entry_renders_only_the_fields_it_has(self) -> None:+ rendered = fetch_catalog.render_entry(self.entries[1])+ self.assertIn("### Climate Reanalysis Grid", rendered)+ self.assertIn("- Type: dataset", rendered)+ self.assertIn("- URL: https://huggingface.co/datasets/example/climate", rendered)+ self.assertNotIn("- Author:", rendered)+ self.assertNotIn("- Date:", rendered)++ def test_grouped_rendering_counts_each_section(self) -> None:+ rendered = fetch_catalog.render_entries(self.entries)+ self.assertIn("## Datasets (2)", rendered)+ self.assertIn("## Models (1)", rendered)+ self.assertIn("## Blog Posts (1)", rendered)++ def test_ungrouped_rendering_omits_section_headers(self) -> None:+ rendered = fetch_catalog.render_entries(self.entries, group_by_section=False)+ self.assertNotIn("## Datasets", rendered)+ self.assertIn("### Genomics Encoder", rendered)++ def test_an_empty_result_says_so_rather_than_rendering_nothing(self) -> None:+ self.assertEqual(fetch_catalog.render_entries([]), "(no entries matched)")++ def test_a_rendered_catalogue_round_trips_through_the_parser(self) -> None:+ # render_entries emits the same H2/H3 shape the parser reads, so a+ # round trip must preserve every title and section.+ reparsed = fetch_catalog.parse_markdown(+ fetch_catalog.render_entries(self.entries)+ )+ self.assertEqual(+ [(e.title, e.section) for e in reparsed],+ [(e.title, e.section) for e in self.entries],+ )+++class CatalogueSourceTests(unittest.TestCase):+ def test_topic_slugs_are_lowercase_hyphenated_and_sorted(self) -> None:+ topics = fetch_catalog.KNOWN_TOPICS+ self.assertTrue(topics)+ self.assertEqual(topics, sorted(topics))+ for topic in topics:+ with self.subTest(topic=topic):+ self.assertRegex(topic, r"^[a-z]+(-[a-z]+)*$")++ def test_the_base_url_is_https(self) -> None:+ self.assertTrue(fetch_catalog.BASE.startswith("https://"))++ def test_requests_identify_the_skill_and_carry_a_timeout(self) -> None:+ response = mock.MagicMock()+ response.__enter__.return_value.read.return_value = b"ok"+ with mock.patch("urllib.request.urlopen", return_value=response) as opened:+ self.assertEqual(fetch_catalog.fetch(f"{fetch_catalog.BASE}/llms.txt"), "ok")++ request = opened.call_args.args[0]+ self.assertIn("hugging-science-skill", request.get_header("User-agent"))+ self.assertEqual(opened.call_args.kwargs["timeout"], 30)++ def test_network_failures_exit_with_a_message_rather_than_a_traceback(self) -> None:+ import urllib.error++ failures = [+ urllib.error.HTTPError("u", 404, "Not Found", {}, None),+ urllib.error.URLError("no route to host"),+ ]+ for error in failures:+ with self.subTest(error=type(error).__name__):+ with mock.patch("urllib.request.urlopen", side_effect=error):+ with self.assertRaises(SystemExit) as raised:+ fetch_catalog.fetch("https://example.invalid/x")+ self.assertNotIn("Traceback", str(raised.exception))+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/hypogenic/test_scripts.py b/tests/hypogenic/test_scripts.pyindex 46c8dc70..3d46e3e0 100644--- a/tests/hypogenic/test_scripts.py+++ b/tests/hypogenic/test_scripts.py@@ -237,7 +237,7 @@ class SafetyAndHelpTests(unittest.TestCase):def test_skill_metadata_progressive_disclosure_and_file_set(self) -> None:skill = (SKILL_ROOT / "SKILL.md").read_text(encoding="utf-8")self.assertIn("license: MIT", skill)- self.assertIn("metadata:\n version: \"1.1\"", skill)+ self.assertRegex(skill, r'\nmetadata:\n version: "\d+\.\d+"\n')self.assertLess(len(skill.splitlines()), 500)self.assertFalse((REFERENCES / "config_template.yaml").exists())self.assertEqual(diff --git a/tests/hypothesis-generation/test_scripts.py b/tests/hypothesis-generation/test_scripts.pyindex 75eec615..bfa1987c 100644--- a/tests/hypothesis-generation/test_scripts.py+++ b/tests/hypothesis-generation/test_scripts.py@@ -3,10 +3,8 @@from __future__ import annotationsimport ast-import copyimport csvimport json-import reimport statimport sysimport tempfile@@ -42,6 +40,8 @@ from validate_hypothesis_schema import ( # noqa: E402)from validate_prediction_matrix import load_matrix, validate_matrix # noqa: E402+import skill_contract+def load_asset_json(name: str) -> dict:return json.loads((ASSETS / name).read_text(encoding="utf-8"))@@ -371,25 +371,10 @@ class FileSafetyAndStaticTests(unittest.TestCase):len(rows), len({row["source_id"] for row in rows}))- def test_markdown_local_path_references_exist(self) -> None:- markdown_files = [- SKILL_ROOT / "SKILL.md",- *(SKILL_ROOT / "references").glob("*.md"),- ]- pattern = re.compile(- r"`((?:assets|references|scripts)/[A-Za-z0-9_./-]+)`"- )- for markdown in markdown_files:- for relative in pattern.findall(markdown.read_text(encoding="utf-8")):- self.assertTrue(- (SKILL_ROOT / relative).is_file(),- f"{markdown.name}: missing {relative}",- )-def test_skill_frontmatter_and_progressive_disclosure(self) -> None:skill = (SKILL_ROOT / "SKILL.md").read_text(encoding="utf-8")self.assertLess(len(skill.splitlines()), 500)- self.assertIn('version: "2.1"', skill)+ self.assertRegex(skill, r'\n version: "\d+\.\d+"\n')self.assertIn("license: MIT", skill)self.assertIn("compatibility:", skill)self.assertNotIn("OPENROUTER", skill)@@ -406,5 +391,10 @@ class FileSafetyAndStaticTests(unittest.TestCase):self.assertFalse(list(SKILL_ROOT.rglob("*.pyc")))+# 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(SKILL_ROOT)+if __name__ == "__main__":unittest.main()diff --git a/tests/infographics/test_scripts.py b/tests/infographics/test_scripts.pynew file mode 100644index 00000000..d8456d64--- /dev/null+++ b/tests/infographics/test_scripts.py@@ -0,0 +1,163 @@+"""Tests for the infographics generator CLI.++Generation goes through OpenRouter, so nothing here calls it. What is testable+offline is the part that decides what the subprocess sees and what the user may+ask for: the environment allowlist (the same design as the schematic scripts --+forward a named set, never the whole parent environment) and the option+catalogue, where `--list-options` documents choices that argparse must actually+accept.++The palette presets get their own attention: this skill advertises them as+colourblind-safe, and a preset the generator does not know is a silent+downgrade to whatever it picks instead.+"""++from __future__ import annotations++import subprocess+import sys+import unittest+from pathlib import Path+from unittest import mock++import skill_contract++SKILL_ROOT = Path(__file__).resolve().parents[2] / "skills" / "infographics"+SCRIPTS = SKILL_ROOT / "scripts"+sys.path.insert(0, str(SCRIPTS))++import generate_infographic # noqa: E402++CliHelpTests = skill_contract.cli.help_test_case(SKILL_ROOT)+++class SubprocessEnvironmentTests(unittest.TestCase):+ def test_only_allowlisted_variables_are_forwarded(self) -> None:+ environment = {+ "PATH": "/usr/bin",+ "HOME": "/home/someone",+ "AWS_SECRET_ACCESS_KEY": "must-not-leak",+ "SLACK_TOKEN": "also-not",+ }+ with mock.patch.dict("os.environ", environment, clear=True):+ built = generate_infographic.build_subprocess_env(None)+ self.assertEqual(set(built), {"PATH", "HOME"})++ def test_the_api_key_is_injected_when_supplied(self) -> None:+ with mock.patch.dict("os.environ", {"PATH": "/usr/bin"}, clear=True):+ built = generate_infographic.build_subprocess_env("sk-or-test")+ self.assertEqual(built["OPENROUTER_API_KEY"], "sk-or-test")++ def test_an_empty_key_is_omitted_rather_than_passed_blank(self) -> None:+ 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",+ generate_infographic.build_subprocess_env(value),+ )++ def test_the_allowlist_carries_no_credential_variables(self) -> None:+ forwarded = " ".join(generate_infographic.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_keeps_tls_and_proxy_settings_working(self) -> None:+ forwarded = set(generate_infographic.FORWARDED_ENV_VARS)+ for required in ("HTTPS_PROXY", "https_proxy", "SSL_CERT_FILE", "REQUESTS_CA_BUNDLE"):+ with self.subTest(variable=required):+ self.assertIn(required, forwarded)++ def test_the_allowlist_matches_the_schematic_scripts(self) -> None:+ # Both CLIs solve the same problem the same way; a divergence means one+ # of them was updated and the other forgotten.+ schematic = (+ SKILL_ROOT.parent / "scientific-schematics" / "scripts" / "generate_schematic.py"+ ).read_text(encoding="utf-8")+ for variable in generate_infographic.FORWARDED_ENV_VARS:+ with self.subTest(variable=variable):+ self.assertIn(f'"{variable}"', schematic)+++class OptionCatalogueTests(unittest.TestCase):+ CATALOGUES = {+ "type": "INFOGRAPHIC_TYPES",+ "style": "STYLE_PRESETS",+ "palette": "PALETTE_PRESETS",+ "doc-type": "DOC_TYPES",+ }++ def setUp(self) -> None:+ self.source = (SCRIPTS / "generate_infographic.py").read_text(encoding="utf-8")++ def test_every_catalogue_is_non_empty_and_free_of_duplicates(self) -> None:+ for attribute in self.CATALOGUES.values():+ with self.subTest(catalogue=attribute):+ values = getattr(generate_infographic, attribute)+ self.assertTrue(values)+ self.assertEqual(len(set(values)), len(values))++ def test_every_catalogued_value_is_documented_by_list_options(self) -> None:+ import io+ from contextlib import redirect_stdout++ buffer = io.StringIO()+ with redirect_stdout(buffer):+ generate_infographic.list_options()+ documented = buffer.getvalue()++ for attribute in self.CATALOGUES.values():+ for value in getattr(generate_infographic, attribute):+ with self.subTest(option=value):+ self.assertIn(value, documented)++ def test_the_parser_offers_each_catalogue_as_choices(self) -> None:+ # `choices=` wired to the catalogue means adding an option is one edit;+ # a hand-copied list drifts.+ for flag, attribute in self.CATALOGUES.items():+ with self.subTest(flag=flag):+ self.assertIn(f"choices={attribute}", self.source)++ def test_the_palettes_are_the_recognised_colourblind_safe_sets(self) -> None:+ self.assertEqual(+ set(generate_infographic.PALETTE_PRESETS), {"wong", "ibm", "tol"}+ )++ def test_option_names_are_lowercase_slugs(self) -> None:+ for attribute in self.CATALOGUES.values():+ for value in getattr(generate_infographic, attribute):+ with self.subTest(option=value):+ self.assertRegex(value, r"^[a-z][a-z0-9-]*$")+++class ParserTests(unittest.TestCase):+ def test_help_lists_every_documented_flag(self) -> None:+ result = skill_contract.cli.run_help(SCRIPTS / "generate_infographic.py")+ self.assertEqual(result.returncode, 0, result.stderr)+ for flag in ("--type", "--style", "--palette", "--doc-type", "--output"):+ with self.subTest(flag=flag):+ self.assertIn(flag, result.stdout)++ def test_an_unknown_option_value_is_rejected_at_the_boundary(self) -> None:+ result = subprocess.run(+ [+ sys.executable,+ str(SCRIPTS / "generate_infographic.py"),+ "a prompt",+ "-o", "out.png",+ "--palette", "rainbow",+ ],+ capture_output=True,+ text=True,+ timeout=60,+ )+ self.assertNotEqual(result.returncode, 0)+ self.assertIn("rainbow", result.stderr)++ def test_the_generator_script_is_shipped(self) -> None:+ self.assertTrue((SCRIPTS / "generate_infographic_ai.py").is_file())+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/iso-standards-readiness/test_scripts.py b/tests/iso-standards-readiness/test_scripts.pyindex fa7718e7..4700b9e4 100644--- a/tests/iso-standards-readiness/test_scripts.py+++ b/tests/iso-standards-readiness/test_scripts.py@@ -674,10 +674,5 @@ class CLITests(unittest.TestCase):self.assertIn("CHOICE_INVALID", codes)self.assertIn("VALUE_UNKNOWN", codes)- def test_no_bytecode_artifacts_created(self) -> None:- for path in ROOT.rglob("__pycache__"):- self.fail(f"unexpected bytecode directory: {path}")--if __name__ == "__main__":unittest.main()diff --git a/tests/labarchive-integration/test_scripts.py b/tests/labarchive-integration/test_scripts.pynew file mode 100644index 00000000..16caf483--- /dev/null+++ b/tests/labarchive-integration/test_scripts.py@@ -0,0 +1,400 @@+"""Tests for the LabArchives integration helpers.++Three security boundaries live in these scripts, and all three are testable+without touching LabArchives:++* the HMAC-SHA-512 request signature, which the vendor documents with a public+ test vector -- so the suite is a known-answer test, not a self-consistency+ check;+* the path validators in front of that signature, which refuse anything that+ would sign a different route than the one actually requested;+* the `.eln` container inspector, which unpacks untrusted archives and must+ reject traversal, absolute paths, and symlink members.++Nothing here uses a real credential; the only key material is the vendor's own+published dummy vector.+"""++from __future__ import annotations++import base64+import hashlib+import hmac+import io+import json+import stat+import sys+import tempfile+import unittest+import zipfile+from contextlib import redirect_stdout+from pathlib import Path++import skill_contract++SKILL_ROOT = Path(__file__).resolve().parents[2] / "skills" / "labarchive-integration"+SCRIPTS = SKILL_ROOT / "scripts"+sys.path.insert(0, str(SCRIPTS))++import entry_operations # noqa: E402+import notebook_operations # noqa: E402+import setup_config # noqa: E402++CliHelpTests = skill_contract.cli.help_test_case(SKILL_ROOT)+++class SignatureTests(unittest.TestCase):+ def test_the_official_vendor_vector_reproduces_exactly(self) -> None:+ vector = entry_operations._OFFICIAL_VECTOR+ signature = entry_operations.create_signature(+ vector["access_key_id"],+ vector["api_method_input"],+ int(vector["expires_ms"]),+ vector["access_password"],+ )+ self.assertEqual(signature, vector["signature"])++ def test_the_signature_is_base64_hmac_sha512_over_the_concatenation(self) -> None:+ # Recomputed independently: any change to the message layout shows up+ # here rather than as a 401 from the API.+ expected = base64.b64encode(+ hmac.new(+ b"secret", b"keyidmethod12345", hashlib.sha512+ ).digest()+ ).decode("ascii")+ self.assertEqual(+ entry_operations.create_signature("keyid", "method", 12345, "secret"),+ expected,+ )++ def test_every_input_changes_the_signature(self) -> None:+ base = entry_operations.create_signature("k", "m", 1, "s")+ variants = {+ "key": entry_operations.create_signature("K", "m", 1, "s"),+ "method": entry_operations.create_signature("k", "M", 1, "s"),+ "expires": entry_operations.create_signature("k", "m", 2, "s"),+ "secret": entry_operations.create_signature("k", "m", 1, "S"),+ }+ for name, signature in variants.items():+ with self.subTest(changed=name):+ self.assertNotEqual(signature, base)++ def test_empty_inputs_are_refused_before_signing(self) -> None:+ cases = [+ (("", "m", 1, "s"), "Access Key ID"),+ (("k", "", 1, "s"), "API method input"),+ (("k", "m", 1, ""), "Access Password"),+ ]+ for arguments, label in cases:+ with self.subTest(label=label):+ with self.assertRaises(setup_config.ConfigError) as raised:+ entry_operations.create_signature(*arguments)+ self.assertIn(label, str(raised.exception))++ def test_a_negative_expiry_is_refused(self) -> None:+ with self.assertRaisesRegex(ValueError, "non-negative"):+ entry_operations.create_signature("k", "m", -1, "s")++ def test_the_signature_is_uri_encoded_for_a_query_parameter(self) -> None:+ # Base64 contains '+' and '/', which are meaningful in a query string.+ encoded = entry_operations.encode_eln_signature("a+b/c==")+ self.assertEqual(encoded, "a%2Bb%2Fc%3D%3D")++ def test_the_self_test_command_reports_a_pass_without_a_network_call(self) -> None:+ class Args:+ compact = True++ buffer = io.StringIO()+ with redirect_stdout(buffer):+ code = entry_operations.command_self_test(Args())++ self.assertEqual(code, 0)+ payload = json.loads(buffer.getvalue())+ self.assertTrue(payload["passed"])+ self.assertFalse(payload["remote_request_performed"])+ # The signature itself must never be printed, only a fingerprint.+ self.assertNotIn(+ entry_operations._OFFICIAL_VECTOR["signature"], buffer.getvalue()+ )+++class AuthParameterTests(unittest.TestCase):+ def test_eln_parameters_carry_the_key_expiry_and_signature(self) -> None:+ params = entry_operations.build_eln_auth_params(+ "keyid", "secret", "entry_attachment", expires_ms=1000+ )+ self.assertEqual(set(params), {"akid", "expires", "sig"})+ self.assertEqual(params["akid"], "keyid")+ self.assertEqual(params["expires"], "1000")+ self.assertEqual(+ params["sig"],+ entry_operations.create_signature("keyid", "entry_attachment", 1000, "secret"),+ )++ def test_the_password_never_appears_in_the_parameters(self) -> None:+ params = entry_operations.build_eln_auth_params(+ "keyid", "hunter2", "entry_attachment", expires_ms=1000+ )+ self.assertNotIn("hunter2", json.dumps(params))++ def test_inventory_headers_sign_the_resolved_path(self) -> None:+ headers = entry_operations.build_inventory_headers(+ "keyid", "secret", "user", "lab", "/public/v1/items/42", expires_ms=1000+ )+ self.assertEqual(+ headers["X-LabArchives-Signature"],+ entry_operations.create_signature(+ "keyid", "/public/v1/items/42", 1000, "secret"+ ),+ )+ self.assertEqual(headers["X-LabArchives-UId"], "user")+ self.assertEqual(headers["X-LabArchives-LabId"], "lab")++ def test_an_omitted_expiry_defaults_to_now(self) -> None:+ params = entry_operations.build_eln_auth_params("k", "s", "entry_attachment")+ self.assertTrue(params["expires"].isdigit())+ self.assertGreater(int(params["expires"]), 1_700_000_000_000)+++class ComponentValidationTests(unittest.TestCase):+ def test_valid_method_names_are_accepted(self) -> None:+ for value in ("entry_attachment", "users", "tree_tools", "a1_b2"):+ with self.subTest(value=value):+ self.assertEqual(+ entry_operations.validate_eln_component(value, "method"), value+ )++ def test_anything_outside_the_documented_shape_is_refused(self) -> None:+ for value in ("Entry", "1entry", "entry-attachment", "entry attachment", "", "entry/x"):+ with self.subTest(value=value):+ with self.assertRaises(setup_config.ConfigError):+ entry_operations.validate_eln_component(value, "method")+++class InventoryPathTests(unittest.TestCase):+ def test_a_resolved_route_is_accepted(self) -> None:+ for path in ("/public/v1/items", "/public/v1/items/42", "/public/v1/a.b~c"):+ with self.subTest(path=path):+ self.assertEqual(entry_operations.validate_inventory_path(path), path)++ def test_a_query_or_fragment_is_refused(self) -> None:+ # Signing a path but sending it with a query signs the wrong thing.+ for path in ("/public/v1/items?page=2", "/public/v1/items#top"):+ with self.subTest(path=path):+ with self.assertRaisesRegex(ValueError, "query strings and fragments"):+ entry_operations.validate_inventory_path(path)++ def test_a_percent_encoded_path_is_refused(self) -> None:+ with self.assertRaisesRegex(ValueError, "unencoded relative route"):+ entry_operations.validate_inventory_path("/public/v1/it%20ems")++ def test_unresolved_placeholders_are_refused(self) -> None:+ with self.assertRaisesRegex(ValueError, "resolve all Inventory route placeholders"):+ entry_operations.validate_inventory_path("/public/v1/items/{id}")++ def test_a_path_outside_the_public_v1_prefix_is_refused(self) -> None:+ for path in ("/private/v1/items", "public/v1/items", "/public/v2/items"):+ with self.subTest(path=path):+ with self.assertRaises(setup_config.ConfigError):+ entry_operations.validate_inventory_path(path)++ def test_traversal_and_ambiguous_segments_are_refused(self) -> None:+ for path in ("/public/v1/../secret", "/public/v1/./items", "/public/v1//items"):+ with self.subTest(path=path):+ with self.assertRaises(setup_config.ConfigError):+ entry_operations.validate_inventory_path(path)++ def test_whitespace_and_backslashes_are_refused(self) -> None:+ for path in ("/public/v1/it ems", "/public/v1/it\tems", "/public/v1\\items"):+ with self.subTest(path=repr(path)):+ with self.assertRaises(setup_config.ConfigError):+ entry_operations.validate_inventory_path(path)+++class ApiUrlTests(unittest.TestCase):+ def test_every_documented_region_url_normalises_to_itself(self) -> None:+ self.assertTrue(setup_config.REGIONS)+ for region, values in setup_config.REGIONS.items():+ with self.subTest(region=region):+ url = values["eln_api_url"]+ self.assertEqual(setup_config.normalize_eln_api_url(url), url)++ def test_a_trailing_slash_and_mixed_case_host_are_normalised(self) -> None:+ url = next(iter(setup_config.REGIONS.values()))["eln_api_url"]+ host = url.removeprefix("https://").removesuffix("/api")+ self.assertEqual(+ setup_config.normalize_eln_api_url(f"https://{host.upper()}/api/"), url+ )++ def test_plain_http_is_refused(self) -> None:+ url = next(iter(setup_config.REGIONS.values()))["eln_api_url"]+ with self.assertRaisesRegex(ValueError, "must use https"):+ setup_config.normalize_eln_api_url(url.replace("https://", "http://"))++ def test_embedded_credentials_are_refused(self) -> None:+ url = next(iter(setup_config.REGIONS.values()))["eln_api_url"]+ host = url.removeprefix("https://").removesuffix("/api")+ with self.assertRaisesRegex(ValueError, "credentials must not be embedded"):+ setup_config.normalize_eln_api_url(f"https://user:pass@{host}/api")++ def test_a_custom_port_query_or_fragment_is_refused(self) -> None:+ url = next(iter(setup_config.REGIONS.values()))["eln_api_url"]+ host = url.removeprefix("https://").removesuffix("/api")+ cases = {+ f"https://{host}:8443/api": "custom port",+ f"https://{host}/api?x=1": "query or fragment",+ f"https://{host}/api#y": "query or fragment",+ }+ for candidate, expected in cases.items():+ with self.subTest(url=candidate):+ with self.assertRaisesRegex(ValueError, expected):+ setup_config.normalize_eln_api_url(candidate)++ def test_a_non_allowlisted_host_is_refused_and_lists_the_alternatives(self) -> None:+ with self.assertRaises(setup_config.ConfigError) as raised:+ setup_config.normalize_eln_api_url("https://evil.example.invalid/api")+ self.assertIn("not allowlisted", str(raised.exception))++ def test_the_path_must_be_exactly_api(self) -> None:+ url = next(iter(setup_config.REGIONS.values()))["eln_api_url"]+ host = url.removeprefix("https://").removesuffix("/api")+ with self.assertRaisesRegex(ValueError, "path must be exactly /api"):+ setup_config.normalize_eln_api_url(f"https://{host}/api/v2")++ def test_an_empty_url_is_refused(self) -> None:+ with self.assertRaisesRegex(ValueError, "is empty"):+ setup_config.normalize_eln_api_url(" ")+++class ContainerMemberTests(unittest.TestCase):+ """`.eln` archives come from outside; every member name is untrusted."""++ def test_ordinary_member_paths_are_accepted(self) -> None:+ for name in ("lamanifest.xml", "data/entry.json", "a/b/c.txt"):+ with self.subTest(name=name):+ self.assertIsNone(notebook_operations._member_path_error(name))++ def test_traversal_and_absolute_paths_are_rejected(self) -> None:+ for name in ("../escape.xml", "a/../../b", "/etc/passwd", "C:\\win\\x"):+ with self.subTest(name=name):+ self.assertIsNotNone(notebook_operations._member_path_error(name))++ def test_backslashes_nulls_and_empty_names_are_rejected(self) -> None:+ for name in ("a\\b", "a\x00b", ""):+ with self.subTest(name=repr(name)):+ self.assertIsNotNone(notebook_operations._member_path_error(name))++ def test_redundant_but_harmless_segments_are_allowed(self) -> None:+ # PurePosixPath collapses `.` and doubled separators, so these resolve+ # inside the extraction root and are not treated as ambiguous. Only+ # `..` actually escapes.+ for name in ("./a.txt", "a/./b", "a//b"):+ with self.subTest(name=name):+ self.assertIsNone(notebook_operations._member_path_error(name))++ def test_symlink_members_are_detected_from_the_mode_bits(self) -> None:+ link = zipfile.ZipInfo("link")+ link.external_attr = (stat.S_IFLNK | 0o777) << 16+ self.assertTrue(notebook_operations._is_symlink(link))++ regular = zipfile.ZipInfo("file")+ regular.external_attr = (stat.S_IFREG | 0o644) << 16+ self.assertFalse(notebook_operations._is_symlink(regular))+++class ContainerLimitTests(unittest.TestCase):+ def test_the_documented_limits_are_positive_and_ordered(self) -> None:+ # Every limit exists to stop a zip bomb; a zero or negative one would+ # disable the guard silently.+ for name in (+ "DEFAULT_MAX_MEMBERS",+ "DEFAULT_MAX_TOTAL_BYTES",+ "DEFAULT_MAX_MANIFEST_BYTES",+ "DEFAULT_MAX_INDEX_BYTES",+ "DEFAULT_MAX_COMPRESSION_RATIO",+ ):+ with self.subTest(limit=name):+ self.assertGreater(getattr(notebook_operations, name), 0)+ self.assertLess(+ notebook_operations.DEFAULT_MAX_MANIFEST_BYTES,+ notebook_operations.DEFAULT_MAX_TOTAL_BYTES,+ )++ def _inspect(self, build) -> dict:+ with tempfile.TemporaryDirectory() as directory:+ archive = Path(directory) / "notebook.eln"+ with zipfile.ZipFile(archive, "w") as handle:+ build(handle)+ return notebook_operations.inspect_container(archive)++ def test_a_traversing_member_is_reported_as_an_error(self) -> None:+ # The inspector reports rather than raises: the point is to hand back a+ # full account of what is wrong with an archive, not to stop at the+ # first problem.+ report = self._inspect(lambda z: z.writestr("../escaped.xml", "<x/>"))+ self.assertTrue(report["errors"])+ self.assertTrue(+ any("unsafe member paths" in error for error in report["errors"]),+ report["errors"],+ )++ def test_a_symlink_member_is_reported_as_an_error(self) -> None:+ def build(handle: zipfile.ZipFile) -> None:+ info = zipfile.ZipInfo("link")+ info.external_attr = (stat.S_IFLNK | 0o777) << 16+ handle.writestr(info, "/etc/passwd")++ report = self._inspect(build)+ self.assertTrue(report["errors"])++ def test_a_missing_manifest_is_reported(self) -> None:+ report = self._inspect(lambda z: z.writestr("data/entry.json", "{}"))+ self.assertTrue(report["errors"] or report["warnings"])+ combined = " ".join(report["errors"] + report["warnings"])+ self.assertIn(notebook_operations.MANIFEST_NAME, combined)++ def test_non_positive_limits_are_refused_outright(self) -> None:+ with tempfile.TemporaryDirectory() as directory:+ archive = Path(directory) / "notebook.eln"+ with zipfile.ZipFile(archive, "w") as handle:+ handle.writestr("a.txt", "x")+ for override in ("max_members", "max_total_bytes", "max_manifest_bytes"):+ with self.subTest(limit=override):+ with self.assertRaisesRegex(+ notebook_operations.InspectionError, "must be positive"+ ):+ notebook_operations.inspect_container(archive, **{override: 0})++ def test_a_member_count_over_the_limit_is_reported(self) -> None:+ with tempfile.TemporaryDirectory() as directory:+ archive = Path(directory) / "notebook.eln"+ with zipfile.ZipFile(archive, "w") as handle:+ for index in range(5):+ handle.writestr(f"file{index}.txt", "x")+ report = notebook_operations.inspect_container(archive, max_members=2)+ self.assertTrue(report["errors"])++ def test_a_missing_file_is_refused(self) -> None:+ with tempfile.TemporaryDirectory() as directory:+ with self.assertRaises((notebook_operations.InspectionError, OSError)):+ notebook_operations.inspect_container(Path(directory) / "absent.eln")++ def test_a_non_zip_file_is_refused_rather_than_crashing(self) -> None:+ with tempfile.TemporaryDirectory() as directory:+ archive = Path(directory) / "notebook.eln"+ archive.write_bytes(b"not a zip at all")+ with self.assertRaises((notebook_operations.InspectionError, zipfile.BadZipFile)):+ notebook_operations.inspect_container(archive)++ def test_the_manifest_name_is_the_documented_one(self) -> None:+ self.assertEqual(notebook_operations.MANIFEST_NAME, "lamanifest.xml")+++class XmlHelperTests(unittest.TestCase):+ def test_namespaced_tags_are_reduced_to_their_local_name(self) -> None:+ self.assertEqual(notebook_operations._local_name("{urn:x}entry"), "entry")+ self.assertEqual(notebook_operations._local_name("entry"), "entry")+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/latchbio-integration/test_scripts.py b/tests/latchbio-integration/test_scripts.pynew file mode 100644index 00000000..3df3f073--- /dev/null+++ b/tests/latchbio-integration/test_scripts.py@@ -0,0 +1,265 @@+"""Tests for the Latch SDK inspector.++`inspect_latch_sdk.py` reports on whichever Latch SDK happens to be installed,+so almost none of it can be asserted against a fixed expectation. What *can* be+pinned is everything around that: the report shape, the exit-code contract, the+address scrubbing that makes two runs comparable, and the graceful degradation+when a module is missing -- which is the normal case in this repo's project+environment, where `latch` is not installed.++`inspect_symbol` is exercised against real standard-library modules rather than+mocks: `json.dumps` is a function that exists, `json.nope` is a symbol that does+not, and `no_such_module` is an import that fails. That covers all three+branches without needing the SDK.+"""++from __future__ import annotations++import json+import subprocess+import sys+import unittest+from pathlib import Path++import skill_contract++SKILL_ROOT = Path(__file__).resolve().parents[2] / "skills" / "latchbio-integration"+SCRIPTS = SKILL_ROOT / "scripts"+sys.path.insert(0, str(SCRIPTS))++import inspect_latch_sdk # noqa: E402++CliHelpTests = skill_contract.cli.help_test_case(SKILL_ROOT)+++class NormalizeReprTests(unittest.TestCase):+ """Two runs of the inspector must be diffable, so addresses are scrubbed."""++ def test_object_repr_loses_its_address(self) -> None:+ self.assertEqual(+ inspect_latch_sdk.normalize_repr("<latch.types.LatchFile object at 0x7f9c8a1b2c40>"),+ "<latch.types.LatchFile>",+ )++ def test_bare_addresses_are_replaced_everywhere(self) -> None:+ self.assertEqual(+ inspect_latch_sdk.normalize_repr("default=0xdeadBEEF, other=0x01"),+ "default=0x<address>, other=0x<address>",+ )++ def test_text_without_an_address_is_untouched(self) -> None:+ for value in ("(x: int) -> str", "", "no hex here"):+ with self.subTest(value=value):+ self.assertEqual(inspect_latch_sdk.normalize_repr(value), value)++ def test_scrubbing_is_idempotent(self) -> None:+ once = inspect_latch_sdk.normalize_repr("<A object at 0x1234abcd>")+ self.assertEqual(inspect_latch_sdk.normalize_repr(once), once)+++class SafeSignatureTests(unittest.TestCase):+ def test_a_signature_is_returned_for_an_ordinary_function(self) -> None:+ signature = inspect_latch_sdk.safe_signature(json.dumps)+ self.assertIsNotNone(signature)+ self.assertTrue(signature.startswith("("))++ def test_objects_without_a_signature_yield_none_rather_than_raising(self) -> None:+ for obj in (42, object(), None):+ with self.subTest(obj=type(obj).__name__):+ self.assertIsNone(inspect_latch_sdk.safe_signature(obj))+++class SymbolInspectionTests(unittest.TestCase):+ def test_an_available_symbol_is_reported_with_its_kind_and_signature(self) -> None:+ result = inspect_latch_sdk.inspect_symbol("json", "dumps")+ self.assertEqual(result["qualified_name"], "json.dumps")+ self.assertTrue(result["available"])+ self.assertEqual(result["kind"], "function")+ self.assertIn("obj", result["signature"])+ self.assertNotIn("error", result)++ def test_a_missing_symbol_is_reported_without_raising(self) -> None:+ result = inspect_latch_sdk.inspect_symbol("json", "definitely_not_here")+ self.assertFalse(result["available"])+ self.assertEqual(result["error"], "symbol not found")++ def test_an_unimportable_module_becomes_the_diagnostic(self) -> None:+ result = inspect_latch_sdk.inspect_symbol("latch_module_that_is_absent", "x")+ self.assertFalse(result["available"])+ self.assertIn("ModuleNotFoundError", result["error"])+ self.assertEqual(+ result["qualified_name"], "latch_module_that_is_absent.x"+ )++ def test_plain_symbols_carry_no_workflow_interface(self) -> None:+ # `python_interface` only appears for Latch workflow objects; it must+ # not be invented for ordinary callables.+ self.assertNotIn(+ "python_interface", inspect_latch_sdk.inspect_symbol("json", "dumps")+ )+++class MethodInspectionTests(unittest.TestCase):+ def test_present_and_absent_methods_are_distinguished(self) -> None:+ result = inspect_latch_sdk.inspect_methods(+ "pathlib", "Path", ["exists", "iterdir", "not_a_method"]+ )+ self.assertTrue(result["exists"]["available"])+ self.assertTrue(result["iterdir"]["available"])+ self.assertFalse(result["not_a_method"]["available"])+ self.assertIsNone(result["not_a_method"]["signature"])++ def test_an_unimportable_class_reports_one_error_not_per_method(self) -> None:+ result = inspect_latch_sdk.inspect_methods("absent_module", "Thing", ["a", "b"])+ self.assertEqual(set(result), {"error"})+ self.assertIn("ModuleNotFoundError", result["error"])+++class CatalogueTests(unittest.TestCase):+ def test_every_symbol_group_is_non_empty_and_latch_scoped(self) -> None:+ self.assertTrue(inspect_latch_sdk.SYMBOL_GROUPS)+ for group, entries in inspect_latch_sdk.SYMBOL_GROUPS.items():+ with self.subTest(group=group):+ self.assertTrue(entries)+ for module_name, symbol_name in entries:+ self.assertTrue(module_name.startswith("latch"))+ self.assertTrue(symbol_name)++ def test_no_symbol_is_catalogued_twice(self) -> None:+ qualified = [+ f"{module}.{symbol}"+ for entries in inspect_latch_sdk.SYMBOL_GROUPS.values()+ for module, symbol in entries+ ]+ duplicates = sorted({name for name in qualified if qualified.count(name) > 1})+ self.assertEqual(duplicates, [])++ def test_method_targets_are_also_catalogued_as_symbols(self) -> None:+ # A class whose methods are probed must itself be in SYMBOL_GROUPS, or+ # the report cannot say whether a missing method means a missing class.+ catalogued = {+ f"{module}.{symbol}"+ for entries in inspect_latch_sdk.SYMBOL_GROUPS.values()+ for module, symbol in entries+ }+ for label, (module, class_name, methods) in inspect_latch_sdk.METHODS.items():+ with self.subTest(target=label):+ self.assertIn(f"{module}.{class_name}", catalogued)+ self.assertTrue(methods)+++class RequiredSymbolTests(unittest.TestCase):+ def _report(self, availability: dict[str, bool]) -> dict:+ return {+ "symbols": {+ "core": [+ {"qualified_name": name, "available": available}+ for name, available in availability.items()+ ]+ }+ }++ REQUIRED = (+ "latch.workflow",+ "latch.resources.tasks.small_task",+ "latch.resources.tasks.custom_task",+ "latch.ldata.path.LPath",+ "latch.registry.table.Table",+ "latch_cli.services.launch.launch_v2.launch",+ )++ def test_a_fully_available_sdk_has_no_required_failures(self) -> None:+ report = self._report({name: True for name in self.REQUIRED})+ self.assertFalse(inspect_latch_sdk.has_required_failures(report))++ def test_any_single_missing_core_symbol_is_a_failure(self) -> None:+ for missing in self.REQUIRED:+ with self.subTest(missing=missing):+ availability = {name: True for name in self.REQUIRED}+ availability[missing] = False+ self.assertTrue(+ inspect_latch_sdk.has_required_failures(self._report(availability))+ )++ def test_an_empty_report_counts_as_failing(self) -> None:+ self.assertTrue(+ inspect_latch_sdk.has_required_failures({"symbols": {}})+ )++ def test_every_required_symbol_is_one_the_script_catalogues(self) -> None:+ catalogued = {+ f"{module}.{symbol}"+ for entries in inspect_latch_sdk.SYMBOL_GROUPS.values()+ for module, symbol in entries+ }+ for name in self.REQUIRED:+ with self.subTest(symbol=name):+ self.assertIn(name, catalogued)+++class ReportShapeTests(unittest.TestCase):+ def test_the_report_describes_the_environment_and_every_group(self) -> None:+ report = inspect_latch_sdk.build_report()+ self.assertEqual(+ set(report),+ {"python", "platform", "latch_version", "symbols", "methods"},+ )+ self.assertEqual(set(report["symbols"]), set(inspect_latch_sdk.SYMBOL_GROUPS))+ self.assertEqual(set(report["methods"]), set(inspect_latch_sdk.METHODS))++ def test_the_report_is_json_serialisable(self) -> None:+ # --json is the documented machine-readable path, so nothing in the+ # report may be a non-serialisable introspection object.+ json.dumps(inspect_latch_sdk.build_report())++ def test_printing_a_report_without_the_sdk_does_not_raise(self) -> None:+ report = inspect_latch_sdk.build_report()+ import io+ from contextlib import redirect_stdout++ buffer = io.StringIO()+ with redirect_stdout(buffer):+ inspect_latch_sdk.print_text(report)+ self.assertIn("Latch SDK:", buffer.getvalue())+++class ExitCodeTests(unittest.TestCase):+ def _run(self, *flags: str) -> subprocess.CompletedProcess:+ return subprocess.run(+ [sys.executable, str(SCRIPTS / "inspect_latch_sdk.py"), *flags],+ capture_output=True,+ text=True,+ timeout=120,+ )++ def test_a_missing_sdk_exits_two_regardless_of_strict(self) -> None:+ try:+ import latch # noqa: F401+ except ImportError:+ pass+ else:+ self.skipTest("latch is installed; this asserts the not-installed path")++ for flags in ((), ("--strict",), ("--json",)):+ with self.subTest(flags=flags):+ result = self._run(*flags)+ self.assertEqual(result.returncode, 2, result.stderr)+ self.assertNotIn("Traceback", result.stderr)++ def test_json_output_parses_even_when_the_sdk_is_absent(self) -> None:+ result = self._run("--json")+ report = json.loads(result.stdout)+ self.assertIn("symbols", report)+ self.assertIn("latch_version", report)++ def test_an_installed_sdk_exits_zero(self) -> None:+ try:+ import latch # noqa: F401+ except ImportError:+ self.skipTest("latch is not installed; run under --isolated")+ result = self._run()+ self.assertIn(result.returncode, (0, 1), result.stderr)+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/latex-posters/test_scripts.py b/tests/latex-posters/test_scripts.pynew file mode 100644index 00000000..877764c1--- /dev/null+++ b/tests/latex-posters/test_scripts.py@@ -0,0 +1,108 @@+"""Tests for the latex-posters helpers.++The two schematic scripts are byte-identical to the copies in+`scientific-schematics` and `literature-review`, so their behaviour comes from+the shared contract. What is specific here is `review_poster.sh`, the shell+helper that renders and inspects a compiled poster.+"""++from __future__ import annotations++import subprocess+import sys+import tempfile+import unittest+from pathlib import Path++import skill_contract++SKILL_ROOT = Path(__file__).resolve().parents[2] / "skills" / "latex-posters"+SCRIPTS = SKILL_ROOT / "scripts"+sys.path.insert(0, str(SCRIPTS))++SchematicTests = skill_contract.schematic.schematic_test_case(SKILL_ROOT)+CliHelpTests = skill_contract.cli.help_test_case(SKILL_ROOT)++REVIEW_SCRIPT = SCRIPTS / "review_poster.sh"+++class ReviewScriptTests(unittest.TestCase):+ def setUp(self) -> None:+ self.text = REVIEW_SCRIPT.read_text(encoding="utf-8")++ def test_it_is_executable_shell_with_a_shebang(self) -> None:+ self.assertTrue(REVIEW_SCRIPT.is_file())+ self.assertTrue(REVIEW_SCRIPT.stat().st_mode & 0o111, "not executable")+ self.assertTrue(self.text.startswith("#!"), "no shebang")++ def test_it_parses_as_bash(self) -> None:+ syntax = subprocess.run(+ ["bash", "-n", str(REVIEW_SCRIPT)],+ capture_output=True,+ text=True,+ timeout=30,+ )+ self.assertEqual(syntax.returncode, 0, syntax.stderr)++ def _run(self, *args: str) -> subprocess.CompletedProcess:+ return subprocess.run(+ ["bash", str(REVIEW_SCRIPT), *args],+ capture_output=True,+ text=True,+ timeout=60,+ cwd=SCRIPTS,+ )++ def test_no_argument_exits_non_zero_with_usage(self) -> None:+ result = self._run()+ self.assertEqual(result.returncode, 1)+ self.assertIn("Usage:", result.stdout + result.stderr)++ def test_a_missing_file_exits_non_zero_and_names_it(self) -> None:+ result = self._run("no-such-poster.pdf")+ self.assertEqual(result.returncode, 1)+ self.assertIn("no-such-poster.pdf", result.stdout + result.stderr)++ def test_a_missing_poppler_tool_degrades_instead_of_aborting(self) -> None:+ # Deliberately no `set -e`: this is a report, and one unavailable+ # inspector must not truncate the remaining checks or the manual+ # checklist. Running with an empty PATH-ish environment proves it.+ with tempfile.TemporaryDirectory() as directory:+ poster = Path(directory) / "poster.pdf"+ poster.write_bytes(b"%PDF-1.4\n%%EOF\n")+ result = subprocess.run(+ ["bash", str(REVIEW_SCRIPT), str(poster)],+ capture_output=True,+ text=True,+ timeout=60,+ cwd=SCRIPTS,+ )+ self.assertEqual(result.returncode, 0)+ output = result.stdout+ # Every numbered section still runs, right through to the summary.+ for section in ("[1]", "[2]", "[3]", "[4]", "[5]", "[6]", "[7]"):+ with self.subTest(section=section):+ self.assertIn(section, output)+ self.assertIn("Quality Check Complete", output)+ self.assertNotIn("Traceback", result.stderr)++ def test_every_python_script_it_invokes_is_shipped(self) -> None:+ for token in self.text.split():+ if token.endswith(".py"):+ with self.subTest(script=token):+ self.assertTrue(+ (SCRIPTS / Path(token).name).is_file(),+ f"{token} is referenced but not shipped",+ )+++class AssetTests(unittest.TestCase):+ def test_every_documented_asset_is_shipped(self) -> None:+ # The skill's value is its templates; a SKILL.md that names one it does+ # not ship sends the agent looking for a file that is not there.+ problems = skill_contract.structure.link_problems(SKILL_ROOT)+ self.assertEqual(problems, [])+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/liteparse/test_scripts.py b/tests/liteparse/test_scripts.pynew file mode 100644index 00000000..e91e8286--- /dev/null+++ b/tests/liteparse/test_scripts.py@@ -0,0 +1,219 @@+"""Tests for the liteparse batch directory parser.++Parsing is liteparse's job; the script owns file discovery, serialisation, and+error containment. All three are testable with a stub parser -- and the third+matters most: a batch run over a hundred documents must not abort because one+of them is corrupt.++`parse_one` names its output from the source *stem*, so two sources whose stems+collide overwrite each other. That is pinned below as current behaviour rather+than asserted to be safe.+"""++from __future__ import annotations++import json+import sys+import tempfile+import unittest+from pathlib import Path+from types import SimpleNamespace++import pytest++import skill_contract++SKILL_ROOT = Path(__file__).resolve().parents[2] / "skills" / "liteparse"+SCRIPTS = SKILL_ROOT / "scripts"+sys.path.insert(0, str(SCRIPTS))++pytest.importorskip("liteparse", reason="liteparse scripts import liteparse")++import batch_parse_dir # noqa: E402++CliHelpTests = skill_contract.cli.help_test_case(SKILL_ROOT)+++def text_item(text: str = "hello"):+ return SimpleNamespace(+ text=text,+ x=1.0,+ y=2.0,+ width=3.0,+ height=4.0,+ font_name="Helvetica",+ font_size=12.0,+ confidence=0.99,+ )+++def parse_result(text: str = "hello"):+ page = SimpleNamespace(+ page_num=1, width=612.0, height=792.0, text=text, text_items=[text_item(text)]+ )+ return SimpleNamespace(text=text, pages=[page])+++class StubParser:+ """Stands in for LiteParse; raises for any source named `broken*`."""++ def __init__(self) -> None:+ self.seen: list[Path] = []++ def parse(self, path: Path):+ self.seen.append(path)+ if path.stem.startswith("broken"):+ raise RuntimeError("unreadable document")+ return parse_result(f"contents of {path.name}")+++class ExtensionTests(unittest.TestCase):+ def test_the_default_set_is_lowercase_and_dotted(self) -> None:+ self.assertTrue(batch_parse_dir.DEFAULT_EXTENSIONS)+ for extension in batch_parse_dir.DEFAULT_EXTENSIONS:+ with self.subTest(extension=extension):+ self.assertTrue(extension.startswith("."))+ self.assertEqual(extension, extension.lower())++ def test_the_documented_document_and_image_families_are_covered(self) -> None:+ defaults = batch_parse_dir.DEFAULT_EXTENSIONS+ for extension in (".pdf", ".docx", ".xlsx", ".pptx", ".csv", ".png", ".tiff"):+ with self.subTest(extension=extension):+ self.assertIn(extension, defaults)+++class DiscoveryTests(unittest.TestCase):+ def setUp(self) -> None:+ self._temporary = tempfile.TemporaryDirectory()+ self.addCleanup(self._temporary.cleanup)+ self.root = Path(self._temporary.name)++ def touch(self, relative: str) -> Path:+ path = self.root / relative+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_bytes(b"x")+ return path++ def _found(self, **kwargs) -> list[str]:+ kwargs.setdefault("recursive", False)+ kwargs.setdefault("extension", None)+ return [path.name for path in batch_parse_dir.iter_files(self.root, **kwargs)]++ def test_only_supported_extensions_are_yielded(self) -> None:+ self.touch("a.pdf")+ self.touch("b.docx")+ self.touch("c.exe")+ self.assertEqual(self._found(), ["a.pdf", "b.docx"])++ def test_matching_is_case_insensitive(self) -> None:+ self.touch("SCAN.PDF")+ self.assertEqual(self._found(), ["SCAN.PDF"])++ def test_an_explicit_extension_narrows_the_selection(self) -> None:+ self.touch("a.pdf")+ self.touch("b.docx")+ self.assertEqual(self._found(extension=".pdf"), ["a.pdf"])++ def test_an_explicit_extension_is_matched_case_insensitively(self) -> None:+ self.touch("a.PDF")+ self.assertEqual(self._found(extension=".PdF"), ["a.PDF"])++ def test_recursion_is_opt_in(self) -> None:+ self.touch("top.pdf")+ self.touch("nested/deep.pdf")+ self.assertEqual(self._found(), ["top.pdf"])+ self.assertEqual(sorted(self._found(recursive=True)), ["deep.pdf", "top.pdf"])++ def test_directories_are_skipped(self) -> None:+ (self.root / "folder.pdf").mkdir()+ self.assertEqual(self._found(), [])++ def test_the_order_is_deterministic(self) -> None:+ for name in ("c.pdf", "a.pdf", "b.pdf"):+ self.touch(name)+ self.assertEqual(self._found(), ["a.pdf", "b.pdf", "c.pdf"])+++class SerialisationTests(unittest.TestCase):+ def test_a_result_becomes_a_json_serialisable_dictionary(self) -> None:+ payload = batch_parse_dir._result_to_dict(parse_result("body text"))+ json.dumps(payload)+ self.assertEqual(payload["text"], "body text")+ self.assertEqual(len(payload["pages"]), 1)++ def test_page_geometry_and_text_items_survive(self) -> None:+ page = batch_parse_dir._result_to_dict(parse_result())["pages"][0]+ self.assertEqual(page["page_num"], 1)+ self.assertEqual(page["width"], 612.0)+ self.assertEqual(len(page["text_items"]), 1)++ def test_a_text_item_keeps_its_position_font_and_confidence(self) -> None:+ item = batch_parse_dir._text_item_dict(text_item("word"))+ self.assertEqual(+ set(item),+ {"text", "x", "y", "width", "height", "font_name", "font_size", "confidence"},+ )+ self.assertEqual(item["text"], "word")+ self.assertEqual(item["font_name"], "Helvetica")+ self.assertEqual(item["confidence"], 0.99)+++class ParseOneTests(unittest.TestCase):+ def setUp(self) -> None:+ self._temporary = tempfile.TemporaryDirectory()+ self.addCleanup(self._temporary.cleanup)+ self.root = Path(self._temporary.name)+ self.output = self.root / "out"+ self.output.mkdir()+ self.parser = StubParser()++ def test_text_output_writes_the_plain_text(self) -> None:+ ok, source, message = batch_parse_dir.parse_one(+ self.parser, Path("paper.pdf"), self.output, "text"+ )+ self.assertTrue(ok)+ self.assertIn("paper.txt", message)+ self.assertEqual(+ (self.output / "paper.txt").read_text(encoding="utf-8"),+ "contents of paper.pdf",+ )++ def test_json_output_writes_the_structured_result(self) -> None:+ ok, _, message = batch_parse_dir.parse_one(+ self.parser, Path("paper.pdf"), self.output, "json"+ )+ self.assertTrue(ok)+ self.assertIn("paper.json", message)+ payload = json.loads((self.output / "paper.json").read_text(encoding="utf-8"))+ self.assertEqual(payload["text"], "contents of paper.pdf")+ self.assertIn("pages", payload)++ def test_a_failing_document_is_reported_not_raised(self) -> None:+ # One corrupt file must not abort a hundred-document batch.+ ok, source, message = batch_parse_dir.parse_one(+ self.parser, Path("broken.pdf"), self.output, "text"+ )+ self.assertFalse(ok)+ self.assertEqual(source, "broken.pdf")+ self.assertIn("unreadable document", message)+ self.assertEqual(list(self.output.iterdir()), [])++ def test_the_output_name_comes_from_the_source_stem(self) -> None:+ # Consequence: report.pdf and report.docx both write report.txt.+ batch_parse_dir.parse_one(self.parser, Path("report.pdf"), self.output, "text")+ batch_parse_dir.parse_one(self.parser, Path("report.docx"), self.output, "text")+ self.assertEqual(+ [path.name for path in self.output.iterdir()], ["report.txt"]+ )+ self.assertEqual(+ (self.output / "report.txt").read_text(encoding="utf-8"),+ "contents of report.docx",+ )++ def test_an_unknown_format_falls_back_to_text(self) -> None:+ batch_parse_dir.parse_one(self.parser, Path("a.pdf"), self.output, "yaml")+ self.assertTrue((self.output / "a.txt").is_file())+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/literature-review/test_scripts.py b/tests/literature-review/test_scripts.pynew file mode 100644index 00000000..7267bfa8--- /dev/null+++ b/tests/literature-review/test_scripts.py@@ -0,0 +1,267 @@+"""Tests for the literature-review result processing.++`search_databases` is pure list manipulation over records from several+databases, so it is fully testable offline -- and worth testing, because every+function here can lose papers silently. Deduplication that trusts a title+merges two distinct papers; a year filter that drops unparseable years quietly+shrinks the corpus; ranking that treats a missing citation count as zero+buries new work.++The schematic scripts this skill also ships are covered by the shared+contract, since `scientific-schematics` and `latex-posters` ship identical+copies.+"""++from __future__ import annotations++import json+import sys+import unittest+from pathlib import Path++import skill_contract++SKILL_ROOT = Path(__file__).resolve().parents[2] / "skills" / "literature-review"+SCRIPTS = SKILL_ROOT / "scripts"+sys.path.insert(0, str(SCRIPTS))++import search_databases # noqa: E402++SchematicTests = skill_contract.schematic.schematic_test_case(SKILL_ROOT)++RESULTS = [+ {+ "title": "Deep Learning for Protein Folding",+ "authors": "Jumper, J. and Evans, R.",+ "first_author": "Jumper",+ "year": "2021",+ "source": "PubMed",+ "doi": "10.1038/s41586-021-03819-2",+ "citations": 15000,+ "journal": "Nature",+ },+ {+ "title": "Attention Is All You Need",+ "authors": "Vaswani, A.",+ "first_author": "Vaswani",+ "year": "2017",+ "source": "arXiv",+ "citations": 90000,+ },+ {+ "title": "A Recent Preprint",+ "authors": "Smith, J.",+ "first_author": "Smith",+ "year": "2026",+ "source": "bioRxiv",+ },+]+++class DeduplicationTests(unittest.TestCase):+ def test_records_sharing_a_doi_collapse_to_one(self) -> None:+ duplicated = [+ {"title": "One Version", "doi": "10.1000/x"},+ {"title": "Another Title Entirely", "doi": "10.1000/X"},+ ]+ self.assertEqual(len(search_databases.deduplicate_results(duplicated)), 1)++ def test_doi_comparison_ignores_case_and_surrounding_space(self) -> None:+ duplicated = [+ {"title": "a", "doi": " 10.1000/X "},+ {"title": "b", "doi": "10.1000/x"},+ ]+ self.assertEqual(len(search_databases.deduplicate_results(duplicated)), 1)++ def test_titles_only_deduplicate_records_that_have_no_doi(self) -> None:+ # Two records with the same title but different DOIs are two papers.+ distinct = [+ {"title": "Same Title", "doi": "10.1000/a"},+ {"title": "Same Title", "doi": "10.1000/b"},+ ]+ self.assertEqual(len(search_databases.deduplicate_results(distinct)), 2)++ same = [{"title": "Same Title"}, {"title": "same title"}]+ self.assertEqual(len(search_databases.deduplicate_results(same)), 1)++ def test_the_first_occurrence_is_the_one_kept(self) -> None:+ records = [+ {"title": "first", "doi": "10.1000/x", "source": "PubMed"},+ {"title": "second", "doi": "10.1000/x", "source": "arXiv"},+ ]+ self.assertEqual(+ search_databases.deduplicate_results(records)[0]["source"], "PubMed"+ )++ def test_an_empty_list_deduplicates_to_an_empty_list(self) -> None:+ self.assertEqual(search_databases.deduplicate_results([]), [])++ def test_records_with_neither_doi_nor_title_are_all_kept(self) -> None:+ records = [{"source": "a"}, {"source": "b"}]+ self.assertEqual(len(search_databases.deduplicate_results(records)), 2)+++class RankingTests(unittest.TestCase):+ def test_citation_ranking_puts_the_most_cited_first(self) -> None:+ ranked = search_databases.rank_results(RESULTS, "citations")+ self.assertEqual(ranked[0]["title"], "Attention Is All You Need")+ self.assertEqual(ranked[-1]["title"], "A Recent Preprint")++ def test_year_ranking_puts_the_newest_first(self) -> None:+ ranked = search_databases.rank_results(RESULTS, "year")+ self.assertEqual(ranked[0]["year"], "2026")+ self.assertEqual(ranked[-1]["year"], "2017")++ def test_relevance_ranking_uses_the_relevance_score(self) -> None:+ scored = [+ {"title": "low", "relevance_score": 0.1},+ {"title": "high", "relevance_score": 0.9},+ ]+ self.assertEqual(+ search_databases.rank_results(scored, "relevance")[0]["title"], "high"+ )++ def test_an_unknown_criterion_leaves_the_order_untouched(self) -> None:+ self.assertEqual(+ [r["title"] for r in search_databases.rank_results(RESULTS, "nonsense")],+ [r["title"] for r in RESULTS],+ )++ def test_ranking_does_not_mutate_the_input(self) -> None:+ original = [dict(record) for record in RESULTS]+ search_databases.rank_results(RESULTS, "citations")+ self.assertEqual(RESULTS, original)++ def test_a_missing_citation_count_sorts_last_rather_than_erroring(self) -> None:+ ranked = search_databases.rank_results(RESULTS, "citations")+ self.assertNotIn("citations", ranked[-1])+++class YearFilterTests(unittest.TestCase):+ def test_both_bounds_are_inclusive(self) -> None:+ filtered = search_databases.filter_by_year(RESULTS, 2017, 2021)+ self.assertEqual(len(filtered), 2)+ self.assertEqual({r["year"] for r in filtered}, {"2017", "2021"})++ def test_each_bound_can_be_used_alone(self) -> None:+ self.assertEqual(len(search_databases.filter_by_year(RESULTS, start_year=2021)), 2)+ self.assertEqual(len(search_databases.filter_by_year(RESULTS, end_year=2017)), 1)++ def test_no_bounds_keeps_everything(self) -> None:+ self.assertEqual(len(search_databases.filter_by_year(RESULTS)), len(RESULTS))++ def test_an_unparseable_year_is_kept_rather_than_silently_dropped(self) -> None:+ # Losing a paper because a database returned "in press" would be worse+ # than including one outside the range.+ records = [{"title": "x", "year": "in press"}, {"title": "y", "year": None}]+ self.assertEqual(len(search_databases.filter_by_year(records, 2020, 2026)), 2)++ def test_filtering_does_not_mutate_the_input(self) -> None:+ original = [dict(record) for record in RESULTS]+ search_databases.filter_by_year(RESULTS, 2020, 2022)+ self.assertEqual(RESULTS, original)+++class SummaryTests(unittest.TestCase):+ def test_the_summary_counts_records_sources_and_years(self) -> None:+ summary = search_databases.generate_search_summary(RESULTS)+ self.assertEqual(summary["total_results"], 3)+ self.assertEqual(+ summary["sources"], {"PubMed": 1, "arXiv": 1, "bioRxiv": 1}+ )+ self.assertEqual(summary["year_distribution"]["2021"], 1)++ def test_citation_statistics_ignore_records_without_a_count(self) -> None:+ summary = search_databases.generate_search_summary(RESULTS)+ self.assertEqual(summary["total_citations"], 105000)+ self.assertEqual(summary["avg_citations"], 105000 / 2)++ def test_an_empty_corpus_summarises_to_zeroes_not_an_error(self) -> None:+ summary = search_databases.generate_search_summary([])+ self.assertEqual(summary["total_results"], 0)+ self.assertEqual(summary["avg_citations"], 0)+ self.assertEqual(summary["sources"], {})++ def test_a_non_numeric_citation_count_is_skipped(self) -> None:+ summary = search_databases.generate_search_summary(+ [{"citations": "many"}, {"citations": 10}]+ )+ self.assertEqual(summary["total_citations"], 10)++ def test_records_with_no_source_are_bucketed_as_unknown(self) -> None:+ summary = search_databases.generate_search_summary([{"title": "x"}])+ self.assertEqual(summary["sources"], {"Unknown": 1})+++class FormattingTests(unittest.TestCase):+ def test_json_output_round_trips(self) -> None:+ rendered = search_databases.format_search_results(RESULTS, "json")+ self.assertEqual(json.loads(rendered), RESULTS)++ def test_markdown_lists_every_record_with_a_resolvable_doi_link(self) -> None:+ rendered = search_databases.format_search_results(RESULTS, "markdown")+ for record in RESULTS:+ with self.subTest(title=record["title"]):+ self.assertIn(record["title"], rendered)+ self.assertIn("https://doi.org/10.1038/s41586-021-03819-2", rendered)+ self.assertIn("**Total Results**: 3", rendered)++ def test_markdown_substitutes_placeholders_for_absent_fields(self) -> None:+ rendered = search_databases.format_search_results([{}], "markdown")+ self.assertIn("Untitled", rendered)+ self.assertIn("Unknown", rendered)+ self.assertIn("N/A", rendered)++ def test_bibtex_entries_are_balanced_and_keyed_by_author_and_year(self) -> None:+ rendered = search_databases.format_search_results(RESULTS, "bibtex")+ self.assertIn("@article{Jumper2021,", rendered)+ self.assertIn("journal = {Nature},", rendered)+ self.assertEqual(rendered.count("@"), 3)+ self.assertEqual(rendered.count("{"), rendered.count("}"))++ def test_bibtex_omits_fields_the_record_does_not_have(self) -> None:+ rendered = search_databases.format_search_results([RESULTS[1]], "bibtex")+ self.assertNotIn("journal =", rendered)+ self.assertNotIn("volume =", rendered)++ def test_bibtex_falls_back_to_a_placeholder_key(self) -> None:+ rendered = search_databases.format_search_results([{}], "bibtex")+ self.assertIn("@article{unknown0000,", rendered)++ def test_an_unknown_format_is_refused_by_name(self) -> None:+ with self.assertRaisesRegex(ValueError, "Unknown format: ris"):+ search_databases.format_search_results(RESULTS, "ris")++ def test_an_empty_corpus_formats_without_error(self) -> None:+ for output_format in ("json", "markdown", "bibtex"):+ with self.subTest(output_format=output_format):+ rendered = search_databases.format_search_results([], output_format)+ self.assertIsInstance(rendered, str)+++class PipelineTests(unittest.TestCase):+ def test_dedupe_filter_and_rank_compose_into_a_stable_corpus(self) -> None:+ raw = RESULTS + [dict(RESULTS[0])] # the same paper found twice+ processed = search_databases.rank_results(+ search_databases.filter_by_year(+ search_databases.deduplicate_results(raw), 2017, 2026+ ),+ "citations",+ )+ titles = [record["title"] for record in processed]+ self.assertEqual(len(titles), 3)+ self.assertEqual(titles[0], "Attention Is All You Need")+++class DependencyCheckTests(unittest.TestCase):+ def test_the_pdf_generator_reports_missing_tooling_rather_than_crashing(self) -> None:+ import generate_pdf++ # check_dependencies inspects the host for pandoc/LaTeX; whatever it+ # finds, it must answer rather than raise.+ result = generate_pdf.check_dependencies()+ self.assertIsNotNone(result)+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/market-research-reports/test_scripts.py b/tests/market-research-reports/test_scripts.pyindex 760a6ab6..78e64142 100644--- a/tests/market-research-reports/test_scripts.py+++ b/tests/market-research-reports/test_scripts.py@@ -36,6 +36,8 @@ from validate_competitor_matrix import ( # noqa: E402)from validate_evidence_ledger import _load_records, validate_records # noqa: E402+import skill_contract+def load_json(name: str) -> dict:with (ASSETS / name).open("r", encoding="utf-8") as handle:@@ -184,5 +186,10 @@ class ScaffoldTests(unittest.TestCase):generate(manifest, output)+# 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(SKILL_ROOT)+if __name__ == "__main__":unittest.main()diff --git a/tests/markitdown/test_scripts.py b/tests/markitdown/test_scripts.pynew file mode 100644index 00000000..7e2fbc0b--- /dev/null+++ b/tests/markitdown/test_scripts.py@@ -0,0 +1,279 @@+"""Tests for the MarkItDown batch converters.++Conversion itself is MarkItDown's job. What these scripts own is everything+around it, and each piece has a failure mode worth guarding:++* `discover_files` decides what gets converted -- and must not silently pick up+ audio and video, because with `markitdown[all]` those are transcribed via+ Google Web Speech, sending local files off the machine.+* `output_path_for` preserves the source suffix in the output name, so+ `report.pdf` and `report.docx` do not collide on `report.md`.+* `atomic_write_text` replaces files through a temporary, so an interrupted+ run never leaves a half-written markdown file.+* `infer_metadata` reads `Author_Year_Title.pdf`, and a loose pattern would+ attribute papers to the wrong author.+"""++from __future__ import annotations++import hashlib+import json+import sys+import tempfile+import unittest+from pathlib import Path++import pytest++import skill_contract++SKILL_ROOT = Path(__file__).resolve().parents[2] / "skills" / "markitdown"+SCRIPTS = SKILL_ROOT / "scripts"+sys.path.insert(0, str(SCRIPTS))++pytest.importorskip("markitdown", reason="markitdown scripts import markitdown")++import batch_convert # noqa: E402+import convert_literature # noqa: E402+import inspect_installation # noqa: E402++CliHelpTests = skill_contract.cli.help_test_case(SKILL_ROOT)+++class ExtensionTests(unittest.TestCase):+ def test_extensions_are_lowercased_dotted_and_deduplicated(self) -> None:+ self.assertEqual(+ batch_convert.normalize_extensions(["PDF", ".pdf", "docx", " .DOCX "]),+ (".docx", ".pdf"),+ )++ def test_blank_entries_are_dropped(self) -> None:+ self.assertEqual(batch_convert.normalize_extensions(["pdf", "", " "]), (".pdf",))++ def test_an_empty_selection_is_refused(self) -> None:+ with self.assertRaisesRegex(ValueError, "At least one file extension"):+ batch_convert.normalize_extensions([])++ def test_a_lone_dot_is_refused(self) -> None:+ with self.assertRaisesRegex(ValueError, "cannot be only"):+ batch_convert.normalize_extensions(["."])++ def test_the_result_is_sorted_so_runs_are_reproducible(self) -> None:+ self.assertEqual(+ batch_convert.normalize_extensions(["xlsx", "csv", "pdf"]),+ (".csv", ".pdf", ".xlsx"),+ )++ def test_the_defaults_carry_no_audio_or_video_formats(self) -> None:+ # Converting those with markitdown[all] would ship the file to Google+ # Web Speech; they must be opt-in, never a default.+ overlap = set(batch_convert.DEFAULT_EXTENSIONS) & batch_convert.EXTERNAL_SERVICE_EXTENSIONS+ self.assertEqual(overlap, set())++ def test_the_defaults_are_sorted_lowercase_and_dotted(self) -> None:+ defaults = batch_convert.DEFAULT_EXTENSIONS+ self.assertEqual(list(defaults), sorted(defaults))+ for extension in defaults:+ with self.subTest(extension=extension):+ self.assertTrue(extension.startswith("."))+ self.assertEqual(extension, extension.lower())+++class DiscoveryTestCase(unittest.TestCase):+ def setUp(self) -> None:+ self._temporary = tempfile.TemporaryDirectory()+ self.addCleanup(self._temporary.cleanup)+ self.root = Path(self._temporary.name)++ def touch(self, relative: str) -> Path:+ path = self.root / relative+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_bytes(b"x")+ return path+++class DiscoveryTests(DiscoveryTestCase):+ def test_only_the_requested_extensions_are_returned(self) -> None:+ self.touch("a.pdf")+ self.touch("b.docx")+ self.touch("c.mp3")+ found = batch_convert.discover_files(self.root, (".pdf", ".docx"), recursive=False)+ self.assertEqual([path.name for path in found], ["a.pdf", "b.docx"])++ def test_matching_is_case_insensitive(self) -> None:+ self.touch("SCAN.PDF")+ found = batch_convert.discover_files(self.root, (".pdf",), recursive=False)+ self.assertEqual([path.name for path in found], ["SCAN.PDF"])++ def test_recursion_is_opt_in(self) -> None:+ self.touch("top.pdf")+ self.touch("nested/deep.pdf")++ shallow = batch_convert.discover_files(self.root, (".pdf",), recursive=False)+ self.assertEqual([path.name for path in shallow], ["top.pdf"])++ deep = batch_convert.discover_files(self.root, (".pdf",), recursive=True)+ self.assertEqual(sorted(path.name for path in deep), ["deep.pdf", "top.pdf"])++ def test_directories_are_never_returned(self) -> None:+ (self.root / "folder.pdf").mkdir()+ self.assertEqual(+ batch_convert.discover_files(self.root, (".pdf",), recursive=False), []+ )++ def test_the_order_is_deterministic(self) -> None:+ for name in ("c.pdf", "a.pdf", "b.pdf"):+ self.touch(name)+ found = batch_convert.discover_files(self.root, (".pdf",), recursive=False)+ self.assertEqual([path.name for path in found], ["a.pdf", "b.pdf", "c.pdf"])++ def test_an_empty_directory_yields_nothing(self) -> None:+ self.assertEqual(+ batch_convert.discover_files(self.root, (".pdf",), recursive=True), []+ )+++class OutputPathTests(unittest.TestCase):+ def test_the_source_suffix_is_kept_in_the_output_name(self) -> None:+ # Without this, report.pdf and report.docx both become report.md and+ # the second silently overwrites the first.+ pdf = batch_convert.output_path_for(+ Path("/in/report.pdf"), Path("/in"), Path("/out")+ )+ docx = batch_convert.output_path_for(+ Path("/in/report.docx"), Path("/in"), Path("/out")+ )+ self.assertEqual(pdf, Path("/out/report.pdf.md"))+ self.assertEqual(docx, Path("/out/report.docx.md"))+ self.assertNotEqual(pdf, docx)++ def test_the_directory_layout_is_mirrored(self) -> None:+ self.assertEqual(+ batch_convert.output_path_for(+ Path("/in/2024/papers/a.pdf"), Path("/in"), Path("/out")+ ),+ Path("/out/2024/papers/a.pdf.md"),+ )+++class AtomicWriteTests(DiscoveryTestCase):+ def test_the_content_lands_at_the_destination(self) -> None:+ path = self.root / "nested" / "out.md"+ batch_convert.atomic_write_text(path, "# Title\n")+ self.assertEqual(path.read_text(encoding="utf-8"), "# Title\n")++ def test_no_temporary_file_survives(self) -> None:+ path = self.root / "out.md"+ batch_convert.atomic_write_text(path, "content")+ self.assertEqual([entry.name for entry in self.root.iterdir()], ["out.md"])++ def test_an_existing_file_is_replaced_wholesale(self) -> None:+ path = self.root / "out.md"+ batch_convert.atomic_write_text(path, "a much longer original document")+ batch_convert.atomic_write_text(path, "short")+ self.assertEqual(path.read_text(encoding="utf-8"), "short")++ def test_non_ascii_content_survives_the_round_trip(self) -> None:+ path = self.root / "out.md"+ batch_convert.atomic_write_text(path, "Grüße — 日本語\n")+ self.assertEqual(path.read_text(encoding="utf-8"), "Grüße — 日本語\n")+++class MetadataInferenceTests(unittest.TestCase):+ def test_an_author_year_title_filename_is_parsed(self) -> None:+ author, year, title = convert_literature.infer_metadata(+ Path("Jumper_2021_Highly_accurate_protein_structure.pdf")+ )+ self.assertEqual(author, "Jumper")+ self.assertEqual(year, "2021")+ self.assertEqual(title, "Highly accurate protein structure")++ def test_a_multi_word_author_is_kept_whole(self) -> None:+ author, year, _ = convert_literature.infer_metadata(+ Path("Van_Der_Berg_1998_A_study.pdf")+ )+ self.assertEqual(year, "1998")+ self.assertEqual(author, "Van Der Berg")++ def test_only_plausible_years_are_accepted(self) -> None:+ # 1899 and 2101 are not publication years the pattern should trust.+ for stem in ("Smith_1899_Old.pdf", "Smith_2101_Future.pdf", "Smith_21_Short.pdf"):+ with self.subTest(stem=stem):+ author, year, title = convert_literature.infer_metadata(Path(stem))+ self.assertIsNone(author)+ self.assertIsNone(year)+ self.assertTrue(title)++ def test_an_unstructured_filename_still_yields_a_readable_title(self) -> None:+ author, year, title = convert_literature.infer_metadata(+ Path("some_random_notes.pdf")+ )+ self.assertIsNone(author)+ self.assertIsNone(year)+ self.assertEqual(title, "some random notes")++ def test_runs_of_whitespace_are_collapsed(self) -> None:+ self.assertEqual(+ convert_literature.humanize_filename_component("a__b___c"), "a b c"+ )+ self.assertEqual(convert_literature.humanize_filename_component(" x "), "x")+++class DigestTests(DiscoveryTestCase):+ def test_the_digest_matches_hashlib(self) -> None:+ path = self.root / "paper.pdf"+ payload = b"%PDF-1.7\n" + b"x" * 5000+ path.write_bytes(payload)+ self.assertEqual(+ convert_literature.digest_file(path), hashlib.sha256(payload).hexdigest()+ )++ def test_an_empty_file_hashes_to_the_empty_digest(self) -> None:+ path = self.root / "empty.pdf"+ path.write_bytes(b"")+ self.assertEqual(+ convert_literature.digest_file(path), hashlib.sha256(b"").hexdigest()+ )++ def test_a_file_larger_than_one_chunk_is_hashed_whole(self) -> None:+ # The reader streams in 1 MiB chunks; a bug there would hash a prefix.+ path = self.root / "large.pdf"+ payload = bytes(range(256)) * 8192 # 2 MiB+ path.write_bytes(payload)+ self.assertEqual(+ convert_literature.digest_file(path), hashlib.sha256(payload).hexdigest()+ )+++class YamlScalarTests(unittest.TestCase):+ def test_ordinary_text_is_quoted(self) -> None:+ self.assertEqual(convert_literature.yaml_scalar("A Title"), '"A Title"')++ def test_quotes_and_colons_are_escaped_safely(self) -> None:+ # An unquoted colon would end the YAML key and corrupt the front matter.+ rendered = convert_literature.yaml_scalar('He said: "hi"')+ self.assertEqual(json.loads(rendered), 'He said: "hi"')++ def test_non_ascii_is_preserved_rather_than_escaped(self) -> None:+ self.assertEqual(convert_literature.yaml_scalar("Grüße"), '"Grüße"')+++class InstallationReportTests(unittest.TestCase):+ def test_the_report_names_the_target_version_and_optional_extras(self) -> None:+ self.assertRegex(inspect_installation.TARGET_VERSION, r"^\d+\.\d+\.\d+$")+ self.assertTrue(inspect_installation.OPTIONAL_DISTRIBUTIONS)++ def test_the_report_is_json_serialisable(self) -> None:+ json.dumps(inspect_installation.inspect_installation())++ def test_an_absent_distribution_reports_none_rather_than_raising(self) -> None:+ self.assertIsNone(+ inspect_installation.distribution_version("definitely-not-installed-xyz")+ )++ def test_an_installed_distribution_reports_its_version(self) -> None:+ self.assertIsNotNone(inspect_installation.distribution_version("markitdown"))+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/matchms/test_scripts.py b/tests/matchms/test_scripts.pynew file mode 100644index 00000000..cbfbbafb--- /dev/null+++ b/tests/matchms/test_scripts.py@@ -0,0 +1,763 @@+"""Tests for the matchms library-search helper.++`library_search.py` is a thin CLI over matchms, and almost everything that can+go wrong in it happens before or after the similarity calculation: the argument+validator that refuses pickle inputs and out-of-range thresholds, the+metric-name-to-class table that must cover every `--metric` choice the parser+advertises, the score-record reader that has to cope with both plain floats and+matchms' structured `(score, matches)` records, and `write_hits`, where the+top-k / min-score / min-matches decisions are actually made.++Those groups are driven directly. The metric table and the score-record reader+guard the two silent-wrong-answer failure modes -- a `--metric` the parser+accepts but `create_metric` cannot build, and a structured record read as a+scalar so `matched_peaks` is dropped. The end-to-end test then searches a+spectrum against a library containing a copy of itself, where cosine similarity+is exactly 1.0 by construction, so it pins the whole pipeline to a value that+is right independently of this code.+"""++from __future__ import annotations++import argparse+import csv+import sys+import tempfile+import unittest+from pathlib import Path++import pytest++import skill_contract++SKILL_ROOT = Path(__file__).resolve().parents[2] / "skills" / "matchms"+SCRIPTS = SKILL_ROOT / "scripts"+sys.path.insert(0, str(SCRIPTS))++pytest.importorskip("matchms", reason="matchms skill needs matchms")+numpy = pytest.importorskip("numpy", reason="matchms skill needs numpy")++from matchms import similarity as matchms_similarity # noqa: E402+from matchms.similarity.BaseSimilarity import BaseSimilarity # noqa: E402++import library_search # noqa: E402++CliHelpTests = skill_contract.cli.help_test_case(SKILL_ROOT)++#: A five-peak MGF spectrum. Five peaks is the minimum `--min-peaks` default+#: accepts, and the intensities stay above the 1% relative cutoff.+QUERY_MGF = """BEGIN IONS+TITLE=alpha+PEPMASS=350.1+CHARGE=1++100.0000 100.0+150.0000 50.0+200.0000 30.0+250.0000 20.0+300.0000 10.0+END IONS+"""++#: Two references: a byte-for-byte copy of the query, and a spectrum sharing no+#: fragment with it.+LIBRARY_MGF = """BEGIN IONS+TITLE=alpha_copy+PEPMASS=350.1+CHARGE=1++100.0000 100.0+150.0000 50.0+200.0000 30.0+250.0000 20.0+300.0000 10.0+END IONS++BEGIN IONS+TITLE=alpha_twin+PEPMASS=350.1+CHARGE=1++100.0000 100.0+150.0000 50.0+200.0000 30.0+250.0000 20.0+300.0000 10.0+END IONS++BEGIN IONS+TITLE=unrelated+PEPMASS=500.2+CHARGE=1++111.0000 100.0+161.0000 50.0+211.0000 30.0+261.0000 20.0+311.0000 10.0+END IONS+"""+++def metric_choices() -> list[str]:+ """The `--metric` values the parser advertises.++ argparse exposes no public accessor for a choice list, so this reads the+ action table; the alternative is duplicating the list here, which is+ exactly the drift the tests below exist to catch.+ """+ for action in library_search.build_parser()._actions:+ if action.dest == "metric":+ return list(action.choices)+ raise AssertionError("the parser no longer defines --metric")+++def score_record(score: float, matches: int):+ """One matchms-style structured score record."""+ dtype = [("Fake_score", "<f8"), ("Fake_matches", "<i8")]+ return numpy.array([(score, matches)], dtype=dtype)[0]+++class FakeSpectrum:+ """Stands in for a matchms Spectrum: metadata lookup and nothing else."""++ def __init__(self, **metadata) -> None:+ self._metadata = metadata++ def get(self, key):+ return self._metadata.get(key)+++class FakeScores:+ """Stands in for matchms Scores with a fixed, hand-chosen ranking."""++ score_names = ("Fake_score", "Fake_matches")++ def __init__(self, ranked) -> None:+ self.ranked = ranked+ self.requested_name = None+ self.requested_sort = None++ def scores_by_query(self, query, name, sort):+ self.requested_name = name+ self.requested_sort = sort+ return self.ranked+++def search_namespace(**overrides) -> argparse.Namespace:+ """A namespace with every default `build_parser` would produce."""+ defaults = dict(+ queries=None,+ references=None,+ output=None,+ metric="modified",+ tolerance=0.02,+ top_k=10,+ min_score=0.0,+ min_matches=0,+ array_type="numpy",+ max_pairs=5_000_000,+ relative_intensity=0.01,+ min_peaks=5,+ max_peaks=None,+ mz_min=None,+ mz_max=None,+ remove_precursor_window=None,+ no_default_filters=False,+ no_normalize=False,+ query_id_field=None,+ reference_id_field=None,+ bin_width=0.001,+ blink_top_k=None,+ force=False,+ quiet=True,+ )+ defaults.update(overrides)+ return argparse.Namespace(**defaults)+++class MetricTableTests(unittest.TestCase):+ """`create_metric` must cover every metric the parser accepts."""++ def test_every_advertised_metric_builds_a_similarity_object(self) -> None:+ # A choice the parser accepts but create_metric cannot build would only+ # fail after both spectrum files have been loaded and processed.+ for name in metric_choices():+ with self.subTest(metric=name):+ metric = library_search.create_metric(search_namespace(metric=name))+ self.assertIsInstance(metric, BaseSimilarity)++ def test_each_metric_name_selects_the_documented_matchms_class(self) -> None:+ expected = {+ "cosine": matchms_similarity.CosineGreedy,+ "cosine-exact": matchms_similarity.CosineHungarian,+ "cosine-linear": matchms_similarity.CosineLinear,+ "modified": matchms_similarity.ModifiedCosineGreedy,+ "modified-exact": matchms_similarity.ModifiedCosineHungarian,+ "neutral-loss": matchms_similarity.NeutralLossesCosine,+ "blink": matchms_similarity.BlinkCosine,+ }+ # Every non-flash choice is covered, so a new metric cannot be added to+ # the parser without landing in this table.+ self.assertEqual(+ set(expected) | {"flash-entropy", "flash-cosine", "flash-modified"},+ set(metric_choices()),+ )+ for name, cls in expected.items():+ with self.subTest(metric=name):+ self.assertIsInstance(+ library_search.create_metric(search_namespace(metric=name)), cls+ )++ def test_the_three_flash_metrics_differ_in_score_type_and_matching_mode(self) -> None:+ # All three build a FlashSimilarity; the distinction is entirely in the+ # constructor arguments, so a copy-paste slip would silently give the+ # user the wrong similarity.+ configurations = {+ name: library_search.create_metric(search_namespace(metric=name))+ for name in ("flash-entropy", "flash-cosine", "flash-modified")+ }+ self.assertEqual(+ {+ name: (metric.score_type, metric.matching_mode)+ for name, metric in configurations.items()+ },+ {+ "flash-entropy": ("spectral_entropy", "fragment"),+ "flash-cosine": ("cosine", "fragment"),+ # "modified" cosine means hybrid (precursor-shifted) matching.+ "flash-modified": ("cosine", "hybrid"),+ },+ )++ def test_an_unknown_metric_is_refused(self) -> None:+ with self.assertRaisesRegex(ValueError, "unsupported metric"):+ library_search.create_metric(search_namespace(metric="tanimoto"))++ def test_blink_receives_the_intensity_and_score_cutoffs(self) -> None:+ metric = library_search.create_metric(+ search_namespace(+ metric="blink", relative_intensity=0.02, blink_top_k=7, min_score=0.3+ )+ )+ self.assertEqual(metric.min_relative_intensity, 0.02)+ self.assertEqual(metric.top_k, 7)+ # BLINK prunes sparse scores itself; passing --min-score through avoids+ # materialising pairs the writer would drop anyway.+ self.assertEqual(metric.sparse_score_min, 0.3)++ def test_the_metric_sets_only_name_metrics_the_parser_offers(self) -> None:+ advertised = set(metric_choices())+ self.assertTrue(library_search.STRUCTURED_METRICS <= advertised)+ self.assertTrue(library_search.PRECURSOR_METRICS <= advertised)+ # Flash metrics report a score but no matched-peak count.+ self.assertEqual(+ library_search.STRUCTURED_METRICS+ & {"flash-entropy", "flash-cosine", "flash-modified"},+ set(),+ )+++class SuffixPolicyTests(unittest.TestCase):+ def test_pickle_suffixes_are_never_also_supported(self) -> None:+ # Refusing pickles is a security decision; the two sets overlapping+ # would quietly re-enable arbitrary code execution on load.+ self.assertEqual(+ library_search.UNSAFE_PICKLE_SUFFIXES & library_search.SUPPORTED_SUFFIXES,+ set(),+ )++ def test_every_suffix_is_lowercase_and_dotted(self) -> None:+ # validate_args lowercases the suffix before the lookup, so an entry+ # spelled ".MGF" here would never match.+ for suffix in library_search.SUPPORTED_SUFFIXES | library_search.UNSAFE_PICKLE_SUFFIXES:+ with self.subTest(suffix=suffix):+ self.assertEqual(suffix, suffix.lower())+ self.assertTrue(suffix.startswith("."))+++class ValidationTests(unittest.TestCase):+ """Both directions: a usable invocation passes, a broken one is named."""++ def setUp(self) -> None:+ self._temporary = tempfile.TemporaryDirectory()+ self.addCleanup(self._temporary.cleanup)+ self.root = Path(self._temporary.name)+ self.queries = self.root / "queries.mgf"+ self.references = self.root / "library.msp"+ for path in (self.queries, self.references):+ path.write_text("", encoding="utf-8")+ self.output = self.root / "hits.csv"++ def args(self, **overrides) -> argparse.Namespace:+ settings = dict(+ queries=self.queries, references=self.references, output=self.output+ )+ settings.update(overrides)+ return search_namespace(**settings)++ def test_a_valid_invocation_passes_silently(self) -> None:+ # Without this the rest of the class only proves the validator can say+ # no -- not that it ever says yes.+ library_search.validate_args(self.args())++ def test_every_supported_suffix_is_accepted_in_both_positions(self) -> None:+ for suffix in sorted(library_search.SUPPORTED_SUFFIXES):+ with self.subTest(suffix=suffix):+ queries = self.root / f"q{suffix}"+ queries.write_text("", encoding="utf-8")+ library_search.validate_args(self.args(queries=queries))++ def test_uppercase_suffixes_are_accepted(self) -> None:+ queries = self.root / "queries.MGF"+ queries.write_text("", encoding="utf-8")+ library_search.validate_args(self.args(queries=queries))++ def test_a_missing_input_is_reported_by_role(self) -> None:+ for role, key in (("query", "queries"), ("reference", "references")):+ with self.subTest(role=role):+ with self.assertRaisesRegex(ValueError, f"{role} file does not exist"):+ library_search.validate_args(+ self.args(**{key: self.root / "absent.mgf"})+ )++ def test_pickle_input_is_refused_with_the_reason(self) -> None:+ for name in ("library.pickle", "library.pkl"):+ with self.subTest(name=name):+ path = self.root / name+ path.write_bytes(b"")+ with self.assertRaisesRegex(ValueError, "unpickling can execute code"):+ library_search.validate_args(self.args(references=path))++ def test_an_unsupported_suffix_lists_the_formats(self) -> None:+ path = self.root / "library.csv"+ path.write_text("", encoding="utf-8")+ with self.assertRaisesRegex(ValueError, "MGF, MSP, mzML, mzXML, or JSON"):+ library_search.validate_args(self.args(references=path))++ def test_an_existing_output_needs_force(self) -> None:+ self.output.write_text("", encoding="utf-8")+ with self.assertRaisesRegex(ValueError, "--force"):+ library_search.validate_args(self.args())+ # With --force the same invocation is fine.+ library_search.validate_args(self.args(force=True))++ def test_a_missing_output_directory_is_refused(self) -> None:+ with self.assertRaisesRegex(ValueError, "output directory does not exist"):+ library_search.validate_args(self.args(output=self.root / "no" / "hits.csv"))++ def test_numeric_bounds_are_enforced_at_the_boundary(self) -> None:+ cases = [+ ({"tolerance": 0.0}, "--tolerance must be positive"),+ ({"tolerance": -0.01}, "--tolerance must be positive"),+ ({"top_k": 0}, "--top-k must be positive"),+ ({"min_score": -0.001}, "--min-score must be between 0 and 1"),+ ({"min_score": 1.001}, "--min-score must be between 0 and 1"),+ ({"min_matches": -1}, "--min-matches cannot be negative"),+ ({"max_pairs": 0}, "--max-pairs must be positive"),+ ({"relative_intensity": 1.5}, "--relative-intensity must be between 0 and 1"),+ ({"min_peaks": -1}, "--min-peaks cannot be negative"),+ ({"max_peaks": 0}, "--max-peaks must be positive"),+ ({"remove_precursor_window": 0.0}, "--remove-precursor-window must be positive"),+ ({"bin_width": 0.0}, "--bin-width must be positive"),+ ({"blink_top_k": 0}, "--blink-top-k must be positive"),+ ]+ for overrides, message in cases:+ with self.subTest(**overrides):+ with self.assertRaisesRegex(ValueError, message):+ library_search.validate_args(self.args(**overrides))++ def test_the_inclusive_ends_of_each_range_are_accepted(self) -> None:+ # 0 disables the peak filters and 0/1 are legal similarity scores, so+ # rejecting them would make documented invocations unusable.+ library_search.validate_args(+ self.args(min_score=0.0, min_peaks=0, relative_intensity=0.0)+ )+ library_search.validate_args(self.args(min_score=1.0, relative_intensity=1.0))++ def test_an_inverted_mz_window_is_refused_but_one_sided_is_fine(self) -> None:+ with self.assertRaisesRegex(ValueError, "--mz-min must be smaller"):+ library_search.validate_args(self.args(mz_min=500.0, mz_max=100.0))+ with self.assertRaisesRegex(ValueError, "--mz-min must be smaller"):+ library_search.validate_args(self.args(mz_min=100.0, mz_max=100.0))+ library_search.validate_args(self.args(mz_min=100.0))+ library_search.validate_args(self.args(mz_max=500.0))++ def test_min_matches_is_refused_for_metrics_that_report_no_matches(self) -> None:+ # Silently ignoring --min-matches would look like a filter that ran.+ with self.assertRaisesRegex(ValueError, "does not report matched-peak counts"):+ library_search.validate_args(self.args(metric="flash-entropy", min_matches=3))+ library_search.validate_args(self.args(metric="cosine", min_matches=3))+ # A zero threshold is a no-op, so it stays legal everywhere.+ library_search.validate_args(self.args(metric="flash-entropy", min_matches=0))+++class ProcessingChainTests(unittest.TestCase):+ """`create_processor` decides which matchms filters run, and in what order."""++ @staticmethod+ def step_names(args: argparse.Namespace) -> list[str]:+ steps = library_search.create_processor(args).processing_steps+ return [step[0] if isinstance(step, tuple) else step for step in steps]++ def test_metadata_filters_run_before_the_peak_filters(self) -> None:+ # SpectrumProcessor keeps registered filters in their canonical order+ # but appends unknown callables; the script expands default_filters by+ # hand precisely so precursor m/z is derived before it is required.+ names = self.step_names(search_namespace(metric="modified"))+ self.assertLess(+ names.index("add_precursor_mz"), names.index("require_precursor_mz")+ )+ self.assertLess(+ names.index("normalize_intensities"),+ names.index("select_by_relative_intensity"),+ )+ self.assertEqual(names[-1], "require_minimum_number_of_peaks")++ def test_precursor_metrics_require_a_precursor_and_others_do_not(self) -> None:+ # A modified-cosine score is meaningless without precursor m/z, so the+ # requirement must switch on with the metric.+ for metric in sorted(library_search.PRECURSOR_METRICS):+ with self.subTest(metric=metric):+ self.assertIn(+ "require_precursor_mz", self.step_names(search_namespace(metric=metric))+ )+ self.assertNotIn(+ "require_precursor_mz", self.step_names(search_namespace(metric="cosine"))+ )++ def test_a_precursor_window_forces_the_precursor_requirement(self) -> None:+ names = self.step_names(+ search_namespace(metric="cosine", remove_precursor_window=17.0)+ )+ self.assertIn("require_precursor_mz", names)+ self.assertIn("remove_peaks_around_precursor_mz", names)++ def test_the_optional_filters_are_absent_by_default(self) -> None:+ names = self.step_names(search_namespace(metric="cosine"))+ for absent in (+ "select_by_mz",+ "remove_peaks_around_precursor_mz",+ "reduce_to_number_of_peaks",+ ):+ with self.subTest(filter=absent):+ self.assertNotIn(absent, names)++ def test_each_switch_adds_exactly_its_own_filter(self) -> None:+ cases = [+ ({"mz_min": 50.0}, "select_by_mz"),+ ({"mz_max": 900.0}, "select_by_mz"),+ ({"max_peaks": 50}, "reduce_to_number_of_peaks"),+ ]+ for overrides, expected in cases:+ with self.subTest(**overrides):+ self.assertIn(expected, self.step_names(search_namespace(**overrides)))++ def test_the_disabling_flags_actually_remove_steps(self) -> None:+ self.assertNotIn(+ "normalize_intensities",+ self.step_names(search_namespace(no_normalize=True)),+ )+ self.assertNotIn(+ "add_compound_name",+ self.step_names(search_namespace(no_default_filters=True)),+ )++ def test_zero_thresholds_disable_their_filters(self) -> None:+ # `--relative-intensity 0` and `--min-peaks 0` are documented as "off",+ # not as "keep everything above zero".+ names = self.step_names(search_namespace(relative_intensity=0.0, min_peaks=0))+ self.assertNotIn("select_by_relative_intensity", names)+ self.assertNotIn("require_minimum_number_of_peaks", names)++ def test_the_same_chain_is_used_for_queries_and_references(self) -> None:+ # Comparing differently processed collections biases every score, so+ # the processor is built once from one namespace.+ args = search_namespace()+ self.assertEqual(self.step_names(args), self.step_names(args))+++class ScoreRecordTests(unittest.TestCase):+ """matchms returns either a bare float or a structured `(score, matches)`."""++ def test_the_score_field_is_the_one_ending_in_score(self) -> None:+ self.assertEqual(+ library_search.choose_score_fields(+ ("CosineGreedy_matches", "CosineGreedy_score")+ ),+ ("CosineGreedy_score", "CosineGreedy_matches"),+ )++ def test_a_metric_without_a_score_suffix_falls_back_to_the_first_field(self) -> None:+ self.assertEqual(+ library_search.choose_score_fields(("FlashSimilarity",)),+ ("FlashSimilarity", None),+ )++ def test_a_structured_record_is_read_field_by_field(self) -> None:+ record = score_record(0.75, 9)+ self.assertEqual(library_search.numeric_field(record, "Fake_score"), 0.75)+ self.assertEqual(library_search.matched_peaks(record, "Fake_matches"), 9)++ def test_a_scalar_score_is_read_directly_and_reports_no_matches(self) -> None:+ self.assertEqual(library_search.numeric_field(numpy.float64(0.4), "Fake_score"), 0.4)+ # Flash metrics return a scalar; inventing a match count would be a lie.+ self.assertIsNone(library_search.matched_peaks(numpy.float64(0.4), "Fake_matches"))+ self.assertIsNone(library_search.matched_peaks(score_record(0.4, 3), None))++ def test_a_field_the_record_does_not_carry_is_not_invented(self) -> None:+ self.assertIsNone(library_search.matched_peaks(score_record(0.4, 3), "Other_matches"))+++class SpectrumIdentityTests(unittest.TestCase):+ def test_the_preferred_field_wins_over_every_default(self) -> None:+ spectrum = FakeSpectrum(feature_id="F7", spectrum_id="S1", compound_name="caffeine")+ self.assertEqual(+ library_search.spectrum_id(+ spectrum, preferred="feature_id", index=3, prefix="query"+ ),+ "F7",+ )++ def test_the_default_order_prefers_spectrum_id_over_a_name(self) -> None:+ spectrum = FakeSpectrum(spectrum_id="S1", compound_name="caffeine", title="scan 4")+ self.assertEqual(+ library_search.spectrum_id(spectrum, preferred=None, index=3, prefix="query"),+ "S1",+ )++ def test_an_empty_value_is_skipped_rather_than_used(self) -> None:+ # An MGF with `TITLE=` yields "", which would produce a blank id column.+ spectrum = FakeSpectrum(spectrum_id="", id=None, compound_name="caffeine")+ self.assertEqual(+ library_search.spectrum_id(spectrum, preferred=None, index=3, prefix="query"),+ "caffeine",+ )++ def test_an_unidentified_spectrum_falls_back_to_prefix_and_index(self) -> None:+ self.assertEqual(+ library_search.spectrum_id(+ FakeSpectrum(), preferred=None, index=0, prefix="reference"+ ),+ "reference-0",+ )++ def test_a_numeric_identifier_is_stringified(self) -> None:+ self.assertEqual(+ library_search.spectrum_id(+ FakeSpectrum(scan_number=42), preferred=None, index=0, prefix="query"+ ),+ "42",+ )++ def test_missing_metadata_becomes_an_empty_cell_not_the_word_none(self) -> None:+ self.assertEqual(library_search.metadata_value(FakeSpectrum(), "inchikey"), "")+ self.assertEqual(+ library_search.metadata_value(FakeSpectrum(precursor_mz=350.1), "precursor_mz"),+ "350.1",+ )+++class HitWritingTests(unittest.TestCase):+ """`write_hits` owns the top-k, min-score and min-matches decisions."""++ def setUp(self) -> None:+ self._temporary = tempfile.TemporaryDirectory()+ self.addCleanup(self._temporary.cleanup)+ self.output = Path(self._temporary.name) / "hits.csv"+ self.references = [+ FakeSpectrum(spectrum_id="R0", compound_name="first", inchikey="AAA"),+ FakeSpectrum(spectrum_id="R1", compound_name="second"),+ FakeSpectrum(spectrum_id="R2", compound_name="third"),+ ]+ self.query = FakeSpectrum(spectrum_id="Q0", precursor_mz=350.1)++ def write(self, ranked, **overrides) -> list[dict[str, str]]:+ args = search_namespace(metric="cosine", **overrides)+ library_search.write_hits(+ self.output,+ scores=FakeScores(ranked),+ queries=[self.query],+ references=self.references,+ args=args,+ )+ with self.output.open(encoding="utf-8", newline="") as handle:+ return list(csv.DictReader(handle))++ def ranked(self, *scores):+ return [+ (self.references[index], score_record(score, matches))+ for index, (score, matches) in enumerate(scores)+ ]++ def test_hits_are_numbered_from_one_and_carry_reference_metadata(self) -> None:+ rows = self.write(self.ranked((0.9, 8), (0.8, 6)))+ self.assertEqual([row["rank"] for row in rows], ["1", "2"])+ self.assertEqual([row["reference_index"] for row in rows], ["0", "1"])+ self.assertEqual([row["reference_id"] for row in rows], ["R0", "R1"])+ self.assertEqual(rows[0]["reference_compound_name"], "first")+ self.assertEqual(rows[0]["reference_inchikey"], "AAA")+ # Reference 1 has no inchikey; the cell must be empty, not "None".+ self.assertEqual(rows[1]["reference_inchikey"], "")+ self.assertEqual(rows[0]["query_id"], "Q0")+ self.assertEqual(rows[0]["metric"], "cosine")+ self.assertEqual(rows[0]["score_field"], "Fake_score")+ self.assertEqual(rows[0]["matched_peaks"], "8")++ def test_top_k_truncates_after_the_filters_not_before(self) -> None:+ # 0.4 is dropped by --min-score, so the third-ranked survivor must+ # still be reported when --top-k is 2.+ rows = self.write(+ self.ranked((0.9, 8), (0.4, 8), (0.7, 8)), min_score=0.5, top_k=2+ )+ self.assertEqual([row["score"] for row in rows], ["0.9", "0.7"])+ self.assertEqual([row["rank"] for row in rows], ["1", "2"])++ def test_a_score_exactly_at_the_threshold_is_kept(self) -> None:+ rows = self.write(self.ranked((0.5, 8)), min_score=0.5)+ self.assertEqual(len(rows), 1)+ rows = self.write(self.ranked((0.5, 8)), min_score=0.5000001)+ self.assertEqual(rows, [])++ def test_the_match_count_threshold_is_inclusive(self) -> None:+ self.assertEqual(len(self.write(self.ranked((0.9, 5)), min_matches=5)), 1)+ self.assertEqual(self.write(self.ranked((0.9, 4)), min_matches=5), [])++ def test_a_scalar_score_survives_a_match_threshold(self) -> None:+ # Metrics with no match count must not be filtered to nothing by a+ # threshold they cannot answer; validate_args already refuses that+ # combination, so write_hits must not silently drop the rows either.+ ranked = [(self.references[0], numpy.float64(0.9))]+ rows = self.write(ranked, min_matches=99)+ self.assertEqual(len(rows), 1)+ self.assertEqual(rows[0]["matched_peaks"], "")++ def test_a_non_finite_score_is_dropped(self) -> None:+ # A NaN comparison is neither above nor below the threshold, so it has+ # to be excluded explicitly or it would rank first after sorting.+ rows = self.write(self.ranked((float("nan"), 8), (0.6, 8)))+ self.assertEqual([row["score"] for row in rows], ["0.6"])+ self.assertEqual([row["rank"] for row in rows], ["1"])++ def test_an_empty_ranking_still_writes_a_header(self) -> None:+ self.assertEqual(self.write([]), [])+ first_line = self.output.read_text(encoding="utf-8").splitlines()[0]+ self.assertTrue(first_line.startswith("query_index,query_id"))++ def test_a_reference_outside_the_library_is_an_error_not_a_blank_row(self) -> None:+ stranger = FakeSpectrum(spectrum_id="X")+ with self.assertRaisesRegex(RuntimeError, "outside the input library"):+ self.write([(stranger, score_record(0.9, 8))])++ def test_the_writer_asks_for_a_sorted_ranking_by_the_score_field(self) -> None:+ scores = FakeScores(self.ranked((0.9, 8)))+ library_search.write_hits(+ self.output,+ scores=scores,+ queries=[self.query],+ references=self.references,+ args=search_namespace(),+ )+ # Ranks are assigned in iteration order, so the sort has to happen in+ # matchms rather than here.+ self.assertTrue(scores.requested_sort)+ self.assertEqual(scores.requested_name, "Fake_score")++ def test_scores_are_written_with_enough_precision_to_be_reproducible(self) -> None:+ rows = self.write(self.ranked((0.123456789012, 8)))+ self.assertEqual(rows[0]["score"], "0.123456789012")+++class EndToEndSearchTests(unittest.TestCase):+ """A spectrum searched against a copy of itself scores exactly 1.0."""++ def setUp(self) -> None:+ self._temporary = tempfile.TemporaryDirectory()+ self.addCleanup(self._temporary.cleanup)+ self.root = Path(self._temporary.name)+ self.queries = self.root / "queries.mgf"+ self.references = self.root / "library.mgf"+ self.queries.write_text(QUERY_MGF, encoding="utf-8")+ self.references.write_text(LIBRARY_MGF, encoding="utf-8")+ self.output = self.root / "hits.csv"++ def args(self, **overrides) -> argparse.Namespace:+ settings = dict(+ queries=self.queries,+ references=self.references,+ output=self.output,+ metric="cosine",+ )+ settings.update(overrides)+ return search_namespace(**settings)++ def rows(self) -> list[dict[str, str]]:+ with self.output.open(encoding="utf-8", newline="") as handle:+ return list(csv.DictReader(handle))++ def test_an_identical_reference_is_reported_with_a_perfect_score(self) -> None:+ self.assertEqual(library_search.run(self.args()), 0)+ rows = self.rows()+ # Two of the three references are copies of the query; the third shares+ # no fragment, and matchms stores no entry for a zero score.+ self.assertEqual(len(rows), 2)+ for row in rows:+ self.assertEqual(float(row["score"]), 1.0)+ # All five peaks match within the 0.02 Da tolerance.+ self.assertEqual(row["matched_peaks"], "5")+ self.assertEqual(row["query_id"], "alpha")+ self.assertEqual(row["query_precursor_mz"], "350.1")+ self.assertEqual(+ sorted(row["reference_id"] for row in rows), ["alpha_copy", "alpha_twin"]+ )++ def test_top_k_limits_the_reported_hits(self) -> None:+ self.assertEqual(library_search.run(self.args(top_k=1)), 0)+ rows = self.rows()+ self.assertEqual(len(rows), 1)+ self.assertEqual(rows[0]["rank"], "1")++ def test_a_match_threshold_above_the_peak_count_reports_nothing(self) -> None:+ # Six matched peaks are impossible for a five-peak spectrum, so this+ # proves the filter is applied rather than merely accepted.+ self.assertEqual(library_search.run(self.args(min_matches=6)), 0)+ self.assertEqual(self.rows(), [])++ def test_the_pair_budget_stops_the_search_before_it_starts(self) -> None:+ with self.assertRaisesRegex(ValueError, "above --max-pairs"):+ library_search.run(self.args(max_pairs=2))+ # Nothing was written, so a refused run cannot look like an empty result.+ self.assertFalse(self.output.exists())++ def test_a_library_that_processing_empties_is_reported(self) -> None:+ # Requiring more peaks than any spectrum has leaves nothing to search.+ with self.assertRaisesRegex(ValueError, "no query spectra remain"):+ library_search.run(self.args(min_peaks=99))++ def test_main_turns_a_validation_error_into_exit_code_two(self) -> None:+ argv = [+ "library_search.py",+ str(self.root / "absent.mgf"),+ str(self.references),+ str(self.output),+ ]+ original = sys.argv+ sys.argv = argv+ try:+ self.assertEqual(library_search.main(), 2)+ finally:+ sys.argv = original+++class VersionPinTests(unittest.TestCase):+ def test_the_installed_version_is_reported_rather_than_assumed(self) -> None:+ # `run` compares this against TARGET_VERSION to warn about drift, so it+ # must be a real version string and not the "unknown" fallback.+ reported = library_search.installed_matchms_version()+ self.assertRegex(reported, r"^\d+\.\d+")+ self.assertRegex(library_search.TARGET_VERSION, r"^\d+\.\d+\.\d+$")++ def test_the_documented_target_matches_the_skill_metadata(self) -> None:+ # SKILL.md tells the agent which release the script was verified on.+ text = (SKILL_ROOT / "SKILL.md").read_text(encoding="utf-8")+ self.assertIn(library_search.TARGET_VERSION, text)+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/matlab/test_static.py b/tests/matlab/test_static.pyindex 67339ccd..e27fa142 100644--- a/tests/matlab/test_static.py+++ b/tests/matlab/test_static.py@@ -42,7 +42,7 @@ class SkillStructureTests(unittest.TestCase):self.assertIn("\ncompatibility: >-\n", text)self.assertRegex(text,- r'\nmetadata:\n version: "1\.1"\n'+ r'\nmetadata:\n version: "\d+\.\d+"\n'r' skill-author: "K-Dense Inc\."\n'r' last-reviewed: "2026-07-23"\n',)diff --git a/tests/matplotlib/test_scripts.py b/tests/matplotlib/test_scripts.pynew file mode 100644index 00000000..d1309dbb--- /dev/null+++ b/tests/matplotlib/test_scripts.py@@ -0,0 +1,236 @@+"""Tests for the matplotlib plotting templates and style configurator.++Rendering assertions are shallow by nature, so these tests go after the things+that can actually be wrong: that every style preset contains only rcParams+matplotlib recognises (a typo'd key is silently ignored, and the figure just+looks wrong), that a saved `.mplstyle` file can be loaded back by matplotlib+itself, and that each plot helper draws onto the axes it is handed rather than+into the global current figure.++Everything runs on the Agg backend and closes its figures; a suite that leaks+figures eventually trips matplotlib's open-figure warning.+"""++from __future__ import annotations++import sys+import tempfile+import unittest+from pathlib import Path++import pytest++import skill_contract++SKILL_ROOT = Path(__file__).resolve().parents[2] / "skills" / "matplotlib"+SCRIPTS = SKILL_ROOT / "scripts"+sys.path.insert(0, str(SCRIPTS))++matplotlib = pytest.importorskip("matplotlib", reason="matplotlib skill needs matplotlib")+matplotlib.use("Agg")+np = pytest.importorskip("numpy", reason="matplotlib scripts need numpy")++import matplotlib.pyplot as plt # noqa: E402++import plot_template # noqa: E402+import style_configurator # noqa: E402++CliHelpTests = skill_contract.cli.help_test_case(SKILL_ROOT)++PLOT_BUILDERS = (+ "create_line_plot",+ "create_scatter_plot",+ "create_bar_chart",+ "create_histogram",+ "create_heatmap",+ "create_contour_plot",+ "create_box_plot",+ "create_violin_plot",+)+++class FigureTestCase(unittest.TestCase):+ def setUp(self) -> None:+ self.addCleanup(plt.close, "all")+++class StylePresetTests(unittest.TestCase):+ def test_presets_exist_and_are_named_dictionaries(self) -> None:+ self.assertTrue(style_configurator.STYLE_PRESETS)+ for name, settings in style_configurator.STYLE_PRESETS.items():+ with self.subTest(preset=name):+ self.assertIsInstance(settings, dict)+ self.assertTrue(settings)++ def test_every_preset_key_is_a_real_rcparam(self) -> None:+ # matplotlib ignores unknown rcParams silently, so a typo here is+ # invisible until someone notices the figure looks wrong.+ valid = set(matplotlib.rcParams)+ for name, settings in style_configurator.STYLE_PRESETS.items():+ unknown = sorted(set(settings) - valid)+ with self.subTest(preset=name):+ self.assertEqual(unknown, [])++ def test_every_preset_applies_cleanly(self) -> None:+ original = matplotlib.rcParams.copy()+ self.addCleanup(matplotlib.rcParams.update, original)+ for name, settings in style_configurator.STYLE_PRESETS.items():+ with self.subTest(preset=name):+ matplotlib.rcParams.update(settings)++ def test_the_publication_preset_saves_at_print_resolution(self) -> None:+ publication = style_configurator.STYLE_PRESETS["publication"]+ self.assertGreaterEqual(publication["savefig.dpi"], 300)+ self.assertEqual(publication["savefig.bbox"], "tight")++ def test_every_documented_preset_is_defined(self) -> None:+ import io+ from contextlib import redirect_stdout++ buffer = io.StringIO()+ with redirect_stdout(buffer):+ style_configurator.list_available_presets()+ listed = buffer.getvalue()++ for name in style_configurator.STYLE_PRESETS:+ with self.subTest(preset=name):+ self.assertIn(name, listed)+++class StyleFileTests(unittest.TestCase):+ def test_a_saved_style_is_loadable_by_matplotlib(self) -> None:+ # The real contract: matplotlib must be able to read what we wrote.+ with tempfile.TemporaryDirectory() as directory:+ path = Path(directory) / "custom.mplstyle"+ style_configurator.save_style_file(+ style_configurator.STYLE_PRESETS["publication"], str(path)+ )+ self.assertTrue(path.is_file())++ original = matplotlib.rcParams.copy()+ self.addCleanup(matplotlib.rcParams.update, original)+ plt.style.use(str(path))++ def test_the_file_is_commented_and_grouped(self) -> None:+ with tempfile.TemporaryDirectory() as directory:+ path = Path(directory) / "custom.mplstyle"+ style_configurator.save_style_file(+ style_configurator.STYLE_PRESETS["publication"], str(path)+ )+ text = path.read_text(encoding="utf-8")+ self.assertIn("# Custom matplotlib style", text)+ self.assertIn("# Figure", text)+ self.assertIn("savefig.dpi: 300", text)++ def test_sequence_values_are_written_comma_separated(self) -> None:+ # `font.sans-serif` is a list; mplstyle wants `a, b`, not `['a', 'b']`.+ with tempfile.TemporaryDirectory() as directory:+ path = Path(directory) / "custom.mplstyle"+ style_configurator.save_style_file(+ {"font.sans-serif": ["Arial", "Helvetica"]}, str(path)+ )+ text = path.read_text(encoding="utf-8")+ self.assertIn("font.sans-serif: Arial, Helvetica", text)+ self.assertNotIn("[", text)++ def test_an_empty_style_still_writes_a_valid_file(self) -> None:+ with tempfile.TemporaryDirectory() as directory:+ path = Path(directory) / "empty.mplstyle"+ style_configurator.save_style_file({}, str(path))+ self.assertTrue(path.is_file())+ original = matplotlib.rcParams.copy()+ self.addCleanup(matplotlib.rcParams.update, original)+ plt.style.use(str(path))+++class SampleDataTests(unittest.TestCase):+ def test_the_sample_data_covers_every_plot_type(self) -> None:+ data = plot_template.generate_sample_data()+ self.assertIsInstance(data, dict)+ self.assertTrue(data)++ def test_the_sample_data_is_deterministic(self) -> None:+ # The templates are documentation; a figure that changes between runs+ # cannot be compared against the one in the docs.+ first = plot_template.generate_sample_data()+ second = plot_template.generate_sample_data()+ self.assertEqual(sorted(first), sorted(second))+ for key, value in first.items():+ with self.subTest(series=key):+ if isinstance(value, np.ndarray):+ np.testing.assert_allclose(value, second[key])++ def test_the_preview_data_is_deterministic_too(self) -> None:+ first = style_configurator.generate_preview_data()+ second = style_configurator.generate_preview_data()+ for key, value in first.items():+ with self.subTest(series=key):+ if isinstance(value, np.ndarray):+ np.testing.assert_allclose(value, second[key])+++class PlotBuilderTests(FigureTestCase):+ def setUp(self) -> None:+ super().setUp()+ self.data = plot_template.generate_sample_data()++ def test_every_builder_draws_onto_the_axes_it_is_given(self) -> None:+ for name in PLOT_BUILDERS:+ with self.subTest(builder=name):+ figure, axes = plt.subplots()+ getattr(plot_template, name)(self.data, ax=axes)+ # Something was drawn: lines, patches, images, or collections.+ drawn = (+ len(axes.lines)+ + len(axes.patches)+ + len(axes.images)+ + len(axes.collections)+ )+ self.assertGreater(drawn, 0, f"{name} drew nothing")+ plt.close(figure)++ def test_every_builder_labels_its_axes(self) -> None:+ # An unlabelled publication figure is a bug, not a style preference.+ for name in PLOT_BUILDERS:+ with self.subTest(builder=name):+ figure, axes = plt.subplots()+ getattr(plot_template, name)(self.data, ax=axes)+ self.assertTrue(+ axes.get_title() or axes.get_xlabel() or axes.get_ylabel(),+ f"{name} produced an unlabelled figure",+ )+ plt.close(figure)++ def test_builders_create_their_own_axes_when_none_is_supplied(self) -> None:+ for name in PLOT_BUILDERS:+ with self.subTest(builder=name):+ before = len(plt.get_fignums())+ getattr(plot_template, name)(self.data)+ self.assertGreaterEqual(len(plt.get_fignums()), before)+ plt.close("all")++ def test_the_publication_style_applies_without_error(self) -> None:+ original = matplotlib.rcParams.copy()+ self.addCleanup(matplotlib.rcParams.update, original)+ plot_template.set_publication_style()+ self.assertGreaterEqual(matplotlib.rcParams["savefig.dpi"], 150)+++class CompositeFigureTests(FigureTestCase):+ def test_the_comprehensive_figure_renders_and_saves(self) -> None:+ result = plot_template.create_comprehensive_figure()+ self.assertIsNotNone(result)+ with tempfile.TemporaryDirectory() as directory:+ output = Path(directory) / "figure.png"+ plt.savefig(output, dpi=72)+ self.assertGreater(output.stat().st_size, 0)++ def test_the_style_preview_renders(self) -> None:+ result = style_configurator.create_style_preview(+ style_configurator.STYLE_PRESETS["minimal"]+ )+ self.assertIsNotNone(result)+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/medchem/test_scripts.py b/tests/medchem/test_scripts.pynew file mode 100644index 00000000..a8475b50--- /dev/null+++ b/tests/medchem/test_scripts.py@@ -0,0 +1,394 @@+"""Tests for the medchem batch-filtering script.++`filter_molecules.py` has two halves worth guarding. The first is input+handling: `load_molecules` reads four file formats, and when it drops an+unparseable SMILES it must drop the matching DataFrame row too -- otherwise+every downstream filter column is offset against the wrong molecule, which is+silent and unrecoverable. The second is the filter wrappers, which rename and+prune the columns medchem returns; a rename that stops matching would leave the+`passes_*` columns invisible to `--filter-output` and to the summary report.++Every filter is therefore exercised in both directions on molecules whose+verdict is known from the published rule rather than from this code: ethanol+satisfies Lipinski and a pentapeptide does not; caffeine carries no ChEMBL+structural alert and catechol is a textbook PAINS/ChEMBL flag. The summary+arithmetic is checked against hand-computed percentages, including the+empty-input case that would otherwise divide by zero.+"""++from __future__ import annotations++import sys+import tempfile+import unittest+from pathlib import Path++import pytest++import skill_contract++SKILL_ROOT = Path(__file__).resolve().parents[2] / "skills" / "medchem"+SCRIPTS = SKILL_ROOT / "scripts"+sys.path.insert(0, str(SCRIPTS))++medchem = pytest.importorskip("medchem", reason="medchem skill needs medchem")+datamol = pytest.importorskip("datamol", reason="medchem skill needs datamol")+pandas = pytest.importorskip("pandas", reason="medchem skill needs pandas")+pytest.importorskip("rdkit", reason="medchem skill needs rdkit")+pytest.importorskip("tqdm", reason="medchem skill needs tqdm")++from rdkit import Chem # noqa: E402++import filter_molecules # noqa: E402++CliHelpTests = skill_contract.cli.help_test_case(SKILL_ROOT)++# Verdicts below are fixed by the published rules, not by medchem's behaviour.+ETHANOL = "CCO"+BENZENE = "c1ccccc1"+CAFFEINE = "CN1C=NC2=C1C(=O)N(C(=O)N2C)C"+#: Benzene-1,2-diol. Catechols are the canonical PAINS class (catechol_A) and+#: are excluded by the ChEMBL common alerts and by the NIBR screening deck.+CATECHOL = "Oc1ccccc1O"+#: Phe-Leu-Lys-Asp-Glu: 5 residues, >500 Da with well over 5 H-bond donors, so+#: it violates Lipinski's rule of five.+PENTAPEPTIDE = (+ "CC(C)C[C@H](NC(=O)[C@@H](N)CC1=CC=CC=C1)C(=O)N[C@@H](CCCCN)"+ "C(=O)N[C@@H](CC(=O)O)C(=O)N[C@@H](CCC(=O)O)C(=O)O"+)+#: Not a parseable SMILES: lowercase q is not an element or aromatic atom.+GARBAGE_SMILES = "qqq(((1"+++def molecules(*smiles):+ return [datamol.to_mol(item) for item in smiles]+++class TemporaryDirectoryTestCase(unittest.TestCase):+ def setUp(self) -> None:+ self._temporary = tempfile.TemporaryDirectory()+ self.addCleanup(self._temporary.cleanup)+ self.root = Path(self._temporary.name)+++class LoadMoleculesTests(TemporaryDirectoryTestCase):+ """Reading four formats, and staying aligned when a SMILES fails to parse."""++ def test_a_csv_is_read_with_its_extra_columns_preserved(self) -> None:+ path = self.root / "input.csv"+ path.write_text("smiles,compound_id\nCCO,c1\nc1ccccc1,c2\n", encoding="utf-8")+ frame, mols = filter_molecules.load_molecules(path)+ self.assertEqual(len(mols), 2)+ self.assertEqual(list(frame["compound_id"]), ["c1", "c2"])+ self.assertEqual(+ [Chem.MolToSmiles(mol) for mol in mols],+ [Chem.MolToSmiles(item) for item in molecules(ETHANOL, BENZENE)],+ )++ def test_a_named_smiles_column_is_honoured(self) -> None:+ path = self.root / "input.csv"+ path.write_text("structure\nCCO\n", encoding="utf-8")+ frame, mols = filter_molecules.load_molecules(path, smiles_column="structure")+ self.assertEqual(len(mols), 1)+ self.assertEqual(list(frame.columns), ["structure"])++ def test_a_tsv_is_split_on_tabs_not_commas(self) -> None:+ # Reading a TSV with the comma separator would leave one column named+ # "smiles\tname", and the missing-column branch would exit instead.+ path = self.root / "input.tsv"+ path.write_text("smiles\tname\nCCO\tethanol\n", encoding="utf-8")+ frame, mols = filter_molecules.load_molecules(path)+ self.assertEqual(list(frame.columns), ["smiles", "name"])+ self.assertEqual(list(frame["name"]), ["ethanol"])+ self.assertEqual(len(mols), 1)++ def test_a_plain_text_file_treats_each_line_as_a_smiles(self) -> None:+ path = self.root / "input.txt"+ # Blank lines and surrounding whitespace are stripped, not parsed.+ path.write_text("CCO\n\n c1ccccc1 \n\n", encoding="utf-8")+ frame, mols = filter_molecules.load_molecules(path)+ self.assertEqual(list(frame["smiles"]), [ETHANOL, BENZENE])+ self.assertEqual(len(mols), 2)++ def test_an_sdf_carries_its_properties_into_the_frame(self) -> None:+ path = self.root / "input.sdf"+ writer = Chem.SDWriter(str(path))+ for smiles, name in ((ETHANOL, "ethanol"), (BENZENE, "benzene")):+ mol = Chem.MolFromSmiles(smiles)+ mol.SetProp("compound_name", name)+ writer.write(mol)+ writer.close()++ frame, mols = filter_molecules.load_molecules(path)+ self.assertEqual(len(mols), 2)+ self.assertEqual(list(frame["compound_name"]), ["ethanol", "benzene"])+ # A canonical SMILES column is synthesised so the CSV output always has+ # a structure column, whatever the SDF happened to carry.+ self.assertEqual(list(frame["smiles"]), [Chem.CanonSmiles(ETHANOL), Chem.CanonSmiles(BENZENE)])++ def test_an_unparseable_smiles_drops_its_row_too(self) -> None:+ # The alignment guarantee: filter results are concatenated positionally+ # onto this frame, so a dropped molecule must drop its metadata row.+ path = self.root / "input.csv"+ path.write_text(+ f"smiles,compound_id\n{ETHANOL},keep-1\n{GARBAGE_SMILES},drop\n"+ f"{BENZENE},keep-2\n",+ encoding="utf-8",+ )+ frame, mols = filter_molecules.load_molecules(path)+ self.assertEqual(len(mols), 2)+ self.assertEqual(len(frame), 2)+ self.assertEqual(list(frame["compound_id"]), ["keep-1", "keep-2"])+ # The index is reset, so positional concatenation lines up.+ self.assertEqual(list(frame.index), [0, 1])++ def test_a_file_of_only_bad_smiles_yields_nothing_rather_than_failing(self) -> None:+ path = self.root / "input.txt"+ path.write_text(f"{GARBAGE_SMILES}\n", encoding="utf-8")+ frame, mols = filter_molecules.load_molecules(path)+ self.assertEqual(mols, [])+ self.assertEqual(len(frame), 0)++ def test_a_header_only_csv_loads_zero_molecules(self) -> None:+ path = self.root / "input.csv"+ path.write_text("smiles\n", encoding="utf-8")+ frame, mols = filter_molecules.load_molecules(path)+ self.assertEqual(mols, [])+ self.assertEqual(len(frame), 0)++ def test_a_missing_smiles_column_exits_rather_than_guessing(self) -> None:+ path = self.root / "input.csv"+ path.write_text("structure\nCCO\n", encoding="utf-8")+ with self.assertRaises(SystemExit) as raised:+ filter_molecules.load_molecules(path)+ self.assertEqual(raised.exception.code, 1)++ def test_an_unsupported_extension_exits(self) -> None:+ path = self.root / "input.xlsx"+ path.write_bytes(b"")+ with self.assertRaises(SystemExit) as raised:+ filter_molecules.load_molecules(path)+ self.assertEqual(raised.exception.code, 1)++ def test_the_extension_check_is_case_insensitive(self) -> None:+ path = self.root / "input.CSV"+ path.write_text("smiles\nCCO\n", encoding="utf-8")+ _, mols = filter_molecules.load_molecules(path)+ self.assertEqual(len(mols), 1)+++class RuleFilterTests(unittest.TestCase):+ """Lipinski and friends, verified against the published rule."""++ def test_rule_of_five_accepts_a_small_molecule_and_rejects_a_pentapeptide(self) -> None:+ results = filter_molecules.apply_rule_filters(+ molecules(ETHANOL, PENTAPEPTIDE), ["rule_of_five"], 1+ )+ self.assertEqual(list(results["rule_of_five"]), [True, False])++ def test_the_molecule_objects_are_not_carried_into_the_output_frame(self) -> None:+ # A `mol` column of RDKit objects cannot be written to CSV.+ results = filter_molecules.apply_rule_filters(molecules(ETHANOL), ["rule_of_five"], 1)+ self.assertNotIn("mol", results.columns)+ self.assertEqual(len(results), 1)++ def test_several_rules_produce_one_column_each_plus_the_aggregates(self) -> None:+ results = filter_molecules.apply_rule_filters(+ molecules(ETHANOL, PENTAPEPTIDE), ["rule_of_five", "rule_of_veber"], 1+ )+ self.assertLessEqual({"rule_of_five", "rule_of_veber"}, set(results.columns))+ # `pass_all` is what generate_summary and --filter-output key on.+ self.assertIn("pass_all", results.columns)+ self.assertEqual(+ list(results["pass_all"]),+ [+ bool(results["rule_of_five"][index] and results["rule_of_veber"][index])+ for index in range(2)+ ],+ )++ def test_the_rule_names_the_cli_validates_against_include_the_documented_ones(self) -> None:+ # main() warns when --rules names something outside this list, so the+ # list has to contain the rules SKILL.md tells the agent to ask for.+ available = set(medchem.rules.RuleFilters.list_available_rules_names())+ self.assertLessEqual({"rule_of_five", "rule_of_cns", "rule_of_veber"}, available)+ self.assertNotIn("rule_of_nonsense", available)++ def test_an_unknown_rule_is_refused_rather_than_ignored(self) -> None:+ with self.assertRaisesRegex(ValueError, "rule_of_nonsense"):+ filter_molecules.apply_rule_filters(molecules(ETHANOL), ["rule_of_nonsense"], 1)+++class StructuralAlertTests(unittest.TestCase):+ """Alert catalogs, and the column renames the rest of the script depends on."""++ def test_common_alerts_pass_caffeine_and_exclude_catechol(self) -> None:+ results = filter_molecules.apply_common_alerts(molecules(CAFFEINE, CATECHOL), 1)+ self.assertEqual(list(results["passes_common_alerts"]), [True, False])+ self.assertEqual(list(results["common_alert_status"]), ["ok", "exclude"])++ def test_common_alerts_columns_are_renamed_to_the_passes_convention(self) -> None:+ # generate_summary and --filter-output only see columns starting with+ # `passes_`, so medchem's generic `pass_filter`/`status` must be renamed.+ results = filter_molecules.apply_common_alerts(molecules(CAFFEINE), 1)+ self.assertNotIn("pass_filter", results.columns)+ self.assertNotIn("status", results.columns)+ self.assertNotIn("mol", results.columns)+ self.assertIn("passes_common_alerts", results.columns)++ def test_nibr_passes_caffeine_and_excludes_catechol(self) -> None:+ results = filter_molecules.apply_nibr(molecules(CAFFEINE, CATECHOL), 1)+ self.assertEqual(list(results["passes_nibr"]), [True, False])+ self.assertEqual(list(results["nibr_status"]), ["ok", "exclude"])++ def test_nibr_columns_are_renamed_too(self) -> None:+ results = filter_molecules.apply_nibr(molecules(CAFFEINE), 1)+ self.assertNotIn("pass_filter", results.columns)+ self.assertNotIn("status", results.columns)+ self.assertIn("passes_nibr", results.columns)++ def test_the_pains_catalog_flags_catechol_and_leaves_caffeine_alone(self) -> None:+ produced = list(+ filter_molecules.apply_alert_catalog(molecules(CAFFEINE, CATECHOL), ["pains"], 1)+ )+ self.assertEqual(len(produced), 1)+ name, passes = produced[0]+ self.assertEqual(name, "pains")+ self.assertEqual(list(passes), [True, False])++ def test_each_requested_catalog_is_yielded_separately(self) -> None:+ # main() pairs each yielded name with its own `passes_<name>` column, so+ # the generator must not merge catalogs into one verdict.+ produced = list(+ filter_molecules.apply_alert_catalog(molecules(CAFFEINE), ["pains", "brenk"], 1)+ )+ self.assertEqual([name for name, _ in produced], ["pains", "brenk"])+ for name, passes in produced:+ with self.subTest(catalog=name):+ self.assertEqual(len(passes), 1)+++class ComplexityAndQueryTests(unittest.TestCase):+ def test_the_complexity_column_records_the_metric_used(self) -> None:+ # Two metrics in one run would collide on a fixed column name.+ bertz = filter_molecules.apply_complexity(molecules(ETHANOL), "99", "bertz", 1)+ sas = filter_molecules.apply_complexity(molecules(ETHANOL), "99", "sas", 1)+ self.assertEqual(list(bertz.columns), ["passes_complexity_bertz"])+ self.assertEqual(list(sas.columns), ["passes_complexity_sas"])++ def test_a_generous_complexity_percentile_keeps_a_simple_molecule(self) -> None:+ # Ethanol sits at the very bottom of the ZINC-15 complexity+ # distribution, so a 99th-percentile ceiling cannot exclude it.+ results = filter_molecules.apply_complexity(molecules(ETHANOL), "99", "bertz", 1)+ self.assertEqual(list(results["passes_complexity_bertz"]), [True])++ def test_a_query_can_both_admit_and_reject_molecules(self) -> None:+ results = filter_molecules.apply_query(+ molecules(ETHANOL, PENTAPEPTIDE), 'MATCHRULE("rule_of_five")', 1+ )+ self.assertEqual(list(results["passes_query"]), [True, False])+ self.assertEqual(list(results.columns), ["passes_query"])++ def test_a_negated_query_inverts_the_verdict(self) -> None:+ results = filter_molecules.apply_query(+ molecules(ETHANOL, PENTAPEPTIDE), 'NOT MATCHRULE("rule_of_five")', 1+ )+ self.assertEqual(list(results["passes_query"]), [False, True])++ def test_a_malformed_query_raises_instead_of_admitting_everything(self) -> None:+ # A parse failure that fell through would look like "all molecules+ # passed" -- the worst possible outcome for a filter.+ with self.assertRaises(Exception) as raised:+ filter_molecules.apply_query(molecules(ETHANOL), "THIS IS NOT A QUERY", 1)+ self.assertNotIsInstance(raised.exception, AssertionError)+++class ChemicalGroupTests(unittest.TestCase):+ def test_one_boolean_column_is_produced_per_requested_group(self) -> None:+ results = filter_molecules.apply_groups(+ molecules(ETHANOL, CAFFEINE), ["amino_acids", "common_organic_solvents"]+ )+ self.assertEqual(+ list(results.columns), ["has_amino_acids", "has_common_organic_solvents"]+ )+ self.assertEqual(len(results), 2)+ for column in results.columns:+ with self.subTest(column=column):+ self.assertTrue(all(isinstance(value, bool) for value in results[column]))++ def test_an_unrecognised_group_reports_no_matches_rather_than_raising(self) -> None:+ # Documented sharp edge: unlike --rules, group names are not validated,+ # so a typo yields an all-False column instead of an error.+ results = filter_molecules.apply_groups(molecules(ETHANOL), ["not_a_real_group"])+ self.assertEqual(list(results["has_not_a_real_group"]), [False])+++class LillyFilterTests(unittest.TestCase):+ def test_a_missing_lilly_installation_yields_a_null_column_of_the_right_length(self) -> None:+ # The Lilly rules are a separate conda package. When absent the script+ # must still return one row per molecule, or the positional concat in+ # main() would misalign every later column.+ results = filter_molecules.apply_lilly(molecules(ETHANOL, CAFFEINE), 160, 1)+ self.assertEqual(list(results.columns), ["passes_lilly"])+ self.assertEqual(len(results), 2)+++class SummaryReportTests(TemporaryDirectoryTestCase):+ """The arithmetic in `generate_summary`, against hand-computed values."""++ def summarize(self, frame: "pandas.DataFrame", name: str = "results.csv") -> str:+ output = self.root / name+ filter_molecules.generate_summary(frame, output)+ return (self.root / f"{output.stem}_summary.txt").read_text(encoding="utf-8")++ def test_counts_and_percentages_are_reported_per_filter(self) -> None:+ frame = pandas.DataFrame(+ {+ "passes_a": [True, True, False],+ "passes_b": [True, False, False],+ }+ )+ text = self.summarize(frame)+ self.assertIn("Total molecules processed: 3", text)+ self.assertIn("passes_a: 2 passed (66.7%)", text)+ self.assertIn("passes_b: 1 passed (33.3%)", text)+ # Only the first molecule clears both filters.+ self.assertIn("All filters passed: 1 (33.3%)", text)++ def test_the_summary_sits_beside_the_output_and_takes_its_stem(self) -> None:+ frame = pandas.DataFrame({"passes_a": [True]})+ self.summarize(frame, name="run_07.csv")+ self.assertTrue((self.root / "run_07_summary.txt").is_file())++ def test_the_aggregate_pass_all_column_is_counted_as_a_filter(self) -> None:+ # apply_rule_filters emits `pass_all`, which does not start with+ # `passes_`; it is named explicitly so rule runs are summarised at all.+ text = self.summarize(pandas.DataFrame({"pass_all": [True, False]}))+ self.assertIn("pass_all: 1 passed (50.0%)", text)++ def test_a_non_boolean_filter_column_is_skipped_not_summed(self) -> None:+ # apply_lilly returns None values when the Lilly rules are missing;+ # summing those would raise rather than report.+ frame = pandas.DataFrame(+ {"passes_a": [True, False], "passes_lilly": [None, None]}+ )+ text = self.summarize(frame)+ self.assertIn("passes_a: 1 passed (50.0%)", text)+ self.assertNotIn("passes_lilly:", text)+ # The all-filters line must ignore the null column rather than zero out.+ self.assertIn("All filters passed: 1 (50.0%)", text)++ def test_an_empty_result_set_does_not_divide_by_zero(self) -> None:+ frame = pandas.DataFrame({"passes_a": pandas.Series(dtype=bool)})+ text = self.summarize(frame)+ self.assertIn("Total molecules processed: 0", text)+ self.assertIn("passes_a: 0 passed (0.0%)", text)++ def test_a_frame_with_no_filter_columns_reports_only_the_total(self) -> None:+ text = self.summarize(pandas.DataFrame({"smiles": [ETHANOL, BENZENE]}))+ self.assertIn("Total molecules processed: 2", text)+ self.assertNotIn("All filters passed", text)+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/neurokit2/test_scripts.py b/tests/neurokit2/test_scripts.pyindex c1cd4cb6..9b34f33e 100644--- a/tests/neurokit2/test_scripts.py+++ b/tests/neurokit2/test_scripts.py@@ -154,7 +154,7 @@ class SafetyAndManifestTests(unittest.TestCase):def test_skill_version_license_references_and_progressive_disclosure(self) -> None:skill = (SKILL_ROOT / "SKILL.md").read_text(encoding="utf-8")- self.assertIn('metadata:\n version: "1.1"', skill)+ self.assertRegex(skill, r'\nmetadata:\n version: "\d+\.\d+"\n')self.assertIn("license: MIT", skill)self.assertIn("compatibility:", skill)self.assertIn('uv pip install "neurokit2==0.2.13"', skill)diff --git a/tests/neuropixels-analysis/test_scripts.py b/tests/neuropixels-analysis/test_scripts.pynew file mode 100644index 00000000..37f52088--- /dev/null+++ b/tests/neuropixels-analysis/test_scripts.py@@ -0,0 +1,316 @@+"""Tests for the Neuropixels SpikeInterface scripts.++Almost everything here is a wrapper around SpikeInterface calls that need a real+recording, but the part that decides which units make it into a published result+is pure: the curation thresholds and the classification they drive. Those are+checked against the criteria the skill's own `references/QUALITY_METRICS.md`+documents -- Allen Visual Coding's `isi_violations_ratio < 0.5`, IBL's tighter+`< 0.1`, strict single-unit `< 0.01` -- and against the ordering that follows+from them: strict is at least as strict as IBL, which is at least as strict as+Allen. A preset whose thresholds drift, or a pair whose names get swapped, is a+silent scientific error, not a crash.++The rest of the coverage is the boundary behaviour that costs a whole rerun to+discover: every classification threshold is tested from both sides, an unknown+curation method must raise rather than quietly drop units, the sorter presets+must keep preprocessing from being applied twice, and the trace plot must+subsample a 384-channel probe rather than draw all of it.+"""++from __future__ import annotations++import sys+import tempfile+import unittest+from pathlib import Path++import pytest++import skill_contract++SKILL_ROOT = Path(__file__).resolve().parents[2] / "skills" / "neuropixels-analysis"+SCRIPTS = SKILL_ROOT / "scripts"+sys.path.insert(0, str(SCRIPTS))++pytest.importorskip("spikeinterface", reason="neuropixels-analysis needs spikeinterface")+pd = pytest.importorskip("pandas", reason="neuropixels-analysis needs pandas")+matplotlib = pytest.importorskip("matplotlib", reason="neuropixels-analysis needs matplotlib")+# explore_recording imports pyplot at module scope, so fix the backend first.+matplotlib.use("Agg")++import matplotlib.pyplot as plt # noqa: E402++import compute_metrics # noqa: E402+import explore_recording # noqa: E402+import neuropixels_pipeline # noqa: E402+import run_sorting # noqa: E402++CliHelpTests = skill_contract.cli.help_test_case(SKILL_ROOT)++CURATION_METHODS = ("allen", "ibl", "strict")++#: A unit that passes every criterion of every preset.+EXEMPLARY = {+ "snr": 10.0,+ "presence_ratio": 0.99,+ "isi_violations_ratio": 0.0,+ "amplitude_cutoff": 0.0,+ "firing_rate": 5.0,+}+++def metrics_table(*units: dict) -> pd.DataFrame:+ """A quality-metrics frame shaped like SpikeInterface's, one row per unit."""+ rows = [{**EXEMPLARY, **unit} for unit in units]+ return pd.DataFrame(rows, index=range(len(rows)))+++class CurationLabelTests(unittest.TestCase):+ """`curate_units` decides which units reach a figure."""++ def label(self, method: str, **overrides) -> str:+ return neuropixels_pipeline.curate_units(metrics_table(overrides), method=method)[0]++ def test_an_exemplary_unit_is_good_under_every_preset(self) -> None:+ # The permissive direction: a validator that rejected this unit would+ # reject every real single unit too.+ for method in CURATION_METHODS:+ with self.subTest(method=method):+ self.assertEqual(self.label(method), "good")++ def test_low_snr_is_noise_whatever_else_the_unit_scores(self) -> None:+ # The noise gate runs before the presets and short-circuits, so a unit+ # with perfect refractory behaviour and no amplitude clipping is still+ # noise if there is no signal to speak of.+ for method in CURATION_METHODS:+ with self.subTest(method=method):+ self.assertEqual(self.label(method, snr=1.0), "noise")++ def test_the_noise_threshold_excludes_its_own_boundary(self) -> None:+ # `row['snr'] < 1.5`, so exactly 1.5 is not noise.+ self.assertEqual(self.label("allen", snr=1.49), "noise")+ self.assertNotEqual(self.label("allen", snr=1.5), "noise")++ def test_allen_tolerates_refractory_violations_that_ibl_calls_multi_unit(self) -> None:+ # This is the documented difference between the two standards: Allen+ # accepts isi_violations_ratio < 0.5, IBL only < 0.1.+ self.assertEqual(self.label("allen", isi_violations_ratio=0.3), "good")+ self.assertEqual(self.label("ibl", isi_violations_ratio=0.3), "mua")++ def test_the_allen_refractory_boundary_is_strict_on_both_sides(self) -> None:+ self.assertEqual(self.label("allen", isi_violations_ratio=0.49), "good")+ # Exactly 0.5 passes neither `< 0.5` nor `> 0.5`, so it is neither good+ # nor multi-unit -- it lands in the "needs a human" bucket.+ self.assertEqual(self.label("allen", isi_violations_ratio=0.5), "unsorted")+ self.assertEqual(self.label("allen", isi_violations_ratio=0.51), "mua")++ def test_presence_ratio_is_a_strict_minimum(self) -> None:+ # `presence_ratio > 0.9`: a unit present for exactly 90% of the+ # recording is not automatically good.+ self.assertEqual(self.label("allen", presence_ratio=0.91), "good")+ self.assertEqual(self.label("allen", presence_ratio=0.9), "unsorted")++ def test_amplitude_clipping_downgrades_without_calling_the_unit_multi_unit(self) -> None:+ # A truncated amplitude distribution means missed spikes, which is a+ # completeness problem, not contamination -- so it must not be labelled+ # 'mua' when the refractory period is clean.+ self.assertEqual(self.label("allen", amplitude_cutoff=0.2), "unsorted")++ def test_ibl_additionally_requires_a_minimum_firing_rate(self) -> None:+ # A unit that fires a handful of times cannot support a rate estimate.+ self.assertEqual(self.label("ibl", firing_rate=0.05), "unsorted")+ self.assertEqual(self.label("ibl", firing_rate=0.2), "good")+ # Allen's criteria do not mention firing rate, so the same unit passes.+ self.assertEqual(self.label("allen", firing_rate=0.05), "good")++ def test_strict_demands_high_snr_and_a_nearly_clean_refractory_period(self) -> None:+ self.assertEqual(self.label("strict", snr=4.0), "unsorted")+ self.assertEqual(self.label("strict", snr=5.1), "good")+ self.assertEqual(self.label("strict", presence_ratio=0.94), "unsorted")+ self.assertEqual(self.label("strict", isi_violations_ratio=0.02), "unsorted")+ self.assertEqual(self.label("strict", isi_violations_ratio=0.06), "mua")++ def test_every_unit_gets_exactly_one_label(self) -> None:+ # A unit missing from the returned mapping disappears from the export+ # rather than being reported as rejected.+ table = metrics_table(+ {},+ {"snr": 1.0},+ {"isi_violations_ratio": 0.9},+ {"presence_ratio": 0.5},+ )+ for method in CURATION_METHODS:+ with self.subTest(method=method):+ labels = neuropixels_pipeline.curate_units(table, method=method)+ self.assertEqual(sorted(labels), list(table.index))+ self.assertLessEqual(set(labels.values()), {"good", "mua", "noise", "unsorted"})++ def test_an_unknown_method_raises_instead_of_dropping_units(self) -> None:+ # Silently returning a partial mapping would make export_results()+ # report zero good units from a perfectly good sorting.+ for method in ("Allen", "allen ", "ibl2", ""):+ with self.subTest(method=method):+ with self.assertRaisesRegex(ValueError, "unknown curation method"):+ neuropixels_pipeline.curate_units(metrics_table({}), method=method)++ def test_an_empty_metrics_table_yields_no_labels(self) -> None:+ empty = pd.DataFrame(columns=list(EXEMPLARY), index=[])+ self.assertEqual(neuropixels_pipeline.curate_units(empty, method="allen"), {})+++class CurationCriteriaTests(unittest.TestCase):+ """The threshold table in compute_metrics.py, against the documented values."""++ def test_the_presets_are_the_three_the_cli_offers(self) -> None:+ self.assertEqual(set(compute_metrics.CURATION_CRITERIA), set(CURATION_METHODS))++ def test_every_preset_carries_the_same_criteria(self) -> None:+ # The curation loop reads each threshold with `criteria.get(name)`, so a+ # renamed or missing key silently disables that criterion instead of+ # failing loudly.+ expected = {"snr", "isi_violations_ratio", "presence_ratio", "amplitude_cutoff"}+ for name, criteria in compute_metrics.CURATION_CRITERIA.items():+ with self.subTest(preset=name):+ self.assertEqual(set(criteria), expected)++ def test_no_threshold_is_zero_or_none(self) -> None:+ # Same truthiness trap: `if criteria.get('snr')` treats 0.0 and None as+ # "no threshold set", so a legitimate-looking 0 would be ignored.+ for name, criteria in compute_metrics.CURATION_CRITERIA.items():+ for key, value in criteria.items():+ with self.subTest(preset=name, criterion=key):+ self.assertIsNotNone(value)+ self.assertGreater(value, 0)++ def test_the_allen_thresholds_are_the_documented_visual_coding_ones(self) -> None:+ allen = compute_metrics.CURATION_CRITERIA["allen"]+ self.assertEqual(allen["isi_violations_ratio"], 0.5)+ self.assertEqual(allen["presence_ratio"], 0.9)+ self.assertEqual(allen["amplitude_cutoff"], 0.1)++ def test_the_ibl_thresholds_are_the_documented_reproducible_ephys_ones(self) -> None:+ ibl = compute_metrics.CURATION_CRITERIA["ibl"]+ self.assertEqual(ibl["isi_violations_ratio"], 0.1)+ self.assertEqual(ibl["presence_ratio"], 0.9)+ self.assertEqual(ibl["amplitude_cutoff"], 0.1)++ def test_the_presets_are_ordered_from_permissive_to_strict(self) -> None:+ # snr and presence_ratio are minima, so stricter means larger; the other+ # two are maxima, so stricter means smaller. Swapping two presets' names+ # -- the kind of edit that looks harmless -- breaks this ordering.+ minima = ("snr", "presence_ratio")+ maxima = ("isi_violations_ratio", "amplitude_cutoff")+ for looser, tighter in (("allen", "ibl"), ("ibl", "strict")):+ for key in minima:+ with self.subTest(pair=(looser, tighter), criterion=key):+ self.assertLessEqual(+ compute_metrics.CURATION_CRITERIA[looser][key],+ compute_metrics.CURATION_CRITERIA[tighter][key],+ )+ for key in maxima:+ with self.subTest(pair=(looser, tighter), criterion=key):+ self.assertGreaterEqual(+ compute_metrics.CURATION_CRITERIA[looser][key],+ compute_metrics.CURATION_CRITERIA[tighter][key],+ )++ def test_the_two_scripts_agree_on_which_standard_is_stricter(self) -> None:+ # neuropixels_pipeline.curate_units hardcodes its refractory thresholds+ # rather than reading this table, so they can drift apart. Prove the+ # relationship holds in both: a unit Allen calls good, IBL calls mua.+ table = compute_metrics.CURATION_CRITERIA+ self.assertGreater(+ table["allen"]["isi_violations_ratio"], table["ibl"]["isi_violations_ratio"]+ )+ between = (table["ibl"]["isi_violations_ratio"] + table["allen"]["isi_violations_ratio"]) / 2+ labels = {+ method: neuropixels_pipeline.curate_units(+ metrics_table({"isi_violations_ratio": between}), method=method+ )[0]+ for method in ("allen", "ibl")+ }+ self.assertEqual(labels, {"allen": "good", "ibl": "mua"})+++class SorterDefaultTests(unittest.TestCase):+ def test_the_presets_match_the_sorters_the_cli_offers(self) -> None:+ self.assertEqual(+ set(run_sorting.SORTER_DEFAULTS),+ {"kilosort4", "kilosort3", "spykingcircus2", "mountainsort5"},+ )++ def test_every_sorter_that_can_preprocess_has_it_switched_off(self) -> None:+ # run_sorting.py consumes an already filtered, referenced, bad-channel+ # removed recording. Letting a sorter filter or re-reference it a second+ # time distorts the waveforms it then tries to cluster.+ defaults = run_sorting.SORTER_DEFAULTS+ self.assertIs(defaults["kilosort3"]["do_CAR"], False)+ self.assertIs(defaults["spykingcircus2"]["apply_preprocessing"], False)+ self.assertIs(defaults["mountainsort5"]["filter"], False)+ self.assertIs(defaults["mountainsort5"]["whiten"], False)++ def test_the_kilosort4_thresholds_are_positive_spike_amplitudes(self) -> None:+ kilosort4 = run_sorting.SORTER_DEFAULTS["kilosort4"]+ self.assertGreater(kilosort4["Th_universal"], 0)+ self.assertGreater(kilosort4["Th_learned"], 0)+ # The universal (template-matching) threshold sits above the learned one+ # in Kilosort4's own defaults, so detection is broader than acceptance.+ self.assertGreater(kilosort4["Th_universal"], kilosort4["Th_learned"])+ self.assertGreater(kilosort4["batch_size"], 0)++ def test_an_unlisted_sorter_gets_no_parameters_rather_than_a_wrong_set(self) -> None:+ # `SORTER_DEFAULTS.get(sorter, {})` -- a sorter with no entry must fall+ # back to that sorter's own upstream defaults, never to another one's.+ self.assertEqual(run_sorting.SORTER_DEFAULTS.get("tridesclous2", {}), {})+++class TracePlotTests(unittest.TestCase):+ """`plot_traces` must stay readable on a full 384-channel Neuropixels probe."""++ @classmethod+ def setUpClass(cls) -> None:+ import spikeinterface.full as si++ cls.si = si++ def setUp(self) -> None:+ self._temporary = tempfile.TemporaryDirectory()+ self.addCleanup(self._temporary.cleanup)+ self.addCleanup(plt.close, "all")+ self.root = Path(self._temporary.name)++ def recording(self, channels: int):+ return self.si.generate_recording(+ num_channels=channels, durations=[0.5], sampling_frequency=30000.0+ )++ def drawn_lines(self, channels: int) -> int:+ target = self.root / f"traces{channels}.png"+ explore_recording.plot_traces(+ self.recording(channels), duration=0.05, output_path=str(target)+ )+ self.assertTrue(target.is_file())+ # plot_traces builds its own figure and does not return it.+ return len(plt.gcf().axes[0].lines)++ def test_a_wide_probe_is_subsampled_to_twenty_traces(self) -> None:+ self.assertEqual(self.drawn_lines(64), 20)++ def test_a_narrow_probe_draws_every_channel_it_has(self) -> None:+ # min(20, n) -- with fewer than 20 channels nothing is dropped, and the+ # linspace must not produce duplicate indices.+ self.assertEqual(self.drawn_lines(6), 6)++ def test_the_time_axis_covers_the_requested_duration(self) -> None:+ target = self.root / "traces.png"+ recording = self.recording(8)+ explore_recording.plot_traces(recording, duration=0.05, output_path=str(target))+ line = plt.gcf().axes[0].lines[0]+ times = line.get_xdata()+ self.assertEqual(len(times), int(0.05 * recording.get_sampling_frequency()))+ self.assertAlmostEqual(float(times[0]), 0.0)+ self.assertLess(float(times[-1]), 0.05)+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/omero-integration/test_scripts.py b/tests/omero-integration/test_scripts.pyindex 92553763..7e668b27 100644--- a/tests/omero-integration/test_scripts.py+++ b/tests/omero-integration/test_scripts.py@@ -28,6 +28,8 @@ from omero_common import ( # noqa: E402take_bounded,)+import skill_contract+class FakeParty:def __init__(self, identifier: int, username: str = "private-user"):@@ -337,5 +339,10 @@ class TransferPlannerTests(unittest.TestCase):plan_transfer.plan_import(args)+# 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(SKILL_ROOT)+if __name__ == "__main__":unittest.main()diff --git a/tests/onekgpd/test_scripts.py b/tests/onekgpd/test_scripts.pynew file mode 100644index 00000000..aa0a8af7--- /dev/null+++ b/tests/onekgpd/test_scripts.py@@ -0,0 +1,1311 @@+"""Tests for the OneKGPd query wrappers over the 1000 Genomes Project.++`onekgpd_api` talks to a public gRPC endpoint, so every test here replaces+`DnaerysClient` with a recorder and asserts on the request that *would* have+been sent: the region, the zygosity pair, the annotation filter, and the+provenance echo written into the JSON. Nothing in this file opens a socket. The+retry helper is exercised with the library's own error classes so "retryable"+means what dnaerys says it means, not what the test assumes.++`onekgpd_meta` answers from a bundled pedigree file and needs no dependency at+all, so its tests run in any environment. They are pinned to published 1000+Genomes facts -- 3,202 individuals, 26 populations, 5 superpopulations, and the+NA19240/NA19239/NA19238 Yoruba trio -- rather than to whatever the asset+happens to contain, so a truncated or re-keyed data file fails loudly.++The paging and sentinel semantics get the same treatment: `skip`/`limit` bounds+are checked at both ends, and a `count` of -1 from `count-samples-hom-ref` must+be reported as "no variant here", never as a count of minus one.+"""++from __future__ import annotations++import io+import json+import sys+import tempfile+import unittest+from argparse import Namespace+from contextlib import redirect_stderr, redirect_stdout+from pathlib import Path+from unittest.mock import patch++import pytest # noqa: F401 -- imported for parity with the other suites++import skill_contract++SKILL_ROOT = Path(__file__).resolve().parents[2] / "skills" / "onekgpd"+SCRIPTS = SKILL_ROOT / "scripts"+sys.path.insert(0, str(SCRIPTS))++import onekgpd_meta # noqa: E402 -- standard library only; always importable++# `pytest.importorskip` is deliberately NOT used at module scope here: it would+# skip the whole file, including the onekgpd_meta tests, which need no+# third-party package at all. Only the onekgpd_api half depends on dnaerys.+try:+ import dnaerys++ import onekgpd_api+except ImportError: # pragma: no cover - exercised only without dnaerys+ dnaerys = None+ onekgpd_api = None++needs_dnaerys = unittest.skipUnless(+ onekgpd_api is not None,+ "onekgpd_api imports dnaerys; run under `tests/run_all.py --isolated`",+)++CliHelpTests = skill_contract.cli.help_test_case(SKILL_ROOT)++# Published 1000 Genomes Project (NYGC 30x, GRCh38) cohort facts.+COHORT_SIZE = 3202+PHASE3_SIZE = 2504+POPULATION_COUNT = 26+SUPERPOPULATION_CODES = {"AFR", "AMR", "EAS", "EUR", "SAS"}+++def emitted(handler, **arguments) -> dict:+ """Run a command handler with `--output` set and return the JSON it wrote."""+ with tempfile.TemporaryDirectory() as directory:+ output = Path(directory) / "result.json"+ # Every handler defaults `--output` to a temp file it names itself; the+ # tests always pin it so the JSON can be read back.+ if not arguments.get("output"):+ arguments["output"] = str(output)+ destination = output+ else:+ destination = Path(arguments["output"])+ with redirect_stdout(io.StringIO()):+ handler(Namespace(**arguments))+ return json.loads(destination.read_text(encoding="utf-8"))+++def failure_message(handler, **arguments) -> str:+ """Run a handler expected to call `_fail`; return what it printed to stderr."""+ errors = io.StringIO()+ with redirect_stdout(io.StringIO()), redirect_stderr(errors):+ try:+ handler(Namespace(**arguments))+ except SystemExit as exit_code:+ assert exit_code.code == 1, exit_code.code+ else: # pragma: no cover - a passing call is a test failure+ raise AssertionError("the handler did not fail")+ return errors.getvalue()+++# ---------------------------------------------------------------------------+# onekgpd_meta -- offline pedigree and population metadata+# ---------------------------------------------------------------------------+++class BundledDataTests(unittest.TestCase):+ """The asset is the whole product for these commands; pin its shape."""++ def test_the_bundled_cohort_is_the_published_one(self) -> None:+ records = onekgpd_meta._load_records()+ self.assertEqual(len(records), COHORT_SIZE)+ self.assertEqual(len({r["pop"] for r in records}), POPULATION_COUNT)+ self.assertEqual({r["reg"] for r in records}, SUPERPOPULATION_CODES)++ def test_the_phase_three_subset_is_the_published_size(self) -> None:+ # 2,504 unrelated phase-3 samples plus 698 related individuals = 3,202.+ records = onekgpd_meta._load_records()+ phase3 = [r for r in records if r["phase3"] == "TRUE"]+ self.assertEqual(len(phase3), PHASE3_SIZE)++ def test_every_record_carries_the_keys_the_commands_read(self) -> None:+ required = {+ "externalIDs", "familyId", "gender", "pid", "mid", "Relationship",+ "pop", "Population", "reg", "region", "phase3",+ }+ for record in onekgpd_meta._load_records():+ missing = required - record.keys()+ if missing: # report the first offender rather than 3,202 failures+ self.fail(f"{record.get('externalIDs')} is missing {sorted(missing)}")++ def test_the_limit_ceiling_is_the_cohort_size(self) -> None:+ # A limit above the cohort could never return more rows, so the cap and+ # the cohort must agree.+ self.assertEqual(onekgpd_meta.MAX_LIMIT, COHORT_SIZE)+ self.assertEqual(onekgpd_meta.DEFAULT_LIMIT, 50)+++class AbsentValueTests(unittest.TestCase):+ """The pedigree file spells "no parent" as `0`, and `''` as "no value"."""++ def test_zero_and_empty_are_absent_but_an_identifier_is_present(self) -> None:+ for absent in (None, "", "0"):+ with self.subTest(value=absent):+ self.assertFalse(onekgpd_meta._present(absent))+ self.assertTrue(onekgpd_meta._present("NA19239"))++ def test_null_if_absent_keeps_zero_out_of_the_output(self) -> None:+ # Emitting "0" as a paternal ID would invent a sample called 0.+ self.assertIsNone(onekgpd_meta._none_if_absent("0"))+ self.assertIsNone(onekgpd_meta._none_if_absent(""))+ self.assertEqual(onekgpd_meta._none_if_absent("NA19239"), "NA19239")++ def test_null_if_empty_keeps_zero_because_a_family_may_be_named_zero(self) -> None:+ # The Java original distinguishes the two helpers; only the pid/mid+ # fields use "0" as a sentinel.+ self.assertEqual(onekgpd_meta._none_if_empty("0"), "0")+ self.assertIsNone(onekgpd_meta._none_if_empty(""))+++class ChildrenIndexTests(unittest.TestCase):+ def test_the_yoruba_trio_is_reconstructed_from_the_asset(self) -> None:+ # Published pedigree: NA19240 is the daughter of NA19239 x NA19238.+ index = onekgpd_meta._children_index(onekgpd_meta._load_records())+ self.assertIn("NA19240", index["NA19239"])+ self.assertIn("NA19240", index["NA19238"])++ def test_a_child_with_one_recorded_parent_is_not_indexed(self) -> None:+ # Mirrors the SQL join: both parents must be present, otherwise the+ # "children" list would imply a trio that the cohort does not contain.+ records = [+ {"externalIDs": "KID", "pid": "DAD", "mid": "0"},+ {"externalIDs": "OTHER", "pid": "DAD", "mid": "MUM"},+ ]+ index = onekgpd_meta._children_index(records)+ self.assertEqual(index["DAD"], ["OTHER"])+ self.assertEqual(index["MUM"], ["OTHER"])++ def test_founders_have_no_children_entry(self) -> None:+ records = [{"externalIDs": "SOLO", "pid": "0", "mid": "0"}]+ self.assertEqual(onekgpd_meta._children_index(records), {})+++class PopulationStatsAggregationTests(unittest.TestCase):+ @staticmethod+ def record(**overrides) -> dict:+ base = {+ "externalIDs": "S", "familyId": "F", "gender": "male",+ "pid": "0", "mid": "0", "Relationship": "",+ "pop": "YRI", "Population": "Yoruba in Ibadan, Nigeria",+ "reg": "AFR", "region": "Africa", "phase3": "TRUE",+ }+ base.update(overrides)+ return base++ def test_counts_are_aggregated_per_population_key(self) -> None:+ subset = [+ self.record(externalIDs="a"),+ self.record(externalIDs="b", gender="female"),+ self.record(externalIDs="c", gender="female", phase3="FALSE",+ pid="a", mid="b"),+ self.record(externalIDs="d", pop="CHS", Population="Southern Han Chinese",+ reg="EAS", region="East Asia"),+ ]+ groups = onekgpd_meta._population_stats(subset)+ self.assertEqual(len(groups), 2)+ yri = groups[("YRI", "Yoruba in Ibadan, Nigeria", "AFR", "Africa")]+ # Hand-counted: 3 samples, 1 male, 2 female, 2 phase-3, 1 trio child.+ self.assertEqual(yri, {"n": 3, "m": 1, "f": 2, "p3": 2, "trio": 1})++ def test_an_unrecorded_sex_counts_toward_neither_column(self) -> None:+ groups = onekgpd_meta._population_stats([self.record(gender="")])+ stats = next(iter(groups.values()))+ self.assertEqual((stats["n"], stats["m"], stats["f"]), (1, 0, 0))++ def test_an_empty_subset_produces_no_groups(self) -> None:+ self.assertEqual(onekgpd_meta._population_stats([]), {})+++class SampleMetadataCommandTests(unittest.TestCase):+ def test_a_trio_child_reports_both_parents_and_its_relationship(self) -> None:+ data = emitted(onekgpd_meta.cmd_sample_metadata, samples="NA19240")+ sample = data["samples"][0]+ self.assertEqual(sample["sample_id"], "NA19240")+ self.assertEqual(sample["paternal_id"], "NA19239")+ self.assertEqual(sample["maternal_id"], "NA19238")+ self.assertEqual(sample["relationship"], "child")+ self.assertEqual(sample["population_code"], "YRI")+ self.assertEqual(sample["superpopulation_code"], "AFR")++ def test_a_founder_reports_no_parents_rather_than_zero(self) -> None:+ data = emitted(onekgpd_meta.cmd_sample_metadata, samples="HG00096")+ sample = data["samples"][0]+ self.assertIsNone(sample["paternal_id"])+ self.assertIsNone(sample["maternal_id"])+ self.assertEqual(sample["population_code"], "GBR")++ def test_several_samples_come_back_sorted_and_deduplicated(self) -> None:+ data = emitted(+ onekgpd_meta.cmd_sample_metadata, samples="NA19240,HG00096,NA19240"+ )+ self.assertEqual(+ [s["sample_id"] for s in data["samples"]], ["HG00096", "NA19240"]+ )++ def test_whitespace_around_identifiers_is_tolerated(self) -> None:+ data = emitted(onekgpd_meta.cmd_sample_metadata, samples=" NA19240 , HG00096 ")+ self.assertEqual(len(data["samples"]), 2)++ def test_an_unknown_identifier_fails_and_names_it(self) -> None:+ message = failure_message(+ onekgpd_meta.cmd_sample_metadata, samples="NA19240,NOT_A_SAMPLE",+ output=None,+ )+ self.assertIn("NOT_A_SAMPLE", message)+ self.assertNotIn("NA19240", message)++ def test_sample_identifiers_are_case_sensitive(self) -> None:+ # The variant commands take the same names; accepting a wrong case here+ # would produce IDs the query layer then rejects.+ message = failure_message(+ onekgpd_meta.cmd_sample_metadata, samples="na19240", output=None+ )+ self.assertIn("Unknown sample IDs", message)++ def test_an_empty_sample_list_fails(self) -> None:+ message = failure_message(+ onekgpd_meta.cmd_sample_metadata, samples=" , ", output=None+ )+ self.assertIn("must not be null or empty", message)+++class PopulationListingTests(unittest.TestCase):+ def test_all_populations_are_listed_and_add_up_to_the_cohort(self) -> None:+ data = emitted(onekgpd_meta.cmd_list_populations)+ self.assertEqual(len(data["populations"]), POPULATION_COUNT)+ self.assertEqual(+ sum(p["sample_count"] for p in data["populations"]), COHORT_SIZE+ )++ def test_populations_are_ordered_by_superpopulation_then_code(self) -> None:+ data = emitted(onekgpd_meta.cmd_list_populations)+ keys = [+ (p["superpopulation_code"], p["population_code"])+ for p in data["populations"]+ ]+ self.assertEqual(keys, sorted(keys))++ def test_the_five_superpopulations_partition_the_cohort(self) -> None:+ data = emitted(onekgpd_meta.cmd_list_superpopulations)+ codes = {sp["superpopulation_code"] for sp in data["superpopulations"]}+ self.assertEqual(codes, SUPERPOPULATION_CODES)+ self.assertEqual(+ sum(sp["sample_count"] for sp in data["superpopulations"]), COHORT_SIZE+ )+ # Every population belongs to exactly one superpopulation.+ listed = [p for sp in data["superpopulations"] for p in sp["populations"]]+ self.assertEqual(len(listed), POPULATION_COUNT)+ self.assertEqual(len(set(listed)), POPULATION_COUNT)+++class PopulationStatsCommandTests(unittest.TestCase):+ def test_the_sex_split_and_trio_count_are_internally_consistent(self) -> None:+ data = emitted(onekgpd_meta.cmd_population_stats, populations=["YRI"])+ stats = data["populations"][0]+ self.assertEqual(stats["population_code"], "YRI")+ self.assertEqual(stats["superpopulation_code"], "AFR")+ self.assertEqual(+ stats["male_count"] + stats["female_count"], stats["sample_count"]+ )+ self.assertLessEqual(stats["phase3_count"], stats["sample_count"])+ self.assertLessEqual(stats["trio_count"], stats["sample_count"])++ def test_the_row_matches_an_independent_count_over_the_asset(self) -> None:+ records = onekgpd_meta._load_records()+ expected = sum(1 for r in records if r["pop"] == "YRI")+ data = emitted(onekgpd_meta.cmd_population_stats, populations=["YRI"])+ self.assertEqual(data["populations"][0]["sample_count"], expected)++ def test_a_code_and_its_full_name_select_the_same_population(self) -> None:+ by_code = emitted(onekgpd_meta.cmd_population_stats, populations=["yri"])+ by_name = emitted(+ onekgpd_meta.cmd_population_stats,+ populations=["Yoruba in Ibadan, Nigeria"],+ )+ self.assertEqual(by_code, by_name)++ def test_several_populations_are_returned_ordered_by_code(self) -> None:+ data = emitted(+ onekgpd_meta.cmd_population_stats, populations=["YRI", "CHS", "GBR"]+ )+ self.assertEqual(+ [p["population_code"] for p in data["populations"]],+ ["CHS", "GBR", "YRI"],+ )++ def test_an_unrecognised_population_fails_before_any_aggregation(self) -> None:+ message = failure_message(+ onekgpd_meta.cmd_population_stats, populations=["YRI", "ZZZ"], output=None+ )+ self.assertIn("ZZZ", message)++ def test_superpopulation_totals_equal_the_sum_of_their_populations(self) -> None:+ data = emitted(+ onekgpd_meta.cmd_superpopulation_summary, superpopulations=["AFR"]+ )+ summary = data["superpopulations"][0]+ self.assertEqual(+ summary["sample_count"],+ sum(p["sample_count"] for p in summary["populations"]),+ )+ self.assertEqual(+ summary["trio_count"], sum(p["trio_count"] for p in summary["populations"])+ )++ def test_an_unrecognised_superpopulation_fails(self) -> None:+ message = failure_message(+ onekgpd_meta.cmd_superpopulation_summary,+ superpopulations=["Atlantis"],+ output=None,+ )+ self.assertIn("Atlantis", message)+++class SelectSamplesByPopulationTests(unittest.TestCase):+ def defaults(self, **overrides) -> dict:+ arguments = {+ "population": None,+ "superpopulation": None,+ "skip": None,+ "limit": None,+ }+ arguments.update(overrides)+ return arguments++ def test_the_page_is_sorted_and_capped_by_limit(self) -> None:+ data = emitted(+ onekgpd_meta.cmd_select_samples_by_population,+ **self.defaults(population="YRI", limit=5),+ )+ self.assertEqual(len(data["samples"]), 5)+ self.assertEqual(data["samples"], sorted(data["samples"]))++ def test_skip_advances_the_window_without_dropping_rows(self) -> None:+ first = emitted(+ onekgpd_meta.cmd_select_samples_by_population,+ **self.defaults(population="YRI", limit=6),+ )["samples"]+ shifted = emitted(+ onekgpd_meta.cmd_select_samples_by_population,+ **self.defaults(population="YRI", skip=2, limit=4),+ )["samples"]+ self.assertEqual(shifted, first[2:6])++ def test_the_default_page_is_fifty_rows(self) -> None:+ data = emitted(+ onekgpd_meta.cmd_select_samples_by_population,+ **self.defaults(population="YRI"),+ )+ self.assertEqual(len(data["samples"]), onekgpd_meta.DEFAULT_LIMIT)+ self.assertEqual(data["request"]["limit"], onekgpd_meta.DEFAULT_LIMIT)+ self.assertEqual(data["request"]["skip"], 0)++ def test_a_skip_past_the_end_returns_an_empty_page_not_an_error(self) -> None:+ data = emitted(+ onekgpd_meta.cmd_select_samples_by_population,+ **self.defaults(population="YRI", skip=COHORT_SIZE),+ )+ self.assertEqual(data["samples"], [])+ self.assertEqual(data["count"], 0)++ def test_population_and_superpopulation_are_combined_with_and(self) -> None:+ # YRI is African, so pairing it with EUR must match nobody -- an OR+ # would return the whole of Europe.+ data = emitted(+ onekgpd_meta.cmd_select_samples_by_population,+ **self.defaults(population="YRI", superpopulation="EUR"),+ )+ self.assertEqual(data["samples"], [])++ agreeing = emitted(+ onekgpd_meta.cmd_select_samples_by_population,+ **self.defaults(population="YRI", superpopulation="AFR", limit=3),+ )+ self.assertEqual(len(agreeing["samples"]), 3)++ def test_a_superpopulation_alone_selects_across_its_populations(self) -> None:+ data = emitted(+ onekgpd_meta.cmd_select_samples_by_population,+ **self.defaults(superpopulation="AFR", limit=10),+ )+ self.assertEqual(len(data["samples"]), 10)++ def test_neither_selector_is_refused(self) -> None:+ message = failure_message(+ onekgpd_meta.cmd_select_samples_by_population,+ **self.defaults(output=None),+ )+ self.assertIn("At least one parameter", message)++ def test_the_limit_bounds_are_enforced_at_both_ends(self) -> None:+ for limit in (0, onekgpd_meta.MAX_LIMIT + 1):+ with self.subTest(limit=limit):+ message = failure_message(+ onekgpd_meta.cmd_select_samples_by_population,+ **self.defaults(population="YRI", limit=limit, output=None),+ )+ self.assertIn("must be between 1", message)+ # The extremes themselves are valid.+ for limit in (1, onekgpd_meta.MAX_LIMIT):+ with self.subTest(limit=limit):+ data = emitted(+ onekgpd_meta.cmd_select_samples_by_population,+ **self.defaults(population="YRI", limit=limit),+ )+ self.assertGreaterEqual(len(data["samples"]), 1)++ def test_a_negative_skip_is_refused(self) -> None:+ message = failure_message(+ onekgpd_meta.cmd_select_samples_by_population,+ **self.defaults(population="YRI", skip=-1, output=None),+ )+ self.assertIn("'skip' must be >= 0", message)++ def test_an_unrecognised_population_is_refused(self) -> None:+ message = failure_message(+ onekgpd_meta.cmd_select_samples_by_population,+ **self.defaults(population="Narnia", output=None),+ )+ self.assertIn("Narnia", message)+++class SharedHelperTests(unittest.TestCase):+ def test_csv_splitting_trims_and_drops_empty_tokens(self) -> None:+ self.assertEqual(+ onekgpd_meta._split_csv(" NA19240 ,, HG00096, "), ["NA19240", "HG00096"]+ )+ self.assertEqual(onekgpd_meta._split_csv(""), [])++ def test_json_is_written_to_the_requested_path(self) -> None:+ with tempfile.TemporaryDirectory() as directory:+ target = Path(directory) / "out.json"+ written = onekgpd_meta._save_json({"a": 1}, "prefix", str(target))+ self.assertEqual(Path(written), target)+ self.assertEqual(json.loads(target.read_text(encoding="utf-8")), {"a": 1})++ def test_without_a_path_a_temp_file_is_used_and_reported(self) -> None:+ buffer = io.StringIO()+ with redirect_stdout(buffer):+ onekgpd_meta._emit({"a": 1}, "prefix", ["summary line"], None)+ printed = buffer.getvalue()+ self.assertIn("summary line", printed)+ path = Path(printed.strip().splitlines()[-1].split("saved to ")[1])+ self.addCleanup(path.unlink)+ self.assertEqual(json.loads(path.read_text(encoding="utf-8")), {"a": 1})+++class MetaParserTests(unittest.TestCase):+ def test_a_subcommand_is_required(self) -> None:+ with self.assertRaises(SystemExit):+ with redirect_stderr(io.StringIO()):+ onekgpd_meta.build_parser().parse_args([])++ def test_every_subcommand_binds_a_handler(self) -> None:+ parser = onekgpd_meta.build_parser()+ for command in (+ ["list-populations"],+ ["list-superpopulations"],+ ["sample-metadata", "--samples", "NA19240"],+ ["population-stats", "--populations", "YRI"],+ ["superpopulation-summary", "--superpopulations", "AFR"],+ ["select-samples-by-population", "--population", "YRI"],+ ):+ with self.subTest(command=command[0]):+ arguments = parser.parse_args(command)+ self.assertTrue(callable(arguments.func))++ def test_repeated_population_flags_accumulate(self) -> None:+ # Full population names contain commas, so this flag repeats rather+ # than splitting on commas.+ arguments = onekgpd_meta.build_parser().parse_args(+ ["population-stats", "--populations", "YRI", "--populations", "CHS"]+ )+ self.assertEqual(arguments.populations, ["YRI", "CHS"])+++# ---------------------------------------------------------------------------+# onekgpd_api -- every network call replaced by a recorder+# ---------------------------------------------------------------------------+++def region_args(**overrides) -> Namespace:+ """The region/annotation flags every region command shares."""+ defaults = dict(+ command="count-variants",+ output=None,+ chrom=None, start=None, end=None, ref=None, alt=None, region=None,+ min_len_bp=None, max_len_bp=None,+ clin_significance=None, consequence=None, impact=None,+ variant_type=None, feature_type=None, bio_type=None,+ alpha_missense_class=None,+ af_lt=None, af_gt=None,+ gnomad_exomes_af_lt=None, gnomad_exomes_af_gt=None,+ gnomad_genomes_af_lt=None, gnomad_genomes_af_gt=None,+ alpha_missense_score_lt=None, alpha_missense_score_gt=None,+ biallelic_only=False, multiallelic_only=False,+ exclude_males=False, exclude_females=False,+ het_only=False, hom_only=False,+ )+ defaults.update(overrides)+ return Namespace(**defaults)+++class RecordingClient:+ """Stands in for `DnaerysClient`: records calls, returns canned results."""++ instances: list["RecordingClient"] = []++ def __init__(self, target=None, **kwargs) -> None:+ self.target = target+ self.calls: list[tuple[str, dict]] = []+ self.results: dict = {}+ RecordingClient.instances.append(self)++ def __enter__(self):+ return self++ def __exit__(self, *exception) -> bool:+ return False++ def __getattr__(self, name):+ if name.startswith("_"):+ raise AttributeError(name)++ def method(**kwargs):+ self.calls.append((name, kwargs))+ return RecordingClient.canned[name]++ return method+++def metadata(affected: bool = False):+ return dnaerys.ResponseMetadata(+ elapsed_ms=1, elapsed_db_ms=1, node_id="test", incomplete_cluster=False,+ affected=affected,+ )+++def variant(start: int = 43044295, **overrides):+ fields = dict(+ chr=dnaerys.Chromosome.CHR17, start=start, end=start, ref="G", alt="A",+ af=0.0125, ac=80, an=6404,+ hom_samples=1, het_samples=78, mis_samples=0,+ hom_samples_fx=1, het_samples_fx=40, mis_samples_fx=0,+ hom_samples_mxy=0, het_samples_mxy=38, mis_samples_mxy=0,+ gnomad_exomes_af=0.01, gnomad_genomes_af=0.011,+ cadd_raw=3.0, cadd_phred=22.0,+ am_score=0.8712, amino_acids="R/H", biallelic=True,+ )+ fields.update(overrides)+ return dnaerys.Variant(**fields)+++class Stream:+ def __init__(self, variants, affected: bool = False) -> None:+ self._variants = list(variants)+ self.metadata = metadata(affected)++ def to_list(self):+ return list(self._variants)+++class Pages:+ def __init__(self, pages, affected: bool = False) -> None:+ self._pages = list(pages)+ self.metadata = metadata(affected)++ def __iter__(self):+ return iter(self._pages)+++@needs_dnaerys+class RegionParsingTests(unittest.TestCase):+ def test_a_region_string_becomes_a_typed_region(self) -> None:+ # BRCA1 on GRCh38, 1-based inclusive.+ region = onekgpd_api._parse_region_str("chr17:43044295-43170245")+ self.assertEqual(region.chr, dnaerys.Chromosome.CHR17)+ self.assertEqual((region.start, region.end), (43044295, 43170245))++ def test_malformed_region_strings_name_the_expected_shape(self) -> None:+ for text in ("chr17", "chr17:43044295", "chr17-43044295", "chr17:a-b"):+ with self.subTest(text=text):+ with self.assertRaisesRegex(ValueError, "CHR:START-END"):+ onekgpd_api._parse_region_str(text)++ def test_coordinate_validation_is_left_to_the_library(self) -> None:+ # An inverted interval must not reach the service as a live query.+ with self.assertRaises(ValueError):+ onekgpd_api._parse_region_str("chr17:100-10")++ def test_a_single_region_carries_the_allele_narrowing(self) -> None:+ region, regions = onekgpd_api._build_regions(+ region_args(chrom="chr17", start=100, end=200, ref="G", alt="A")+ )+ self.assertIsNone(regions)+ self.assertEqual((region.ref, region.alt), ("G", "A"))++ def test_multiple_regions_are_parsed_in_order(self) -> None:+ region, regions = onekgpd_api._build_regions(+ region_args(region=["chr1:100-200", "chrX:1-2"])+ )+ self.assertIsNone(region)+ self.assertEqual(+ [r.chr for r in regions],+ [dnaerys.Chromosome.CHR1, dnaerys.Chromosome.CHRX],+ )++ def test_mixing_the_two_region_modes_is_refused(self) -> None:+ with self.assertRaisesRegex(ValueError, "not both"):+ onekgpd_api._build_regions(+ region_args(chrom="chr1", start=1, end=2, region=["chr2:1-2"])+ )++ def test_a_region_is_mandatory(self) -> None:+ with self.assertRaisesRegex(ValueError, "region is required"):+ onekgpd_api._build_regions(region_args())++ def test_an_incomplete_single_region_is_refused(self) -> None:+ for missing in ({"start": 1}, {"end": 2}, {}):+ with self.subTest(**missing):+ with self.assertRaisesRegex(ValueError, "requires --start and --end"):+ onekgpd_api._build_regions(region_args(chrom="chr1", **missing))++ def test_allele_narrowing_cannot_apply_to_many_regions(self) -> None:+ # One ref/alt pair cannot be meaningful across several intervals.+ with self.assertRaisesRegex(ValueError, "only to a single"):+ onekgpd_api._build_regions(region_args(region=["chr1:1-2"], ref="G"))+++@needs_dnaerys+class ZygosityTests(unittest.TestCase):+ def test_both_zygosities_are_included_by_default(self) -> None:+ # Defaulting to one of them would silently halve every carrier count.+ self.assertEqual(onekgpd_api._zygosity(region_args()), (True, True))++ def test_each_flag_narrows_to_its_own_zygosity(self) -> None:+ self.assertEqual(+ onekgpd_api._zygosity(region_args(het_only=True)), (False, True)+ )+ self.assertEqual(+ onekgpd_api._zygosity(region_args(hom_only=True)), (True, False)+ )++ def test_the_label_names_what_was_queried(self) -> None:+ self.assertEqual(onekgpd_api._zyg_label(True, True), "hom+het")+ self.assertEqual(onekgpd_api._zyg_label(False, True), "het only")+ self.assertEqual(onekgpd_api._zyg_label(True, False), "hom only")+++@needs_dnaerys+class AnnotationFilterTests(unittest.TestCase):+ def test_no_flags_means_no_filter_at_all(self) -> None:+ # An empty AnnotationFilter is not the same as None; sending one would+ # change the query semantics for an unfiltered run.+ self.assertIsNone(onekgpd_api._build_annotation_filter(region_args()))++ def test_csv_terms_become_a_tuple_of_library_enums(self) -> None:+ built = onekgpd_api._build_annotation_filter(+ region_args(consequence="MISSENSE_VARIANT,STOP_GAINED")+ )+ self.assertEqual(+ built.consequence,+ (dnaerys.Consequence.MISSENSE_VARIANT, dnaerys.Consequence.STOP_GAINED),+ )++ def test_whitespace_in_a_csv_term_list_is_tolerated(self) -> None:+ built = onekgpd_api._build_annotation_filter(+ region_args(impact="HIGH , MODERATE")+ )+ self.assertEqual(+ built.impact, (dnaerys.Impact.HIGH, dnaerys.Impact.MODERATE)+ )++ def test_an_unknown_vocabulary_term_is_rejected(self) -> None:+ with self.assertRaisesRegex(ValueError, "MISSENSE_VARIANTS"):+ onekgpd_api._build_annotation_filter(+ region_args(consequence="MISSENSE_VARIANTS")+ )++ def test_numeric_thresholds_pass_through_including_zero(self) -> None:+ # af_lt=0 is falsy; a truthiness test would drop it.+ built = onekgpd_api._build_annotation_filter(+ region_args(af_lt=0.0, gnomad_exomes_af_gt=0.25)+ )+ self.assertEqual(built.af_lt, 0.0)+ self.assertEqual(built.gnomad_exomes_af_gt, 0.25)++ def test_boolean_flags_are_only_set_when_asked(self) -> None:+ default = onekgpd_api._build_annotation_filter(region_args(af_lt=0.1))+ self.assertFalse(default.biallelic_only)+ self.assertFalse(default.exclude_males)+ asked = onekgpd_api._build_annotation_filter(+ region_args(biallelic_only=True, exclude_females=True)+ )+ self.assertTrue(asked.biallelic_only)+ self.assertTrue(asked.exclude_females)++ def test_an_alphamissense_class_and_score_together_are_refused(self) -> None:+ # The class is derived from the score, so combining them is a+ # contradiction argparse cannot express as one group.+ with self.assertRaises(SystemExit):+ with redirect_stdout(io.StringIO()), redirect_stderr(io.StringIO()):+ onekgpd_api._build_annotation_filter(+ region_args(+ alpha_missense_class="AM_LIKELY_PATHOGENIC",+ alpha_missense_score_gt=0.9,+ )+ )++ def test_either_alphamissense_selector_alone_is_accepted(self) -> None:+ by_class = onekgpd_api._build_annotation_filter(+ region_args(alpha_missense_class="AM_LIKELY_PATHOGENIC")+ )+ self.assertEqual(+ by_class.am_class, (dnaerys.AlphaMissense.AM_LIKELY_PATHOGENIC,)+ )+ by_score = onekgpd_api._build_annotation_filter(+ region_args(alpha_missense_score_gt=0.9)+ )+ self.assertEqual(by_score.am_score_gt, 0.9)+ self.assertEqual(by_score.am_class, ())++ def test_length_bounds_are_not_annotation_filter_fields(self) -> None:+ # They are client-method kwargs; putting them in the filter would raise.+ self.assertIsNone(+ onekgpd_api._build_annotation_filter(+ region_args(min_len_bp=1, max_len_bp=50)+ )+ )+++@needs_dnaerys+class LabelAndEchoTests(unittest.TestCase):+ def test_chromosome_enums_render_as_their_conventional_names(self) -> None:+ for member, expected in (+ (dnaerys.Chromosome.CHR17, "chr17"),+ (dnaerys.Chromosome.CHRX, "chrX"),+ (dnaerys.Chromosome.CHRMT, "chrMT"),+ ):+ with self.subTest(member=member):+ self.assertEqual(onekgpd_api._chr_to_str(member), expected)++ def test_a_region_label_round_trips_the_parsed_string(self) -> None:+ text = "chr17:43044295-43170245"+ self.assertEqual(+ onekgpd_api._region_one_label(onekgpd_api._parse_region_str(text)), text+ )++ def test_many_regions_are_labelled_as_a_list(self) -> None:+ regions = [+ onekgpd_api._parse_region_str("chr1:1-2"),+ onekgpd_api._parse_region_str("chrX:5-6"),+ ]+ self.assertEqual(+ onekgpd_api._region_label(None, regions), "chr1:1-2, chrX:5-6"+ )++ def test_the_filter_echo_reports_only_what_was_set(self) -> None:+ echo = onekgpd_api._filters_echo(+ region_args(af_lt=0.01, consequence="MISSENSE_VARIANT", min_len_bp=2)+ )+ self.assertEqual(+ echo,+ {+ "af_lt": 0.01,+ "consequence": ["MISSENSE_VARIANT"],+ "variant_min_length": 2,+ },+ )++ def test_an_unfiltered_request_echoes_no_filter_block(self) -> None:+ echo = onekgpd_api._request_echo(+ region_args(),+ samples=None,+ region=onekgpd_api._parse_region_str("chr1:1-2"),+ regions=None,+ hom=True,+ het=True,+ )+ self.assertEqual(echo, {"region": "chr1:1-2", "zygosity": "hom+het"})++ def test_the_request_echo_records_alleles_and_samples(self) -> None:+ region, _ = onekgpd_api._build_regions(+ region_args(chrom="chr17", start=100, end=200, ref="G", alt="A")+ )+ echo = onekgpd_api._request_echo(+ region_args(), samples=["NA19240"], region=region, regions=None,+ hom=False, het=True,+ )+ self.assertEqual(echo["ref"], "G")+ self.assertEqual(echo["alt"], "A")+ self.assertEqual(echo["samples"], ["NA19240"])+ self.assertEqual(echo["zygosity"], "het only")++ def test_a_variant_serialises_to_json_safe_keys(self) -> None:+ record = onekgpd_api._variant_to_dict(variant())+ self.assertEqual(record["chr"], "chr17") # enum rendered as text+ self.assertEqual(record["ref"], "G")+ self.assertEqual(record["am_score"], 0.8712)+ self.assertEqual(record["an"], 6404) # 3,202 individuals x 2 alleles+ json.dumps(record, allow_nan=False)+++@needs_dnaerys+class RetryTests(unittest.TestCase):+ def test_a_successful_call_is_made_exactly_once(self) -> None:+ calls = []++ def fetch():+ calls.append(1)+ return "result"++ self.assertEqual(onekgpd_api._call_with_retry(fetch), "result")+ self.assertEqual(len(calls), 1)++ def test_a_retryable_error_is_retried_up_to_the_bound_then_raised(self) -> None:+ calls = []++ def fetch():+ calls.append(1)+ raise dnaerys.DnaerysConnectionError("endpoint unreachable")++ with patch.object(onekgpd_api.time, "sleep") as sleep:+ with self.assertRaises(dnaerys.DnaerysConnectionError):+ onekgpd_api._call_with_retry(fetch)+ self.assertEqual(len(calls), onekgpd_api.MAX_RETRIES)+ # Backoff doubles: 1s then 2s, and no sleep after the final failure.+ self.assertEqual(+ [call.args[0] for call in sleep.call_args_list],+ [onekgpd_api.RETRY_BASE_DELAY, onekgpd_api.RETRY_BASE_DELAY * 2],+ )++ def test_a_non_retryable_error_is_raised_without_a_second_attempt(self) -> None:+ # Retrying a rejected request just multiplies the load.+ calls = []++ def fetch():+ calls.append(1)+ raise dnaerys.DnaerysInvalidRequestError("bad region")++ with patch.object(onekgpd_api.time, "sleep") as sleep:+ with self.assertRaises(dnaerys.DnaerysInvalidRequestError):+ onekgpd_api._call_with_retry(fetch)+ self.assertEqual(len(calls), 1)+ sleep.assert_not_called()++ def test_a_call_that_recovers_returns_the_later_result(self) -> None:+ attempts = []++ def fetch():+ attempts.append(1)+ if len(attempts) == 1:+ raise dnaerys.DnaerysConnectionError("transient")+ return "recovered"++ with patch.object(onekgpd_api.time, "sleep"):+ self.assertEqual(onekgpd_api._call_with_retry(fetch), "recovered")+ self.assertEqual(len(attempts), 2)+++@needs_dnaerys+class ApiCommandTestCase(unittest.TestCase):+ """Each test replaces DnaerysClient, so no test opens a connection."""++ def setUp(self) -> None:+ RecordingClient.instances = []+ RecordingClient.canned = {}+ patcher = patch.object(onekgpd_api, "DnaerysClient", RecordingClient)+ patcher.start()+ self.addCleanup(patcher.stop)++ @property+ def client(self) -> RecordingClient:+ self.assertEqual(len(RecordingClient.instances), 1)+ return RecordingClient.instances[0]++ def sent(self, method: str) -> dict:+ calls = [kwargs for name, kwargs in self.client.calls if name == method]+ self.assertEqual(len(calls), 1, f"{method} was called {len(calls)} times")+ return calls[0]+++class CountCommandTests(ApiCommandTestCase):+ def test_the_request_carries_the_region_zygosity_and_filter(self) -> None:+ RecordingClient.canned["count_variants"] = dnaerys.CountResult(+ count=1234, metadata=metadata()+ )+ data = emitted(+ onekgpd_api.cmd_count_variants,+ **vars(+ region_args(+ chrom="chr17", start=43044295, end=43170245,+ consequence="MISSENSE_VARIANT", het_only=True,+ min_len_bp=1, max_len_bp=50,+ )+ ),+ )+ request = self.sent("count_variants")+ self.assertEqual(request["region"].chr, dnaerys.Chromosome.CHR17)+ self.assertEqual(request["region"].start, 43044295)+ self.assertIsNone(request["regions"])+ self.assertIsNone(request["samples"])+ self.assertEqual((request["hom"], request["het"]), (False, True))+ self.assertEqual(+ request["annotations"].consequence,+ (dnaerys.Consequence.MISSENSE_VARIANT,),+ )+ self.assertEqual(request["variant_min_length"], 1)+ self.assertEqual(request["variant_max_length"], 50)++ self.assertEqual(data["count"], 1234)+ self.assertEqual(data["request"]["region"], "chr17:43044295-43170245")+ self.assertEqual(data["request"]["zygosity"], "het only")+ self.assertFalse(data["result_incomplete"])++ def test_the_public_1000_genomes_endpoint_is_the_one_contacted(self) -> None:+ RecordingClient.canned["count_variants"] = dnaerys.CountResult(+ count=0, metadata=metadata()+ )+ emitted(+ onekgpd_api.cmd_count_variants,+ **vars(region_args(chrom="chr1", start=1, end=2)),+ )+ self.assertEqual(self.client.target, onekgpd_api.DEFAULT_ENDPOINT)+ self.assertEqual(onekgpd_api.DEFAULT_ENDPOINT, "db.dnaerys.org:443")++ def test_named_individuals_are_split_from_the_csv_flag(self) -> None:+ RecordingClient.canned["count_variants"] = dnaerys.CountResult(+ count=7, metadata=metadata()+ )+ emitted(+ onekgpd_api.cmd_count_variants_in_samples,+ **vars(+ region_args(+ command="count-variants-in-samples",+ chrom="chr1", start=1, end=2,+ samples="NA19240, NA19238 ,",+ )+ ),+ )+ self.assertEqual(self.sent("count_variants")["samples"], ["NA19240", "NA19238"])++ def test_an_incomplete_cluster_result_is_flagged_in_the_json(self) -> None:+ # A partial answer that looks complete is the dangerous failure here.+ RecordingClient.canned["count_variants"] = dnaerys.CountResult(+ count=5, metadata=metadata(affected=True)+ )+ data = emitted(+ onekgpd_api.cmd_count_variants,+ **vars(region_args(chrom="chr1", start=1, end=2)),+ )+ self.assertTrue(data["result_incomplete"])++ def test_counting_individuals_never_passes_a_sample_list(self) -> None:+ RecordingClient.canned["count_samples"] = dnaerys.CountResult(+ count=42, metadata=metadata()+ )+ data = emitted(+ onekgpd_api.cmd_count_samples,+ **vars(region_args(command="count-samples", chrom="chr1", start=1, end=2)),+ )+ self.assertNotIn("samples", self.sent("count_samples"))+ self.assertEqual(data["count"], 42)+++class SelectVariantsCommandTests(ApiCommandTestCase):+ def base(self, **overrides) -> dict:+ arguments = vars(+ region_args(+ command="select-variants",+ chrom="chr17", start=43044295, end=43170245,+ )+ )+ arguments["limit"] = onekgpd_api.DEFAULT_VARIANT_LIMIT+ arguments["page_size"] = None+ arguments.update(overrides)+ return arguments++ def test_variants_are_returned_with_the_default_limit_applied(self) -> None:+ RecordingClient.canned["select_variants"] = Stream([variant(), variant(43044296)])+ data = emitted(onekgpd_api.cmd_select_variants, **self.base())+ self.assertEqual(self.sent("select_variants")["limit"], 200)+ self.assertEqual(onekgpd_api.DEFAULT_VARIANT_LIMIT, 200)+ self.assertEqual(data["count_returned"], 2)+ self.assertEqual(data["request"]["limit"], 200)+ self.assertNotIn("page_size", data["request"])+ self.assertEqual([v["start"] for v in data["variants"]], [43044295, 43044296])++ def test_hitting_the_limit_marks_the_result_as_truncated(self) -> None:+ # Silently returning a capped list would understate every carrier.+ RecordingClient.canned["select_variants"] = Stream(+ [variant(43044295 + i) for i in range(3)]+ )+ data = emitted(onekgpd_api.cmd_select_variants, **self.base(limit=3))+ self.assertTrue(data["truncated"])++ def test_a_result_below_the_limit_is_not_truncated(self) -> None:+ RecordingClient.canned["select_variants"] = Stream([variant()])+ data = emitted(onekgpd_api.cmd_select_variants, **self.base(limit=3))+ self.assertFalse(data["truncated"])++ def test_an_empty_result_is_reported_as_zero_not_as_an_error(self) -> None:+ RecordingClient.canned["select_variants"] = Stream([])+ data = emitted(onekgpd_api.cmd_select_variants, **self.base())+ self.assertEqual(data["count_returned"], 0)+ self.assertEqual(data["variants"], [])+ self.assertFalse(data["truncated"])++ def test_paging_walks_every_page_and_cannot_truncate(self) -> None:+ RecordingClient.canned["paginate_variants"] = Pages(+ [+ Namespace(variants=[variant(1), variant(2)]),+ Namespace(variants=[variant(3)]),+ ]+ )+ data = emitted(onekgpd_api.cmd_select_variants, **self.base(page_size=2))+ self.assertEqual(self.sent("paginate_variants")["page_size"], 2)+ self.assertEqual(data["count_returned"], 3)+ self.assertFalse(data["truncated"])+ self.assertEqual(data["request"]["page_size"], 2)+ self.assertNotIn("limit", data["request"])++ def test_selecting_within_individuals_forwards_the_sample_list(self) -> None:+ RecordingClient.canned["select_variants"] = Stream([variant()])+ emitted(+ onekgpd_api.cmd_select_variants_in_samples,+ **self.base(command="select-variants-in-samples", samples="NA19240"),+ )+ self.assertEqual(self.sent("select_variants")["samples"], ["NA19240"])+++class SelectSamplesCommandTests(ApiCommandTestCase):+ def test_paging_arguments_reach_the_service_and_the_echo(self) -> None:+ RecordingClient.canned["select_samples"] = dnaerys.SamplesResult(+ samples=("NA19238", "NA19240"), metadata=metadata()+ )+ data = emitted(+ onekgpd_api.cmd_select_samples,+ **vars(+ region_args(command="select-samples", chrom="chr1", start=1, end=2)+ ),+ skip=10,+ limit=2,+ )+ request = self.sent("select_samples")+ self.assertEqual((request["skip"], request["limit"]), (10, 2))+ self.assertEqual(data["count"], 2)+ self.assertEqual(data["samples"], ["NA19238", "NA19240"])+ self.assertEqual(data["request"]["skip"], 10)++ def test_unset_paging_is_omitted_from_the_echo(self) -> None:+ RecordingClient.canned["select_samples"] = dnaerys.SamplesResult(+ samples=(), metadata=metadata()+ )+ data = emitted(+ onekgpd_api.cmd_select_samples,+ **vars(+ region_args(command="select-samples", chrom="chr1", start=1, end=2)+ ),+ skip=None,+ limit=None,+ )+ self.assertNotIn("skip", data["request"])+ self.assertNotIn("limit", data["request"])+ self.assertEqual(data["samples"], [])+++class HomozygousReferenceTests(ApiCommandTestCase):+ def arguments(self) -> dict:+ return {+ "command": "count-samples-hom-ref",+ "chrom": "chr17",+ "position": 43044295,+ "output": None,+ }++ def test_a_real_count_is_reported_as_a_count(self) -> None:+ RecordingClient.canned["count_samples_hom_ref"] = dnaerys.CountResult(+ count=3100, metadata=metadata()+ )+ data = emitted(onekgpd_api.cmd_count_samples_hom_ref, **self.arguments())+ self.assertEqual(data["count"], 3100)+ self.assertTrue(data["variant_present"])+ self.assertEqual(+ self.sent("count_samples_hom_ref"),+ {"chr": "chr17", "position": 43044295},+ )++ def test_minus_one_means_no_variant_here_not_a_negative_count(self) -> None:+ # The service uses -1 as a sentinel; reporting it as a count would be+ # nonsense, and reporting 0 would wrongly imply everyone carries it.+ RecordingClient.canned["count_samples_hom_ref"] = dnaerys.CountResult(+ count=-1, metadata=metadata()+ )+ buffer = io.StringIO()+ with tempfile.TemporaryDirectory() as directory:+ output = str(Path(directory) / "out.json")+ with redirect_stdout(buffer):+ onekgpd_api.cmd_count_samples_hom_ref(+ Namespace(**{**self.arguments(), "output": output})+ )+ data = json.loads(Path(output).read_text(encoding="utf-8"))+ self.assertFalse(data["variant_present"])+ self.assertEqual(data["count"], -1)+ self.assertIn("No variant exists", buffer.getvalue())++ def test_zero_means_the_variant_exists_but_nobody_is_hom_ref(self) -> None:+ RecordingClient.canned["count_samples_hom_ref"] = dnaerys.CountResult(+ count=0, metadata=metadata()+ )+ buffer = io.StringIO()+ with tempfile.TemporaryDirectory() as directory:+ output = str(Path(directory) / "out.json")+ with redirect_stdout(buffer):+ onekgpd_api.cmd_count_samples_hom_ref(+ Namespace(**{**self.arguments(), "output": output})+ )+ data = json.loads(Path(output).read_text(encoding="utf-8"))+ self.assertTrue(data["variant_present"])+ self.assertIn("no individual is homozygous reference", buffer.getvalue())++ def test_listing_hom_ref_individuals_echoes_the_position(self) -> None:+ RecordingClient.canned["select_samples_hom_ref"] = dnaerys.SamplesResult(+ samples=("HG00096",), metadata=metadata()+ )+ data = emitted(+ onekgpd_api.cmd_select_samples_hom_ref,+ command="select-samples-hom-ref",+ chrom="chrX",+ position=100,+ )+ self.assertEqual(data["samples"], ["HG00096"])+ self.assertEqual(data["request"], {"chrom": "chrX", "position": 100})+++class KinshipCommandTests(ApiCommandTestCase):+ def test_a_pair_is_reported_with_its_degree_and_coefficient(self) -> None:+ # NA19238 x NA19240 are mother and daughter: a first-degree pair with+ # an expected KING coefficient near 0.25.+ RecordingClient.canned["kinship_duo"] = dnaerys.KinshipResult(+ pairs=(+ dnaerys.Relatedness(+ sample1="NA19238",+ sample2="NA19240",+ degree=dnaerys.KinshipDegree.FIRST_DEGREE,+ phi_bwf=0.2493,+ ),+ ),+ metadata=metadata(),+ )+ data = emitted(+ onekgpd_api.cmd_kinship,+ command="kinship",+ sample1="NA19238",+ sample2="NA19240",+ )+ self.assertEqual(+ self.sent("kinship_duo"), {"sample1": "NA19238", "sample2": "NA19240"}+ )+ self.assertEqual(data["degree"], "FIRST_DEGREE")+ self.assertAlmostEqual(data["phi_bwf"], 0.2493)++ def test_an_empty_pair_list_fails_rather_than_reporting_nothing(self) -> None:+ RecordingClient.canned["kinship_duo"] = dnaerys.KinshipResult(+ pairs=(), metadata=metadata()+ )+ message = failure_message(+ onekgpd_api.cmd_kinship,+ command="kinship",+ sample1="NA19238",+ sample2="NOBODY",+ output=None,+ )+ self.assertIn("no relatedness result", message)+++class DatasetInfoTests(ApiCommandTestCase):+ def test_the_totals_and_cohorts_are_echoed_verbatim(self) -> None:+ RecordingClient.canned["dataset_info"] = dnaerys.DatasetInfo(+ cohorts=(+ dnaerys.Cohort(+ cohort_name="1000 Genomes",+ samples_count=COHORT_SIZE,+ female_count=1604,+ male_count=1598,+ female_sample_names=(),+ male_sample_names=(),+ synthetic=False,+ ),+ ),+ samples_total=COHORT_SIZE,+ females_total=1604,+ males_total=1598,+ variants_total=125_000_000,+ assembly=dnaerys.RefAssembly.GRCh38,+ rto=False,+ prs=(),+ timestamp="2026-01-01",+ data_format=1,+ notes="",+ rings_total=1,+ elapsed_ms=1,+ node_id="test",+ )+ data = emitted(onekgpd_api.cmd_dataset_info, command="dataset-info")+ self.assertEqual(data["samples_total"], COHORT_SIZE)+ self.assertEqual(data["females_total"] + data["males_total"], COHORT_SIZE)+ self.assertEqual(data["assembly"], "GRCh38")+ self.assertEqual(data["cohorts"][0]["samples_count"], COHORT_SIZE)+ self.assertFalse(data["cohorts"][0]["synthetic"])+++@needs_dnaerys+class ApiMainTests(unittest.TestCase):+ def test_an_invalid_region_exits_one_with_a_message(self) -> None:+ # ValueError from the input builders must never reach the user as a+ # traceback, and must never reach the service as a query.+ errors = io.StringIO()+ with redirect_stderr(errors), redirect_stdout(io.StringIO()):+ with self.assertRaises(SystemExit) as raised:+ onekgpd_api.main(["count-variants", "--chrom", "chr17"])+ self.assertEqual(raised.exception.code, 1)+ self.assertIn("--start and --end", errors.getvalue())++ def test_a_subcommand_is_required(self) -> None:+ with redirect_stderr(io.StringIO()):+ with self.assertRaises(SystemExit):+ onekgpd_api.main([])++ def test_the_documented_subcommands_all_parse(self) -> None:+ parser = onekgpd_api.build_parser()+ for command in (+ ["dataset-info"],+ ["count-variants", "--region", "chr1:1-2"],+ ["select-variants", "--region", "chr1:1-2"],+ ["count-variants-in-samples", "--region", "chr1:1-2", "--samples", "x"],+ ["select-variants-in-samples", "--region", "chr1:1-2", "--samples", "x"],+ ["count-samples", "--region", "chr1:1-2"],+ ["select-samples", "--region", "chr1:1-2"],+ ["count-samples-hom-ref", "--chrom", "chr1", "--position", "5"],+ ["select-samples-hom-ref", "--chrom", "chr1", "--position", "5"],+ ["kinship", "--sample1", "a", "--sample2", "b"],+ ):+ with self.subTest(command=command[0]):+ self.assertTrue(callable(parser.parse_args(command).func))++ def test_limit_and_page_size_are_mutually_exclusive(self) -> None:+ # Both together would mean "cap the walk" and "walk everything".+ with redirect_stderr(io.StringIO()):+ with self.assertRaises(SystemExit):+ onekgpd_api.build_parser().parse_args(+ ["select-variants", "--region", "chr1:1-2",+ "--limit", "10", "--page-size", "10"]+ )++ def test_the_zygosity_flags_are_mutually_exclusive(self) -> None:+ with redirect_stderr(io.StringIO()):+ with self.assertRaises(SystemExit):+ onekgpd_api.build_parser().parse_args(+ ["count-variants", "--region", "chr1:1-2",+ "--het-only", "--hom-only"]+ )+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/ontology-term-resolution/test_scripts.py b/tests/ontology-term-resolution/test_scripts.pyindex b36c6b84..e3812dd0 100644--- a/tests/ontology-term-resolution/test_scripts.py+++ b/tests/ontology-term-resolution/test_scripts.py@@ -20,6 +20,8 @@ from contextlib import redirect_stdoutfrom pathlib import Pathfrom unittest.mock import patch+import skill_contract+SKILL_ROOT = Path(__file__).resolve().parents[2] / "skills" / "ontology-term-resolution"SCRIPTS_DIR = SKILL_ROOT / "scripts"LIVE = os.environ.get("OLS_LIVE_TESTS") == "1"@@ -477,5 +479,10 @@ class LiveApiTests(unittest.TestCase):self.assertIsNone(ols_client.term_detail("UBERON:9999999"))+# 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(SKILL_ROOT)+if __name__ == "__main__":unittest.main()diff --git a/tests/openpiv/test_scripts.py b/tests/openpiv/test_scripts.pynew file mode 100644index 00000000..054f342b--- /dev/null+++ b/tests/openpiv/test_scripts.py@@ -0,0 +1,493 @@+"""Tests for the OpenPIV processing and post-processing scripts.++A PIV pipeline can be wired up wrongly and still produce a plausible-looking+vector field, so the substantive tests here are built on fields whose answer is+known before the code runs. `run_openpiv` is driven with synthetic particle+image pairs displaced by an exact integer number of pixels, and the recovered+vectors have to reproduce that displacement -- in magnitude, in direction, and+in the sign convention `transform_coordinates` imposes -- plus the documented+`dt` and pixels-per-unit scaling. `PIVAnalyzer`'s derivatives are checked against+analytic flows (solid-body rotation, pure shear, uniform extension) whose+vorticity and strain rate are textbook constants, which is also what pins the+axis orientation: the saved `y` decreases with the row index, so an unsigned+`np.gradient` would flip `du/dy` and report zero vorticity for a rotating flow.++The window-geometry guards are proved in both directions -- a legal combination+runs, an illegal one is refused before any image is read.+"""++from __future__ import annotations++import sys+import tempfile+import unittest+from pathlib import Path++import pytest++import skill_contract++SKILL_ROOT = Path(__file__).resolve().parents[2] / "skills" / "openpiv"+SCRIPTS = SKILL_ROOT / "scripts"+sys.path.insert(0, str(SCRIPTS))++np = pytest.importorskip("numpy", reason="openpiv skill needs numpy")+pytest.importorskip("openpiv", reason="openpiv skill needs openpiv")+matplotlib = pytest.importorskip("matplotlib", reason="openpiv skill needs matplotlib")+# runner.py selects Agg itself; set it here too so importing analyze's plotting+# path in this process can never try to open a window.+matplotlib.use("Agg")++import matplotlib.pyplot as plt # noqa: E402++import analyze # noqa: E402+import run_example # noqa: E402+import runner # noqa: E402++CliHelpTests = skill_contract.cli.help_test_case(SKILL_ROOT)++#: Synthetic image geometry. 160 px with a 32 px window and 16 px overlap steps+#: by 16, giving (160 - 32) / 16 + 1 = 9 vectors per axis.+IMAGE_SIZE = 160+WINDOW = 32+OVERLAP = 16+EXPECTED_GRID = 9+++def particle_image(rows: np.ndarray, columns: np.ndarray, dy: int, dx: int) -> np.ndarray:+ """A uint8 frame of 3x3 particles at (rows + dy, columns + dx)."""+ frame = np.zeros((IMAGE_SIZE, IMAGE_SIZE), dtype=np.float64)+ for row, column in zip(rows + dy, columns + dx):+ frame[row - 1 : row + 2, column - 1 : column + 2] += 200.0+ return np.clip(frame, 0, 255).astype(np.uint8)+++class DisplacementRecoveryTests(unittest.TestCase):+ """Whole-pipeline correctness: a known shift must come back out."""++ @classmethod+ def setUpClass(cls) -> None:+ # A fixed seed keeps the particle pattern -- and therefore the+ # correlation quality -- identical from run to run.+ generator = np.random.default_rng(20260727)+ margin = 12+ cls.rows = generator.integers(margin, IMAGE_SIZE - margin, 900)+ cls.columns = generator.integers(margin, IMAGE_SIZE - margin, 900)++ def setUp(self) -> None:+ self._temporary = tempfile.TemporaryDirectory()+ self.addCleanup(self._temporary.cleanup)+ self.addCleanup(plt.close, "all")+ self.root = Path(self._temporary.name)++ def pair(self, dy: int, dx: int) -> tuple[Path, Path]:+ import imageio.v3 as iio++ first = self.root / "a.png"+ second = self.root / "b.png"+ iio.imwrite(first, particle_image(self.rows, self.columns, 0, 0))+ iio.imwrite(second, particle_image(self.rows, self.columns, dy, dx))+ return first, second++ def field(self, dy: int, dx: int, **overrides) -> dict:+ first, second = self.pair(dy, dx)+ settings = dict(+ output_dir=str(self.root / "out"),+ window_size=WINDOW,+ overlap=OVERLAP,+ search_area=WINDOW,+ dt=1.0,+ scaling_factor=1.0,+ threshold=1.05,+ )+ settings.update(overrides)+ output = runner.run_openpiv(str(first), str(second), **settings)+ with np.load(output / "params.npz") as data:+ return {key: data[key] for key in ("x", "y", "u", "v", "flags")}++ def test_a_rightward_shift_is_recovered_as_a_positive_u(self) -> None:+ # Particles move exactly +4 px in x, so with dt = 1 s and 1 px per unit+ # every valid vector must read u = 4 and v = 0.+ field = self.field(dy=0, dx=4)+ valid = ~field["flags"]+ self.assertTrue(valid.any(), "the correlation flagged every vector as spurious")+ np.testing.assert_allclose(field["u"][valid], 4.0, atol=0.3)+ np.testing.assert_allclose(field["v"][valid], 0.0, atol=0.3)++ def test_a_leftward_shift_is_recovered_as_a_negative_u(self) -> None:+ field = self.field(dy=0, dx=-4)+ valid = ~field["flags"]+ np.testing.assert_allclose(field["u"][valid], -4.0, atol=0.3)++ def test_a_downward_shift_is_recovered_as_a_negative_v(self) -> None:+ # transform_coordinates() puts the field in a right-handed y-up frame,+ # so motion towards higher row indices -- down the image -- is negative+ # v. Getting this backwards mirrors every reported flow.+ field = self.field(dy=5, dx=0)+ valid = ~field["flags"]+ np.testing.assert_allclose(field["v"][valid], -5.0, atol=0.3)+ np.testing.assert_allclose(field["u"][valid], 0.0, atol=0.3)++ def test_identical_frames_recover_no_motion(self) -> None:+ field = self.field(dy=0, dx=0)+ valid = ~field["flags"]+ np.testing.assert_allclose(field["u"][valid], 0.0, atol=0.3)+ np.testing.assert_allclose(field["v"][valid], 0.0, atol=0.3)++ def test_the_grid_geometry_follows_the_window_and_overlap(self) -> None:+ field = self.field(dy=0, dx=4)+ self.assertEqual(field["u"].shape, (EXPECTED_GRID, EXPECTED_GRID))+ # First window centre is at window_size / 2, then one step of+ # window_size - overlap per vector.+ self.assertAlmostEqual(float(field["x"][0, 0]), WINDOW / 2)+ self.assertAlmostEqual(+ float(field["x"][0, -1]), WINDOW / 2 + (EXPECTED_GRID - 1) * OVERLAP+ )+ # y is the flipped axis: it runs downwards through the array.+ self.assertGreater(float(field["y"][0, 0]), float(field["y"][-1, 0]))++ def test_dt_converts_the_displacement_into_a_velocity(self) -> None:+ # 4 px over 0.5 s is 8 px/s.+ field = self.field(dy=0, dx=4, dt=0.5)+ np.testing.assert_allclose(field["u"][~field["flags"]], 8.0, atol=0.6)++ def test_the_scaling_factor_is_pixels_per_physical_unit(self) -> None:+ # 4 px at 2 px/mm is 2 mm/s, so u must be divided by the factor, not+ # multiplied by it.+ field = self.field(dy=0, dx=4, scaling_factor=2.0)+ np.testing.assert_allclose(field["u"][~field["flags"]], 2.0, atol=0.2)+ # The coordinates are rescaled too: the first centre is 16 px = 8 mm.+ self.assertAlmostEqual(float(field["x"][0, 0]), WINDOW / 2 / 2.0)++ def test_a_larger_search_area_still_recovers_the_shift(self) -> None:+ # search_area > window_size switches the correlation to "linear"; the+ # answer must not change.+ field = self.field(dy=0, dx=4, search_area=WINDOW + 6)+ np.testing.assert_allclose(field["u"][~field["flags"]], 4.0, atol=0.4)++ def test_every_documented_output_file_is_written(self) -> None:+ first, second = self.pair(0, 4)+ output = runner.run_openpiv(+ str(first),+ str(second),+ output_dir=str(self.root / "files"),+ window_size=WINDOW,+ overlap=OVERLAP,+ search_area=WINDOW,+ dt=1.0,+ scaling_factor=1.0,+ )+ for name in ("vectors.txt", "params.npz", "vector_field.png"):+ with self.subTest(name=name):+ self.assertTrue((output / name).is_file())++ def test_dropping_invalid_vectors_leaves_holes_where_they_were_flagged(self) -> None:+ # By default a flagged vector is replaced by the local mean, so the+ # field has no holes; --drop_invalid must NaN out exactly the flagged+ # positions and leave every other vector untouched.+ kept = self.field(dy=0, dx=4, output_dir=str(self.root / "kept"))+ flags = kept["flags"]+ self.assertTrue(flags.any(), "nothing was flagged, so the branch is untested")+ self.assertFalse(np.isnan(kept["u"]).any())++ dropped = self.field(+ dy=0, dx=4, output_dir=str(self.root / "dropped"), drop_invalid=True+ )+ np.testing.assert_array_equal(np.isnan(dropped["u"]), flags)+ np.testing.assert_array_equal(np.isnan(dropped["v"]), flags)+ np.testing.assert_allclose(dropped["u"][~flags], kept["u"][~flags])++ def test_a_uniform_translation_has_no_vorticity(self) -> None:+ # End to end: rigid translation carries no rotation, so the derived+ # vorticity must stay at the noise level rather than pick up a bias.+ first, second = self.pair(0, 4)+ output = runner.run_openpiv(+ str(first),+ str(second),+ output_dir=str(self.root / "vort"),+ window_size=WINDOW,+ overlap=OVERLAP,+ search_area=WINDOW,+ dt=1.0,+ scaling_factor=1.0,+ )+ analyzer = analyze.PIVAnalyzer(output / "params.npz")+ self.assertLess(float(np.nanmax(np.abs(analyzer.compute_vorticity()))), 0.05)+++class WindowGeometryTests(unittest.TestCase):+ """The window/overlap/search-area guards, before any image is touched."""++ def test_a_search_area_smaller_than_the_window_is_refused(self) -> None:+ with self.assertRaisesRegex(ValueError, r"search_area \(16\) must be >="):+ runner.run_openpiv("a.png", "b.png", window_size=32, search_area=16)++ def test_an_overlap_at_or_above_the_window_is_refused(self) -> None:+ # overlap == window_size would give a zero step and an infinite grid.+ for overlap in (32, 40):+ with self.subTest(overlap=overlap):+ with self.assertRaisesRegex(ValueError, "must be <"):+ runner.run_openpiv(+ "a.png", "b.png", window_size=32, overlap=overlap, search_area=32+ )++ def test_the_guards_fire_before_the_images_are_opened(self) -> None:+ # Both paths below do not exist; a FileNotFoundError instead of a+ # ValueError would mean the geometry check runs too late to be useful.+ with self.assertRaises(ValueError):+ runner.run_openpiv("no-such-a.png", "no-such-b.png", search_area=1)++ def test_the_shipped_defaults_satisfy_their_own_guards(self) -> None:+ # window 32 / overlap 12 / search 38 is a legal combination, so the+ # documented defaults must reach the image read rather than be refused.+ with tempfile.TemporaryDirectory() as directory:+ with self.assertRaises(FileNotFoundError):+ runner.run_openpiv(+ "no-such-a.png", "no-such-b.png", output_dir=directory+ )+++class CliArgumentTests(unittest.TestCase):+ def test_exactly_two_images_are_required(self) -> None:+ for images in ([], ["one.png"], ["a.png", "b.png", "c.png"]):+ with self.subTest(images=images):+ argv = ["runner.py"]+ for image in images:+ argv += ["--image", image]+ original = sys.argv+ sys.argv = argv+ try:+ with self.assertRaises(SystemExit) as raised:+ runner.main()+ finally:+ sys.argv = original+ self.assertEqual(raised.exception.code, 2)+++class AnalyzerFixtureCase(unittest.TestCase):+ """Base class only: builds a `params.npz` from arrays and loads it back.++ Ships no tests of its own, so pytest collects it once per real subclass.+ """++ def setUp(self) -> None:+ self._temporary = tempfile.TemporaryDirectory()+ self.addCleanup(self._temporary.cleanup)+ self.root = Path(self._temporary.name)+ self._written = 0++ def analyzer(+ self,+ u: np.ndarray,+ v: np.ndarray,+ x: np.ndarray,+ y: np.ndarray,+ flags: np.ndarray | None = None,+ ) -> analyze.PIVAnalyzer:+ self._written += 1+ path = self.root / f"params{self._written}.npz"+ np.savez(+ path,+ x=x,+ y=y,+ u=u,+ v=v,+ flags=np.zeros(u.shape, dtype=bool) if flags is None else flags,+ )+ return analyze.PIVAnalyzer(path)+++class GridSpacingTests(AnalyzerFixtureCase):+ def test_the_spacing_is_read_off_the_coordinates_not_assumed(self) -> None:+ x = np.tile(np.arange(5) * 2.5, (4, 1))+ y = np.tile((np.arange(4) * 1.5)[:, None], (1, 5))+ analyzer = self.analyzer(np.zeros((4, 5)), np.zeros((4, 5)), x, y)+ self.assertEqual(analyzer.grid_spacing, (2.5, 1.5))++ def test_the_spacing_is_positive_even_when_a_coordinate_runs_backwards(self) -> None:+ # runner.py writes y decreasing; the reported spacing is a magnitude.+ x = np.tile(np.arange(5) * 2.0, (4, 1))+ y = np.tile((np.arange(4)[::-1] * 3.0)[:, None], (1, 5))+ analyzer = self.analyzer(np.zeros((4, 5)), np.zeros((4, 5)), x, y)+ self.assertEqual(analyzer.grid_spacing, (2.0, 3.0))+ self.assertEqual(analyzer.axis_signs, (1.0, -1.0))++ def test_a_degenerate_axis_falls_back_to_one(self) -> None:+ # A single-column field has no spacing to infer; 1.0 keeps the+ # derivative per grid cell instead of dividing by zero.+ x = np.zeros((3, 1))+ y = np.array([[0.0], [2.0], [4.0]])+ analyzer = self.analyzer(np.zeros((3, 1)), np.zeros((3, 1)), x, y)+ self.assertEqual(analyzer.grid_spacing, (1.0, 2.0))+ self.assertEqual(analyzer.axis_signs, (1.0, 1.0))+++class AnalyticFlowTests(AnalyzerFixtureCase):+ """Vorticity and strain rate against flows with closed-form answers."""++ SIDE = 7+ STEP = 2.0++ def grid(self, descending_y: bool) -> tuple[np.ndarray, np.ndarray]:+ indices = np.arange(self.SIDE)+ x = np.tile(indices * self.STEP, (self.SIDE, 1))+ rows = indices[::-1] if descending_y else indices+ y = np.tile((rows * self.STEP)[:, None], (1, self.SIDE))+ return x, y++ def test_solid_body_rotation_has_vorticity_twice_the_rate(self) -> None:+ # u = -omega*y, v = omega*x is rigid rotation at omega; its vorticity+ # dv/dx - du/dy is exactly 2*omega everywhere, including at the edges,+ # because the field is linear and np.gradient is exact for linear data.+ omega = 0.5+ for descending_y in (True, False):+ with self.subTest(descending_y=descending_y):+ x, y = self.grid(descending_y)+ analyzer = self.analyzer(-omega * y, omega * x, x, y)+ np.testing.assert_allclose(+ analyzer.compute_vorticity(), 2 * omega, atol=1e-12+ )++ def test_rotation_carries_no_strain(self) -> None:+ omega = 0.5+ x, y = self.grid(descending_y=True)+ analyzer = self.analyzer(-omega * y, omega * x, x, y)+ exx, eyy, exy = analyzer.compute_strain()+ for name, component in (("exx", exx), ("eyy", eyy), ("exy", exy)):+ with self.subTest(component=name):+ np.testing.assert_allclose(component, 0.0, atol=1e-12)++ def test_pure_shear_splits_between_vorticity_and_shear_strain(self) -> None:+ # u = k*y, v = 0: dv/dx - du/dy = -k, and exy = 0.5*(du/dy + dv/dx) = k/2.+ rate = 0.4+ x, y = self.grid(descending_y=True)+ analyzer = self.analyzer(rate * y, np.zeros_like(y), x, y)+ np.testing.assert_allclose(analyzer.compute_vorticity(), -rate, atol=1e-12)+ exx, eyy, exy = analyzer.compute_strain()+ np.testing.assert_allclose(exy, rate / 2, atol=1e-12)+ np.testing.assert_allclose(exx, 0.0, atol=1e-12)+ np.testing.assert_allclose(eyy, 0.0, atol=1e-12)++ def test_incompressible_extension_gives_opposite_normal_strains(self) -> None:+ # u = a*x, v = -a*y is divergence free, so exx = a and eyy = -a.+ rate = 0.3+ x, y = self.grid(descending_y=True)+ analyzer = self.analyzer(rate * x, -rate * y, x, y)+ exx, eyy, exy = analyzer.compute_strain()+ np.testing.assert_allclose(exx, rate, atol=1e-12)+ np.testing.assert_allclose(eyy, -rate, atol=1e-12)+ np.testing.assert_allclose(exy, 0.0, atol=1e-12)+ np.testing.assert_allclose(exx + eyy, 0.0, atol=1e-12)++ def test_a_supplied_spacing_overrides_the_inferred_one(self) -> None:+ # The gradients are per unit length, so halving the assumed spacing+ # doubles every derivative.+ omega = 0.5+ x, y = self.grid(descending_y=True)+ analyzer = self.analyzer(-omega * y, omega * x, x, y)+ np.testing.assert_allclose(+ analyzer.compute_vorticity(dx=self.STEP / 2, dy=self.STEP / 2),+ 4 * omega,+ atol=1e-12,+ )++ def test_a_uniform_flow_has_neither_vorticity_nor_strain(self) -> None:+ x, y = self.grid(descending_y=True)+ analyzer = self.analyzer(np.full_like(x, 3.0), np.full_like(x, -2.0), x, y)+ np.testing.assert_allclose(analyzer.compute_vorticity(), 0.0, atol=1e-12)+ for component in analyzer.compute_strain():+ np.testing.assert_allclose(component, 0.0, atol=1e-12)+++class VelocityMagnitudeTests(AnalyzerFixtureCase):+ def test_the_magnitude_is_the_euclidean_norm(self) -> None:+ x = np.tile(np.arange(2) * 1.0, (1, 1))+ u = np.array([[3.0, -3.0]])+ v = np.array([[4.0, 4.0]])+ analyzer = self.analyzer(u, v, x, np.zeros_like(x))+ np.testing.assert_allclose(analyzer.get_velocity_magnitude(), [[5.0, 5.0]])+++class StatisticsTests(AnalyzerFixtureCase):+ def field(self, u: np.ndarray, v: np.ndarray) -> analyze.PIVAnalyzer:+ x = np.tile(np.arange(u.shape[1]) * 1.0, (u.shape[0], 1))+ y = np.tile((np.arange(u.shape[0]) * 1.0)[:, None], (1, u.shape[1]))+ return self.analyzer(u, v, x, y)++ def test_a_uniform_field_has_zero_fluctuation_and_zero_energy(self) -> None:+ stats = self.field(np.full((4, 4), 2.0), np.full((4, 4), -1.0)).compute_statistics()+ self.assertAlmostEqual(stats["u_mean"], 2.0)+ self.assertAlmostEqual(stats["v_mean"], -1.0)+ self.assertAlmostEqual(stats["rms_u"], 0.0)+ self.assertAlmostEqual(stats["rms_v"], 0.0)+ self.assertAlmostEqual(stats["tke"], 0.0)++ def test_the_rms_is_the_population_standard_deviation(self) -> None:+ # [-2, -2, 2, 2] has mean 0 and population variance 4, so sd = 2 exactly+ # -- the sample (n-1) convention would give 2.309 instead.+ u = np.array([[-2.0, -2.0, 2.0, 2.0]])+ stats = self.field(u, np.zeros_like(u)).compute_statistics()+ self.assertAlmostEqual(stats["u_mean"], 0.0)+ self.assertAlmostEqual(stats["rms_u"], 2.0)+ # tke = 0.5 * (rms_u^2 + rms_v^2) = 0.5 * 4 = 2.+ self.assertAlmostEqual(stats["tke"], 2.0)++ def test_subtracting_the_mean_makes_the_rms_offset_invariant(self) -> None:+ # The fluctuation statistics describe the spread, so adding a uniform+ # 100 to every vector must move only the means.+ u = np.array([[-2.0, -2.0, 2.0, 2.0]])+ base = self.field(u, np.zeros_like(u)).compute_statistics()+ shifted = self.field(u + 100.0, np.zeros_like(u)).compute_statistics()+ self.assertAlmostEqual(shifted["u_mean"], base["u_mean"] + 100.0)+ self.assertAlmostEqual(shifted["rms_u"], base["rms_u"])+ self.assertAlmostEqual(shifted["tke"], base["tke"])++ def test_holes_left_by_drop_invalid_are_ignored_not_propagated(self) -> None:+ # --drop_invalid writes NaN where a vector was rejected; the statistics+ # must describe the surviving vectors instead of returning NaN.+ u = np.array([[2.0, np.nan, 2.0, np.nan]])+ stats = self.field(u, np.zeros_like(u)).compute_statistics()+ self.assertAlmostEqual(stats["u_mean"], 2.0)+ self.assertAlmostEqual(stats["rms_u"], 0.0)+++class FlagsTests(AnalyzerFixtureCase):+ def test_flags_are_loaded_as_a_boolean_mask(self) -> None:+ # runner.py saves them as bool, but a float or int array from an older+ # run must still index correctly rather than be read as positions.+ u = np.arange(4.0).reshape(1, 4)+ x = np.tile(np.arange(4) * 1.0, (1, 1))+ analyzer = self.analyzer(+ u, np.zeros_like(u), x, np.zeros_like(x), flags=np.array([[0, 1, 0, 1]])+ )+ self.assertEqual(analyzer.flags.dtype, np.dtype(bool))+ np.testing.assert_array_equal(analyzer.u[~analyzer.flags], [0.0, 2.0])++ def test_the_quiver_plot_draws_only_the_valid_vectors(self) -> None:+ u = np.arange(4.0).reshape(1, 4)+ x = np.tile(np.arange(4) * 1.0, (1, 1))+ analyzer = self.analyzer(+ u, np.zeros_like(u), x, np.zeros_like(x), flags=np.array([[0, 1, 0, 1]])+ )+ self.addCleanup(plt.close, "all")+ target = self.root / "quiver.png"+ figure = analyzer.plot_vector_field(save_path=str(target))+ self.assertTrue(target.is_file())+ quivers = figure.axes[0].collections+ self.assertEqual(len(quivers), 1)+ self.assertEqual(len(quivers[0].get_offsets()), 2)+++class BundledExampleTests(unittest.TestCase):+ def test_the_example_pair_ships_inside_the_installed_openpiv(self) -> None:+ # run_example.py's whole premise is that no external data is needed, so+ # if upstream drops these files the script is broken.+ first, second = run_example.bundled_image_pair()+ self.assertTrue(first.is_file())+ self.assertTrue(second.is_file())+ self.assertEqual(first.name, "exp1_001_a.bmp")+ self.assertEqual(second.name, "exp1_001_b.bmp")+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/opentrons-integration/test_scripts.py b/tests/opentrons-integration/test_scripts.pynew file mode 100644index 00000000..f59f97f6--- /dev/null+++ b/tests/opentrons-integration/test_scripts.py@@ -0,0 +1,599 @@+"""Tests for the Opentrons protocol templates.++These scripts are not command-line tools: each is a Protocol API v2 file that the+Opentrons App loads, so the meaningful check is the one the App performs --+simulation. `opentrons.simulate.simulate()` runs each Flex template against the+virtual hardware in about a tenth of a second, and the resulting run log is+asserted against volumes and step counts derived by hand from the labware and+the documented method:++* 8 wells x 50 uL plus three 20 uL disposal volumes is 460 uL of buffer, in+ aspirations no larger than the 200 uL tips (runtime parameters);+* eleven 1:2 dilution steps need 1 + 11 + 1 tips and 23 aspirations of 100 uL+ (serial dilution);+* eight 25 uL reactions need one 170 uL master-mix aspiration (8 x 20 + 10 uL+ disposal) and 35 cycles (PCR).++A template that silently changes its volume budget, reuses the master-mix tube as+a template source, or exceeds a tip's capacity fails those assertions.++The OT-2 template cannot be simulated by the Flex-line package: opentrons 9.1+rejects OT-2 protocols outright, which `SKILL.md` documents and one test pins.+Its robot-specific declarations -- numeric deck slots, GEN2 pipettes, no+`load_trash_bin()` for the fixed slot-12 trash -- are checked by parsing the+source instead.++No `--help` or demo contract is instantiated: none of these files parses+arguments, and none has a `__main__` block to run.+"""++from __future__ import annotations++import ast+import importlib+import sys+import unittest+from collections import Counter+from pathlib import Path++import pytest++SKILL_ROOT = Path(__file__).resolve().parents[2] / "skills" / "opentrons-integration"+SCRIPTS = SKILL_ROOT / "scripts"+sys.path.insert(0, str(SCRIPTS))++pytest.importorskip("opentrons", reason="opentrons-integration needs opentrons")++from opentrons.protocols.api_support.definitions import ( # noqa: E402+ MAX_SUPPORTED_VERSION,+)+from opentrons.simulate import simulate # noqa: E402++#: Every template this suite knows about, and the robot each one targets.+TEMPLATES = {+ "absorbance_reader_template.py": "Flex",+ "basic_protocol_template.py": "Flex",+ "ot2_basic_protocol_template.py": "OT-2",+ "pcr_setup_template.py": "Flex",+ "runtime_parameters_template.py": "Flex",+ "serial_dilution_template.py": "Flex",+}+FLEX_TEMPLATES = tuple(+ name for name, robot in TEMPLATES.items() if robot == "Flex"+)++#: API level each robot line supports at this skill's baseline (SKILL.md).+EXPECTED_API_LEVEL = {"Flex": "2.29", "OT-2": "2.28"}++_INSTALLED_MAX = tuple(int(part) for part in str(MAX_SUPPORTED_VERSION).split("."))++_LOG_CACHE: dict[str, list[str]] = {}+++def declarations(name: str):+ """Import a template and hand back the module object."""+ return importlib.import_module(Path(name).stem)+++def run_log(name: str) -> list[str]:+ """Simulate a template once and return the run log as plain text lines."""+ if name not in _LOG_CACHE:+ with (SCRIPTS / name).open() as handle:+ entries, _bundle = simulate(handle, name)+ _LOG_CACHE[name] = [entry["payload"].get("text", "") for entry in entries]+ return _LOG_CACHE[name]+++def calls(name: str) -> list[tuple[str, list, dict]]:+ """(method name, literal positional args, literal keyword args) for every call.++ Non-literal arguments are dropped rather than guessed at, so a caller can+ ask "was this called with these constants" but not reconstruct expressions.+ """+ tree = ast.parse((SCRIPTS / name).read_text(encoding="utf-8"), filename=name)+ found = []+ for node in ast.walk(tree):+ if not isinstance(node, ast.Call):+ continue+ function = node.func+ label = (+ function.attr+ if isinstance(function, ast.Attribute)+ else getattr(function, "id", "")+ )+ positional = []+ for argument in node.args:+ try:+ positional.append(ast.literal_eval(argument))+ except ValueError:+ positional.append(None)+ keywords = {}+ for keyword in node.keywords:+ if keyword.arg is None:+ continue+ try:+ keywords[keyword.arg] = ast.literal_eval(keyword.value)+ except ValueError:+ keywords[keyword.arg] = None+ found.append((label, positional, keywords))+ return found+++def call_argument(name: str, method: str, index: int, keyword: str):+ """The `index`-th positional or `keyword` argument of the first `method` call."""+ for label, positional, keywords in calls(name):+ if label != method:+ continue+ if keyword in keywords:+ return keywords[keyword]+ if len(positional) > index:+ return positional[index]+ return None+++def load_names(name: str, method: str) -> list[str]:+ """The load names / module names passed to every `method` call."""+ values = []+ for label, positional, keywords in calls(name):+ if label != method:+ continue+ for candidate in ("load_name", "module_name", "instrument_name"):+ if candidate in keywords:+ values.append(keywords[candidate])+ break+ else:+ if positional:+ values.append(positional[0])+ return values+++def slots(name: str) -> list[str]:+ """Every deck slot a template loads labware, a module, or trash into."""+ found = []+ for method, index in (+ ("load_labware", 1),+ ("load_module", 1),+ ("load_trash_bin", 0),+ ):+ for label, positional, keywords in calls(name):+ if label != method:+ continue+ for candidate in ("location",):+ if candidate in keywords:+ found.append(keywords[candidate])+ break+ else:+ if len(positional) > index:+ found.append(positional[index])+ return [value for value in found if isinstance(value, str)]+++def closing_comment(name: str) -> str | None:+ """The last constant string a template passes to `protocol.comment()`.++ Interpolated comments are skipped -- their text is only known at run time.+ """+ literals = [+ positional[0]+ for label, positional, _ in calls(name)+ if label == "comment" and positional and isinstance(positional[0], str)+ ]+ return literals[-1] if literals else None+++def counted(log: list[str], prefix: str) -> int:+ return sum(1 for line in log if line.startswith(prefix))+++class TemplateInventoryTests(unittest.TestCase):+ def test_the_shipped_templates_are_the_ones_under_test(self) -> None:+ # A new template must be added here deliberately, with tests.+ self.assertEqual(+ {path.name for path in SCRIPTS.glob("*.py")}, set(TEMPLATES)+ )+++class DeclarationTests(unittest.TestCase):+ """Every template must declare what the App needs to load it."""++ def test_each_template_names_itself_and_its_purpose(self) -> None:+ for name in TEMPLATES:+ with self.subTest(template=name):+ metadata = declarations(name).metadata+ for key in ("protocolName", "author", "description"):+ self.assertTrue(+ metadata.get(key), f"{name}: metadata.{key} is missing or empty"+ )++ def test_each_template_declares_its_robot_and_api_level(self) -> None:+ for name, robot in TEMPLATES.items():+ with self.subTest(template=name):+ requirements = declarations(name).requirements+ self.assertEqual(requirements["robotType"], robot)+ self.assertEqual(+ requirements["apiLevel"], EXPECTED_API_LEVEL[robot]+ )++ def test_no_template_asks_for_a_newer_api_than_the_installed_package(self) -> None:+ # A protocol declaring an unsupported apiLevel fails analysis before a+ # single command runs, and the error names the level rather than the bug.+ for name in TEMPLATES:+ with self.subTest(template=name):+ declared = tuple(+ int(part)+ for part in declarations(name).requirements["apiLevel"].split(".")+ )+ self.assertLessEqual(declared, _INSTALLED_MAX)++ def test_each_template_exposes_a_single_argument_run_entry_point(self) -> None:+ for name in TEMPLATES:+ with self.subTest(template=name):+ run = declarations(name).run+ self.assertEqual(run.__code__.co_argcount, 1)+++class RobotSpecificApiTests(unittest.TestCase):+ """Flex and OT-2 disagree about slots, pipettes, tips, and the trash."""++ OT2 = "ot2_basic_protocol_template.py"++ def test_the_ot2_template_uses_numbered_deck_slots(self) -> None:+ self.assertTrue(slots(self.OT2), "no deck slots found")+ for slot in slots(self.OT2):+ with self.subTest(slot=slot):+ self.assertTrue(slot.isdigit(), f"{slot} is Flex coordinate style")++ def test_the_flex_templates_use_coordinate_deck_slots(self) -> None:+ for name in FLEX_TEMPLATES:+ with self.subTest(template=name):+ self.assertTrue(slots(name), "no deck slots found")+ for slot in slots(name):+ self.assertRegex(slot, r"^[A-D][1-4]$")++ def test_the_ot2_template_leaves_the_fixed_trash_alone(self) -> None:+ # The OT-2 trash is wired to slot 12; calling load_trash_bin() on an+ # OT-2 is an error, which is why the template only comments on it.+ methods = {label for label, _, _ in calls(self.OT2)}+ self.assertNotIn("load_trash_bin", methods)++ def test_every_flex_template_with_a_pipette_loads_a_trash_bin(self) -> None:+ # Flex has no fixed trash: a protocol that picks up a tip and never+ # declares somewhere to drop it fails analysis.+ for name in FLEX_TEMPLATES:+ methods = {label for label, _, _ in calls(name)}+ if "load_instrument" not in methods:+ continue+ with self.subTest(template=name):+ self.assertIn("load_trash_bin", methods)++ def test_pipette_names_match_the_robot_line(self) -> None:+ for name in FLEX_TEMPLATES:+ for instrument in load_names(name, "load_instrument"):+ with self.subTest(template=name, instrument=instrument):+ self.assertTrue(instrument.startswith("flex_"))+ for instrument in load_names(self.OT2, "load_instrument"):+ with self.subTest(instrument=instrument):+ self.assertFalse(instrument.startswith("flex_"))+ # GEN2 hardware is what current OT-2 software calibrates.+ self.assertTrue(instrument.endswith("_gen2"))++ def test_tip_racks_match_the_robot_line(self) -> None:+ for name in FLEX_TEMPLATES:+ for labware in load_names(name, "load_labware"):+ if "tiprack" not in labware:+ continue+ with self.subTest(template=name, labware=labware):+ self.assertTrue(labware.startswith("opentrons_flex_"))+ for labware in load_names(self.OT2, "load_labware"):+ if "tiprack" in labware:+ self.assertFalse(labware.startswith("opentrons_flex_"))+++class SimulationTests(unittest.TestCase):+ def test_every_flex_template_simulates_to_its_closing_comment(self) -> None:+ for name in FLEX_TEMPLATES:+ with self.subTest(template=name):+ log = run_log(name)+ self.assertTrue(log, "simulation produced an empty run log")+ # The last command is the protocol's own summary comment, so a+ # truncated run shows up here rather than as a silent pass.+ expected = closing_comment(name)+ self.assertIsNotNone(expected, "template ends without a comment")+ self.assertEqual(log[-1], expected)++ def test_the_flex_package_refuses_the_ot2_template(self) -> None:+ name = "ot2_basic_protocol_template.py"+ try:+ log = run_log(name)+ except RuntimeError as error:+ # Documented in SKILL.md: 9.1.x rejects OT-2 protocols after the+ # release-line split, so OT-2 analysis belongs in the OT-2 App.+ self.assertIn("OT-2", str(error))+ return+ # An older, OT-2-capable package is installed: then it must simulate.+ self.assertTrue(log)+ self.assertEqual(log[-1], "Transfer complete.")+++class BasicTransferTests(unittest.TestCase):+ NAME = "basic_protocol_template.py"++ def setUp(self) -> None:+ self.log = run_log(self.NAME)++ def test_one_tip_is_used_for_the_single_transfer(self) -> None:+ self.assertEqual(counted(self.log, "Picking up tip"), 1)+ self.assertEqual(counted(self.log, "Dropping tip"), 1)++ def test_the_declared_hundred_microlitres_move_from_reservoir_to_plate(self) -> None:+ aspirations = [line for line in self.log if line.startswith("Aspirating")]+ dispenses = [line for line in self.log if line.startswith("Dispensing")]+ self.assertEqual(len(aspirations), 1)+ self.assertEqual(len(dispenses), 1)+ self.assertIn("100.0 uL from A1 of Buffer Reservoir", aspirations[0])+ self.assertIn("100.0 uL into A1 of Destination Plate", dispenses[0])++ def test_the_transfer_stays_within_the_declared_reservoir_volume(self) -> None:+ # 1000 uL is loaded into A1; one 100 uL transfer cannot overdraw it.+ loaded = call_argument(self.NAME, "load_liquid", 1, "volume")+ self.assertGreaterEqual(loaded, 100)+++class RuntimeParameterTests(unittest.TestCase):+ NAME = "runtime_parameters_template.py"++ class Recorder:+ """Stand-in for ParameterContext that records the declared space."""++ def __init__(self) -> None:+ self.parameters = {}++ def _add(self, kind, **kwargs):+ self.parameters[kwargs["variable_name"]] = {"kind": kind, **kwargs}++ def add_int(self, **kwargs):+ self._add("int", **kwargs)++ def add_float(self, **kwargs):+ self._add("float", **kwargs)++ def add_bool(self, **kwargs):+ self._add("bool", **kwargs)++ def setUp(self) -> None:+ self.recorder = self.Recorder()+ declarations(self.NAME).add_parameters(self.recorder)+ self.log = run_log(self.NAME)++ def test_the_three_documented_parameters_are_declared(self) -> None:+ self.assertEqual(+ set(self.recorder.parameters),+ {"sample_count", "transfer_volume", "dry_run"},+ )++ def test_every_numeric_default_sits_inside_its_own_bounds(self) -> None:+ # A default outside the range is rejected at run setup, and the operator+ # sees a validation error rather than the protocol.+ for name, spec in self.recorder.parameters.items():+ if spec["kind"] == "bool":+ continue+ with self.subTest(parameter=name):+ self.assertLessEqual(spec["minimum"], spec["default"])+ self.assertLessEqual(spec["default"], spec["maximum"])++ def test_the_volume_ceiling_fits_the_tips_the_template_loads(self) -> None:+ # 200 uL tips: a maximum above that cannot be aspirated in one go.+ self.assertEqual(+ self.recorder.parameters["transfer_volume"]["maximum"], 100.0+ )+ self.assertTrue(+ any("200ul" in labware for labware in load_names(self.NAME, "load_labware"))+ )++ def test_the_sample_ceiling_fits_the_destination_plate(self) -> None:+ # A 96-well plate; the ceiling of 12 is one row of a reservoir's worth.+ self.assertLessEqual(self.recorder.parameters["sample_count"]["maximum"], 96)++ def test_the_defaults_fill_eight_wells_with_fifty_microlitres(self) -> None:+ self.assertIn("Filling 8 wells with 50.0 µL each.", self.log)+ dispenses = [line for line in self.log if line.startswith("Dispensing 50.0")]+ self.assertEqual(len(dispenses), 8)+ # Column 1, top to bottom: A1 through H1.+ for row, line in zip("ABCDEFGH", dispenses):+ self.assertIn(f"into {row}1 of Destination Plate", line)++ def test_the_aspirated_total_is_the_eight_doses_plus_disposal(self) -> None:+ volumes = [+ float(line.split()[1])+ for line in self.log+ if line.startswith("Aspirating")+ ]+ # 8 x 50 uL delivered, plus a 20 uL disposal volume per aspiration.+ self.assertEqual(sum(volumes), 8 * 50 + len(volumes) * 20)+ # And no aspiration may exceed the 200 uL tip capacity.+ self.assertLessEqual(max(volumes), 200)++ def test_distributing_reuses_one_tip(self) -> None:+ self.assertEqual(counted(self.log, "Picking up tip"), 1)++ def test_the_dry_run_default_gives_the_one_second_incubation(self) -> None:+ # The alternative branch waits 60 s; a simulated dry run must not.+ delays = [line for line in self.log if line.startswith("Delaying")]+ self.assertEqual(len(delays), 1)+ self.assertIn("1.0 seconds", delays[0])+++class SerialDilutionTests(unittest.TestCase):+ NAME = "serial_dilution_template.py"+ #: Columns 2-12 of a 96-well plate: eleven 1:2 steps.+ STEPS = 11+ CHANNELS = 8+ VOLUME = 100++ def setUp(self) -> None:+ self.log = run_log(self.NAME)++ def test_the_documented_number_of_dilution_steps_is_performed(self) -> None:+ mixes = [line for line in self.log if line.startswith("Mixing")]+ self.assertEqual(len(mixes), self.STEPS)++ def test_one_tip_per_dilution_step_plus_the_diluent_and_cleanup_tips(self) -> None:+ # new_tip="once" for the diluent fill, "always" across the series, and+ # one more to remove the final 100 uL: 1 + 11 + 1.+ self.assertEqual(counted(self.log, "Picking up tip"), self.STEPS + 2)+ self.assertEqual(counted(self.log, "Dropping tip"), self.STEPS + 2)++ def test_every_hundred_microlitre_draw_is_accounted_for(self) -> None:+ draws = counted(self.log, f"Aspirating {self.VOLUME}.0")+ # 11 diluent fills + 11 dilution transfers + 1 removal from column 12.+ self.assertEqual(draws, self.STEPS * 2 + 1)++ def test_the_declared_diluent_covers_every_row_of_every_step(self) -> None:+ # An 8-channel head fills eight wells per command, so the reservoir+ # needs 8 x 11 x 100 uL = 8800 uL; the template declares 12 mL.+ declared = call_argument(self.NAME, "load_liquid", 1, "volume")+ self.assertGreaterEqual(+ declared, self.CHANNELS * self.STEPS * self.VOLUME+ )+ self.assertIn("12 mL", declarations(self.NAME).__doc__)++ def test_the_final_column_is_equalised_into_the_trash(self) -> None:+ # Without this the last column holds 200 uL and the series is not 1:2.+ discards = [+ line+ for line in self.log+ if line.startswith("Dispensing 100.0") and "Trash" in line+ ]+ self.assertEqual(len(discards), 1)++ def test_the_stock_column_is_never_diluted_from_the_reservoir(self) -> None:+ # Diluent goes into columns 2-12 only; column 1 holds the stock.+ filled = [+ line+ for line in self.log+ if line.startswith("Dispensing 100.0") and "Dilution Plate" in line+ ]+ self.assertTrue(filled)+ for line in filled:+ self.assertNotIn("into A1 of Dilution Plate", line)+++class PcrSetupTests(unittest.TestCase):+ NAME = "pcr_setup_template.py"+ REACTIONS = 8+ MASTER_MIX = 20+ TEMPLATE = 5++ def setUp(self) -> None:+ self.log = run_log(self.NAME)++ def test_the_reaction_volume_matches_the_advertised_twenty_five(self) -> None:+ self.assertEqual(self.MASTER_MIX + self.TEMPLATE, 25)+ self.assertIn("25 µL", declarations(self.NAME).metadata["description"])++ def test_the_master_mix_is_distributed_in_one_aspiration(self) -> None:+ # 8 x 20 uL plus the 10 uL disposal volume is 170 uL, inside a 200 uL+ # tip -- so the whole plate column is filled from a single draw.+ draws = [+ float(line.split()[1])+ for line in self.log+ if line.startswith("Aspirating") and "PCR Reagents" in line and "170" in line+ ]+ self.assertEqual(draws, [self.REACTIONS * self.MASTER_MIX + 10])++ def test_the_declared_master_mix_volume_covers_the_run(self) -> None:+ volumes = [+ keywords.get("volume")+ for label, _, keywords in calls(self.NAME)+ if label == "load_liquid"+ ]+ self.assertGreaterEqual(+ max(volumes), self.REACTIONS * self.MASTER_MIX + 10+ )++ def test_each_reaction_gets_one_template_from_its_own_tube(self) -> None:+ sources = [+ line.split(" from ")[1].split(" of ")[0]+ for line in self.log+ if line.startswith(f"Transferring {self.TEMPLATE}.0")+ ]+ self.assertEqual(len(sources), self.REACTIONS)+ # Distinct tubes, and none of them A1 -- that tube holds the master mix,+ # so drawing a template from it would contaminate the stock.+ self.assertEqual(len(set(sources)), self.REACTIONS)+ self.assertNotIn("A1", sources)++ def test_one_tip_for_the_master_mix_and_one_per_template(self) -> None:+ self.assertEqual(counted(self.log, "Picking up tip"), 1 + self.REACTIONS)++ def test_the_cycling_profile_runs_thirty_five_repetitions(self) -> None:+ profiles = [line for line in self.log if "repetitions" in line]+ self.assertEqual(len(profiles), 1)+ self.assertIn("35 repetitions", profiles[0])+ for temperature in (95, 60, 72):+ self.assertIn(f"'temperature': {temperature}", profiles[0])++ def test_the_block_and_lid_temperatures_are_the_documented_ones(self) -> None:+ joined = "\n".join(self.log)+ # 105 °C lid stops condensation on the seal.+ self.assertIn("lid temperature to 105.0", joined)+ # 3 min at 95 °C to activate, 5 min at 72 °C to finish, then a 4 °C hold.+ self.assertIn("block temperature to 95.0 °C with a hold time of 3.0 minutes", joined)+ self.assertIn("block temperature to 72.0 °C with a hold time of 5.0 minutes", joined)+ self.assertIn("block temperature to 4.0 °C", joined)++ def test_the_lid_is_opened_before_pipetting_and_after_cycling(self) -> None:+ opens = [i for i, line in enumerate(self.log) if line == "Opening Thermocycler lid"]+ closes = [i for i, line in enumerate(self.log) if line == "Closing Thermocycler lid"]+ self.assertEqual(len(opens), 2)+ self.assertEqual(len(closes), 1)+ # Pipetting happens between the first open and the close.+ self.assertLess(opens[0], closes[0])+ self.assertLess(closes[0], opens[1])++ def test_every_thermocycler_step_declares_the_reaction_volume(self) -> None:+ # block_max_volume drives the ramp: understating it under-heats the mix.+ for label, _, keywords in calls(self.NAME):+ if label in {"set_block_temperature", "execute_profile"}:+ with self.subTest(step=label):+ self.assertIn("block_max_volume", keywords)+++class AbsorbanceReaderTests(unittest.TestCase):+ NAME = "absorbance_reader_template.py"++ def setUp(self) -> None:+ self.log = run_log(self.NAME)++ def test_the_reader_is_initialised_at_both_documented_wavelengths(self) -> None:+ wavelengths = call_argument(self.NAME, "initialize", 1, "wavelengths")+ self.assertEqual(wavelengths, [450, 650])+ # Two wavelengths require multi mode; "single" would raise at runtime.+ self.assertEqual(call_argument(self.NAME, "initialize", 0, "mode"), "multi")++ def test_the_lid_is_closed_before_initialisation(self) -> None:+ # Required even when the physical lid starts closed, per the module docs.+ sequence = [label for label, _, _ in calls(self.NAME)]+ self.assertLess(sequence.index("close_lid"), sequence.index("initialize"))++ def test_the_plate_is_moved_onto_the_reader_and_back_to_its_slot(self) -> None:+ moves = [line for line in self.log if line.startswith("Moving Assay Plate")]+ self.assertEqual(len(moves), 2)+ self.assertIn("Absorbance Plate Reader", moves[0])+ self.assertIn("to slot C2", moves[1])+ # Both hops use the Gripper; a manual move would stall the run.+ for line in moves:+ self.assertIn("with gripper", line)++ def test_the_read_is_exported_under_a_filename(self) -> None:+ # Without export_filename the measurements stay in the run only.+ self.assertTrue(call_argument(self.NAME, "read", 0, "export_filename"))++ def test_no_pipette_is_loaded_so_no_trash_is_needed(self) -> None:+ methods = {label for label, _, _ in calls(self.NAME)}+ self.assertNotIn("load_instrument", methods)+ self.assertNotIn("load_trash_bin", methods)+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/pacsomatic/test_run_pacsomatic.py b/tests/pacsomatic/test_run_pacsomatic.pyindex 7ee89498..cf7e4d84 100644--- a/tests/pacsomatic/test_run_pacsomatic.py+++ b/tests/pacsomatic/test_run_pacsomatic.py@@ -4,6 +4,8 @@ import unittestfrom pathlib import Pathfrom types import SimpleNamespace+import skill_contract+SKILL_ROOT = Path(__file__).resolve().parents[2] / "skills" / "pacsomatic"SCRIPT_PATH = SKILL_ROOT / "scripts" / "run_pacsomatic.py"@@ -73,5 +75,10 @@ class RunPacsomaticUnitTests(unittest.TestCase):self.assertIn("P001,P001_N,0,/data/normal.bam,", content)+# 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(SKILL_ROOT)+if __name__ == "__main__":unittest.main()diff --git a/tests/pathml/test_scripts.py b/tests/pathml/test_scripts.pyindex a23a4cd5..0c17d642 100644--- a/tests/pathml/test_scripts.py+++ b/tests/pathml/test_scripts.py@@ -148,7 +148,7 @@ class SafetyTests(unittest.TestCase):def test_skill_version_and_progressive_disclosure(self) -> None:skill = (SKILL_ROOT / "SKILL.md").read_text(encoding="utf-8")- self.assertIn('version: "1.1"', skill)+ self.assertRegex(skill, r'\n version: "\d+\.\d+"\n')self.assertIn("license: MIT", skill)self.assertLess(len(skill.splitlines()), 500)self.assertEqual(diff --git a/tests/pathogen-variant-surveillance/test_scripts.py b/tests/pathogen-variant-surveillance/test_scripts.pyindex 8073240f..6122fb5c 100644--- a/tests/pathogen-variant-surveillance/test_scripts.py+++ b/tests/pathogen-variant-surveillance/test_scripts.py@@ -20,6 +20,8 @@ from contextlib import redirect_stderr, redirect_stdoutfrom pathlib import Pathfrom unittest.mock import patch+import skill_contract+SKILL_ROOT = Path(__file__).resolve().parents[2] / "skills" / "pathogen-variant-surveillance"SCRIPTS_DIR = SKILL_ROOT / "scripts"LIVE = os.environ.get("LAPIS_LIVE_TESTS") == "1"@@ -954,5 +956,10 @@ class LiveApiTests(unittest.TestCase):self.assertTrue(lapis_client.data_version(url))+# 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(SKILL_ROOT)+if __name__ == "__main__":unittest.main()diff --git a/tests/pathway-enrichment/test_scripts.py b/tests/pathway-enrichment/test_scripts.pynew file mode 100644index 00000000..07609ac5--- /dev/null+++ b/tests/pathway-enrichment/test_scripts.py@@ -0,0 +1,232 @@+"""Tests for the pathway-enrichment input handling.++The enrichment call itself goes to Enrichr or a local GMT, so what is worth+testing offline is everything that decides *which genes, in which order* get+sent -- and that is where enrichment analyses usually go wrong. A mouse symbol+left upper-cased silently matches nothing in a mouse library; a ranking built+from an unsigned p-value puts up- and down-regulated genes at the same end of+the list and quietly inverts GSEA's answer.+"""++from __future__ import annotations++import sys+import tempfile+import unittest+from pathlib import Path++import pytest++import skill_contract++SKILL_ROOT = Path(__file__).resolve().parents[2] / "skills" / "pathway-enrichment"+SCRIPTS = SKILL_ROOT / "scripts"+sys.path.insert(0, str(SCRIPTS))++pd = pytest.importorskip("pandas", reason="pathway-enrichment needs pandas")+pytest.importorskip("numpy", reason="pathway-enrichment needs numpy")+pytest.importorskip("gseapy", reason="run_enrichment imports gseapy at module scope")++import run_enrichment # noqa: E402++CliHelpTests = skill_contract.cli.help_test_case(SKILL_ROOT)+++class SymbolCleaningTests(unittest.TestCase):+ def test_human_symbols_are_upper_cased(self) -> None:+ self.assertEqual(+ run_enrichment._clean_symbols(["tp53", "Brca1"], "human"),+ ["TP53", "BRCA1"],+ )++ def test_mouse_symbols_are_title_cased(self) -> None:+ # Mouse libraries key on Trp53, not TRP53 -- getting this wrong returns+ # an empty enrichment with no error.+ self.assertEqual(+ run_enrichment._clean_symbols(["TRP53", "brca1"], "mouse"),+ ["Trp53", "Brca1"],+ )++ def test_an_unknown_organism_leaves_case_alone(self) -> None:+ self.assertEqual(+ run_enrichment._clean_symbols(["dpp", "Hh"], "fly"), ["dpp", "Hh"]+ )++ def test_blank_and_placeholder_entries_are_dropped(self) -> None:+ self.assertEqual(+ run_enrichment._clean_symbols(+ ["TP53", "", " ", "nan", "NaN", "None", "BRCA1"], "human"+ ),+ ["TP53", "BRCA1"],+ )++ def test_duplicates_are_removed_after_normalisation(self) -> None:+ # "tp53" and "TP53" are the same gene once case is normalised.+ self.assertEqual(+ run_enrichment._clean_symbols(["tp53", "TP53", "Tp53"], "human"), ["TP53"]+ )++ def test_input_order_is_preserved(self) -> None:+ self.assertEqual(+ run_enrichment._clean_symbols(["c", "a", "b", "a"], "other"),+ ["c", "a", "b"],+ )++ def test_surrounding_whitespace_is_stripped(self) -> None:+ self.assertEqual(run_enrichment._clean_symbols([" TP53 "], "human"), ["TP53"])+++class GeneListReadingTests(unittest.TestCase):+ def setUp(self) -> None:+ self._temporary = tempfile.TemporaryDirectory()+ self.addCleanup(self._temporary.cleanup)+ self.root = Path(self._temporary.name)++ def test_a_plain_text_list_is_read_one_gene_per_line(self) -> None:+ path = self.root / "genes.txt"+ path.write_text("TP53\nBRCA1\n\nEGFR\n", encoding="utf-8")+ self.assertEqual(+ run_enrichment._read_gene_list(path), ["TP53", "BRCA1", "EGFR"]+ )++ def test_a_csv_uses_its_first_column(self) -> None:+ path = self.root / "genes.csv"+ path.write_text("gene,log2FC\nTP53,1.2\nBRCA1,-0.8\n", encoding="utf-8")+ self.assertEqual(run_enrichment._read_gene_list(path), ["TP53", "BRCA1"])++ def test_a_tsv_is_split_on_tabs_not_commas(self) -> None:+ path = self.root / "genes.tsv"+ path.write_text("gene\tlog2FC\nTP53\t1.2\nBRCA1\t-0.8\n", encoding="utf-8")+ self.assertEqual(run_enrichment._read_gene_list(path), ["TP53", "BRCA1"])+++class RankingTests(unittest.TestCase):+ def setUp(self) -> None:+ self._temporary = tempfile.TemporaryDirectory()+ self.addCleanup(self._temporary.cleanup)+ self.root = Path(self._temporary.name)++ def _deseq2(self, text: str) -> Path:+ path = self.root / "deseq2.csv"+ path.write_text(text, encoding="utf-8")+ return path++ def test_the_wald_statistic_is_preferred_when_present(self) -> None:+ path = self._deseq2(+ "gene,baseMean,log2FoldChange,stat,pvalue\n"+ "TP53,100,2.0,5.0,1e-6\n"+ "BRCA1,100,-1.0,-3.0,1e-3\n"+ "EGFR,100,0.1,0.2,0.8\n"+ )+ ranks = run_enrichment._build_rank_from_deseq2(path, "human")+ self.assertEqual(list(ranks.index), ["TP53", "EGFR", "BRCA1"])+ self.assertEqual(ranks["TP53"], 5.0)++ def test_the_fallback_metric_keeps_the_direction_of_the_fold_change(self) -> None:+ # sign(log2FC) * -log10(p): a strongly down-regulated gene must land at+ # the bottom of the ranking, not the top.+ path = self._deseq2(+ "gene,log2FoldChange,pvalue\n"+ "UP,3.0,1e-10\n"+ "DOWN,-3.0,1e-10\n"+ "FLAT,0.1,0.9\n"+ )+ ranks = run_enrichment._build_rank_from_deseq2(path, "human")+ self.assertEqual(list(ranks.index), ["UP", "FLAT", "DOWN"])+ self.assertGreater(ranks["UP"], 0)+ self.assertLess(ranks["DOWN"], 0)++ def test_a_zero_pvalue_is_clipped_rather_than_becoming_infinite(self) -> None:+ path = self._deseq2("gene,log2FoldChange,pvalue\nA,2.0,0.0\nB,1.0,0.5\n")+ ranks = run_enrichment._build_rank_from_deseq2(path, "human")+ self.assertTrue(all(abs(value) < float("inf") for value in ranks))+ self.assertEqual(ranks.idxmax(), "A")++ def test_a_table_with_neither_metric_exits_naming_its_columns(self) -> None:+ path = self._deseq2("gene,baseMean,padj\nTP53,100,0.01\n")+ with self.assertRaises(SystemExit) as raised:+ run_enrichment._build_rank_from_deseq2(path, "human")+ self.assertIn("baseMean", str(raised.exception))++ def test_column_names_are_matched_case_insensitively(self) -> None:+ path = self._deseq2("gene,LOG2FOLDCHANGE,PVALUE\nA,2.0,1e-5\nB,-1.0,1e-2\n")+ ranks = run_enrichment._build_rank_from_deseq2(path, "human")+ self.assertEqual(list(ranks.index), ["A", "B"])++ def test_rows_with_missing_statistics_are_dropped(self) -> None:+ path = self._deseq2("gene,stat\nA,3.0\nB,\nC,1.0\n")+ ranks = run_enrichment._build_rank_from_deseq2(path, "human")+ self.assertEqual(list(ranks.index), ["A", "C"])++ def test_duplicate_symbols_keep_their_first_occurrence(self) -> None:+ path = self._deseq2("gene,stat\ntp53,5.0\nTP53,1.0\n")+ ranks = run_enrichment._build_rank_from_deseq2(path, "human")+ self.assertEqual(list(ranks.index), ["TP53"])+ self.assertEqual(ranks["TP53"], 5.0)++ def test_the_ranking_is_returned_in_descending_order(self) -> None:+ path = self._deseq2("gene,stat\nA,1.0\nB,9.0\nC,-4.0\n")+ ranks = run_enrichment._build_rank_from_deseq2(path, "human")+ self.assertEqual(list(ranks.values), sorted(ranks.values, reverse=True))+++class RankedFileTests(unittest.TestCase):+ def setUp(self) -> None:+ self._temporary = tempfile.TemporaryDirectory()+ self.addCleanup(self._temporary.cleanup)+ self.root = Path(self._temporary.name)++ def _rnk(self, text: str) -> Path:+ path = self.root / "ranked.rnk"+ path.write_text(text, encoding="utf-8")+ return path++ def test_a_headerless_two_column_file_is_read_directly(self) -> None:+ ranks = run_enrichment._read_rnk(self._rnk("TP53,5.0\nBRCA1,-2.0\n"), "human")+ self.assertEqual(list(ranks.index), ["TP53", "BRCA1"])+ self.assertEqual(ranks["TP53"], 5.0)++ def test_a_header_row_is_detected_and_dropped(self) -> None:+ ranks = run_enrichment._read_rnk(+ self._rnk("gene,score\nTP53,5.0\nBRCA1,-2.0\n"), "human"+ )+ self.assertEqual(list(ranks.index), ["TP53", "BRCA1"])++ def test_a_single_column_file_is_refused(self) -> None:+ with self.assertRaises(SystemExit) as raised:+ run_enrichment._read_rnk(self._rnk("TP53\nBRCA1\n"), "human")+ self.assertIn("two columns", str(raised.exception))++ def test_symbols_are_normalised_for_the_organism(self) -> None:+ ranks = run_enrichment._read_rnk(self._rnk("trp53,5.0\n"), "mouse")+ self.assertEqual(list(ranks.index), ["Trp53"])++ def test_rows_with_unparseable_scores_are_dropped(self) -> None:+ ranks = run_enrichment._read_rnk(self._rnk("A,1.0\nB,n/a\nC,2.0\n"), "human")+ self.assertEqual(sorted(ranks.index), ["A", "C"])++ def test_the_result_is_sorted_descending(self) -> None:+ ranks = run_enrichment._read_rnk(self._rnk("A,1.0\nB,9.0\nC,-4.0\n"), "human")+ self.assertEqual(list(ranks.index), ["B", "A", "C"])+++class LibraryTests(unittest.TestCase):+ def test_the_default_libraries_are_named_and_versioned(self) -> None:+ # Enrichr library names carry a year; an unversioned name silently+ # resolves to whatever is current and makes results irreproducible.+ self.assertTrue(run_enrichment.DEFAULT_LIBRARIES)+ for library in run_enrichment.DEFAULT_LIBRARIES:+ with self.subTest(library=library):+ # The year may be terminal (Reactome_2022) or followed by a+ # species suffix (KEGG_2021_Human).+ self.assertRegex(library, r"_\d{4}(_[A-Za-z]+)?$")++ def test_the_default_set_is_free_of_duplicates(self) -> None:+ self.assertEqual(+ len(set(run_enrichment.DEFAULT_LIBRARIES)),+ len(run_enrichment.DEFAULT_LIBRARIES),+ )+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/pdf/test_scripts.py b/tests/pdf/test_scripts.pynew file mode 100644index 00000000..3490f2ad--- /dev/null+++ b/tests/pdf/test_scripts.py@@ -0,0 +1,287 @@+"""Tests for the pdf skill's form tooling.++The coordinate transforms are the part worth pinning. PDF puts the origin at+the bottom-left and images put it at the top-left, so filling a form from+image-space boxes means flipping the y axis and scaling both axes. Getting the+flip backwards places every field on the wrong half of the page, and nothing+raises -- the output just looks wrong. Both transforms are pure arithmetic, so+they are tested directly with hand-computed expectations.++The remaining tests build real PDFs with reportlab where a fixture is needed,+and skip when the reader libraries are absent.+"""++from __future__ import annotations++import io+import json+import sys+import tempfile+import unittest+from pathlib import Path++import pytest++import skill_contract++SKILL_ROOT = Path(__file__).resolve().parents[2] / "skills" / "pdf"+SCRIPTS = SKILL_ROOT / "scripts"+sys.path.insert(0, str(SCRIPTS))++# These scripts take positional paths via `sys.argv` rather than argparse, so+# there is no `--help` contract to apply here.+++def coords():+ pytest.importorskip("pypdf", reason="pdf scripts need pypdf")+ import fill_pdf_form_with_annotations++ return fill_pdf_form_with_annotations+++class ImageToPdfTransformTests(unittest.TestCase):+ """Image space: origin top-left, y grows down. PDF: origin bottom-left."""++ def test_a_box_at_the_image_origin_lands_at_the_pdf_top(self) -> None:+ # Image (0,0)-(100,50) on a 1000x500 image over a 200x100 page:+ # x scales by 0.2, y flips -> top of the page.+ transformed = coords().transform_from_image_coords(+ (0, 0, 100, 50), 1000, 500, 200, 100+ )+ left, bottom, right, top = transformed+ self.assertAlmostEqual(left, 0.0)+ self.assertAlmostEqual(right, 20.0)+ self.assertAlmostEqual(top, 100.0)+ self.assertAlmostEqual(bottom, 90.0)++ def test_a_box_at_the_image_bottom_lands_at_the_pdf_origin(self) -> None:+ transformed = coords().transform_from_image_coords(+ (0, 450, 100, 500), 1000, 500, 200, 100+ )+ _, bottom, _, top = transformed+ self.assertAlmostEqual(bottom, 0.0)+ self.assertAlmostEqual(top, 10.0)++ def test_identity_scaling_only_flips_the_y_axis(self) -> None:+ transformed = coords().transform_from_image_coords(+ (10, 20, 30, 40), 100, 100, 100, 100+ )+ left, bottom, right, top = transformed+ self.assertAlmostEqual(left, 10.0)+ self.assertAlmostEqual(right, 30.0)+ self.assertAlmostEqual(bottom, 60.0) # 100 - 40+ self.assertAlmostEqual(top, 80.0) # 100 - 20++ def test_the_box_keeps_its_size_under_a_pure_flip(self) -> None:+ left, bottom, right, top = coords().transform_from_image_coords(+ (10, 20, 30, 50), 100, 100, 100, 100+ )+ self.assertAlmostEqual(right - left, 20.0)+ self.assertAlmostEqual(top - bottom, 30.0)++ def test_the_transform_is_invertible_within_rounding(self) -> None:+ original = (12.0, 34.0, 56.0, 78.0)+ once = coords().transform_from_image_coords(original, 200, 200, 200, 200)+ twice = coords().transform_from_image_coords(once, 200, 200, 200, 200)+ for expected, actual in zip(original, twice):+ self.assertAlmostEqual(expected, actual, places=6)+++class PdfCoordinateTests(unittest.TestCase):+ def test_the_y_axis_is_flipped_about_the_page_height(self) -> None:+ left, bottom, right, top = coords().transform_from_pdf_coords(+ (10, 20, 30, 40), 100+ )+ self.assertAlmostEqual(left, 10.0)+ self.assertAlmostEqual(right, 30.0)+ self.assertAlmostEqual(bottom, 60.0)+ self.assertAlmostEqual(top, 80.0)++ def test_flipping_twice_returns_the_original(self) -> None:+ original = (5.0, 15.0, 25.0, 35.0)+ once = coords().transform_from_pdf_coords(original, 100)+ twice = coords().transform_from_pdf_coords(once, 100)+ for expected, actual in zip(original, twice):+ self.assertAlmostEqual(expected, actual, places=9)++ def test_a_box_spanning_the_full_page_is_unchanged_vertically(self) -> None:+ _, bottom, _, top = coords().transform_from_pdf_coords((0, 0, 10, 100), 100)+ self.assertAlmostEqual(bottom, 0.0)+ self.assertAlmostEqual(top, 100.0)+++def field(description: str, label: list, entry: list, page: int = 1) -> dict:+ return {+ "description": description,+ "label_bounding_box": label,+ "entry_bounding_box": entry,+ "page_number": page,+ }+++class BoundingBoxCheckTests(unittest.TestCase):+ """Overlapping boxes put text on top of text in the filled PDF."""++ def _messages(self, *fields) -> list[str]:+ import check_bounding_boxes++ return check_bounding_boxes.get_bounding_box_messages(+ io.StringIO(json.dumps({"form_fields": list(fields)}))+ )++ def _failures(self, *fields) -> list[str]:+ return [m for m in self._messages(*fields) if m.startswith("FAILURE")]++ def test_a_clean_layout_reports_only_the_field_count(self) -> None:+ messages = self._messages(+ field("Full name", [10, 10, 100, 30], [110, 10, 300, 30]),+ field("Email", [10, 40, 100, 60], [110, 40, 300, 60]),+ )+ self.assertEqual(+ messages, ["Read 2 fields", "SUCCESS: All bounding boxes are valid"]+ )++ def test_an_empty_form_reports_zero_fields(self) -> None:+ self.assertEqual(+ self._messages(), ["Read 0 fields", "SUCCESS: All bounding boxes are valid"]+ )++ def test_a_label_overlapping_its_own_entry_is_reported(self) -> None:+ failures = self._failures(+ field("Full name", [10, 10, 100, 30], [50, 10, 300, 30])+ )+ self.assertTrue(failures)+ self.assertIn("label and entry", failures[0])+ self.assertIn("Full name", failures[0])++ def test_two_fields_overlapping_each_other_are_reported(self) -> None:+ failures = self._failures(+ field("Full name", [10, 10, 100, 30], [110, 10, 300, 30]),+ field("Email", [90, 15, 200, 25], [310, 15, 400, 25]),+ )+ self.assertTrue(failures)+ joined = " ".join(failures)+ self.assertIn("Full name", joined)+ self.assertIn("Email", joined)++ def test_boxes_on_different_pages_never_collide(self) -> None:+ self.assertEqual(+ self._failures(+ field("A", [10, 10, 100, 30], [110, 10, 300, 30], page=1),+ field("B", [10, 10, 100, 30], [110, 10, 300, 30], page=2),+ ),+ [],+ )++ def test_boxes_that_merely_touch_do_not_count_as_intersecting(self) -> None:+ # Edge-sharing is how adjacent fields are normally laid out.+ self.assertEqual(+ self._failures(field("A", [10, 10, 100, 30], [100, 10, 200, 30])), []+ )++ def test_the_report_stops_after_twenty_messages(self) -> None:+ # A form where everything overlaps would otherwise produce thousands.+ overlapping = [+ field(f"Field {index}", [0, 0, 100, 100], [0, 0, 100, 100])+ for index in range(30)+ ]+ messages = self._messages(*overlapping)+ self.assertLessEqual(len(messages), 21)+ self.assertIn("Aborting further checks", messages[-1])+++class FieldDescriptorTests(unittest.TestCase):+ """`make_field_dict` turns raw AcroForm entries into the filler's schema."""++ def _descriptor(self, raw: dict, field_id: str = "full_name") -> dict:+ pytest.importorskip("pypdf", reason="pdf scripts need pypdf")+ import extract_form_field_info++ return extract_form_field_info.make_field_dict(raw, field_id)++ def test_a_text_field_is_typed_as_text(self) -> None:+ descriptor = self._descriptor({"/FT": "/Tx"})+ self.assertEqual(descriptor["type"], "text")+ self.assertEqual(descriptor["field_id"], "full_name")++ def test_a_checkbox_learns_its_checked_and_unchecked_values(self) -> None:+ descriptor = self._descriptor(+ {"/FT": "/Btn", "/_States_": ["/Off", "/Yes"]}, "subscribe"+ )+ self.assertEqual(descriptor["type"], "checkbox")+ self.assertEqual(descriptor["checked_value"], "/Yes")+ self.assertEqual(descriptor["unchecked_value"], "/Off")++ def test_the_state_order_does_not_decide_which_value_means_checked(self) -> None:+ # "/Off" is the unchecked state wherever it appears in the list.+ descriptor = self._descriptor({"/FT": "/Btn", "/_States_": ["/Yes", "/Off"]})+ self.assertEqual(descriptor["checked_value"], "/Yes")+ self.assertEqual(descriptor["unchecked_value"], "/Off")++ def test_a_choice_field_carries_its_options(self) -> None:+ descriptor = self._descriptor(+ {"/FT": "/Ch", "/_States_": [("a", "Alpha"), ("b", "Beta")]}, "pick"+ )+ self.assertEqual(descriptor["type"], "choice")+ self.assertEqual(+ descriptor["choice_options"],+ [{"value": "a", "text": "Alpha"}, {"value": "b", "text": "Beta"}],+ )++ def test_an_unrecognised_field_type_is_labelled_rather_than_dropped(self) -> None:+ descriptor = self._descriptor({"/FT": "/Sig"})+ self.assertIn("unknown", descriptor["type"])+ self.assertIn("/Sig", descriptor["type"])+++class ValueValidationTests(unittest.TestCase):+ def _error(self, field_info, value):+ pytest.importorskip("pypdf", reason="pdf scripts need pypdf")+ import fill_fillable_fields++ return fill_fillable_fields.validation_error_for_field_value(field_info, value)++ CHECKBOX = {+ "field_id": "subscribe",+ "type": "checkbox",+ "checked_value": "/Yes",+ "unchecked_value": "/Off",+ }++ def test_a_checkbox_accepts_only_its_two_declared_states(self) -> None:+ self.assertIsNone(self._error(self.CHECKBOX, "/Yes"))+ self.assertIsNone(self._error(self.CHECKBOX, "/Off"))++ error = self._error(self.CHECKBOX, "/Maybe")+ self.assertIsNotNone(error)+ self.assertIn("subscribe", error)+ self.assertIn("/Yes", error)++ def test_a_choice_field_accepts_only_its_option_values(self) -> None:+ choice = {+ "field_id": "country",+ "type": "choice",+ "choice_options": [{"value": "uk", "text": "United Kingdom"}],+ }+ self.assertIsNone(self._error(choice, "uk"))+ # The display text is not a valid value -- only the option value is.+ self.assertIsNotNone(self._error(choice, "United Kingdom"))++ def test_a_radio_group_accepts_only_its_option_values(self) -> None:+ radio = {+ "field_id": "size",+ "type": "radio_group",+ "radio_options": [{"value": "/S"}, {"value": "/M"}],+ }+ self.assertIsNone(self._error(radio, "/M"))+ self.assertIsNotNone(self._error(radio, "/XL"))++ def test_a_text_field_accepts_any_string(self) -> None:+ text_field = {"field_id": "full_name", "type": "text"}+ for value in ("Ada Lovelace", "", "12345"):+ with self.subTest(value=value):+ self.assertIsNone(self._error(text_field, value))+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/peer-review/test_scripts.py b/tests/peer-review/test_scripts.pyindex fff95e16..45942aff 100644--- a/tests/peer-review/test_scripts.py+++ b/tests/peer-review/test_scripts.py@@ -3,10 +3,8 @@from __future__ import annotationsimport ast-import copyimport csvimport json-import reimport statimport sysimport tempfile@@ -46,6 +44,8 @@ from validate_claim_evidence import load_matrix # noqa: E402from validate_claim_evidence import validate_matrix # noqa: E402from validate_review_intake import validate_intake # noqa: E402+import skill_contract+def load_asset_json(name: str) -> dict:return json.loads((ASSETS / name).read_text(encoding="utf-8"))@@ -370,25 +370,10 @@ class FileSafetyAndStaticTests(unittest.TestCase):self.assertTrue(all(row["verified_on"] == "2026-07-23" for row in rows))self.assertTrue(all(row["url"].startswith("https://") for row in rows))- def test_markdown_local_path_references_exist(self) -> None:- markdown_files = [- SKILL_ROOT / "SKILL.md",- *(SKILL_ROOT / "references").glob("*.md"),- ]- pattern = re.compile(- r"`((?:assets|references|scripts)/[A-Za-z0-9_./-]+)`"- )- for markdown in markdown_files:- for relative in pattern.findall(markdown.read_text(encoding="utf-8")):- self.assertTrue(- (SKILL_ROOT / relative).is_file(),- f"{markdown.name}: missing {relative}",- )-def test_skill_frontmatter_and_progressive_disclosure(self) -> None:skill = (SKILL_ROOT / "SKILL.md").read_text(encoding="utf-8")self.assertLess(len(skill.splitlines()), 500)- self.assertIn('version: "2.1"', skill)+ self.assertRegex(skill, r'\n version: "\d+\.\d+"\n')self.assertIn("license: MIT", skill)self.assertIn("compatibility:", skill)self.assertNotIn("OPENROUTER", skill)@@ -402,5 +387,10 @@ class FileSafetyAndStaticTests(unittest.TestCase):self.assertFalse((SCRIPTS / "generate_schematic_ai.py").exists())+# 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(SKILL_ROOT)+if __name__ == "__main__":unittest.main()diff --git a/tests/phylogenetics/test_scripts.py b/tests/phylogenetics/test_scripts.pynew file mode 100644index 00000000..e77db8d7--- /dev/null+++ b/tests/phylogenetics/test_scripts.py@@ -0,0 +1,507 @@+"""Tests for the phylogenetics pipeline script.++The pipeline is a thin shell around MAFFT, IQ-TREE 2, and FastTree, none of+which are Python packages and none of which are installed here. What can still+be wrong -- and would only show up as a wasted multi-hour run -- is the *command+line* the script hands to them: MAFFT's accuracy/speed strategy is chosen from+the sequence count, and FastTree's substitution model must match the sequence+type (`-gtr` is nucleotide-only, `-lg` protein-only). Those commands are+therefore asserted argument by argument with `subprocess.run` replaced by a+recorder, so no external binary is ever invoked.++`count_sequences` and the ETE3 tree summary are checked against a FASTA and a+Newick string whose answers are known by construction; the summary's branch+lengths hold because rerooting relocates the root along an existing branch and+so preserves the tree's total length.+"""++from __future__ import annotations++import contextlib+import io+import subprocess+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" / "phylogenetics"+SCRIPTS = SKILL_ROOT / "scripts"+sys.path.insert(0, str(SCRIPTS))++# The script imports nothing heavier than the standard library at module scope+# -- ete3 is imported lazily inside the two visualisation helpers -- so there is+# no module-level package to guard. The ete3-dependent tests skip individually.+import phylogenetic_analysis as pipeline # noqa: E402++CliHelpTests = skill_contract.cli.help_test_case(SKILL_ROOT)++#: Four taxa, total branch length 8 (1+1+1+1+2+2); the six non-zero branches+#: give a mean of 8/6 and a maximum of 2.+FOUR_TAXA = "((A:1,B:1):1,(C:2,D:2):1);"+++class Recorder:+ """Stands in for `subprocess.run`: records argv, launches nothing."""++ def __init__(self, returncode: int = 0, stderr: str = "", failing: str | None = None):+ self.calls: list[list[str]] = []+ self._returncode = returncode+ self._stderr = stderr+ self._failing = failing++ def __call__(self, command, **kwargs) -> subprocess.CompletedProcess:+ self.calls.append(list(command))+ returncode = self._returncode+ if self._failing is not None:+ returncode = 1 if self._failing in command else 0+ return subprocess.CompletedProcess(+ list(command), returncode, stdout="", stderr=self._stderr+ )++ @property+ def command(self) -> list[str]:+ self.assert_called()+ return self.calls[-1]++ def assert_called(self) -> None:+ if not self.calls:+ raise AssertionError("subprocess.run was never called")+++def recorded(recorder: Recorder):+ with mock.patch.object(pipeline.subprocess, "run", recorder):+ yield recorder+++class ScratchCase(unittest.TestCase):+ def setUp(self) -> None:+ self._temporary = tempfile.TemporaryDirectory()+ self.addCleanup(self._temporary.cleanup)+ self.root = Path(self._temporary.name)++ def fasta(self, count: int, name: str | None = None) -> Path:+ path = self.root / (name or f"seqs{count}.fasta")+ path.write_text(+ "".join(f">seq{index}\nACGTACGT\n" for index in range(count)),+ encoding="utf-8",+ )+ return path++ def newick(self, text: str = FOUR_TAXA, name: str = "tree.nwk") -> Path:+ path = self.root / name+ path.write_text(text + "\n", encoding="utf-8")+ return path+++class SequenceCountTests(ScratchCase):+ def test_headers_are_counted_not_lines(self) -> None:+ self.assertEqual(pipeline.count_sequences(str(self.fasta(3))), 3)++ def test_an_empty_file_has_no_sequences(self) -> None:+ # 0 must come back as 0 rather than raise: run_mafft divides the world+ # into size bands on this number.+ self.assertEqual(pipeline.count_sequences(str(self.fasta(0))), 0)++ def test_a_wrapped_sequence_counts_once(self) -> None:+ path = self.root / "wrapped.fasta"+ path.write_text(">only\nACGT\nACGT\nACGT\n", encoding="utf-8")+ self.assertEqual(pipeline.count_sequences(str(path)), 1)++ def test_an_angle_bracket_that_does_not_start_a_line_is_not_a_header(self) -> None:+ # Indented or mid-line ">" appears in quality lines and comments; only a+ # line-initial one opens a FASTA record.+ path = self.root / "odd.fasta"+ path.write_text(">real\nACGT\n >indented\nAC>GT\n", encoding="utf-8")+ self.assertEqual(pipeline.count_sequences(str(path)), 1)++ def test_a_missing_file_raises_rather_than_reporting_zero(self) -> None:+ with self.assertRaises(FileNotFoundError):+ pipeline.count_sequences(str(self.root / "absent.fasta"))+++class MafftCommandTests(ScratchCase):+ """`--mafft-method auto` trades accuracy for speed as the dataset grows."""++ def align(self, sequences: int, **kwargs) -> list[str]:+ source = self.fasta(sequences)+ with recorded(Recorder()) as recorder:+ with contextlib.redirect_stdout(io.StringIO()):+ pipeline.run_mafft(+ str(source), str(self.root / "aligned.fasta"), **kwargs+ )+ return recorder.command++ def test_small_datasets_get_the_accurate_pairwise_strategy(self) -> None:+ command = self.align(10)+ self.assertEqual(command[0], "mafft")+ self.assertIn("--localpair", command)+ self.assertEqual(command[command.index("--maxiterate") + 1], "1000")++ def test_the_two_hundred_sequence_boundary_is_inclusive(self) -> None:+ # `n_seqs <= 200` -- 200 still gets --localpair, 201 drops to --auto.+ self.assertIn("--localpair", self.align(200))+ self.assertNotIn("--localpair", self.align(201))+ self.assertIn("--auto", self.align(201))++ def test_the_thousand_sequence_boundary_is_inclusive(self) -> None:+ # `n_seqs <= 1000` -- above it MAFFT must drop to the FFT-NS heuristic,+ # because --auto on a large alignment can run for days.+ self.assertIn("--auto", self.align(1000))+ self.assertNotIn("--auto", self.align(1001))+ self.assertIn("--fftns", self.align(1001))++ def test_an_explicit_method_overrides_the_size_bands(self) -> None:+ command = self.align(10, method="fftns")+ self.assertIn("--fftns", command)+ self.assertNotIn("--localpair", command)++ def test_the_thread_count_reaches_mafft_as_a_string(self) -> None:+ for sequences in (10, 500, 2000):+ with self.subTest(sequences=sequences):+ command = self.align(sequences, n_threads=7)+ self.assertEqual(command[command.index("--thread") + 1], "7")++ def test_the_input_order_is_preserved_and_the_file_comes_last(self) -> None:+ # Without --inputorder MAFFT reorders the alignment, which silently+ # breaks any downstream code that pairs it with a metadata table.+ source = self.fasta(10, "in.fasta")+ with recorded(Recorder()) as recorder:+ with contextlib.redirect_stdout(io.StringIO()):+ pipeline.run_mafft(str(source), str(self.root / "out.fasta"))+ self.assertIn("--inputorder", recorder.command)+ self.assertEqual(recorder.command[-1], str(source))++ def test_the_alignment_is_written_to_the_requested_path(self) -> None:+ destination = self.root / "aligned.fasta"+ with recorded(Recorder()):+ with contextlib.redirect_stdout(io.StringIO()):+ returned = pipeline.run_mafft(str(self.fasta(5)), str(destination))+ self.assertEqual(returned, str(destination))+ self.assertTrue(destination.exists())++ def test_a_mafft_failure_is_raised_not_swallowed(self) -> None:+ # Continuing with a truncated alignment would produce a tree from+ # nothing, so a non-zero exit has to stop the pipeline.+ with recorded(Recorder(returncode=1, stderr="mafft: bad input")):+ with contextlib.redirect_stdout(io.StringIO()):+ with self.assertRaisesRegex(RuntimeError, "MAFFT failed"):+ pipeline.run_mafft(+ str(self.fasta(5)), str(self.root / "aligned.fasta")+ )+++class IqTreeCommandTests(ScratchCase):+ def build(self, **kwargs) -> tuple[list[str], str, str]:+ alignment = self.root / "aligned.fasta"+ alignment.write_text(">a\nACGT\n", encoding="utf-8")+ prefix = str(self.root / "run")+ buffer = io.StringIO()+ with recorded(Recorder()) as recorder:+ with contextlib.redirect_stdout(buffer):+ tree_file = pipeline.run_iqtree(str(alignment), prefix, **kwargs)+ return recorder.command, tree_file, buffer.getvalue()++ def test_the_command_carries_the_documented_flags(self) -> None:+ command, _, _ = self.build(bootstrap=1000, n_threads=4)+ self.assertEqual(command[0], "iqtree2")+ pairs = {+ "-s": str(self.root / "aligned.fasta"),+ "--prefix": str(self.root / "run"),+ # TEST selects the substitution model instead of assuming one.+ "-m": "TEST",+ "-B": "1000",+ "-T": "4",+ # SH-aLRT is a second branch test alongside ultrafast bootstrap.+ "-alrt": "1000",+ }+ for flag, value in pairs.items():+ with self.subTest(flag=flag):+ self.assertEqual(command[command.index(flag) + 1], value)+ self.assertIn("--redo", command)++ def test_the_bootstrap_and_thread_counts_are_not_hardcoded(self) -> None:+ command, _, _ = self.build(bootstrap=5000, n_threads=16)+ self.assertEqual(command[command.index("-B") + 1], "5000")+ self.assertEqual(command[command.index("-T") + 1], "16")++ def test_an_outgroup_is_passed_only_when_one_is_given(self) -> None:+ command, _, _ = self.build()+ self.assertNotIn("-o", command)+ command, _, _ = self.build(outgroup="Escherichia_coli")+ self.assertEqual(command[command.index("-o") + 1], "Escherichia_coli")++ def test_the_returned_path_is_iqtrees_treefile(self) -> None:+ _, tree_file, _ = self.build()+ self.assertEqual(tree_file, str(self.root / "run.treefile"))++ def test_the_selected_model_is_echoed_from_the_log(self) -> None:+ # The chosen model is the one result a reader needs to report, and it+ # only exists in IQ-TREE's log file.+ (self.root / "run.log").write_text(+ "Reading alignment\nBest-fit model: GTR+F+I+G4 chosen according to BIC\n",+ encoding="utf-8",+ )+ _, _, output = self.build()+ self.assertIn("Best-fit model: GTR+F+I+G4", output)++ def test_a_missing_log_is_not_an_error(self) -> None:+ _, tree_file, output = self.build()+ self.assertTrue(tree_file)+ self.assertNotIn("Best-fit model", output)++ def test_an_iqtree_failure_is_raised(self) -> None:+ alignment = self.root / "aligned.fasta"+ alignment.write_text(">a\nACGT\n", encoding="utf-8")+ with recorded(Recorder(returncode=2, stderr="ERROR: too few sites")):+ with contextlib.redirect_stdout(io.StringIO()):+ with self.assertRaisesRegex(RuntimeError, "IQ-TREE failed"):+ pipeline.run_iqtree(str(alignment), str(self.root / "run"))+++class FastTreeCommandTests(ScratchCase):+ def build(self, seq_type: str) -> list[str]:+ alignment = self.root / "aligned.fasta"+ alignment.write_text(">a\nACGT\n", encoding="utf-8")+ with recorded(Recorder()) as recorder:+ with contextlib.redirect_stdout(io.StringIO()):+ pipeline.run_fasttree(+ str(alignment), str(self.root / "out.tree"), seq_type=seq_type+ )+ return recorder.command++ def test_nucleotides_get_the_nucleotide_model(self) -> None:+ # -nt switches FastTree out of its protein default, and GTR is only+ # defined for nucleotides.+ command = self.build("nt")+ self.assertEqual(command[:4], ["FastTree", "-nt", "-gtr", "-gamma"])++ def test_amino_acids_get_a_protein_model_and_no_nucleotide_flag(self) -> None:+ # Passing -nt on protein data makes FastTree read every residue as an+ # ambiguous base, so the flag must be absent here.+ command = self.build("aa")+ self.assertEqual(command[:3], ["FastTree", "-lg", "-gamma"])+ self.assertNotIn("-nt", command)+ self.assertNotIn("-gtr", command)++ def test_the_alignment_is_the_final_argument(self) -> None:+ for seq_type in ("nt", "aa"):+ with self.subTest(seq_type=seq_type):+ self.assertEqual(+ self.build(seq_type)[-1], str(self.root / "aligned.fasta")+ )++ def test_the_tree_path_is_returned_and_created(self) -> None:+ alignment = self.root / "aligned.fasta"+ alignment.write_text(">a\nACGT\n", encoding="utf-8")+ destination = self.root / "out.tree"+ with recorded(Recorder()):+ with contextlib.redirect_stdout(io.StringIO()):+ returned = pipeline.run_fasttree(str(alignment), str(destination))+ self.assertEqual(returned, str(destination))+ self.assertTrue(destination.exists())++ def test_a_fasttree_failure_is_raised(self) -> None:+ alignment = self.root / "aligned.fasta"+ alignment.write_text(">a\nACGT\n", encoding="utf-8")+ with recorded(Recorder(returncode=1, stderr="FastTree: no sequences")):+ with contextlib.redirect_stdout(io.StringIO()):+ with self.assertRaisesRegex(RuntimeError, "FastTree failed"):+ pipeline.run_fasttree(str(alignment), str(self.root / "out.tree"))+++class DependencyCheckTests(unittest.TestCase):+ def test_a_complete_toolchain_reports_success_and_returns(self) -> None:+ buffer = io.StringIO()+ with recorded(Recorder(returncode=0)) as recorder:+ with contextlib.redirect_stdout(buffer):+ pipeline.check_dependencies()+ self.assertIn("All dependencies found", buffer.getvalue())+ # Both binaries are probed, not just the first.+ self.assertEqual(+ [call[1] for call in recorder.calls], ["mafft", "iqtree2"]+ )++ def test_a_missing_tool_exits_with_its_install_command(self) -> None:+ buffer = io.StringIO()+ with recorded(Recorder(failing="iqtree2")):+ with contextlib.redirect_stdout(buffer):+ with self.assertRaises(SystemExit) as raised:+ pipeline.check_dependencies()+ self.assertEqual(raised.exception.code, 1)+ report = buffer.getvalue()+ self.assertIn("Missing dependencies", report)+ self.assertIn("conda install -c bioconda iqtree", report)+ # mafft was present, so it must not be listed as missing.+ self.assertNotIn("bioconda mafft", report)++ def test_every_tool_is_probed_by_name_on_the_path(self) -> None:+ with recorded(Recorder(returncode=0)) as recorder:+ with contextlib.redirect_stdout(io.StringIO()):+ pipeline.check_dependencies()+ for call in recorder.calls:+ self.assertEqual(call[0], "which")+++class TreeSummaryTests(ScratchCase):+ def test_the_summary_matches_the_newick_string(self) -> None:+ pytest.importorskip("ete3", reason="tree summaries need ete3")+ with contextlib.redirect_stdout(io.StringIO()):+ stats = pipeline.tree_summary(str(self.newick()))+ self.assertEqual(stats["n_taxa"], 4)+ # Midpoint rooting relocates the root along an existing branch, splitting+ # it in two, so the total length is unchanged at 1+1+1+1+2+2 = 8.+ self.assertAlmostEqual(stats["total_branch_length"], 8.0)+ self.assertAlmostEqual(stats["max_branch_length"], 2.0)+ # Six non-zero branches survive rerooting, so the mean is 8/6.+ self.assertAlmostEqual(stats["mean_branch_length"], 8 / 6)++ def test_the_mean_is_consistent_with_the_total(self) -> None:+ pytest.importorskip("ete3", reason="tree summaries need ete3")+ with contextlib.redirect_stdout(io.StringIO()):+ stats = pipeline.tree_summary(str(self.newick("(A:0.5,(B:0.5,C:1.5):0.5);")))+ self.assertEqual(stats["n_taxa"], 3)+ self.assertAlmostEqual(stats["total_branch_length"], 3.0)+ self.assertLessEqual(stats["mean_branch_length"], stats["max_branch_length"])++ def test_an_unreadable_tree_returns_an_empty_summary(self) -> None:+ # tree_summary is called for its report, so a bad tree file must not+ # abort a pipeline that has already produced its outputs.+ buffer = io.StringIO()+ with contextlib.redirect_stdout(buffer):+ self.assertEqual(pipeline.tree_summary(str(self.root / "absent.nwk")), {})+ self.assertIn("Could not compute tree stats", buffer.getvalue())++ def test_malformed_newick_returns_an_empty_summary(self) -> None:+ malformed = self.root / "bad.nwk"+ malformed.write_text("((A:1,B:1)\n", encoding="utf-8")+ with contextlib.redirect_stdout(io.StringIO()):+ self.assertEqual(pipeline.tree_summary(str(malformed)), {})+++class VisualisationTests(ScratchCase):+ def test_the_rooting_choice_is_reported(self) -> None:+ ete3 = pytest.importorskip("ete3", reason="visualisation needs ete3")+ if not hasattr(ete3, "TreeStyle"):+ self.skipTest("ete3's Qt treeview is unavailable, so rooting is not reached")+ for outgroup, expected in (("A", "Rooted at outgroup: A"), ("Z", "midpoint")):+ with self.subTest(outgroup=outgroup):+ buffer = io.StringIO()+ with contextlib.redirect_stdout(buffer):+ pipeline.visualize_tree(+ str(self.newick()),+ str(self.root / f"{outgroup}.png"),+ outgroup=outgroup,+ )+ self.assertIn(expected, buffer.getvalue())++ def test_a_missing_qt_backend_names_the_package_it_needs(self) -> None:+ ete3 = pytest.importorskip("ete3", reason="visualisation needs ete3")+ if hasattr(ete3, "TreeStyle"):+ self.skipTest("ete3's Qt treeview is installed, so the hint is not reached")+ # ete3 imports fine without PyQt5 but cannot render, so the diagnostic+ # has to name PyQt5 rather than tell the user to install ete3 again.+ buffer = io.StringIO()+ with contextlib.redirect_stdout(buffer):+ self.assertIsNone(+ pipeline.visualize_tree(str(self.newick()), str(self.root / "t.png"))+ )+ report = buffer.getvalue()+ self.assertIn("PyQt5", report)+ self.assertIn("Skipping visualization", report)+++class PipelineWiringTests(ScratchCase):+ """`main` end to end with every external tool replaced by a recorder."""++ def run_pipeline(self, extra: list[str] | None = None) -> tuple[Recorder, mock.Mock]:+ source = self.fasta(5, "in.fasta")+ output_dir = self.root / "results"+ argv = [+ "phylogenetic_analysis.py",+ str(source),+ "--output-dir",+ str(output_dir),+ *(extra or []),+ ]+ recorder = Recorder()+ with mock.patch.object(pipeline.subprocess, "run", recorder), mock.patch.object(+ pipeline, "visualize_tree"+ ) as visualise, mock.patch.object(+ pipeline, "tree_summary", return_value={}+ ), mock.patch.object(sys, "argv", argv):+ with contextlib.redirect_stdout(io.StringIO()):+ pipeline.main()+ self.assertTrue(output_dir.is_dir())+ return recorder, visualise++ def test_the_default_run_is_align_then_iqtree(self) -> None:+ recorder, visualise = self.run_pipeline()+ self.assertEqual([call[0] for call in recorder.calls], ["mafft", "iqtree2"])+ # IQ-TREE must be handed MAFFT's *output*, not the unaligned input.+ aligned = str(self.root / "results" / "in_aligned.fasta")+ iqtree = recorder.calls[1]+ self.assertEqual(iqtree[iqtree.index("-s") + 1], aligned)+ visualise.assert_called_once()+ self.assertEqual(+ visualise.call_args.args,+ (+ str(self.root / "results" / "in.treefile"),+ str(self.root / "results" / "in_tree.png"),+ ),+ )++ def test_fasttree_replaces_iqtree_rather_than_running_alongside_it(self) -> None:+ recorder, _ = self.run_pipeline(["--fasttree"])+ self.assertEqual([call[0] for call in recorder.calls], ["mafft", "FastTree"])++ def test_the_sequence_type_reaches_fasttrees_model_choice(self) -> None:+ recorder, _ = self.run_pipeline(["--fasttree", "--type", "aa"])+ self.assertIn("-lg", recorder.calls[1])+ self.assertNotIn("-nt", recorder.calls[1])++ def test_the_outgroup_reaches_both_iqtree_and_the_visualisation(self) -> None:+ recorder, visualise = self.run_pipeline(["--outgroup", "Outgroup_sp"])+ iqtree = recorder.calls[1]+ self.assertEqual(iqtree[iqtree.index("-o") + 1], "Outgroup_sp")+ self.assertEqual(visualise.call_args.kwargs["outgroup"], "Outgroup_sp")++ def test_an_unsupported_sequence_type_is_refused_before_any_tool_runs(self) -> None:+ recorder = Recorder()+ argv = ["phylogenetic_analysis.py", str(self.fasta(5, "in.fasta")), "--type", "protein"]+ with mock.patch.object(pipeline.subprocess, "run", recorder), mock.patch.object(+ sys, "argv", argv+ ):+ with contextlib.redirect_stderr(io.StringIO()):+ with self.assertRaises(SystemExit) as raised:+ pipeline.main()+ self.assertEqual(raised.exception.code, 2)+ self.assertEqual(recorder.calls, [])++ def test_an_unsupported_mafft_method_is_refused(self) -> None:+ # An unknown method would otherwise be interpolated straight into+ # `--{method}` and reach MAFFT as an invalid flag.+ recorder = Recorder()+ argv = [+ "phylogenetic_analysis.py",+ str(self.fasta(5, "in.fasta")),+ "--mafft-method",+ "hmmalign",+ ]+ with mock.patch.object(pipeline.subprocess, "run", recorder), mock.patch.object(+ sys, "argv", argv+ ):+ with contextlib.redirect_stderr(io.StringIO()):+ with self.assertRaises(SystemExit):+ pipeline.main()+ self.assertEqual(recorder.calls, [])+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/pkpd-modeling/test_scripts.py b/tests/pkpd-modeling/test_scripts.pyindex 426d2926..757fbe15 100644--- a/tests/pkpd-modeling/test_scripts.py+++ b/tests/pkpd-modeling/test_scripts.py@@ -27,10 +27,16 @@ import tempfileimport unittestfrom pathlib import Path-import numpy as np+import pytestimport skill_contract+# The scripts import scipy indirectly through `_models`. Guarding here turns a+# bare project-environment run into a clean skip instead of a pytest+# INTERNALERROR; the real run is `tests/run_all.py --isolated pkpd-modeling`.+np = pytest.importorskip("numpy", reason="pkpd-modeling needs numpy")+pytest.importorskip("scipy", reason="pkpd-modeling needs scipy")+SKILL_ROOT = Path(__file__).resolve().parents[2] / "skills" / "pkpd-modeling"SCRIPTS = SKILL_ROOT / "scripts"FIXTURES = Path(__file__).resolve().parent / "fixtures"diff --git a/tests/pptx-posters/test_static.py b/tests/pptx-posters/test_static.pyindex 90f5ff8b..f8c932ef 100644--- a/tests/pptx-posters/test_static.py+++ b/tests/pptx-posters/test_static.py@@ -53,7 +53,7 @@ class FrontmatterTests(unittest.TestCase):self.assertRegex(text, r"(?m)^name: pptx-posters$")self.assertRegex(text, r"(?m)^license: MIT$")self.assertRegex(text, r"(?m)^compatibility: .+")- self.assertRegex(text, r"(?ms)^metadata:\n version: \"2\.1\"\n")+ self.assertRegex(text, r"(?ms)^metadata:\n version: \"\d+\.\d+\"\n")self.assertNotRegex(text, r"(?m)^metadata:\s*\{")self.assertNotIn("required_environment_variables", text)# The spec requires allowed-tools to be a space-separated string, not a YAML list.@@ -169,10 +169,6 @@ class PythonPolicyTests(unittest.TestCase):module.main(["--help"])self.assertEqual(caught.exception.code, 0)- def test_no_bytecode_artifacts(self) -> None:- self.assertEqual(list(SKILL_ROOT.rglob("*.pyc")), [])--class DocumentationPolicyTests(unittest.TestCase):def test_no_retired_service_or_script_names(self) -> None:combined = "\n".join(@@ -214,19 +210,5 @@ class DocumentationPolicyTests(unittest.TestCase):):self.assertIn(token, ledger)- def test_documented_local_paths_exist(self) -> None:- pattern = re.compile(- r"`((?:assets|references|scripts)/[A-Za-z0-9_./-]*)`"- )- for markdown in sorted(SKILL_ROOT.rglob("*.md")):- text = markdown.read_text(encoding="utf-8")- for relative in pattern.findall(text):- with self.subTest(- markdown=markdown.relative_to(SKILL_ROOT),- relative=relative,- ):- self.assertTrue((SKILL_ROOT / relative).exists())--if __name__ == "__main__":unittest.main()diff --git a/tests/pptx/test_scripts.py b/tests/pptx/test_scripts.pynew file mode 100644index 00000000..aa10f26a--- /dev/null+++ b/tests/pptx/test_scripts.py@@ -0,0 +1,236 @@+"""Tests for the pptx skill's package editors.++The shared `office/` tree is covered by the contract. What is specific here is+slide bookkeeping: `add_slide` has to pick a free slide number and a legal+slide id, and `clean` has to delete orphaned parts without deleting anything+the presentation still references.++`clean` is the dangerous one -- it removes files -- so the tests concentrate on+its refusal path. A package whose `sldIdLst` cannot be read must make the tool+stop rather than conclude that every slide is an orphan and delete the deck.+"""++from __future__ import annotations++import re+import sys+import tempfile+import unittest+from pathlib import Path++import pytest++import skill_contract++SKILL_ROOT = Path(__file__).resolve().parents[2] / "skills" / "pptx"+SCRIPTS = SKILL_ROOT / "scripts"+sys.path.insert(0, str(SCRIPTS))++pytest.importorskip("defusedxml", reason="pptx scripts need defusedxml")++import add_slide # noqa: E402+import clean # noqa: E402++OfficeTests = skill_contract.office.office_test_case(SKILL_ROOT)+CliHelpTests = skill_contract.cli.help_test_case(SKILL_ROOT)++RELATIONSHIPS_NS = "http://schemas.openxmlformats.org/package/2006/relationships"+SLIDE_TYPE = (+ "http://schemas.openxmlformats.org/officeDocument/2006/relationships/slide"+)+++class Deck:+ """A minimal unpacked .pptx directory with `count` registered slides."""++ def __init__(self, root: Path, count: int, *, orphans: int = 0) -> None:+ self.root = root+ self.slides = root / "ppt" / "slides"+ self.slides.mkdir(parents=True)+ (self.slides / "_rels").mkdir()+ (root / "ppt" / "_rels").mkdir(parents=True)++ total = count + orphans+ for number in range(1, total + 1):+ (self.slides / f"slide{number}.xml").write_text("<p:sld/>", encoding="utf-8")+ (self.slides / "_rels" / f"slide{number}.xml.rels").write_text(+ f'<Relationships xmlns="{RELATIONSHIPS_NS}"/>', encoding="utf-8"+ )++ # Only the first `count` slides are registered in the presentation.+ relationships = "".join(+ f'<Relationship Id="rId{n}" Type="{SLIDE_TYPE}" Target="slides/slide{n}.xml"/>'+ for n in range(1, total + 1)+ )+ (root / "ppt" / "_rels" / "presentation.xml.rels").write_text(+ f'<Relationships xmlns="{RELATIONSHIPS_NS}">{relationships}</Relationships>',+ encoding="utf-8",+ )+ slide_ids = "".join(+ f'<p:sldId id="{255 + n}" r:id="rId{n}"/>' for n in range(1, count + 1)+ )+ (root / "ppt" / "presentation.xml").write_text(+ '<p:presentation xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main"'+ ' xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">'+ f"<p:sldIdLst>{slide_ids}</p:sldIdLst></p:presentation>",+ encoding="utf-8",+ )+++class DeckTestCase(unittest.TestCase):+ def setUp(self) -> None:+ self._temporary = tempfile.TemporaryDirectory()+ self.addCleanup(self._temporary.cleanup)+ self.root = Path(self._temporary.name)+++class SlideNumberingTests(DeckTestCase):+ def test_the_first_slide_in_an_empty_deck_is_one(self) -> None:+ slides = self.root / "slides"+ slides.mkdir()+ self.assertEqual(add_slide.get_next_slide_number(slides), 1)++ def test_the_next_number_follows_the_highest_existing_slide(self) -> None:+ slides = self.root / "slides"+ slides.mkdir()+ for number in (1, 2, 7):+ (slides / f"slide{number}.xml").write_text("<p:sld/>", encoding="utf-8")+ # 8, not 4: reusing a gap would collide with a relationship target.+ self.assertEqual(add_slide.get_next_slide_number(slides), 8)++ def test_files_that_are_not_slides_are_ignored(self) -> None:+ slides = self.root / "slides"+ slides.mkdir()+ (slides / "slide1.xml").write_text("<p:sld/>", encoding="utf-8")+ (slides / "slideLayout9.xml").write_text("<p:sldLayout/>", encoding="utf-8")+ (slides / "notes.xml").write_text("<x/>", encoding="utf-8")+ self.assertEqual(add_slide.get_next_slide_number(slides), 2)+++class SourceParsingTests(unittest.TestCase):+ def test_a_layout_filename_is_recognised(self) -> None:+ self.assertEqual(+ add_slide.parse_source("slideLayout2.xml"), ("layout", "slideLayout2.xml")+ )++ def test_anything_else_is_treated_as_a_slide_source(self) -> None:+ for source in ("deck.pptx", "slideLayout2", "layout.xml", ""):+ with self.subTest(source=source):+ self.assertEqual(add_slide.parse_source(source), ("slide", None))+++class SlideIdTests(unittest.TestCase):+ def test_the_id_range_matches_the_ooxml_specification(self) -> None:+ # Outside 256..2147483647 PowerPoint refuses to open the file.+ self.assertEqual(add_slide.SLIDE_ID_MIN, 256)+ self.assertEqual(add_slide.SLIDE_ID_MAX, 2147483647)++ def test_the_minimal_slide_xml_is_well_formed(self) -> None:+ import defusedxml.ElementTree as ElementTree++ ElementTree.fromstring(add_slide.MINIMAL_SLIDE_XML)++ def test_shared_part_types_are_the_documented_set(self) -> None:+ self.assertEqual(+ set(add_slide.SHARED_PART_TYPES),+ {"chart", "diagramData", "oleObject", "package"},+ )++ def test_the_relationship_pattern_matches_both_element_forms(self) -> None:+ both = (+ '<Relationship Id="rId1" Target="a.xml"/>'+ '<Relationship Id="rId2" Target="b.xml"></Relationship>'+ )+ self.assertEqual(len(add_slide.RELATIONSHIP_RE.findall(both)), 2)+++class OrphanDetectionTests(DeckTestCase):+ def test_registered_slides_are_reported_as_referenced(self) -> None:+ Deck(self.root, count=3)+ self.assertEqual(+ clean.get_slides_in_sldidlst(self.root),+ {"slide1.xml", "slide2.xml", "slide3.xml"},+ )++ def test_an_unregistered_slide_is_not_reported_as_referenced(self) -> None:+ Deck(self.root, count=2, orphans=1)+ referenced = clean.get_slides_in_sldidlst(self.root)+ self.assertEqual(referenced, {"slide1.xml", "slide2.xml"})++ def test_only_the_orphan_is_removed(self) -> None:+ deck = Deck(self.root, count=2, orphans=1)+ removed = clean.remove_orphaned_slides(self.root)++ # The slide and its relationship part are both reported.+ self.assertEqual(+ sorted(Path(name).name for name in removed),+ ["slide3.xml", "slide3.xml.rels"],+ )+ self.assertTrue((deck.slides / "slide1.xml").is_file())+ self.assertTrue((deck.slides / "slide2.xml").is_file())+ self.assertFalse((deck.slides / "slide3.xml").is_file())++ def test_a_deck_with_no_orphans_loses_nothing(self) -> None:+ deck = Deck(self.root, count=3)+ self.assertEqual(clean.remove_orphaned_slides(self.root), [])+ self.assertEqual(len(list(deck.slides.glob("slide*.xml"))), 3)++ def test_a_package_with_no_slides_directory_is_a_no_op(self) -> None:+ self.assertEqual(clean.remove_orphaned_slides(self.root), [])++ def test_an_unreadable_presentation_refuses_rather_than_deleting_everything(+ self,+ ) -> None:+ # If sldIdLst cannot be parsed, every slide looks orphaned. Deleting+ # them would destroy the deck, so the tool must refuse instead.+ deck = Deck(self.root, count=3)+ # sldIdLst still lists three slides, but every r:id now points at a+ # relationship that does not exist -- exactly what a parse failure+ # looks like from here.+ (self.root / "ppt" / "presentation.xml").write_text(+ '<p:presentation xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main"'+ ' xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">'+ "<p:sldIdLst>"+ '<p:sldId id="256" r:id="rIdMissing1"/>'+ '<p:sldId id="257" r:id="rIdMissing2"/>'+ '<p:sldId id="258" r:id="rIdMissing3"/>'+ "</p:sldIdLst></p:presentation>",+ encoding="utf-8",+ )+ with self.assertRaises(clean.RefusedToClean):+ clean.remove_orphaned_slides(self.root)+ self.assertEqual(len(list(deck.slides.glob("slide*.xml"))), 3)++ def test_the_rels_file_goes_with_its_slide(self) -> None:+ deck = Deck(self.root, count=1, orphans=1)+ clean.remove_orphaned_slides(self.root)+ self.assertFalse((deck.slides / "_rels" / "slide2.xml.rels").is_file())+ self.assertTrue((deck.slides / "_rels" / "slide1.xml.rels").is_file())+++class TrashRemovalTests(DeckTestCase):+ def test_a_trash_directory_is_removed(self) -> None:+ # The directory PowerPoint leaves behind is literally named "[trash]".+ trash = self.root / "[trash]"+ trash.mkdir()+ (trash / "leftover.xml").write_text("<x/>", encoding="utf-8")+ removed = clean.remove_trash_directory(self.root)+ self.assertEqual([Path(name).name for name in removed], ["leftover.xml"])+ self.assertFalse(trash.exists())++ def test_a_package_without_one_is_untouched(self) -> None:+ self.assertEqual(clean.remove_trash_directory(self.root), [])+++class ThumbnailConstantTests(unittest.TestCase):+ def test_the_grid_constants_are_sane(self) -> None:+ import thumbnail++ self.assertGreater(thumbnail.THUMBNAIL_WIDTH, 0)+ self.assertGreater(thumbnail.CONVERSION_DPI, 0)+ self.assertLessEqual(thumbnail.DEFAULT_COLS, thumbnail.MAX_COLS)+ self.assertTrue(0 < thumbnail.JPEG_QUALITY <= 100)+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/primekg/test_scripts.py b/tests/primekg/test_scripts.pynew file mode 100644index 00000000..01290836--- /dev/null+++ b/tests/primekg/test_scripts.py@@ -0,0 +1,188 @@+"""Tests for the PrimeKG query helpers.++PrimeKG itself is a ~4 million edge CSV nobody should download to run a test,+so these drive the same code against a small hand-built edge list with the+real column layout (`x_id, x_type, x_name, x_source, relation,+display_relation, y_*`). The queries treat the graph as undirected -- a node+can appear on either side of an edge -- and that symmetry is the easiest thing+to get wrong, so most of the assertions are about it.+"""++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" / "primekg"+SCRIPTS = SKILL_ROOT / "scripts"+sys.path.insert(0, str(SCRIPTS))++pytest.importorskip("pandas", reason="primekg needs pandas")++import query_primekg # noqa: E402++EDGES = """\+x_id,x_type,x_name,x_source,relation,display_relation,y_id,y_type,y_name,y_source+7157,gene/protein,TP53,NCBI,protein_protein,interacts with,672,gene/protein,BRCA1,NCBI+D001,disease,Breast Cancer,MONDO,disease_protein,associated with,672,gene/protein,BRCA1,NCBI+CHEMBL1,drug,Olaparib,DrugBank,drug_protein,targets,672,gene/protein,BRCA1,NCBI+D001,disease,Breast Cancer,MONDO,disease_phenotype,presents,HP001,phenotype,Breast Mass,HPO+D001,disease,Breast Cancer,MONDO,disease_disease,related to,D002,disease,Ovarian Cancer,MONDO+D002,disease,Ovarian Cancer,MONDO,disease_protein,associated with,7157,gene/protein,TP53,NCBI+"""+++class PrimeKgTestCase(unittest.TestCase):+ """Point DATA_PATH at a small synthetic knowledge graph."""++ def setUp(self) -> None:+ self._temporary = tempfile.TemporaryDirectory()+ self.addCleanup(self._temporary.cleanup)+ self.data = Path(self._temporary.name) / "kg.csv"+ self.data.write_text(EDGES, encoding="utf-8")+ patcher = mock.patch.object(query_primekg, "DATA_PATH", str(self.data))+ patcher.start()+ self.addCleanup(patcher.stop)+++class DataPathTests(unittest.TestCase):+ def test_the_default_path_is_relative_and_env_overridable(self) -> None:+ # A hardcoded absolute path would name one machine and work on no other.+ self.assertFalse(Path(query_primekg.DATA_PATH).is_absolute())++ with mock.patch.dict("os.environ", {"PRIMEKG_DATA": "/somewhere/kg.csv"}):+ import importlib++ reloaded = importlib.reload(query_primekg)+ self.assertEqual(reloaded.DATA_PATH, "/somewhere/kg.csv")+ importlib.reload(query_primekg)++ def test_a_missing_file_explains_where_to_get_the_data(self) -> None:+ with mock.patch.object(query_primekg, "DATA_PATH", "/no/such/kg.csv"):+ with self.assertRaises(FileNotFoundError) as raised:+ query_primekg._load_kg()+ message = str(raised.exception)+ self.assertIn("/no/such/kg.csv", message)+ self.assertIn("PRIMEKG_DATA", message)+++class SearchTests(PrimeKgTestCase):+ def test_nodes_are_found_on_either_side_of_an_edge(self) -> None:+ # TP53 appears as x in one row and as y in another; one record either way.+ results = query_primekg.search_nodes("TP53")+ self.assertEqual(len(results), 1)+ # PrimeKG mixes numeric gene ids with string disease ids in one column,+ # so pandas reads it as object dtype and ids come back as strings --+ # which is why get_neighbors coerces with str() before comparing.+ self.assertEqual(str(results[0]["id"]), "7157")+ self.assertEqual(results[0]["type"], "gene/protein")++ def test_search_is_case_insensitive_and_substring_based(self) -> None:+ for query in ("breast cancer", "BREAST", "east Can"):+ with self.subTest(query=query):+ names = {row["name"] for row in query_primekg.search_nodes(query)}+ self.assertIn("Breast Cancer", names)++ def test_a_type_filter_narrows_the_result(self) -> None:+ # "Breast" matches both the disease and the phenotype.+ unfiltered = {row["name"] for row in query_primekg.search_nodes("Breast")}+ self.assertEqual(unfiltered, {"Breast Cancer", "Breast Mass"})++ filtered = query_primekg.search_nodes("Breast", node_type="phenotype")+ self.assertEqual([row["name"] for row in filtered], ["Breast Mass"])++ def test_no_match_returns_an_empty_list(self) -> None:+ self.assertEqual(query_primekg.search_nodes("no-such-gene"), [])++ def test_results_carry_the_source_database(self) -> None:+ self.assertEqual(query_primekg.search_nodes("Olaparib")[0]["source"], "DrugBank")+++class NeighborTests(PrimeKgTestCase):+ def test_neighbors_are_collected_from_both_directions(self) -> None:+ # BRCA1 is only ever a y-node, so a one-sided query would return none.+ neighbors = query_primekg.get_neighbors(672)+ names = {row["neighbor_name"] for row in neighbors}+ self.assertEqual(names, {"TP53", "Breast Cancer", "Olaparib"})++ def test_a_node_id_is_matched_as_a_string_or_a_number(self) -> None:+ self.assertEqual(+ len(query_primekg.get_neighbors(672)),+ len(query_primekg.get_neighbors("672")),+ )++ def test_a_relation_filter_restricts_the_edge_type(self) -> None:+ targeted = query_primekg.get_neighbors(672, relation_type="drug_protein")+ self.assertEqual([row["neighbor_name"] for row in targeted], ["Olaparib"])++ def test_the_display_relation_is_carried_through(self) -> None:+ targeted = query_primekg.get_neighbors(672, relation_type="drug_protein")+ self.assertEqual(targeted[0]["display_relation"], "targets")++ def test_an_unknown_node_has_no_neighbors(self) -> None:+ self.assertEqual(query_primekg.get_neighbors("not-a-node"), [])+++class PathTests(PrimeKgTestCase):+ def test_a_direct_edge_is_returned_as_a_one_hop_path(self) -> None:+ paths = query_primekg.find_paths("D001", "672")+ self.assertEqual(len(paths), 1)+ self.assertEqual(len(paths[0]), 1)+ self.assertEqual(paths[0][0]["relation"], "disease_protein")++ def test_direction_does_not_matter(self) -> None:+ self.assertEqual(+ len(query_primekg.find_paths("D001", "672")),+ len(query_primekg.find_paths("672", "D001")),+ )++ def test_unconnected_nodes_yield_no_path(self) -> None:+ self.assertEqual(query_primekg.find_paths("CHEMBL1", "HP001"), [])++ def test_two_hop_search_is_documented_as_unimplemented(self) -> None:+ # The depth-2 branch is a stub; assert the current contract rather than+ # a capability the script does not have.+ self.assertEqual(query_primekg.find_paths("CHEMBL1", "D001", max_depth=2), [])+++class DiseaseContextTests(PrimeKgTestCase):+ def test_the_context_is_bucketed_by_neighbour_type(self) -> None:+ context = query_primekg.get_disease_context("Breast Cancer")+ self.assertEqual(context["disease_info"]["name"], "Breast Cancer")+ self.assertEqual(+ [row["neighbor_name"] for row in context["associated_genes"]], ["BRCA1"]+ )+ self.assertEqual(+ [row["neighbor_name"] for row in context["phenotypes"]], ["Breast Mass"]+ )+ self.assertEqual(+ [row["neighbor_name"] for row in context["related_diseases"]],+ ["Ovarian Cancer"],+ )++ def test_a_disease_with_no_drug_edges_reports_an_empty_bucket(self) -> None:+ context = query_primekg.get_disease_context("Breast Cancer")+ self.assertEqual(context["associated_drugs"], [])++ def test_an_unknown_disease_reports_an_error_rather_than_raising(self) -> None:+ self.assertEqual(+ query_primekg.get_disease_context("no-such-disease"),+ {"error": "Disease not found"},+ )++ def test_a_gene_name_is_not_mistaken_for_a_disease(self) -> None:+ # search_nodes is type-filtered to 'disease', so a gene must not match.+ self.assertEqual(+ query_primekg.get_disease_context("TP53"), {"error": "Disease not found"}+ )+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/pydeseq2/test_scripts.py b/tests/pydeseq2/test_scripts.pynew file mode 100644index 00000000..f79104fb--- /dev/null+++ b/tests/pydeseq2/test_scripts.py@@ -0,0 +1,410 @@+"""Tests for the PyDESeq2 analysis driver.++Everything expensive in this script happens inside PyDESeq2; what the script+itself owns is the data handling around it, and each piece of that is a way to+get a plausible-looking but wrong answer:++* orientation -- the counts file is genes x samples and DESeq2 wants samples x+ genes, so a transposition mistake silently analyses genes as if they were+ samples;+* alignment -- counts and metadata must end up on the same index in the same+ order, or every sample is compared against another sample's condition;+* the shrinkage coefficient -- `condition[T.treated]` is a formulaic naming+ convention, and the test below checks it against a design matrix PyDESeq2+ actually built rather than against the string the script composes;+* thresholds -- gene filtering is `>=` and significance is a strict `<`, both+ pinned at the boundary here.++One end-to-end fit runs on a synthetic dataset with a known 8-fold change, so+the pipeline is checked against log2(8) = 3 rather than against itself.+"""++from __future__ import annotations++import sys+import tempfile+import unittest+from pathlib import Path++import pytest++import skill_contract++SKILL_ROOT = Path(__file__).resolve().parents[2] / "skills" / "pydeseq2"+SCRIPTS = SKILL_ROOT / "scripts"+sys.path.insert(0, str(SCRIPTS))++np = pytest.importorskip("numpy", reason="pydeseq2 scripts need numpy")+pd = pytest.importorskip("pandas", reason="pydeseq2 scripts need pandas")+pytest.importorskip("pydeseq2", reason="pydeseq2 skill needs pydeseq2")+anndata = pytest.importorskip("anndata", reason="save_results writes an .h5ad")+matplotlib = pytest.importorskip("matplotlib", reason="create_plots needs matplotlib")++matplotlib.use("Agg") # never open a window; must precede pyplot import+import matplotlib.pyplot as plt # noqa: E402++import run_deseq2_analysis as driver # noqa: E402++CliHelpTests = skill_contract.cli.help_test_case(SKILL_ROOT)+++class TemporaryDirectoryTestCase(unittest.TestCase):+ def setUp(self) -> None:+ self._temporary = tempfile.TemporaryDirectory()+ self.addCleanup(self._temporary.cleanup)+ self.root = Path(self._temporary.name)++ def write_csv(self, name: str, frame: pd.DataFrame) -> Path:+ path = self.root / name+ frame.to_csv(path)+ return path+++class LoadAndValidateTests(TemporaryDirectoryTestCase):+ """The counts file is genes x samples; DESeq2 needs samples x genes."""++ def setUp(self) -> None:+ super().setUp()+ # Two genes, three samples. GENE1 in s3 is 6 -- a unique value, so the+ # orientation of the result can be checked by where it lands.+ self.counts = pd.DataFrame(+ {"s1": [1, 10], "s2": [2, 20], "s3": [6, 30]},+ index=["GENE1", "GENE2"],+ )+ self.metadata = pd.DataFrame(+ {"condition": ["control", "control", "treated"]},+ index=["s1", "s2", "s3"],+ )+ self.counts_path = self.write_csv("counts.csv", self.counts)+ self.metadata_path = self.write_csv("metadata.csv", self.metadata)++ def test_the_counts_matrix_is_transposed_by_default(self) -> None:+ counts, metadata = driver.load_and_validate_data(+ self.counts_path, self.metadata_path+ )+ self.assertEqual(list(counts.index), ["s1", "s2", "s3"])+ self.assertEqual(list(counts.columns), ["GENE1", "GENE2"])+ # The value that was at (GENE1, s3) must now be at (s3, GENE1).+ self.assertEqual(counts.loc["s3", "GENE1"], 6)+ self.assertEqual(list(metadata.index), ["s1", "s2", "s3"])++ def test_an_already_oriented_matrix_is_left_alone(self) -> None:+ path = self.write_csv("oriented.csv", self.counts.T)+ counts, _ = driver.load_and_validate_data(+ path, self.metadata_path, transpose_counts=False+ )+ self.assertEqual(list(counts.index), ["s1", "s2", "s3"])+ self.assertEqual(counts.loc["s3", "GENE1"], 6)++ def test_negative_counts_are_rejected(self) -> None:+ # DESeq2's negative-binomial model has no meaning for negative counts;+ # they indicate the file holds normalised or logged values.+ broken = self.counts.copy()+ broken.loc["GENE1", "s2"] = -5+ with self.assertRaisesRegex(ValueError, "negative values"):+ driver.load_and_validate_data(+ self.write_csv("negative.csv", broken), self.metadata_path+ )++ def test_zero_counts_are_accepted(self) -> None:+ # Zero is a legitimate observation -- only negatives are invalid.+ zeroed = self.counts.copy()+ zeroed.loc["GENE1", "s2"] = 0+ counts, _ = driver.load_and_validate_data(+ self.write_csv("zeroed.csv", zeroed), self.metadata_path+ )+ self.assertEqual(counts.loc["s2", "GENE1"], 0)++ def test_extra_metadata_samples_are_dropped_to_the_intersection(self) -> None:+ # Unequal lengths: element-wise index comparison raises here, so this+ # is the case the intersection fallback exists for.+ extra = pd.DataFrame(+ {"condition": ["control", "control", "treated", "treated"]},+ index=["s1", "s2", "s3", "s4"],+ )+ counts, metadata = driver.load_and_validate_data(+ self.counts_path, self.write_csv("extra.csv", extra)+ )+ self.assertEqual(list(counts.index), ["s1", "s2", "s3"])+ self.assertEqual(list(metadata.index), ["s1", "s2", "s3"])++ def test_extra_count_samples_are_dropped_to_the_intersection(self) -> None:+ wider = self.counts.copy()+ wider["s4"] = [7, 40]+ counts, metadata = driver.load_and_validate_data(+ self.write_csv("wider.csv", wider), self.metadata_path+ )+ self.assertEqual(list(counts.index), ["s1", "s2", "s3"])+ self.assertTrue(counts.index.equals(metadata.index))++ def test_a_reordered_metadata_index_is_realigned_not_left_shuffled(self) -> None:+ # Same samples, different order. If the two frames were handed to+ # DESeq2 as-is, every sample would carry another sample's condition.+ shuffled = self.metadata.loc[["s3", "s1", "s2"]]+ counts, metadata = driver.load_and_validate_data(+ self.counts_path, self.write_csv("shuffled.csv", shuffled)+ )+ self.assertTrue(counts.index.equals(metadata.index))+ self.assertEqual(metadata.loc["s3", "condition"], "treated")++ def test_a_matching_pair_survives_untouched(self) -> None:+ counts, metadata = driver.load_and_validate_data(+ self.counts_path, self.metadata_path+ )+ self.assertEqual(counts.shape, (3, 2))+ self.assertEqual(metadata.shape, (3, 1))+++class FilterDataTests(unittest.TestCase):+ def setUp(self) -> None:+ # Column totals: KEEP 30, EDGE 10, DROP 9.+ self.counts = pd.DataFrame(+ {"KEEP": [10, 10, 10], "EDGE": [5, 5, 0], "DROP": [3, 3, 3]},+ index=["s1", "s2", "s3"],+ )+ self.metadata = pd.DataFrame(+ {"condition": ["control", "treated", "treated"]},+ index=["s1", "s2", "s3"],+ )++ def test_genes_below_the_total_count_threshold_are_removed(self) -> None:+ counts, _ = driver.filter_data(self.counts, self.metadata, min_counts=10)+ self.assertEqual(list(counts.columns), ["KEEP", "EDGE"])++ def test_the_threshold_is_inclusive_at_the_boundary(self) -> None:+ # EDGE totals exactly 10; `>=` keeps it and `>` would not.+ counts, _ = driver.filter_data(self.counts, self.metadata, min_counts=10)+ self.assertIn("EDGE", counts.columns)+ counts, _ = driver.filter_data(self.counts, self.metadata, min_counts=11)+ self.assertNotIn("EDGE", counts.columns)++ def test_a_zero_threshold_keeps_every_gene(self) -> None:+ counts, _ = driver.filter_data(self.counts, self.metadata, min_counts=0)+ self.assertEqual(list(counts.columns), ["KEEP", "EDGE", "DROP"])++ def test_samples_with_no_condition_are_dropped_from_both_frames(self) -> None:+ metadata = self.metadata.copy()+ metadata.loc["s2", "condition"] = np.nan+ counts, filtered = driver.filter_data(+ self.counts, metadata, min_counts=0, condition_col="condition"+ )+ self.assertEqual(list(counts.index), ["s1", "s3"])+ self.assertEqual(list(filtered.index), ["s1", "s3"])++ def test_no_samples_are_dropped_when_the_column_is_absent(self) -> None:+ counts, metadata = driver.filter_data(+ self.counts, self.metadata, min_counts=0, condition_col="batch"+ )+ self.assertEqual(len(counts.index), 3)+ self.assertEqual(len(metadata.index), 3)++ def test_gene_filtering_does_not_disturb_the_sample_axis(self) -> None:+ counts, metadata = driver.filter_data(+ self.counts, self.metadata, min_counts=10, condition_col="condition"+ )+ self.assertTrue(counts.index.equals(metadata.index))+++class ShrinkageCoefficientTests(unittest.TestCase):+ """`condition[T.treated]` is formulaic's name for the contrast column."""++ class FakeDataSet:+ def __init__(self, columns: list[str]) -> None:+ self.obsm = {"design_matrix": pd.DataFrame(columns=columns)}++ def test_the_coefficient_name_follows_the_design_matrix(self) -> None:+ dds = self.FakeDataSet(["Intercept", "condition[T.treated]"])+ self.assertEqual(+ driver.infer_shrink_coeff(dds, ["condition", "treated", "control"]),+ "condition[T.treated]",+ )++ def test_an_absent_coefficient_raises_and_names_the_alternatives(self) -> None:+ # Reference level as the test level is the classic mistake; the error+ # has to show what the design actually offers.+ dds = self.FakeDataSet(["Intercept", "condition[T.treated]"])+ with self.assertRaises(ValueError) as raised:+ driver.infer_shrink_coeff(dds, ["condition", "control", "treated"])+ message = str(raised.exception)+ self.assertIn("condition[T.control]", message)+ self.assertIn("condition[T.treated]", message)+ self.assertIn("--no-shrink", message)++ def test_a_multi_factor_design_resolves_the_requested_variable_only(self) -> None:+ dds = self.FakeDataSet(+ ["Intercept", "batch[T.b2]", "condition[T.treated]"]+ )+ self.assertEqual(+ driver.infer_shrink_coeff(dds, ["condition", "treated", "control"]),+ "condition[T.treated]",+ )+++class FakeStats:+ """A `DeseqStats` stand-in exposing only `results_df`."""++ def __init__(self, results: pd.DataFrame) -> None:+ self.results_df = results+++class FakeDataSet:+ """A `DeseqDataSet` stand-in whose h5ad export is a real AnnData."""++ def __init__(self, samples: int = 2, genes: int = 3) -> None:+ self._adata = anndata.AnnData(+ X=np.arange(samples * genes, dtype="float32").reshape(samples, genes)+ )++ def to_picklable_anndata(self):+ return self._adata+++def results_frame() -> pd.DataFrame:+ """Four genes spanning the significance boundary, plus a filtered-out gene."""+ return pd.DataFrame(+ {+ "baseMean": [500.0, 100.0, 80.0, 60.0],+ "log2FoldChange": [3.0, -2.0, 0.1, 0.5],+ "pvalue": [1e-30, 1e-10, 0.4, np.nan],+ # 0.05 exactly must NOT count as significant: the test is `< 0.05`.+ "padj": [1e-28, 0.01, 0.05, np.nan],+ },+ index=["UP", "DOWN", "BORDERLINE", "FILTERED"],+ )+++class SaveResultsTests(TemporaryDirectoryTestCase):+ def setUp(self) -> None:+ super().setUp()+ self.results = results_frame()+ self.output = self.root / "results"+ driver.save_results(FakeStats(self.results), FakeDataSet(), self.output)++ def test_the_four_documented_artefacts_are_written(self) -> None:+ written = {path.name for path in self.output.iterdir()}+ self.assertEqual(+ written,+ {+ "deseq2_results.csv",+ "significant_genes.csv",+ "results_sorted_by_padj.csv",+ "deseq_dataset.h5ad",+ },+ )++ def test_every_gene_is_kept_in_the_full_table(self) -> None:+ full = pd.read_csv(self.output / "deseq2_results.csv", index_col=0)+ self.assertEqual(list(full.index), ["UP", "DOWN", "BORDERLINE", "FILTERED"])++ def test_only_genes_strictly_below_the_fdr_cutoff_are_significant(self) -> None:+ significant = pd.read_csv(self.output / "significant_genes.csv", index_col=0)+ # BORDERLINE sits exactly at 0.05 and FILTERED has no padj at all.+ self.assertEqual(sorted(significant.index), ["DOWN", "UP"])++ def test_the_sorted_table_puts_the_strongest_evidence_first(self) -> None:+ sorted_results = pd.read_csv(+ self.output / "results_sorted_by_padj.csv", index_col=0+ )+ self.assertEqual(list(sorted_results.index)[:2], ["UP", "DOWN"])+ # A gene with no adjusted p-value must sort last, not first.+ self.assertEqual(list(sorted_results.index)[-1], "FILTERED")++ def test_the_dataset_is_exported_as_readable_h5ad_not_a_pickle(self) -> None:+ # Pickles execute arbitrary code on load; h5ad does not.+ loaded = anndata.read_h5ad(self.output / "deseq_dataset.h5ad")+ self.assertEqual(loaded.shape, (2, 3))++ def test_a_missing_output_directory_is_created(self) -> None:+ nested = self.root / "a" / "b" / "c"+ driver.save_results(FakeStats(self.results), FakeDataSet(), nested)+ self.assertTrue((nested / "deseq2_results.csv").is_file())++ def test_no_significant_genes_still_writes_every_file(self) -> None:+ # An empty result set is a valid outcome, not an error.+ nothing = self.results.copy()+ nothing["padj"] = 0.9+ output = self.root / "none"+ driver.save_results(FakeStats(nothing), FakeDataSet(), output)+ significant = pd.read_csv(output / "significant_genes.csv", index_col=0)+ self.assertEqual(len(significant), 0)+++class PlotTests(TemporaryDirectoryTestCase):+ def setUp(self) -> None:+ super().setUp()+ self.addCleanup(plt.close, "all")+ self.results = results_frame()++ def test_both_plots_are_written_as_non_empty_files(self) -> None:+ driver.create_plots(FakeStats(self.results), self.root)+ for name in ("volcano_plot.png", "ma_plot.png"):+ with self.subTest(name=name):+ path = self.root / name+ self.assertTrue(path.is_file())+ self.assertGreater(path.stat().st_size, 0)++ def test_plotting_does_not_mutate_the_results_table(self) -> None:+ # The volcano plot adds a -log10 column; leaking it into results_df+ # would put a derived column into every file written afterwards.+ stats = FakeStats(self.results)+ driver.create_plots(stats, self.root)+ self.assertEqual(list(stats.results_df.columns), list(results_frame().columns))++ def test_genes_filtered_out_by_deseq2_do_not_break_the_plots(self) -> None:+ # padj is NaN for independent-filtered genes; -log10(NaN) would be NaN+ # and matplotlib would silently drop the point, so the script fills 1.+ only_nan = self.results.copy()+ only_nan["padj"] = np.nan+ driver.create_plots(FakeStats(only_nan), self.root)+ self.assertTrue((self.root / "volcano_plot.png").is_file())+++class EndToEndFitTests(unittest.TestCase):+ """One real fit, checked against a fold change that is true by construction."""++ @classmethod+ def setUpClass(cls) -> None:+ rng = np.random.default_rng(0)+ samples = [f"s{i}" for i in range(6)]+ genes = [f"G{j}" for j in range(40)]+ counts = rng.poisson(100, size=(6, 40))+ counts[3:, 0] *= 8 # G0 is exactly 8-fold higher in the treated group+ cls.counts = pd.DataFrame(counts, index=samples, columns=genes)+ cls.metadata = pd.DataFrame(+ {"condition": ["control"] * 3 + ["treated"] * 3}, index=samples+ )+ cls.dds, cls.inference = driver.run_deseq2(+ cls.counts, cls.metadata, "~condition", n_cpus=1+ )+ cls.stats = driver.run_statistical_tests(+ cls.dds,+ contrast=["condition", "treated", "control"],+ alpha=0.05,+ shrink_lfc=True,+ inference=cls.inference,+ )++ def test_the_inferred_coefficient_matches_the_real_design_matrix(self) -> None:+ # The whole point of infer_shrink_coeff: the composed name must exist+ # in the matrix PyDESeq2 built, not merely look plausible.+ self.assertIn(+ driver.infer_shrink_coeff(self.dds, ["condition", "treated", "control"]),+ list(self.dds.obsm["design_matrix"].columns),+ )++ def test_the_planted_eight_fold_change_is_recovered(self) -> None:+ # log2(8) == 3. Shrinkage pulls the estimate in slightly, so allow+ # half a log2 unit -- but the sign and magnitude must be right.+ lfc = self.stats.results_df.loc["G0", "log2FoldChange"]+ self.assertAlmostEqual(lfc, 3.0, delta=0.5)++ def test_the_planted_gene_is_the_only_significant_one(self) -> None:+ significant = self.stats.results_df[self.stats.results_df.padj < 0.05]+ self.assertEqual(list(significant.index), ["G0"])++ def test_every_tested_gene_gets_a_row(self) -> None:+ self.assertEqual(len(self.stats.results_df), 40)+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/pydicom/test_static.py b/tests/pydicom/test_static.pyindex 9bce7755..0ada999e 100644--- a/tests/pydicom/test_static.py+++ b/tests/pydicom/test_static.py@@ -30,7 +30,7 @@ class SkillDocumentationTests(unittest.TestCase):self.assertIn("\ncompatibility:", text)self.assertRegex(text,- r"\nmetadata:\n version: \"1\.1\"\n skill-author:",+ r"\nmetadata:\n version: \"\d+\.\d+\"\n skill-author:",)self.assertIn('last-reviewed: "2026-07-23"', text)diff --git a/tests/pymatgen/test_static.py b/tests/pymatgen/test_static.pyindex e8fa9a7d..68e7a37a 100644--- a/tests/pymatgen/test_static.py+++ b/tests/pymatgen/test_static.py@@ -21,7 +21,7 @@ class SkillStructureTests(unittest.TestCase):self.assertIn("\ncompatibility:", text)self.assertRegex(text,- r'\nmetadata:\n version: "1\.2"\n skill-author:',+ r'\nmetadata:\n version: "\d+\.\d+"\n skill-author:',)self.assertNotIn('metadata: {"version"', text)self.assertIn('last-reviewed: "2026-07-23"', text)diff --git a/tests/pymc/test_scripts.py b/tests/pymc/test_scripts.pynew file mode 100644index 00000000..51057b78--- /dev/null+++ b/tests/pymc/test_scripts.py@@ -0,0 +1,450 @@+"""Tests for the PyMC diagnostic and model-comparison helpers.++These scripts are the layer an agent trusts to say "this fit is usable" and+"this model wins", so the tests attack both halves of that. The diagnostic+branches are driven from hand-built posteriors where the right answer is known+by construction -- 2 chains of standard normal draws must pass every check, a+posterior whose every transition diverged must be flagged, and a threshold set+absurdly high must flag ESS -- which proves the checker rejects bad fits *and*+stays silent on good ones. The comparison half is anchored on data with a real+slope: a regression that includes the slope must outrank an intercept-only model+and take essentially all of the stacking weight.++Two regressions are guarded explicitly, both from the ArviZ 1.x API. `az.summary`+now formats its output for display by default, returning strings, so every+threshold comparison raised TypeError until `round_to="none"` was passed; and+ArviZ 1.x plots return a PlotCollection instead of drawing into pyplot's current+figure, so saving through `plt.savefig` produced blank images.+"""++from __future__ import annotations++import functools+import sys+import tempfile+import unittest+from pathlib import Path++import pytest++import skill_contract++SKILL_ROOT = Path(__file__).resolve().parents[2] / "skills" / "pymc"+SCRIPTS = SKILL_ROOT / "scripts"+sys.path.insert(0, str(SCRIPTS))++np = pytest.importorskip("numpy", reason="pymc scripts need numpy")+pd = pytest.importorskip("pandas", reason="pymc scripts need pandas")+az = pytest.importorskip("arviz", reason="pymc scripts need arviz")+pm = pytest.importorskip("pymc", reason="pymc scripts need pymc")+xr = pytest.importorskip("xarray", reason="pymc posteriors are xarray DataTrees")+matplotlib = pytest.importorskip("matplotlib", reason="the reports save figures")+matplotlib.use("Agg")++import matplotlib.image as mpimg # noqa: E402+import matplotlib.pyplot as plt # noqa: E402++import model_comparison # noqa: E402+import model_diagnostics # noqa: E402++# Both scripts are importable libraries: their `__main__` blocks only print+# usage text, so there is no argparse CLI to exercise and no worked example to+# run. `demo_test_case` would assert nothing beyond "print works".++# 800 independent draws: comfortably above check_diagnostics' default ESS floor+# of 400, so the default thresholds describe a fit that genuinely passes.+CHAINS, DRAWS = 2, 400+++def synthetic_posterior(+ *,+ diverging: int = 0,+ tree_depth: int = 3,+ with_energy: bool = True,+ shift_second_chain: float = 0.0,+) -> "xr.DataTree":+ """A posterior with known diagnostics, built without sampling.++ Independent standard-normal draws have R-hat ~ 1 and ESS ~ the draw count,+ so the default is a fit that must pass every check. `shift_second_chain`+ offsets one chain to force chains that disagree, which is what R-hat exists+ to catch.+ """+ generator = np.random.default_rng(0)+ draws = generator.standard_normal((CHAINS, DRAWS))+ draws[1] += shift_second_chain+ coords = {"chain": np.arange(CHAINS), "draw": np.arange(DRAWS)}+ posterior = xr.Dataset(+ {"theta": (("chain", "draw"), draws)},+ coords=coords,+ )+ statistics = {+ "diverging": (+ ("chain", "draw"),+ np.full((CHAINS, DRAWS), bool(diverging)),+ ),+ "tree_depth": (+ ("chain", "draw"),+ np.full((CHAINS, DRAWS), tree_depth),+ ),+ }+ if with_energy:+ statistics["energy"] = (+ ("chain", "draw"),+ generator.standard_normal((CHAINS, DRAWS)),+ )+ return xr.DataTree.from_dict(+ {+ "posterior": posterior,+ "sample_stats": xr.Dataset(statistics, coords=coords),+ }+ )++[email protected]_cache(maxsize=1)+def fitted_models() -> tuple:+ """One short fit per model, shared by every test that needs real MCMC.++ The data really does have slope 2, so the model that can represent a slope+ must win the comparison. Draws are kept small on purpose: nothing here needs+ a converged chain, only a coherent one.+ """+ generator = np.random.default_rng(0)+ predictor = generator.normal(size=40)+ outcome = 2.0 * predictor + generator.normal(scale=0.3, size=40)++ def fit(with_slope: bool, seed: int):+ with pm.Model():+ intercept = pm.Normal("intercept", 0, 5)+ sigma = pm.HalfNormal("sigma", 1)+ if with_slope:+ slope = pm.Normal("slope", 0, 5)+ mean = intercept + slope * predictor+ else:+ mean = intercept+ pm.Normal("y_obs", mean, sigma, observed=outcome)+ idata = pm.sample(+ draws=250,+ tune=250,+ chains=2,+ random_seed=seed,+ progressbar=False,+ )+ pm.compute_log_likelihood(idata, progressbar=False)+ pm.sample_posterior_predictive(+ idata, extend_inferencedata=True, random_seed=seed, progressbar=False+ )+ prior = pm.sample_prior_predictive(draws=200, random_seed=seed)+ return idata, prior++ with_slope, prior = fit(True, 1)+ intercept_only, _ = fit(False, 2)+ return with_slope, intercept_only, prior+++class SummaryNumericTests(unittest.TestCase):+ def test_the_summary_columns_are_numeric_not_formatted_strings(self) -> None:+ # The regression: ArviZ 1.x rounds `summary` for display by default, so+ # `summary['r_hat'] > 1.01` raised "'>' not supported between instances+ # of 'str' and 'float'".+ results = model_diagnostics.check_diagnostics(synthetic_posterior())+ summary = results["summary"]+ for column in ("mean", "sd", "r_hat", "ess_bulk", "ess_tail"):+ with self.subTest(column=column):+ self.assertTrue(+ pd.api.types.is_numeric_dtype(summary[column]),+ f"{column} is {summary[column].dtype}, not numeric",+ )++ def test_the_summary_describes_the_draws_it_was_given(self) -> None:+ # Standard-normal draws: mean near 0, sd near 1, and -- because the draws+ # are independent -- an effective sample size close to the draw count.+ summary = model_diagnostics.check_diagnostics(synthetic_posterior())["summary"]+ self.assertAlmostEqual(float(summary.loc["theta", "mean"]), 0.0, delta=0.2)+ self.assertAlmostEqual(float(summary.loc["theta", "sd"]), 1.0, delta=0.2)+ self.assertAlmostEqual(+ float(summary.loc["theta", "ess_bulk"]), CHAINS * DRAWS, delta=0.25 * CHAINS * DRAWS+ )+ self.assertAlmostEqual(float(summary.loc["theta", "r_hat"]), 1.0, delta=0.01)+++class DiagnosticBranchTests(unittest.TestCase):+ def test_a_healthy_posterior_raises_no_issues(self) -> None:+ # The direction a suite of broken inputs would never prove: a clean fit+ # must come back clean.+ results = model_diagnostics.check_diagnostics(synthetic_posterior())+ self.assertFalse(results["has_issues"])+ self.assertEqual(results["issues"], [])+ self.assertNotIn("n_divergences", results)++ def test_disagreeing_chains_are_flagged_as_a_convergence_failure(self) -> None:+ # Offsetting one chain by three standard deviations is exactly the+ # situation R-hat is designed to detect.+ results = model_diagnostics.check_diagnostics(+ synthetic_posterior(shift_second_chain=3.0)+ )+ self.assertTrue(results["has_issues"])+ self.assertIn("convergence", results["issues"])+ self.assertGreater(float(results["summary"].loc["theta", "r_hat"]), 1.01)++ def test_a_stricter_ess_threshold_flags_a_posterior_that_otherwise_passes(self) -> None:+ clean = model_diagnostics.check_diagnostics(+ synthetic_posterior(), ess_threshold=10+ )+ strict = model_diagnostics.check_diagnostics(+ synthetic_posterior(), ess_threshold=10_000+ )+ self.assertEqual(clean["issues"], [])+ self.assertIn("low_ess", strict["issues"])+ self.assertTrue(strict["has_issues"])++ def test_every_divergent_transition_is_counted(self) -> None:+ results = model_diagnostics.check_diagnostics(synthetic_posterior(diverging=1))+ self.assertIn("divergences", results["issues"])+ self.assertTrue(results["has_issues"])+ self.assertEqual(results["n_divergences"], CHAINS * DRAWS)++ def test_hitting_the_maximum_tree_depth_is_reported(self) -> None:+ # PyMC's default max_treedepth is 10. This costs sampling efficiency+ # rather than validity, so it is listed as an issue without setting the+ # has_issues flag that divergences and bad R-hat do.+ results = model_diagnostics.check_diagnostics(synthetic_posterior(tree_depth=10))+ self.assertIn("max_treedepth", results["issues"])++ def test_a_posterior_without_energy_statistics_is_still_checked(self) -> None:+ # Non-NUTS samplers record no energy; the checker must not require it.+ results = model_diagnostics.check_diagnostics(+ synthetic_posterior(with_energy=False)+ )+ self.assertEqual(results["issues"], [])++ def test_var_names_restricts_the_summary(self) -> None:+ idata, _, _ = fitted_models()+ results = model_diagnostics.check_diagnostics(idata, var_names=["slope"])+ self.assertEqual(list(results["summary"].index), ["slope"])+ # The generating slope was 2.0, and a short but healthy chain finds it.+ self.assertAlmostEqual(float(results["summary"].loc["slope", "mean"]), 2.0, delta=0.2)+++class DiagnosticReportTests(unittest.TestCase):+ def setUp(self) -> None:+ self.addCleanup(plt.close, "all")++ def test_the_report_writes_every_documented_artefact(self) -> None:+ idata, _, _ = fitted_models()+ with tempfile.TemporaryDirectory() as directory:+ results = model_diagnostics.create_diagnostic_report(+ idata, var_names=["intercept", "slope", "sigma"], output_dir=directory+ )+ written = {path.name for path in Path(directory).iterdir()}+ self.assertEqual(+ written,+ {+ "trace_plots.png",+ "rank_plots.png",+ "autocorr_plots.png",+ "energy_plot.png",+ "ess_local.png",+ "summary_statistics.csv",+ },+ )+ # The regression: ArviZ 1.x plots do not draw into pyplot's current+ # figure, so saving with plt.savefig() wrote an all-white image.+ image = mpimg.imread(str(Path(directory) / "trace_plots.png"))+ self.assertLess(+ float(image[..., :3].min()), 0.5, "trace_plots.png is blank"+ )+ summary = pd.read_csv(Path(directory) / "summary_statistics.csv", index_col=0)+ self.assertEqual(set(summary.index), {"intercept", "slope", "sigma"})+ self.assertEqual(list(summary.index), list(results["summary"].index))++ def test_the_report_leaves_no_open_figures(self) -> None:+ idata, _, _ = fitted_models()+ with tempfile.TemporaryDirectory() as directory:+ model_diagnostics.create_diagnostic_report(+ idata, var_names=["slope"], output_dir=directory+ )+ self.assertEqual(plt.get_fignums(), [])++ def test_the_output_directory_is_created_if_it_is_missing(self) -> None:+ idata, _, _ = fitted_models()+ with tempfile.TemporaryDirectory() as directory:+ nested = Path(directory) / "a" / "b"+ model_diagnostics.create_diagnostic_report(+ idata, var_names=["slope"], output_dir=str(nested)+ )+ self.assertTrue((nested / "summary_statistics.csv").is_file())++ def test_the_prior_and_posterior_are_overlaid_in_one_figure(self) -> None:+ idata, _, prior = fitted_models()+ with tempfile.TemporaryDirectory() as directory:+ path = Path(directory) / "prior_posterior.png"+ collection = model_diagnostics.compare_prior_posterior(+ idata, prior, var_names=["intercept", "slope"], output_path=str(path)+ )+ self.assertGreater(path.stat().st_size, 0)+ image = mpimg.imread(str(path))+ self.assertLess(float(image[..., :3].min()), 0.5, "the figure is blank")+ # One panel per requested variable.+ self.assertEqual(len(collection.viz["figure"].item().axes), 2)+++class ModelComparisonTests(unittest.TestCase):+ @classmethod+ def setUpClass(cls) -> None:+ with_slope, intercept_only, _ = fitted_models()+ cls.models = {"with_slope": with_slope, "intercept_only": intercept_only}+ cls.comparison = model_comparison.compare_models(cls.models, verbose=False)++ def test_the_model_that_matches_the_data_generating_process_wins(self) -> None:+ # The data is y = 2x + noise, so dropping the slope must cost predictive+ # accuracy. This is known before the code runs.+ self.assertEqual(list(self.comparison.index)[0], "with_slope")+ self.assertEqual(int(self.comparison.loc["with_slope", "rank"]), 0)+ self.assertAlmostEqual(float(self.comparison.loc["with_slope", "elpd_diff"]), 0.0)+ self.assertLess(float(self.comparison.loc["intercept_only", "elpd_diff"]), -4.0)+ self.assertGreater(+ float(self.comparison.loc["with_slope", "elpd"]),+ float(self.comparison.loc["intercept_only", "elpd"]),+ )++ def test_the_stacking_weights_form_a_distribution(self) -> None:+ weights = self.comparison["weight"]+ self.assertAlmostEqual(float(weights.sum()), 1.0, places=6)+ self.assertGreater(float(weights.loc["with_slope"]), 0.95)++ def test_the_comparison_columns_are_numeric(self) -> None:+ # Same display-formatting trap as az.summary: the interpretation block+ # compares elpd_diff against dse.+ for column in ("elpd", "elpd_diff", "dse", "se", "weight", "p"):+ with self.subTest(column=column):+ self.assertTrue(pd.api.types.is_numeric_dtype(self.comparison[column]))++ def test_the_difference_is_large_relative_to_its_own_standard_error(self) -> None:+ difference = abs(float(self.comparison.loc["intercept_only", "elpd_diff"]))+ self.assertGreater(difference, 2 * float(self.comparison.loc["intercept_only", "dse"]))++ def test_loo_is_accepted_under_either_spelling_and_any_case(self) -> None:+ for criterion in ("loo", "LOO", "elpd"):+ with self.subTest(ic=criterion):+ frame = model_comparison.compare_models(+ self.models, ic=criterion, verbose=False+ )+ self.assertEqual(list(frame.index), list(self.comparison.index))++ def test_an_unsupported_criterion_is_refused_with_a_way_forward(self) -> None:+ for criterion in ("waic", "bic", "dic"):+ with self.subTest(ic=criterion):+ with self.assertRaisesRegex(ValueError, "az.waic"):+ model_comparison.compare_models(self.models, ic=criterion)++ def test_the_verbose_report_names_the_winner(self) -> None:+ # verbose=True is the default, so it must not raise on the way through+ # the interpretation and reliability blocks.+ frame = model_comparison.compare_models(self.models, verbose=True)+ self.assertEqual(list(frame.index)[0], "with_slope")+++class LooReliabilityTests(unittest.TestCase):+ @classmethod+ def setUpClass(cls) -> None:+ with_slope, _, _ = fitted_models()+ cls.results = model_comparison.check_loo_reliability(+ {"with_slope": with_slope}, verbose=False+ )["with_slope"]++ def test_one_pareto_k_is_reported_per_observation(self) -> None:+ self.assertEqual(np.shape(self.results["pareto_k"]), (40,))++ def test_the_counts_agree_with_the_threshold_they_were_given(self) -> None:+ pareto_k = np.asarray(self.results["pareto_k"])+ self.assertEqual(self.results["n_high"], int((pareto_k > 0.7).sum()))+ self.assertEqual(self.results["n_very_high"], int((pareto_k > 1.0).sum()))+ self.assertAlmostEqual(float(self.results["max_k"]), float(pareto_k.max()))++ def test_a_well_specified_model_has_no_problem_observations(self) -> None:+ # Correct model, 40 well-behaved points: PSIS must be reliable.+ self.assertEqual(self.results["n_high"], 0)+ self.assertLess(float(self.results["max_k"]), 0.7)++ def test_lowering_the_threshold_flags_more_observations(self) -> None:+ with_slope, _, _ = fitted_models()+ lenient = model_comparison.check_loo_reliability(+ {"m": with_slope}, threshold=0.7, verbose=False+ )["m"]+ strict = model_comparison.check_loo_reliability(+ {"m": with_slope}, threshold=0.0, verbose=False+ )["m"]+ pareto_k = np.asarray(lenient["pareto_k"])+ self.assertEqual(lenient["n_high"], 0)+ # Only strictly greater than the threshold counts, and some k are+ # negative, so this is not simply every observation.+ self.assertEqual(strict["n_high"], int((pareto_k > 0.0).sum()))+ self.assertGreater(strict["n_high"], lenient["n_high"])+++class ModelAveragingTests(unittest.TestCase):+ @classmethod+ def setUpClass(cls) -> None:+ with_slope, intercept_only, _ = fitted_models()+ cls.models = {"with_slope": with_slope, "intercept_only": intercept_only}++ def test_explicit_weights_are_normalised_and_applied_exactly(self) -> None:+ averaged, weights = model_comparison.model_averaging(+ self.models, weights=[3, 1], var_name="y_obs"+ )+ np.testing.assert_allclose(weights, [0.75, 0.25])+ expected = 0.75 * self.models["with_slope"].posterior_predictive["y_obs"].values + (+ 0.25 * self.models["intercept_only"].posterior_predictive["y_obs"].values+ )+ np.testing.assert_allclose(averaged, expected)++ def test_derived_weights_come_from_the_comparison_and_sum_to_one(self) -> None:+ averaged, weights = model_comparison.model_averaging(+ self.models, var_name="y_obs"+ )+ self.assertAlmostEqual(float(np.sum(weights)), 1.0, places=6)+ self.assertEqual(+ np.shape(averaged),+ self.models["with_slope"].posterior_predictive["y_obs"].values.shape,+ )+ # Weights are ordered by the comparison, best model first.+ self.assertGreater(weights[0], 0.95)++ def test_a_variable_no_model_predicts_is_skipped_rather_than_raising(self) -> None:+ averaged, weights = model_comparison.model_averaging(+ self.models, weights=[1, 1], var_name="not_a_variable"+ )+ np.testing.assert_allclose(weights, [0.5, 0.5])+ self.assertEqual(averaged, 0)+++class ComparisonPlotTests(unittest.TestCase):+ def setUp(self) -> None:+ self.addCleanup(plt.close, "all")++ def test_the_comparison_plot_is_saved_and_is_not_blank(self) -> None:+ with_slope, intercept_only, _ = fitted_models()+ comparison = model_comparison.compare_models(+ {"with_slope": with_slope, "intercept_only": intercept_only}, verbose=False+ )+ with tempfile.TemporaryDirectory() as directory:+ path = Path(directory) / "comparison.png"+ figure = model_comparison.plot_model_comparison(+ comparison, output_path=str(path), show=False+ )+ self.assertIsInstance(figure, matplotlib.figure.Figure)+ image = mpimg.imread(str(path))+ self.assertLess(float(image[..., :3].min()), 0.5, "the figure is blank")+ self.assertEqual(plt.get_fignums(), [])+++class CrossValidationGuidanceTests(unittest.TestCase):+ def test_the_guidance_names_the_fold_count_it_was_asked_about(self) -> None:+ # Documentation-only helper: it must not touch the posteriors it is+ # handed, so passing an empty dict has to be safe.+ model_comparison.cross_validation_comparison({}, k=7, verbose=True)+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/pymoo/test_scripts.py b/tests/pymoo/test_scripts.pynew file mode 100644index 00000000..c66f271a--- /dev/null+++ b/tests/pymoo/test_scripts.py@@ -0,0 +1,309 @@+"""Tests for the pymoo optimisation examples.++The examples are worth testing at two levels. The problem definitions are pure+arithmetic with hand-computable answers -- `MyBiObjectiveProblem` at (0, 0) must+be (0, 2), and `ConstrainedProblem` must call (1.0, 0.0) feasible and (0.1, 0.0)+infeasible -- so a transcription slip in an objective or a sign flip in a+constraint conversion is caught exactly. The optimisation runs are then checked+against properties that hold by construction rather than against a converged+result: pymoo's `sphere` has its minimum at x = 0.5 with value 0, ZDT1's true+front satisfies f2 = 1 - sqrt(f1), every feasible DTLZ2 point has ||f|| >= 1,+and any NSGA-II result set must be mutually non-dominated. The guard that+matters most is `get_reference_directions`, whose dimension argument is+positional -- passing it by keyword raises TypeError, which made the+many-objective example unrunnable.+"""++from __future__ import annotations++import sys+import unittest+from pathlib import Path++import pytest++import skill_contract++SKILL_ROOT = Path(__file__).resolve().parents[2] / "skills" / "pymoo"+SCRIPTS = SKILL_ROOT / "scripts"+sys.path.insert(0, str(SCRIPTS))++np = pytest.importorskip("numpy", reason="pymoo scripts need numpy")+pytest.importorskip("pymoo", reason="pymoo scripts need pymoo")+matplotlib = pytest.importorskip("matplotlib", reason="the examples plot their results")+matplotlib.use("Agg")++from pymoo.algorithms.moo.nsga2 import NSGA2 # noqa: E402+from pymoo.algorithms.moo.nsga3 import NSGA3 # noqa: E402+from pymoo.algorithms.soo.nonconvex.ga import GA # noqa: E402+from pymoo.optimize import minimize # noqa: E402+from pymoo.problems import get_problem # noqa: E402+from pymoo.util.nds.non_dominated_sorting import NonDominatedSorting # noqa: E402+from pymoo.util.ref_dirs import get_reference_directions # noqa: E402++import custom_problem_example # noqa: E402+import decision_making_example # noqa: E402++# Imported for the side effect of importing: these three modules do their work+# inside functions, so a broken import line here fails at collection time rather+# than 30 seconds into the demo run below.+import many_objective_example # noqa: E402,F401+import multi_objective_example # noqa: E402,F401+import single_objective_example # noqa: E402,F401++# No script here builds an argparse parser; each is an importable module with a+# worked example under `if __name__ == "__main__"`. Four of them finish in about+# two seconds; `many_objective_example` costs roughly 30 (NSGA-III, 5+# objectives, 300 generations) and is included anyway because running it is the+# only thing that exercises its reference-direction call for real.+DemoBlockTests = skill_contract.cli.demo_test_case(+ SKILL_ROOT,+ (+ "single_objective_example.py",+ "multi_objective_example.py",+ "custom_problem_example.py",+ "decision_making_example.py",+ "many_objective_example.py",+ ),+)+++def is_non_dominated(front: "np.ndarray") -> bool:+ """True when no row in `front` is dominated by another."""+ fronts = NonDominatedSorting().do(front)+ return len(fronts[0]) == len(front)+++class BiObjectiveProblemDefinitionTests(unittest.TestCase):+ def setUp(self) -> None:+ self.problem = custom_problem_example.MyBiObjectiveProblem()++ def test_the_declared_shape_matches_the_docstring(self) -> None:+ self.assertEqual(self.problem.n_var, 2)+ self.assertEqual(self.problem.n_obj, 2)+ self.assertEqual(self.problem.n_ieq_constr, 0)+ np.testing.assert_allclose(self.problem.xl, [0.0, 0.0])+ np.testing.assert_allclose(self.problem.xu, [5.0, 5.0])++ def test_the_objectives_are_the_two_squared_distances(self) -> None:+ # f1 = |x|^2 and f2 = |x - (1, 1)|^2, so the corners are exact.+ evaluated = self.problem.evaluate(+ np.array([[0.0, 0.0], [1.0, 1.0], [0.5, 0.5], [2.0, 3.0]])+ )+ np.testing.assert_allclose(+ evaluated,+ [[0.0, 2.0], [2.0, 0.0], [0.5, 0.5], [13.0, 5.0]],+ )++ def test_the_two_objectives_genuinely_conflict(self) -> None:+ # The origin minimises f1 and (1, 1) minimises f2; if one point were+ # best at both there would be nothing to trade off.+ origin, unit = self.problem.evaluate(np.array([[0.0, 0.0], [1.0, 1.0]]))+ self.assertLess(origin[0], unit[0])+ self.assertGreater(origin[1], unit[1])+++class ConstrainedProblemDefinitionTests(unittest.TestCase):+ def setUp(self) -> None:+ self.problem = custom_problem_example.ConstrainedProblem()++ def test_two_inequality_constraints_are_declared_over_the_stated_box(self) -> None:+ self.assertEqual(self.problem.n_ieq_constr, 2)+ np.testing.assert_allclose(self.problem.xl, [0.1, 0.0])+ np.testing.assert_allclose(self.problem.xu, [1.0, 5.0])++ def test_a_feasible_point_evaluates_to_non_positive_constraints(self) -> None:+ # At (1.0, 0.0): f = (1, (1+0)/1) = (1, 1); g1 = -(0 + 9 - 6) = -3 and+ # g2 = -(-0 + 9 - 1) = -8, so both original inequalities hold.+ objectives, constraints = self.problem.evaluate(+ np.array([[1.0, 0.0]]), return_values_of=["F", "G"]+ )+ np.testing.assert_allclose(objectives, [[1.0, 1.0]])+ np.testing.assert_allclose(constraints, [[-3.0, -8.0]])+ self.assertTrue(np.all(constraints <= 0.0))++ def test_a_point_violating_both_constraints_is_reported_infeasible(self) -> None:+ # At (0.1, 0.0): g1 = -(0 + 0.9 - 6) = 5.1 and g2 = -(-0 + 0.9 - 1) = 0.1,+ # both positive, so the sign conversion in the docstring is the real one.+ constraints = self.problem.evaluate(+ np.array([[0.1, 0.0]]), return_values_of=["G"]+ )+ np.testing.assert_allclose(constraints, [[5.1, 0.1]])+ self.assertTrue(np.all(constraints > 0.0))++ def test_the_search_returns_only_feasible_solutions(self) -> None:+ result = minimize(+ custom_problem_example.ConstrainedProblem(),+ NSGA2(pop_size=20),+ ("n_gen", 10),+ seed=1,+ verbose=False,+ )+ # The example reads feasibility off column 0 of CV, so it must exist.+ self.assertEqual(result.CV.shape[1], 1)+ np.testing.assert_allclose(result.CV[:, 0], 0.0)+++class SingleObjectiveExampleTests(unittest.TestCase):+ def test_pymoos_sphere_has_its_optimum_at_one_half(self) -> None:+ # pymoo's Sphere is sum (x_i - 0.5)^2 on [0, 1]^n: zero at 0.5 and+ # n * 0.25 at the origin. The GA below is judged against that.+ problem = get_problem("sphere", n_var=5)+ np.testing.assert_allclose(problem.xl, np.zeros(5))+ np.testing.assert_allclose(problem.xu, np.ones(5))+ self.assertEqual(problem.n_obj, 1)+ np.testing.assert_allclose(problem.evaluate(np.full((1, 5), 0.5)), [[0.0]])+ np.testing.assert_allclose(problem.evaluate(np.zeros((1, 5))), [[1.25]])++ def test_a_short_genetic_algorithm_run_approaches_the_known_optimum(self) -> None:+ problem = get_problem("sphere", n_var=5)+ result = minimize(problem, GA(pop_size=30), ("n_gen", 25), seed=1, verbose=False)+ self.assertLess(float(result.F[0]), 0.01)+ np.testing.assert_allclose(result.X, np.full(5, 0.5), atol=0.1)++ def test_the_example_reports_the_evaluation_budget_it_used(self) -> None:+ # pop_size * n_gen evaluations, which is what the example prints.+ result = minimize(+ get_problem("sphere", n_var=3), GA(pop_size=20), ("n_gen", 5), seed=1, verbose=False+ )+ self.assertEqual(result.algorithm.evaluator.n_eval, 100)++ def test_the_same_seed_gives_the_same_answer(self) -> None:+ runs = [+ minimize(+ get_problem("sphere", n_var=5), GA(pop_size=20), ("n_gen", 5), seed=7, verbose=False+ ).F+ for _ in range(2)+ ]+ np.testing.assert_allclose(runs[0], runs[1])+++class MultiObjectiveExampleTests(unittest.TestCase):+ def test_zdt1_is_the_thirty_variable_bi_objective_benchmark(self) -> None:+ problem = get_problem("zdt1")+ self.assertEqual((problem.n_var, problem.n_obj), (30, 2))++ def test_the_analytic_front_satisfies_f2_equals_one_minus_root_f1(self) -> None:+ # ZDT1's true front is a published closed form; the example plots it as+ # the reference curve, so it must be the real one.+ front = get_problem("zdt1").pareto_front()+ np.testing.assert_allclose(front[:, 1], 1.0 - np.sqrt(front[:, 0]), atol=1e-9)++ def test_an_nsga2_run_returns_a_mutually_non_dominated_set(self) -> None:+ result = minimize(+ get_problem("zdt1"), NSGA2(pop_size=20, eliminate_duplicates=True),+ ("n_gen", 10), seed=1, verbose=False,+ )+ self.assertEqual(result.F.shape[1], 2)+ self.assertLessEqual(len(result.F), 20)+ self.assertTrue(is_non_dominated(result.F))++ def test_no_solution_can_beat_the_analytic_front(self) -> None:+ # Nothing feasible lies below f2 = 1 - sqrt(f1); a result that did would+ # mean the problem or the front is wrong.+ result = minimize(+ get_problem("zdt1"), NSGA2(pop_size=20), ("n_gen", 10), seed=2, verbose=False+ )+ self.assertTrue(np.all(result.F[:, 1] >= 1.0 - np.sqrt(result.F[:, 0]) - 1e-9))+++class ManyObjectiveExampleTests(unittest.TestCase):+ def test_das_dennis_directions_take_the_dimension_positionally(self) -> None:+ # The regression this guards: get_reference_directions("das-dennis",+ # n_obj=5, ...) raises TypeError because the factory's first argument is+ # n_dim, which made the many-objective example unrunnable.+ with self.assertRaises(TypeError):+ get_reference_directions("das-dennis", n_obj=5, n_partitions=6)+ directions = get_reference_directions("das-dennis", 5, n_partitions=6)+ # C(p + m - 1, m - 1) = C(10, 4) = 210 simplex-lattice points.+ self.assertEqual(directions.shape, (210, 5))+ np.testing.assert_allclose(directions.sum(axis=1), 1.0, atol=1e-12)++ def test_more_partitions_give_more_directions(self) -> None:+ counts = [+ len(get_reference_directions("das-dennis", 3, n_partitions=p))+ for p in (4, 6, 8)+ ]+ # C(p + 2, 2) for three objectives: 15, 28, 45.+ self.assertEqual(counts, [15, 28, 45])++ def test_every_feasible_dtlz2_point_lies_on_or_outside_the_unit_sphere(self) -> None:+ # DTLZ2 scales the unit sphere by 1 + g with g >= 0, so ||f|| >= 1 with+ # equality exactly on the Pareto front.+ problem = get_problem("dtlz2", n_obj=3)+ front = problem.pareto_front()+ np.testing.assert_allclose(np.linalg.norm(front, axis=1), 1.0, atol=1e-9)+ rng = np.random.default_rng(0)+ random_points = problem.evaluate(rng.random((20, problem.n_var)))+ self.assertTrue(np.all(np.linalg.norm(random_points, axis=1) >= 1.0 - 1e-9))++ def test_nsga3_optimises_a_three_objective_problem_towards_the_sphere(self) -> None:+ directions = get_reference_directions("das-dennis", 3, n_partitions=6)+ result = minimize(+ get_problem("dtlz2", n_obj=3),+ NSGA3(ref_dirs=directions, eliminate_duplicates=True),+ ("n_gen", 15),+ seed=1,+ verbose=False,+ )+ self.assertEqual(result.F.shape[1], 3)+ self.assertTrue(is_non_dominated(result.F))+ # Optimisation shrinks 1 + g towards 1; it must not run away from it.+ self.assertLess(float(np.linalg.norm(result.F, axis=1).min()), 1.5)+++class PseudoWeightDecisionTests(unittest.TestCase):+ """A five-point synthetic front where the right answer is obvious."""++ def setUp(self) -> None:+ from pymoo.mcdm.pseudo_weights import PseudoWeights++ self.PseudoWeights = PseudoWeights+ self.front = np.array(+ [[0.0, 1.0], [0.25, 0.75], [0.5, 0.5], [0.75, 0.25], [1.0, 0.0]]+ )++ def test_weighting_one_objective_selects_the_best_point_in_it(self) -> None:+ self.assertEqual(self.PseudoWeights(np.array([0.9, 0.1])).do(self.front), 0)+ self.assertEqual(self.PseudoWeights(np.array([0.1, 0.9])).do(self.front), 4)++ def test_equal_weights_select_the_balanced_compromise(self) -> None:+ self.assertEqual(self.PseudoWeights(np.array([0.5, 0.5])).do(self.front), 2)+++class DecisionMakingExampleTests(unittest.TestCase):+ @classmethod+ def setUpClass(cls) -> None:+ cls.result = minimize(+ get_problem("zdt1"), NSGA2(pop_size=24), ("n_gen", 12), seed=1, verbose=False+ )++ def test_the_selection_indexes_into_both_result_arrays_consistently(self) -> None:+ index, variables, objectives = decision_making_example.apply_pseudo_weights(+ self.result, np.array([0.5, 0.5])+ )+ np.testing.assert_allclose(objectives, self.result.F[index])+ np.testing.assert_allclose(variables, self.result.X[index])++ def test_shifting_the_weights_moves_the_choice_along_the_front(self) -> None:+ _, _, prefer_first = decision_making_example.apply_pseudo_weights(+ self.result, np.array([0.9, 0.1])+ )+ _, _, prefer_second = decision_making_example.apply_pseudo_weights(+ self.result, np.array([0.1, 0.9])+ )+ # Weighting f1 must not pick a solution that is worse in f1 than the+ # one chosen when f1 barely matters.+ self.assertLess(prefer_first[0], prefer_second[0])+ self.assertGreater(prefer_first[1], prefer_second[1])++ def test_the_extreme_solutions_are_the_per_objective_minima(self) -> None:+ best_f1, best_f2 = decision_making_example.find_extreme_solutions(self.result)+ self.assertEqual(best_f1, int(np.argmin(self.result.F[:, 0])))+ self.assertEqual(best_f2, int(np.argmin(self.result.F[:, 1])))+ # On a two-objective front the extremes cannot be the same point.+ self.assertNotEqual(best_f1, best_f2)+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/pyopenms/test_scripts.py b/tests/pyopenms/test_scripts.pynew file mode 100644index 00000000..18ce0d9d--- /dev/null+++ b/tests/pyopenms/test_scripts.py@@ -0,0 +1,823 @@+"""Tests for the pyOpenMS workflow scripts.++Sixteen scripts, most of them thin wrappers whose real content is a chain of+OpenMS algorithm calls that need instrument data to run. What can be checked+without a real LC-MS run is the part that goes wrong quietly, and that is what+these tests cover.++The mass arithmetic comes first: `PROTON` and the `(M + zH)/z` conversions are+copied into two scripts, and an error there shifts every reported m/z by a+constant nobody notices. Those are pinned to published values -- the CODATA+proton mass, the monoisotopic mass of DFPIANGER (the OpenMS reference peptide),+glucose at 180.06339 Da, and the y1 ion of arginine at 175.11895 -- so the+assertions are independent of what this code currently prints.++Next the pure data plumbing: `filter_experiment` must not mutate the experiment+it reads, `collect_ms1` must drop MS2 scans, `dump_spectra_csv` must compute TIC+and base peak per scan, and the feature linker must group co-eluting features+across samples while keeping distinct ones apart -- all verifiable on+experiments built peak by peak in memory, where the right answer is known by+construction.++Feature *detection* (FeatureFindingMetabo, FeatureFinderAlgorithmPicked),+adduct deconvolution and identification post-processing are deliberately not+driven end to end: they need real profile data, and a synthetic experiment would+only prove that the algorithms return nothing. Their static configuration --+adduct tables, the shared detector import -- is checked instead.+"""++from __future__ import annotations++import argparse+import csv+import os+import statistics+import subprocess+import sys+import tempfile+import unittest+from pathlib import Path++import pytest++import skill_contract++SKILL_ROOT = Path(__file__).resolve().parents[2] / "skills" / "pyopenms"+SCRIPTS = SKILL_ROOT / "scripts"+sys.path.insert(0, str(SCRIPTS))++pyopenms = pytest.importorskip("pyopenms", reason="pyopenms skill needs pyopenms")+numpy = pytest.importorskip("numpy", reason="pyopenms skill needs numpy")+matplotlib = pytest.importorskip("matplotlib", reason="pyopenms skill needs matplotlib")+pytest.importorskip("pandas", reason="pyopenms skill needs pandas")++# Headless before anything imports pyplot: plot_ms_data draws at import time.+matplotlib.use("Agg")+import matplotlib.pyplot as pyplot # noqa: E402++import align_link_quantify # noqa: E402+import convert_format # noqa: E402+import detect_adducts # noqa: E402+import detect_features_metabo # noqa: E402+import digest_protein # noqa: E402+import extract_chromatograms # noqa: E402+import inspect_ms_data # noqa: E402+import mass_calculator # noqa: E402+import plot_ms_data # noqa: E402++CliHelpTests = skill_contract.cli.help_test_case(SKILL_ROOT)++#: CODATA 2018 proton mass in unified atomic mass units.+CODATA_PROTON_MASS_U = 1.007276466621++#: OpenMS' reference peptide. Its monoisotopic mass is quoted throughout the+#: pyOpenMS documentation, which makes it a fixed point independent of this code.+DFPIANGER_MONOISOTOPIC = 1017.4879641373++#: Monoisotopic mass of glucose, C6H12O6.+GLUCOSE_MONOISOTOPIC = 180.0633903828++#: Monoisotopic mass of water, used as the reference for an H-2O-1 loss adduct.+WATER_MONOISOTOPIC = 18.0105646863+++def run_script(name: str, *arguments: str, cwd: Path) -> subprocess.CompletedProcess:+ """Run one bundled script in a subprocess, headless and byte-code free."""+ environment = {+ **os.environ,+ "PYTHONDONTWRITEBYTECODE": "1",+ "MPLBACKEND": "Agg",+ }+ return subprocess.run(+ [sys.executable, str(SCRIPTS / name), *arguments],+ capture_output=True,+ text=True,+ timeout=300,+ env=environment,+ cwd=str(cwd),+ )+++def spectrum(rt: float, level: int, peaks, precursor_mz: float | None = None):+ """An MSSpectrum built from explicit (m/z, intensity) pairs."""+ built = pyopenms.MSSpectrum()+ built.setRT(rt)+ built.setMSLevel(level)+ mz = numpy.array([pair[0] for pair in peaks], dtype=float)+ intensities = numpy.array([pair[1] for pair in peaks], dtype=float)+ built.set_peaks((mz, intensities))+ if precursor_mz is not None:+ precursor = pyopenms.Precursor()+ precursor.setMZ(precursor_mz)+ precursor.setCharge(2)+ built.setPrecursors([precursor])+ return built+++def feature_map(entries):+ """A FeatureMap from explicit (rt, mz, intensity) triples."""+ built = pyopenms.FeatureMap()+ for rt, mz, intensity in entries:+ feature = pyopenms.Feature()+ feature.setRT(rt)+ feature.setMZ(mz)+ feature.setIntensity(intensity)+ feature.setCharge(1)+ built.push_back(feature)+ built.setUniqueIds()+ return built+++class TemporaryDirectoryTestCase(unittest.TestCase):+ def setUp(self) -> None:+ self._temporary = tempfile.TemporaryDirectory()+ self.addCleanup(self._temporary.cleanup)+ self.root = Path(self._temporary.name)+++class ExampleExperimentMixin:+ """A three-scan experiment whose every summary statistic is hand-computable.++ RT 10 s, MS1: 100/10, 200/500, 300/5 -> TIC 515, base peak 200 at 500+ RT 20 s, MS2: 110/7, 210/8 -> TIC 15, precursor m/z 250, z 2+ RT 30 s, MS1: 100/1000, 200/20 -> TIC 1020, base peak 100 at 1000+ """++ @staticmethod+ def experiment():+ built = pyopenms.MSExperiment()+ built.addSpectrum(spectrum(10.0, 1, [(100.0, 10.0), (200.0, 500.0), (300.0, 5.0)]))+ built.addSpectrum(spectrum(20.0, 2, [(110.0, 7.0), (210.0, 8.0)], precursor_mz=250.0))+ built.addSpectrum(spectrum(30.0, 1, [(100.0, 1000.0), (200.0, 20.0)]))+ return built+++class ProtonMassTests(unittest.TestCase):+ def test_the_proton_mass_matches_codata(self) -> None:+ # Every reported m/z is (M + z*PROTON)/z, so an error here is a constant+ # offset on every row of every output table.+ self.assertAlmostEqual(mass_calculator.PROTON, CODATA_PROTON_MASS_U, delta=1e-9)++ def test_both_scripts_that_convert_to_mz_use_the_same_constant(self) -> None:+ # mass_calculator and digest_protein each define PROTON; tables produced+ # by the two would otherwise disagree in the last digits.+ self.assertEqual(mass_calculator.PROTON, digest_protein.PROTON)++ def test_the_proton_is_lighter_than_a_hydrogen_atom(self) -> None:+ # A protonated ion has lost an electron. Using the neutral H mass+ # instead is the classic off-by-one-electron error, worth ~0.5 mDa.+ hydrogen = pyopenms.EmpiricalFormula("H").getMonoWeight()+ self.assertGreater(hydrogen, mass_calculator.PROTON)+ self.assertAlmostEqual(hydrogen - mass_calculator.PROTON, 0.000548, delta=1e-5)+++class IsotopePatternTests(TemporaryDirectoryTestCase):+ """`report_isotopes` against the natural isotope abundances of glucose."""++ def rows(self, formula: str, count: int) -> list[tuple[float, float]]:+ output = self.root / "iso.csv"+ mass_calculator.report_isotopes(+ pyopenms.EmpiricalFormula(formula), count, str(output)+ )+ with output.open(encoding="utf-8", newline="") as handle:+ reader = csv.reader(handle)+ self.assertEqual(next(reader), ["mass", "rel_abundance"])+ return [(float(mass), float(abundance)) for mass, abundance in reader]++ def test_the_first_peak_is_the_monoisotopic_mass(self) -> None:+ rows = self.rows("C6H12O6", 4)+ self.assertEqual(len(rows), 4)+ self.assertAlmostEqual(rows[0][0], GLUCOSE_MONOISOTOPIC, places=5)++ def test_consecutive_peaks_are_one_neutron_apart(self) -> None:+ # The 13C-12C mass difference is 1.00336 u; anything near 0.5 or 2 would+ # mean the container was misread.+ rows = self.rows("C6H12O6", 4)+ for lighter, heavier in zip(rows, rows[1:]):+ with self.subTest(mass=lighter[0]):+ self.assertAlmostEqual(heavier[0] - lighter[0], 1.0034, delta=0.002)++ def test_the_abundances_fall_away_from_the_monoisotopic_peak(self) -> None:+ rows = self.rows("C6H12O6", 4)+ abundances = [abundance for _, abundance in rows]+ self.assertEqual(abundances, sorted(abundances, reverse=True))+ # 6 carbons at 1.07% 13C give M+1/M ~ 0.065; the rest is 2H and 17O.+ self.assertAlmostEqual(abundances[1] / abundances[0], 0.065, delta=0.008)+ # Coarse patterns are normalised, so the reported peaks sum to ~1.+ self.assertAlmostEqual(sum(abundances), 1.0, delta=0.01)++ def test_a_single_requested_peak_is_the_monoisotopic_one(self) -> None:+ rows = self.rows("C6H12O6", 1)+ self.assertEqual(len(rows), 1)+ self.assertAlmostEqual(rows[0][0], GLUCOSE_MONOISOTOPIC, places=4)++ def test_no_csv_is_written_when_none_is_requested(self) -> None:+ mass_calculator.report_isotopes(pyopenms.EmpiricalFormula("C6H12O6"), 3, None)+ self.assertEqual(list(self.root.iterdir()), [])+++class MassCalculatorCliTests(TemporaryDirectoryTestCase):+ """The m/z arithmetic lives in `main`, so it is driven through the CLI."""++ def test_the_reference_peptide_masses_are_reported(self) -> None:+ result = run_script(+ "mass_calculator.py", "--peptide", "DFPIANGER", "--charges", "1", "2", "3",+ cwd=self.root,+ )+ self.assertEqual(result.returncode, 0, result.stderr)+ self.assertIn(f"Monoisotopic mass: {DFPIANGER_MONOISOTOPIC:.5f}", result.stdout)+ # (M + z*proton)/z, computed from the published monoisotopic mass.+ for charge in (1, 2, 3):+ expected = (+ DFPIANGER_MONOISOTOPIC + charge * CODATA_PROTON_MASS_U+ ) / charge+ with self.subTest(charge=charge):+ self.assertIn(f"m/z = {expected:.5f} (z={charge})", result.stdout)+ # The elemental composition of DFPIANGER.+ self.assertIn("Formula: C44H67N13O15", result.stdout)++ def test_a_formula_reports_the_neutral_and_the_protonated_mass(self) -> None:+ result = run_script(+ "mass_calculator.py", "--formula", "C6H12O6", "--charges", "1", cwd=self.root+ )+ self.assertEqual(result.returncode, 0, result.stderr)+ self.assertIn(f"Monoisotopic mass: {GLUCOSE_MONOISOTOPIC:.5f}", result.stdout)+ expected = GLUCOSE_MONOISOTOPIC + CODATA_PROTON_MASS_U+ self.assertIn(f"m/z = {expected:.5f} (z=1)", result.stdout)++ def test_negative_mode_subtracts_the_proton_instead_of_adding_it(self) -> None:+ # [M-H]- for glucose is 179.05611; reporting 181.07 would be a sign bug+ # that silently invalidates every negative-mode search.+ result = run_script(+ "mass_calculator.py", "--formula", "C6H12O6", "--charges", "1", "--negative",+ cwd=self.root,+ )+ self.assertEqual(result.returncode, 0, result.stderr)+ expected = GLUCOSE_MONOISOTOPIC - CODATA_PROTON_MASS_U+ self.assertIn(f"m/z = {expected:.5f} (z=1)", result.stdout)++ def test_neither_a_peptide_nor_a_formula_is_a_usage_error(self) -> None:+ result = run_script("mass_calculator.py", cwd=self.root)+ self.assertEqual(result.returncode, 2)+ self.assertIn("provide --peptide and/or --formula", result.stderr)+++class DigestionTests(TemporaryDirectoryTestCase):+ """Trypsin's cleavage rule, which is fixed by biochemistry."""++ def peptides(self, sequence: str, **overrides) -> list[str]:+ settings = dict(enzyme="Trypsin", missed=0, min_len=1, max_len=100)+ settings.update(overrides)+ return [+ peptide.toString()+ for peptide in digest_protein.digest(+ sequence,+ settings["enzyme"],+ settings["missed"],+ settings["min_len"],+ settings["max_len"],+ )+ ]++ def test_trypsin_cleaves_after_lysine_and_arginine(self) -> None:+ self.assertEqual(self.peptides("SAMPLERSAMPLEK"), ["SAMPLER", "SAMPLEK"])++ def test_trypsin_does_not_cleave_before_proline(self) -> None:+ # The Keil rule: K/R followed by P is not a cleavage site. Getting this+ # wrong inflates the search space and invents peptides that never exist.+ self.assertEqual(self.peptides("SAMPLERPSAMPLEK"), ["SAMPLERPSAMPLEK"])++ def test_allowing_a_missed_cleavage_adds_the_joined_peptide(self) -> None:+ self.assertEqual(+ self.peptides("SAMPLERSAMPLEK", missed=1),+ ["SAMPLER", "SAMPLEK", "SAMPLERSAMPLEK"],+ )++ def test_lysc_ignores_the_arginine_site_trypsin_uses(self) -> None:+ # Proves the --enzyme argument reaches the digester rather than being+ # accepted and dropped.+ self.assertEqual(self.peptides("SAMPLERSAMPLEK", enzyme="Lys-C"), ["SAMPLERSAMPLEK"])++ def test_the_length_window_excludes_at_both_ends(self) -> None:+ # Both peptides are 7 residues long.+ self.assertEqual(len(self.peptides("SAMPLERSAMPLEK", min_len=7, max_len=7)), 2)+ self.assertEqual(self.peptides("SAMPLERSAMPLEK", min_len=8), [])+ self.assertEqual(self.peptides("SAMPLERSAMPLEK", max_len=6), [])++ def test_a_fasta_entry_keeps_its_accession_and_sequence(self) -> None:+ fasta = self.root / "proteins.fasta"+ fasta.write_text(+ ">sp|P00001|ONE_TEST first protein\nSAMPLERSAMPLEK\n"+ ">sp|P00002|TWO_TEST second protein\nPEPTIDEK\n",+ encoding="utf-8",+ )+ self.assertEqual(+ digest_protein.read_fasta(str(fasta)),+ [("sp|P00001|ONE_TEST", "SAMPLERSAMPLEK"), ("sp|P00002|TWO_TEST", "PEPTIDEK")],+ )++ def test_the_peptide_table_reports_published_masses(self) -> None:+ # DFPIANGER ends in R, so trypsin returns the whole sequence and the row+ # can be checked against the documented monoisotopic mass and m/z.+ output = self.root / "peptides.csv"+ result = run_script(+ "digest_protein.py", "--sequence", "DFPIANGER",+ "--charges", "1", "2", "--out", str(output),+ cwd=self.root,+ )+ self.assertEqual(result.returncode, 0, result.stderr)+ with output.open(encoding="utf-8", newline="") as handle:+ rows = list(csv.DictReader(handle))+ self.assertEqual(len(rows), 1)+ row = rows[0]+ self.assertEqual(row["peptide"], "DFPIANGER")+ self.assertEqual(row["length"], "9")+ self.assertAlmostEqual(float(row["mono_mass"]), DFPIANGER_MONOISOTOPIC, places=5)+ for charge in (1, 2):+ expected = (DFPIANGER_MONOISOTOPIC + charge * CODATA_PROTON_MASS_U) / charge+ with self.subTest(charge=charge):+ self.assertAlmostEqual(float(row[f"mz_z{charge}"]), expected, places=5)+++class TheoreticalSpectrumTests(TemporaryDirectoryTestCase):+ def test_the_y_ion_series_of_the_reference_peptide(self) -> None:+ output = self.root / "peaks.csv"+ result = run_script(+ "theoretical_spectrum.py", "DFPIANGER", "--ions", "y",+ "--out-csv", str(output), cwd=self.root,+ )+ self.assertEqual(result.returncode, 0, result.stderr)+ with output.open(encoding="utf-8", newline="") as handle:+ rows = list(csv.DictReader(handle))+ # A 9-residue peptide has 8 y ions.+ self.assertEqual(len(rows), 8)+ self.assertEqual([row["ion"] for row in rows], [f"y{i}+" for i in range(1, 9)])+ # y1 is the C-terminal arginine: residue 156.10111 + H2O + proton.+ arginine = pyopenms.ResidueDB().getResidue("R").getMonoWeight(+ pyopenms.Residue.ResidueType.Internal+ )+ expected_y1 = arginine + WATER_MONOISOTOPIC + CODATA_PROTON_MASS_U+ self.assertAlmostEqual(float(rows[0]["mz"]), expected_y1, places=4)+ self.assertAlmostEqual(float(rows[0]["mz"]), 175.11895, places=4)++ def test_the_default_series_omits_b1_as_openms_does(self) -> None:+ # b+y for a 9-mer would be 16 peaks if b1 were generated; OpenMS leaves+ # it out because b1 ions are not observed, giving 15.+ result = run_script("theoretical_spectrum.py", "DFPIANGER", cwd=self.root)+ self.assertEqual(result.returncode, 0, result.stderr)+ self.assertIn("(15 fragment peaks)", result.stdout)++ def test_restricting_the_series_reduces_the_peak_count(self) -> None:+ both = run_script("theoretical_spectrum.py", "PEPTIDEK", cwd=self.root)+ only_y = run_script(+ "theoretical_spectrum.py", "PEPTIDEK", "--ions", "y", cwd=self.root+ )+ self.assertEqual(only_y.returncode, 0, only_y.stderr)+ # 8 residues: 7 y ions on their own, 7 y + 6 b together.+ self.assertIn("(7 fragment peaks)", only_y.stdout)+ self.assertIn("(13 fragment peaks)", both.stdout)+++class FilterExperimentTests(ExampleExperimentMixin, unittest.TestCase):+ """`convert_format.filter_experiment` -- the only pure logic in that script."""++ def test_an_ms_level_filter_keeps_only_that_level(self) -> None:+ filtered = convert_format.filter_experiment(self.experiment(), ms_level=1)+ self.assertEqual([spec.getRT() for spec in filtered], [10.0, 30.0])+ filtered = convert_format.filter_experiment(self.experiment(), ms_level=2)+ self.assertEqual([spec.getRT() for spec in filtered], [20.0])++ def test_an_unused_ms_level_yields_an_empty_experiment(self) -> None:+ filtered = convert_format.filter_experiment(self.experiment(), ms_level=3)+ self.assertEqual(filtered.getNrSpectra(), 0)++ def test_the_retention_time_window_includes_its_endpoints(self) -> None:+ filtered = convert_format.filter_experiment(+ self.experiment(), rt_min=20.0, rt_max=30.0+ )+ self.assertEqual([spec.getRT() for spec in filtered], [20.0, 30.0])+ filtered = convert_format.filter_experiment(+ self.experiment(), rt_min=20.1, rt_max=29.9+ )+ self.assertEqual(filtered.getNrSpectra(), 0)++ def test_an_intensity_threshold_prunes_peaks_and_keeps_the_scan(self) -> None:+ # Emptied scans are retained on purpose: dropping them would renumber+ # every spectrum index downstream.+ filtered = convert_format.filter_experiment(self.experiment(), min_intensity=100.0)+ self.assertEqual(filtered.getNrSpectra(), 3)+ self.assertEqual(+ [list(spec.get_peaks()[1]) for spec in filtered],+ [[500.0], [], [1000.0]],+ )++ def test_the_threshold_is_inclusive(self) -> None:+ filtered = convert_format.filter_experiment(self.experiment(), min_intensity=500.0)+ self.assertEqual(list(filtered[0].get_peaks()[1]), [500.0])++ def test_filtering_does_not_mutate_the_experiment_it_reads(self) -> None:+ # The source is often written back out under a different name; pruning+ # its peaks in place would corrupt an unrelated output.+ source = self.experiment()+ convert_format.filter_experiment(source, min_intensity=100.0)+ self.assertEqual([len(spec.get_peaks()[0]) for spec in source], [3, 2, 2])++ def test_chromatograms_survive_only_when_no_ms_level_is_selected(self) -> None:+ source = self.experiment()+ chromatogram = pyopenms.MSChromatogram()+ chromatogram.set_peaks(+ (numpy.array([1.0, 2.0]), numpy.array([5.0, 6.0]))+ )+ source.addChromatogram(chromatogram)++ kept = convert_format.filter_experiment(source, rt_min=0.0)+ self.assertEqual(kept.getNrChromatograms(), 1)+ # An MS-level selection is a spectrum-level request; carrying whole+ # chromatograms through it would contradict the filter.+ dropped = convert_format.filter_experiment(source, ms_level=1)+ self.assertEqual(dropped.getNrChromatograms(), 0)+++class StoreExperimentTests(ExampleExperimentMixin, TemporaryDirectoryTestCase):+ def test_an_unknown_extension_names_the_supported_ones(self) -> None:+ with self.assertRaisesRegex(ValueError, r"\.mzML, \.mzXML, or \.mgf"):+ convert_format.store_experiment(self.experiment(), str(self.root / "out.txt"))++ def test_an_mzml_round_trip_preserves_every_scan(self) -> None:+ path = self.root / "out.mzML"+ convert_format.store_experiment(self.experiment(), str(path))+ reloaded = convert_format.load_experiment(str(path))+ self.assertEqual(reloaded.getNrSpectra(), 3)+ self.assertEqual([spec.getMSLevel() for spec in reloaded], [1, 2, 1])+ self.assertEqual([spec.getRT() for spec in reloaded], [10.0, 20.0, 30.0])+ self.assertEqual(list(reloaded[0].get_peaks()[0]), [100.0, 200.0, 300.0])++ def test_the_extension_test_is_case_insensitive(self) -> None:+ path = self.root / "out.MZML"+ convert_format.store_experiment(self.experiment(), str(path))+ self.assertTrue(path.is_file())++ def test_mgf_is_accepted_as_an_output_format(self) -> None:+ path = self.root / "out.mgf"+ convert_format.store_experiment(self.experiment(), str(path))+ self.assertTrue(path.is_file())+++class CollectMs1Tests(ExampleExperimentMixin, unittest.TestCase):+ def test_only_ms1_scans_contribute_a_chromatogram_point(self) -> None:+ # A TIC that included MS2 scans would show spurious dips and spikes.+ rts, mz_arrays, intensity_arrays = extract_chromatograms.collect_ms1(+ self.experiment()+ )+ self.assertEqual(rts, [10.0, 30.0])+ self.assertEqual([len(array) for array in mz_arrays], [3, 2])+ self.assertEqual([float(array.sum()) for array in intensity_arrays], [515.0, 1020.0])++ def test_the_three_returned_lists_stay_index_aligned(self) -> None:+ rts, mz_arrays, intensity_arrays = extract_chromatograms.collect_ms1(+ self.experiment()+ )+ self.assertEqual(len(rts), len(mz_arrays))+ self.assertEqual(len(rts), len(intensity_arrays))+ for mz, intensities in zip(mz_arrays, intensity_arrays):+ self.assertEqual(len(mz), len(intensities))++ def test_an_ms2_only_experiment_yields_nothing(self) -> None:+ experiment = pyopenms.MSExperiment()+ experiment.addSpectrum(spectrum(5.0, 2, [(100.0, 1.0)], precursor_mz=200.0))+ self.assertEqual(extract_chromatograms.collect_ms1(experiment), ([], [], []))+++class SpectrumTableTests(ExampleExperimentMixin, TemporaryDirectoryTestCase):+ """`inspect_ms_data.dump_spectra_csv`, against hand-computed statistics."""++ def rows(self, experiment) -> list[dict[str, str]]:+ output = self.root / "spectra.csv"+ inspect_ms_data.dump_spectra_csv(experiment, str(output))+ with output.open(encoding="utf-8", newline="") as handle:+ return list(csv.DictReader(handle))++ def test_every_scan_is_summarised_once_in_order(self) -> None:+ rows = self.rows(self.experiment())+ self.assertEqual([row["index"] for row in rows], ["0", "1", "2"])+ self.assertEqual([row["ms_level"] for row in rows], ["1", "2", "1"])+ self.assertEqual([row["rt"] for row in rows], ["10.000", "20.000", "30.000"])++ def test_the_tic_is_the_sum_of_the_scan_intensities(self) -> None:+ rows = self.rows(self.experiment())+ self.assertEqual([row["tic"] for row in rows], ["515.0", "15.0", "1020.0"])+ self.assertEqual([row["n_peaks"] for row in rows], ["3", "2", "2"])++ def test_the_base_peak_is_the_most_intense_peak_not_the_first(self) -> None:+ rows = self.rows(self.experiment())+ self.assertEqual(+ [(row["base_peak_mz"], row["base_peak_int"]) for row in rows],+ [("200.0000", "500.0"), ("210.0000", "8.0"), ("100.0000", "1000.0")],+ )++ def test_precursor_columns_are_filled_only_for_msn_scans(self) -> None:+ rows = self.rows(self.experiment())+ self.assertEqual([row["precursor_mz"] for row in rows], ["", "250.0000", ""])+ self.assertEqual([row["precursor_charge"] for row in rows], ["", "2", ""])++ def test_an_empty_scan_reports_zero_rather_than_failing(self) -> None:+ experiment = pyopenms.MSExperiment()+ experiment.addSpectrum(spectrum(1.0, 1, []))+ row = self.rows(experiment)[0]+ self.assertEqual(row["n_peaks"], "0")+ self.assertEqual(row["tic"], "0.0")+ self.assertEqual(row["base_peak_mz"], "")++ def test_the_experiment_summary_reads_a_stored_file(self) -> None:+ path = self.root / "data.mzML"+ convert_format.store_experiment(self.experiment(), str(path))+ reloaded = inspect_ms_data.summarize_experiment(str(path))+ self.assertEqual(reloaded.getNrSpectra(), 3)+++class PlotTests(ExampleExperimentMixin, TemporaryDirectoryTestCase):+ def setUp(self) -> None:+ super().setUp()+ self.addCleanup(pyplot.close, "all")+ self.path = self.root / "data.mzML"+ convert_format.store_experiment(self.experiment(), str(self.path))++ def args(self, **overrides) -> argparse.Namespace:+ settings = dict(input=str(self.path), index=0, rt=None, out=None)+ settings.update(overrides)+ return argparse.Namespace(**settings)++ def test_every_advertised_plot_kind_has_a_function(self) -> None:+ # `--kind` uses `choices=list(PLOTS)`, and main() dispatches through the+ # same dict, so the two cannot drift; what matters is that the kinds+ # documented in the module docstring are all present.+ self.assertEqual(+ set(plot_ms_data.PLOTS), {"spectrum", "tic", "featuremap", "map2d"}+ )++ def test_a_spectrum_is_selected_by_index(self) -> None:+ plot_ms_data.plot_spectrum(self.args(index=2))+ self.assertIn("RT=30.0s", pyplot.gca().get_title())+ self.assertIn("MS1", pyplot.gca().get_title())++ def test_a_requested_retention_time_selects_the_nearest_scan(self) -> None:+ # 21 s is nearest the 20 s scan; picking the first scan instead would+ # silently plot the wrong spectrum.+ plot_ms_data.plot_spectrum(self.args(rt=21.0))+ self.assertIn("RT=20.0s", pyplot.gca().get_title())+ plot_ms_data.plot_spectrum(self.args(rt=26.0))+ self.assertIn("RT=30.0s", pyplot.gca().get_title())++ def test_a_retention_time_beyond_the_run_clamps_to_the_last_scan(self) -> None:+ plot_ms_data.plot_spectrum(self.args(rt=10_000.0))+ self.assertIn("RT=30.0s", pyplot.gca().get_title())++ def test_the_tic_plot_sums_ms1_scans_only(self) -> None:+ plot_ms_data.plot_tic(self.args())+ line = pyplot.gca().get_lines()[0]+ self.assertEqual(list(line.get_xdata()), [10.0, 30.0])+ self.assertEqual(list(line.get_ydata()), [515.0, 1020.0])++ def test_the_signal_map_plots_one_point_per_ms1_peak(self) -> None:+ plot_ms_data.plot_map2d(self.args())+ offsets = pyplot.gca().collections[0].get_offsets()+ # 3 peaks at RT 10 plus 2 at RT 30; the MS2 scan contributes none.+ self.assertEqual(len(offsets), 5)++ def test_a_plot_can_be_saved_through_the_cli(self) -> None:+ output = self.root / "tic.png"+ result = run_script(+ "plot_ms_data.py", "tic", str(self.path), "--out", str(output), cwd=self.root+ )+ self.assertEqual(result.returncode, 0, result.stderr)+ self.assertTrue(output.is_file())+ self.assertGreater(output.stat().st_size, 0)+++class AdductDefaultTests(unittest.TestCase):+ """The default adduct tables, in OpenMS deconvolution syntax."""++ @staticmethod+ def entries(table: str) -> list[list[str]]:+ return [part.strip().split(":") for part in table.split(",")]++ def test_every_entry_has_elements_a_charge_and_a_probability(self) -> None:+ for name, table in (+ ("positive", detect_adducts.DEFAULT_POS),+ ("negative", detect_adducts.DEFAULT_NEG),+ ):+ for entry in self.entries(table):+ with self.subTest(mode=name, entry=":".join(entry)):+ self.assertEqual(len(entry), 3)+ probability = float(entry[2])+ self.assertGreater(probability, 0.0)+ self.assertLessEqual(probability, 1.0)++ def test_every_element_string_parses_as_an_empirical_formula(self) -> None:+ # A typo here surfaces only as an OpenMS parameter error deep inside+ # MetaboliteFeatureDeconvolution.+ for table in (detect_adducts.DEFAULT_POS, detect_adducts.DEFAULT_NEG):+ for entry in self.entries(table):+ with self.subTest(elements=entry[0]):+ pyopenms.EmpiricalFormula(entry[0])++ def test_the_charge_signs_match_the_ionisation_mode(self) -> None:+ # An H-1 (deprotonation) adduct offered in positive mode, or Na+ in+ # negative mode, would explain mass differences that cannot occur.+ for entry in self.entries(detect_adducts.DEFAULT_POS):+ with self.subTest(entry=":".join(entry)):+ self.assertNotIn("-", entry[1])+ for entry in self.entries(detect_adducts.DEFAULT_NEG):+ with self.subTest(entry=":".join(entry)):+ self.assertNotIn("+", entry[1])++ def test_protonation_is_the_most_likely_form_in_each_mode(self) -> None:+ for table, elements in (+ (detect_adducts.DEFAULT_POS, "H"),+ (detect_adducts.DEFAULT_NEG, "H-1"),+ ):+ with self.subTest(elements=elements):+ probabilities = {+ entry[0]: float(entry[2]) for entry in self.entries(table)+ }+ self.assertEqual(+ max(probabilities, key=probabilities.__getitem__), elements+ )++ def test_the_water_loss_adduct_has_the_mass_of_a_lost_water(self) -> None:+ # `H-2O-1` is the OpenMS spelling of a neutral water loss; if it parsed+ # as an addition the sign of the mass shift would flip.+ loss = pyopenms.EmpiricalFormula("H-2O-1").getMonoWeight()+ self.assertAlmostEqual(loss, -WATER_MONOISOTOPIC, places=5)+ self.assertIn("H-2O-1", detect_adducts.DEFAULT_POS)++ def test_the_negative_defaults_include_a_chloride_adduct(self) -> None:+ chloride = pyopenms.EmpiricalFormula("Cl").getMonoWeight()+ # 35Cl is the monoisotopic chlorine.+ self.assertAlmostEqual(chloride, 34.96885, places=4)+ self.assertIn("Cl:-", detect_adducts.DEFAULT_NEG)+++class AlignAndLinkTests(TemporaryDirectoryTestCase):+ """Multi-sample alignment and linking, on maps built feature by feature."""++ def test_the_reference_map_is_the_one_with_the_most_features(self) -> None:+ # Aligning to the sparsest map throws away the retention-time anchors+ # the pose-clustering algorithm needs.+ small = feature_map([(100.0, 300.1, 1000.0)])+ large = feature_map(+ [(100.0, 300.1, 1000.0), (200.0, 400.2, 2000.0), (300.0, 500.3, 500.0)]+ )+ self.assertEqual(align_link_quantify.align([small, large]), 1)+ self.assertEqual(align_link_quantify.align([large, small]), 0)++ def test_co_eluting_features_are_linked_across_samples(self) -> None:+ first = feature_map([(100.0, 300.1000, 1000.0), (200.0, 400.2000, 2000.0)])+ second = feature_map([(100.5, 300.1005, 1100.0), (200.5, 400.2010, 2100.0)])+ consensus = align_link_quantify.link(+ [first, second], ["a.featureXML", "b.featureXML"], 20.0, 10.0, "ppm"+ )+ self.assertEqual(consensus.size(), 2)+ # Each consensus feature must gather one feature from each sample.+ self.assertEqual([feature.size() for feature in consensus], [2, 2])++ def test_features_outside_the_retention_time_tolerance_stay_separate(self) -> None:+ first = feature_map([(100.0, 300.1, 1000.0)])+ second = feature_map([(500.0, 300.1, 1000.0)])+ consensus = align_link_quantify.link(+ [first, second], ["a", "b"], 5.0, 10.0, "ppm"+ )+ self.assertEqual(consensus.size(), 2)+ self.assertEqual([feature.size() for feature in consensus], [1, 1])++ def test_the_column_headers_record_each_sample_and_its_size(self) -> None:+ # The headers become the column names of the quantification matrix, so+ # a missing filename produces an unusable table.+ first = feature_map([(100.0, 300.1, 1000.0)])+ second = feature_map([(100.0, 300.1, 1000.0), (200.0, 400.2, 2000.0)])+ consensus = align_link_quantify.link(+ [first, second], ["one.mzML", "two.mzML"], 20.0, 10.0, "ppm"+ )+ headers = consensus.getColumnHeaders()+ self.assertEqual(+ {index: (header.filename, header.size) for index, header in headers.items()},+ {0: ("one.mzML", 1), 1: ("two.mzML", 2)},+ )++ def test_the_metabolomics_detector_is_shared_rather_than_reimplemented(self) -> None:+ # align_link_quantify imports detect_features under a bare+ # `except Exception`, which would silently fall back to "featureXML+ # inputs only" if the import ever broke.+ self.assertIsNotNone(align_link_quantify.detect_features)+ self.assertIs(+ align_link_quantify.detect_features, detect_features_metabo.detect_features+ )++ def test_a_featurexml_input_is_loaded_rather_than_re_detected(self) -> None:+ path = self.root / "sample.featureXML"+ pyopenms.FeatureXMLFile().store(+ str(path), feature_map([(100.0, 300.1, 1000.0), (200.0, 400.2, 2000.0)])+ )+ loaded = align_link_quantify.load_or_detect(str(path), 10.0, 1000.0)+ self.assertEqual(loaded.size(), 2)+ self.assertEqual(+ sorted(round(feature.getMZ(), 4) for feature in loaded), [300.1, 400.2]+ )+++class ConsensusMatrixTests(TemporaryDirectoryTestCase):+ """`consensus_to_matrix` end to end, on a consensusXML built here."""++ def setUp(self) -> None:+ super().setUp()+ first = feature_map([(100.0, 300.1000, 1000.0), (200.0, 400.2000, 2000.0)])+ second = feature_map([(100.5, 300.1005, 1100.0), (200.5, 400.2010, 2100.0)])+ consensus = align_link_quantify.link(+ [first, second], ["one.mzML", "two.mzML"], 20.0, 10.0, "ppm"+ )+ self.consensus_path = self.root / "study.consensusXML"+ pyopenms.ConsensusXMLFile().store(str(self.consensus_path), consensus)++ def test_the_wide_matrix_has_one_row_per_feature_and_one_column_per_sample(self) -> None:+ wide = self.root / "quant.csv"+ result = run_script(+ "consensus_to_matrix.py", str(self.consensus_path), "--out", str(wide),+ cwd=self.root,+ )+ self.assertEqual(result.returncode, 0, result.stderr)+ with wide.open(encoding="utf-8", newline="") as handle:+ rows = list(csv.DictReader(handle))+ self.assertEqual(len(rows), 2)+ self.assertLessEqual({"one.mzML", "two.mzML"}, set(rows[0]))+ # Feature metadata is joined onto the intensities, not replaced by them.+ self.assertLessEqual({"rt", "mz", "charge", "quality"}, set(rows[0]))+ self.assertEqual([row["consensus_id"] for row in rows], ["0", "1"])+ # Every intensity was supplied by construction, so none may be missing.+ for row in rows:+ for sample in ("one.mzML", "two.mzML"):+ with self.subTest(feature=row["consensus_id"], sample=sample):+ self.assertGreater(float(row[sample]), 0.0)++ def test_the_long_table_has_one_row_per_feature_and_sample(self) -> None:+ long = self.root / "long.csv"+ result = run_script(+ "consensus_to_matrix.py", str(self.consensus_path),+ "--out", str(self.root / "quant.csv"), "--long", str(long),+ cwd=self.root,+ )+ self.assertEqual(result.returncode, 0, result.stderr)+ with long.open(encoding="utf-8", newline="") as handle:+ rows = list(csv.DictReader(handle))+ # 2 consensus features x 2 samples.+ self.assertEqual(len(rows), 4)+ self.assertEqual(list(rows[0]), ["consensus_id", "sample", "intensity"])+ self.assertEqual({row["sample"] for row in rows}, {"one.mzML", "two.mzML"})++ def test_a_missing_input_file_exits_rather_than_writing_an_empty_matrix(self) -> None:+ result = run_script(+ "consensus_to_matrix.py", str(self.root / "absent.consensusXML"),+ "--out", str(self.root / "quant.csv"), cwd=self.root,+ )+ self.assertEqual(result.returncode, 1)+ self.assertIn("file not found", result.stdout + result.stderr)+ self.assertFalse((self.root / "quant.csv").exists())++ def sample_medians(self, path: Path) -> dict[str, float]:+ with path.open(encoding="utf-8", newline="") as handle:+ rows = list(csv.DictReader(handle))+ return {+ sample: statistics.median(float(row[sample]) for row in rows)+ for sample in ("one.mzML", "two.mzML")+ }++ def test_median_normalization_equalises_the_per_sample_medians(self) -> None:+ # Sample two was built 10% hotter than sample one -- medians 1600 and+ # 1500 -- which is exactly the loading difference median scaling exists+ # to remove. Comparing medians rather than a single cell keeps the+ # assertion independent of the order the linker emits features in.+ plain = self.root / "raw.csv"+ normalized = self.root / "normalized.csv"++ untouched = run_script(+ "consensus_to_matrix.py", str(self.consensus_path), "--out", str(plain),+ cwd=self.root,+ )+ self.assertEqual(untouched.returncode, 0, untouched.stderr)+ before = self.sample_medians(plain)+ self.assertAlmostEqual(before["one.mzML"], 1500.0, places=3)+ self.assertAlmostEqual(before["two.mzML"], 1600.0, places=3)++ scaled = run_script(+ "consensus_to_matrix.py", str(self.consensus_path), "--out", str(normalized),+ "--normalize", "median", cwd=self.root,+ )+ self.assertEqual(scaled.returncode, 0, scaled.stderr)+ self.assertIn("Applied median normalization", scaled.stdout)+ after = self.sample_medians(normalized)+ self.assertAlmostEqual(after["one.mzML"], after["two.mzML"], delta=1.0)+ # And the scaling really moved something.+ self.assertNotAlmostEqual(after["two.mzML"], before["two.mzML"], places=3)+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/pysam/test_scripts.py b/tests/pysam/test_scripts.pynew file mode 100644index 00000000..9b26e1d6--- /dev/null+++ b/tests/pysam/test_scripts.py@@ -0,0 +1,286 @@+"""Tests for the pysam alignment helpers.++Reading a BAM needs pysam, but the decisions these scripts make before opening+one do not: the file-mode chosen from the suffix (`rb` vs `rc` vs `r` -- get it+wrong and htslib misreads the file), the argument validators, and the+destination checks that stop a filter run from overwriting its own input.++Where a real alignment is needed the tests build one with pysam and skip when+it is unavailable, so the suite is meaningful in the project environment and+complete under `--isolated`.+"""++from __future__ import annotations++import argparse+import sys+import tempfile+import unittest+from pathlib import Path++import pytest++import skill_contract++SKILL_ROOT = Path(__file__).resolve().parents[2] / "skills" / "pysam"+SCRIPTS = SKILL_ROOT / "scripts"+sys.path.insert(0, str(SCRIPTS))++pysam = pytest.importorskip("pysam", reason="pysam skill needs pysam")++import alignment_qc # noqa: E402+import filter_alignments # noqa: E402+import inspect_hts # noqa: E402++CliHelpTests = skill_contract.cli.help_test_case(SKILL_ROOT)+++class ArgumentValidatorTests(unittest.TestCase):+ def test_positive_int_accepts_only_values_above_zero(self) -> None:+ self.assertEqual(alignment_qc.positive_int("5"), 5)+ for value in ("0", "-1"):+ with self.subTest(value=value):+ with self.assertRaises(argparse.ArgumentTypeError):+ alignment_qc.positive_int(value)++ def test_nonnegative_int_admits_zero(self) -> None:+ self.assertEqual(alignment_qc.nonnegative_int("0"), 0)+ with self.assertRaises(argparse.ArgumentTypeError):+ alignment_qc.nonnegative_int("-1")++ def test_non_numeric_input_raises(self) -> None:+ for validator in (alignment_qc.positive_int, alignment_qc.nonnegative_int):+ with self.subTest(validator=validator.__name__):+ with self.assertRaises(ValueError):+ validator("many")++ def test_the_validators_are_shared_across_the_scripts(self) -> None:+ # Three scripts define the same pair; they must agree.+ for module in (alignment_qc, filter_alignments, inspect_hts):+ with self.subTest(module=module.__name__):+ self.assertEqual(module.positive_int("3"), 3)+ self.assertEqual(module.nonnegative_int("0"), 0)+++class FileModeTests(unittest.TestCase):+ def test_the_htslib_mode_follows_the_suffix(self) -> None:+ cases = {"reads.sam": "r", "reads.bam": "rb", "reads.cram": "rc"}+ for name, expected in cases.items():+ with self.subTest(name=name):+ self.assertEqual(alignment_qc.alignment_mode(Path(name)), expected)++ def test_the_suffix_check_is_case_insensitive(self) -> None:+ self.assertEqual(alignment_qc.alignment_mode(Path("READS.BAM")), "rb")++ def test_an_unrecognised_suffix_is_refused(self) -> None:+ for name in ("reads.txt", "reads", "reads.bam.gz"):+ with self.subTest(name=name):+ with self.assertRaisesRegex(ValueError, r"\.sam, \.bam, or \.cram"):+ alignment_qc.alignment_mode(Path(name))++ def test_the_writing_mode_differs_from_the_reading_mode(self) -> None:+ # htslib needs "wb" to write a BAM; reusing "rb" silently produces SAM.+ self.assertEqual(+ filter_alignments.alignment_mode(Path("out.bam"), writing=True), "wb"+ )+ self.assertEqual(+ filter_alignments.alignment_mode(Path("out.bam"), writing=False), "rb"+ )+++class RatioTests(unittest.TestCase):+ def test_a_ratio_over_zero_is_none_rather_than_an_error(self) -> None:+ # An empty BAM must report "no reads", not divide by zero.+ self.assertIsNone(alignment_qc.ratio(0, 0))+ self.assertIsNone(alignment_qc.average(0, 0))++ def test_ordinary_ratios_and_averages(self) -> None:+ self.assertEqual(alignment_qc.ratio(1, 4), 0.25)+ self.assertEqual(alignment_qc.average(10, 4), 2.5)++ def test_a_zero_numerator_is_zero_not_none(self) -> None:+ self.assertEqual(alignment_qc.ratio(0, 10), 0.0)+++class LocalFileTests(unittest.TestCase):+ def setUp(self) -> None:+ self._temporary = tempfile.TemporaryDirectory()+ self.addCleanup(self._temporary.cleanup)+ self.root = Path(self._temporary.name)++ def test_an_existing_file_is_returned(self) -> None:+ path = self.root / "reads.bam"+ path.write_bytes(b"")+ self.assertEqual(alignment_qc.require_local_file(path, "input"), path)++ def test_a_missing_path_is_reported_with_its_label(self) -> None:+ with self.assertRaisesRegex(FileNotFoundError, "input does not exist"):+ alignment_qc.require_local_file(self.root / "absent.bam", "input")++ def test_a_directory_is_not_a_regular_file(self) -> None:+ with self.assertRaisesRegex(ValueError, "not a regular file"):+ alignment_qc.require_local_file(self.root, "input")+++class DestinationTests(unittest.TestCase):+ def setUp(self) -> None:+ self._temporary = tempfile.TemporaryDirectory()+ self.addCleanup(self._temporary.cleanup)+ self.root = Path(self._temporary.name)+ self.source = self.root / "in.bam"+ self.source.write_bytes(b"")++ def test_a_fresh_destination_is_accepted(self) -> None:+ filter_alignments.validate_destinations(+ self.source, self.root / "out.bam", None+ )++ def test_an_existing_output_is_never_overwritten(self) -> None:+ output = self.root / "out.bam"+ output.write_bytes(b"")+ with self.assertRaises(FileExistsError):+ filter_alignments.validate_destinations(self.source, output, None)++ def test_writing_over_the_input_is_refused(self) -> None:+ # Truncating the input mid-filter would destroy the only copy. The+ # exists-check happens to fire first, so accept either refusal --+ # what matters is that the call does not go through.+ with self.assertRaises((FileExistsError, ValueError)):+ filter_alignments.validate_destinations(self.source, self.source, None)++ def test_a_differently_spelled_path_to_the_input_is_also_refused(self) -> None:+ alias = self.root / "sub" / ".." / "in.bam"+ (self.root / "sub").mkdir()+ with self.assertRaises((FileExistsError, ValueError)):+ filter_alignments.validate_destinations(self.source, alias, None)++ def test_a_missing_output_directory_is_refused(self) -> None:+ with self.assertRaises(FileNotFoundError):+ filter_alignments.validate_destinations(+ self.source, self.root / "nope" / "out.bam", None+ )+++class ExclusionTests(unittest.TestCase):+ """`exclusion_reasons` decides which reads a filter run drops, and why."""++ @staticmethod+ def flags(**overrides) -> argparse.Namespace:+ defaults = dict(+ exclude_unmapped=False,+ exclude_secondary=False,+ exclude_supplementary=False,+ exclude_duplicates=False,+ exclude_qcfail=False,+ proper_pairs_only=False,+ min_mapq=0,+ )+ defaults.update(overrides)+ return argparse.Namespace(**defaults)++ @staticmethod+ def read(**attributes):+ class Read:+ is_unmapped = False+ is_secondary = False+ is_supplementary = False+ is_duplicate = False+ is_qcfail = False+ is_proper_pair = True+ mapping_quality = 60++ read = Read()+ for name, value in attributes.items():+ setattr(read, name, value)+ return read++ def test_a_clean_read_has_no_exclusion_reasons(self) -> None:+ self.assertEqual(+ filter_alignments.exclusion_reasons(self.read(), self.flags()), []+ )++ def test_each_flag_excludes_only_its_own_category(self) -> None:+ cases = [+ ("exclude_unmapped", "is_unmapped", "unmapped"),+ ("exclude_secondary", "is_secondary", "secondary"),+ ("exclude_supplementary", "is_supplementary", "supplementary"),+ ("exclude_duplicates", "is_duplicate", "duplicate"),+ ("exclude_qcfail", "is_qcfail", "qc_fail"),+ ]+ for flag, attribute, reason in cases:+ with self.subTest(flag=flag):+ read = self.read(**{attribute: True})+ # Flag off: the read survives.+ self.assertEqual(+ filter_alignments.exclusion_reasons(read, self.flags()), []+ )+ # Flag on: it is dropped with the documented reason.+ self.assertEqual(+ filter_alignments.exclusion_reasons(read, self.flags(**{flag: True})),+ [reason],+ )++ def test_a_read_below_the_mapq_threshold_is_dropped(self) -> None:+ read = self.read(mapping_quality=20)+ self.assertEqual(+ filter_alignments.exclusion_reasons(read, self.flags(min_mapq=30)),+ ["mapq_below_threshold"],+ )+ # The threshold is inclusive at the boundary.+ self.assertEqual(+ filter_alignments.exclusion_reasons(read, self.flags(min_mapq=20)), []+ )++ def test_improper_pairs_are_dropped_only_when_asked(self) -> None:+ read = self.read(is_proper_pair=False)+ self.assertEqual(filter_alignments.exclusion_reasons(read, self.flags()), [])+ self.assertEqual(+ filter_alignments.exclusion_reasons(+ read, self.flags(proper_pairs_only=True)+ ),+ ["not_proper_pair"],+ )++ def test_every_applicable_reason_is_reported_not_just_the_first(self) -> None:+ read = self.read(is_unmapped=True, is_duplicate=True, mapping_quality=0)+ reasons = filter_alignments.exclusion_reasons(+ read,+ self.flags(exclude_unmapped=True, exclude_duplicates=True, min_mapq=30),+ )+ self.assertEqual(+ set(reasons), {"unmapped", "duplicate", "mapq_below_threshold"}+ )+++class KindDetectionTests(unittest.TestCase):+ def test_the_documented_kinds_are_the_advertised_set(self) -> None:+ self.assertEqual(+ set(inspect_hts.KINDS),+ {"alignment", "variant", "fasta", "fastx", "tabix"},+ )++ def test_alignment_suffixes_are_detected(self) -> None:+ for name in ("reads.bam", "reads.sam", "reads.cram"):+ with self.subTest(name=name):+ self.assertEqual(inspect_hts.detect_kind(Path(name)), "alignment")++ def test_variant_suffixes_are_detected(self) -> None:+ for name in ("calls.vcf", "calls.vcf.gz", "calls.bcf"):+ with self.subTest(name=name):+ self.assertEqual(inspect_hts.detect_kind(Path(name)), "variant")++ def test_detection_is_case_insensitive(self) -> None:+ self.assertEqual(inspect_hts.detect_kind(Path("READS.BAM")), "alignment")++ def test_every_detected_kind_is_one_the_script_handles(self) -> None:+ for name in ("a.bam", "a.vcf", "a.fa", "a.fastq", "a.bed.gz"):+ with self.subTest(name=name):+ try:+ kind = inspect_hts.detect_kind(Path(name))+ except ValueError:+ continue+ self.assertIn(kind, inspect_hts.KINDS)+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/pytdc/test_scripts.py b/tests/pytdc/test_scripts.pyindex d77bd911..0b8220d0 100644--- a/tests/pytdc/test_scripts.py+++ b/tests/pytdc/test_scripts.py@@ -22,6 +22,8 @@ import discover_metadata as discover # noqa: E402import load_and_split_data as loader # noqa: E402import molecular_generation as molecular # noqa: E402+import skill_contract+class WorkingDirectoryTestCase(unittest.TestCase):def setUp(self) -> None:@@ -218,5 +220,10 @@ class CacheAuditTests(WorkingDirectoryTestCase):self.assertEqual(result["symlink_count_skipped"], 1)+# 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(SCRIPTS.parent)+if __name__ == "__main__":unittest.main()diff --git a/tests/pytorch-lightning/test_scripts.py b/tests/pytorch-lightning/test_scripts.pynew file mode 100644index 00000000..3e0dceb8--- /dev/null+++ b/tests/pytorch-lightning/test_scripts.py@@ -0,0 +1,443 @@+"""Tests for the PyTorch Lightning module, datamodule, and trainer templates.++A template is only useful if it runs, and these had three ways of not running.+`configure_optimizers` passed `verbose=True` to `ReduceLROnPlateau`, which+PyTorch removed, so every model built from the template raised TypeError before+the first step. Two trainer builders asked `ModelCheckpoint` for the top 3+checkpoints without a `monitor`, which Lightning rejects outright -- so those+functions could not be called on any machine. And the module demo printed+`model.num_parameters`, an attribute LightningModule does not have.++Beyond that the tests assert the configuration the templates claim, because+claiming it is the whole point: Adam at the requested learning rate with 1e-5+weight decay, a plateau scheduler watching `val/loss` on an epoch interval, a+784 -> hidden -> 10 network whose parameter count is arithmetic, and a+train/val split that is reproducible because it is seeded. One short CPU fit+then proves the pieces compose -- in particular that the metric the scheduler+monitors is one the module actually logs, which Lightning enforces at runtime.++Anything needing a GPU skips: `build_or_skip` accepts a hardware complaint but+fails on a configuration error, so the checkpoint regression stays guarded even+on a CPU-only machine.+"""++from __future__ import annotations++import sys+import tempfile+import unittest+from pathlib import Path++import pytest++import skill_contract++SKILL_ROOT = Path(__file__).resolve().parents[2] / "skills" / "pytorch-lightning"+SCRIPTS = SKILL_ROOT / "scripts"+sys.path.insert(0, str(SCRIPTS))++torch = pytest.importorskip("torch", reason="the templates need torch")+L = pytest.importorskip("lightning", reason="the templates need lightning")++from lightning.pytorch.accelerators import CUDAAccelerator, MPSAccelerator # noqa: E402+from lightning.pytorch.callbacks import ( # noqa: E402+ EarlyStopping,+ LearningRateMonitor,+ ModelCheckpoint,+)+from torch.utils.data import DataLoader, TensorDataset # noqa: E402++import quick_trainer_setup # noqa: E402+import template_datamodule # noqa: E402+import template_lightning_module # noqa: E402++# All three scripts are importable templates with a worked example under+# `if __name__ == "__main__"`, and none builds an argparse parser.+DemoBlockTests = skill_contract.cli.demo_test_case(+ SKILL_ROOT,+ (+ "template_lightning_module.py",+ "template_datamodule.py",+ "quick_trainer_setup.py",+ ),+)++CUDA_DEVICES = CUDAAccelerator.auto_device_count() if CUDAAccelerator.is_available() else 0+++def build_or_skip(test: unittest.TestCase, builder, *args, **kwargs):+ """Build a trainer, skipping when the machine lacks the hardware it wants.++ A missing accelerator is a fact about the runner. An invalid callback+ configuration is a bug in the template, so it must still fail.+ """+ try:+ return builder(*args, **kwargs)+ except Exception as error: # noqa: BLE001 - the message is the assertion+ message = str(error)+ for configuration_bug in ("top_k to track", "not a valid configuration"):+ test.assertNotIn(+ configuration_bug,+ message,+ f"{builder.__name__} is misconfigured, not hardware-limited",+ )+ test.skipTest(+ f"{builder.__name__} needs unavailable hardware "+ f"({type(error).__name__}: {message.splitlines()[0][:120]})"+ )+++class ModuleArchitectureTests(unittest.TestCase):+ def test_the_hyperparameters_are_saved_and_reachable(self) -> None:+ # save_hyperparameters() is what makes checkpoints reloadable without+ # repeating the constructor arguments.+ module = template_lightning_module.TemplateLightningModule(+ learning_rate=0.01, hidden_dim=32, dropout=0.25+ )+ self.assertEqual(+ dict(module.hparams),+ {"learning_rate": 0.01, "hidden_dim": 32, "dropout": 0.25},+ )++ def test_the_network_maps_784_inputs_to_10_logits(self) -> None:+ module = template_lightning_module.TemplateLightningModule(hidden_dim=16)+ output = module(torch.randn(5, 784))+ self.assertEqual(tuple(output.shape), (5, 10))++ def test_the_parameter_count_is_the_two_dense_layers(self) -> None:+ # 784*h + h + h*10 + 10, which the demo block now prints correctly.+ for hidden_dim in (8, 256):+ with self.subTest(hidden_dim=hidden_dim):+ module = template_lightning_module.TemplateLightningModule(+ hidden_dim=hidden_dim+ )+ self.assertEqual(+ sum(p.numel() for p in module.parameters()),+ 784 * hidden_dim + hidden_dim + hidden_dim * 10 + 10,+ )++ def test_dropout_is_active_in_training_and_disabled_in_eval(self) -> None:+ # A template that leaves dropout on at inference reports noisy metrics.+ module = template_lightning_module.TemplateLightningModule(+ hidden_dim=64, dropout=0.9+ )+ batch = torch.randn(8, 784)+ module.train()+ torch.manual_seed(0)+ first = module(batch)+ torch.manual_seed(1)+ second = module(batch)+ self.assertFalse(torch.allclose(first, second))+ module.eval()+ with torch.no_grad():+ self.assertTrue(torch.allclose(module(batch), module(batch)))+++class OptimiserConfigurationTests(unittest.TestCase):+ def setUp(self) -> None:+ self.module = template_lightning_module.TemplateLightningModule(+ learning_rate=0.003, hidden_dim=8+ )+ # The regression: ReduceLROnPlateau dropped `verbose`, so this call+ # raised TypeError and no model built from the template could train.+ self.configuration = self.module.configure_optimizers()++ def test_it_returns_an_adam_optimiser_at_the_requested_learning_rate(self) -> None:+ optimizer = self.configuration["optimizer"]+ self.assertIsInstance(optimizer, torch.optim.Adam)+ self.assertEqual(optimizer.param_groups[0]["lr"], 0.003)+ self.assertEqual(optimizer.param_groups[0]["weight_decay"], 1e-5)++ def test_the_optimiser_owns_every_model_parameter(self) -> None:+ optimised = sum(+ p.numel() for group in self.configuration["optimizer"].param_groups+ for p in group["params"]+ )+ self.assertEqual(optimised, sum(p.numel() for p in self.module.parameters()))++ def test_the_scheduler_halves_the_rate_on_a_five_epoch_plateau(self) -> None:+ scheduler = self.configuration["lr_scheduler"]["scheduler"]+ self.assertIsInstance(scheduler, torch.optim.lr_scheduler.ReduceLROnPlateau)+ self.assertEqual(scheduler.mode, "min")+ self.assertEqual(scheduler.factor, 0.5)+ self.assertEqual(scheduler.patience, 5)++ def test_the_scheduler_watches_a_metric_the_module_logs(self) -> None:+ # Lightning raises at the end of the first epoch if the monitored key+ # was never logged, so these two have to agree.+ self.assertEqual(self.configuration["lr_scheduler"]["monitor"], "val/loss")+ self.assertEqual(self.configuration["lr_scheduler"]["interval"], "epoch")+ self.assertEqual(self.configuration["lr_scheduler"]["frequency"], 1)++ def test_the_plateau_scheduler_actually_reduces_the_rate(self) -> None:+ # patience=5 means six non-improving epochs before the drop.+ scheduler = self.configuration["lr_scheduler"]["scheduler"]+ optimizer = self.configuration["optimizer"]+ for _ in range(7):+ scheduler.step(1.0)+ self.assertAlmostEqual(optimizer.param_groups[0]["lr"], 0.0015)+++class DataModuleTests(unittest.TestCase):+ """The placeholder dataset is 1000 x 3 x 224 x 224, so build it once."""++ @classmethod+ def setUpClass(cls) -> None:+ cls.datamodule = template_datamodule.TemplateDataModule(+ data_dir="./data", batch_size=8, num_workers=0, train_val_split=0.75+ )+ cls.datamodule.prepare_data()+ cls.datamodule.setup(stage="fit")++ def test_the_split_honours_the_requested_ratio(self) -> None:+ self.assertEqual(len(self.datamodule.train_dataset), 750)+ self.assertEqual(len(self.datamodule.val_dataset), 250)+ self.assertEqual(+ len(self.datamodule.train_dataset) + len(self.datamodule.val_dataset), 1000+ )++ def test_the_split_is_seeded_so_two_runs_agree(self) -> None:+ # random_split is given an explicit generator seed; without it the+ # validation set would change every run and every resumed checkpoint.+ other = template_datamodule.TemplateDataModule(+ data_dir="./data", batch_size=8, num_workers=0, train_val_split=0.75+ )+ other.setup(stage="fit")+ self.assertEqual(+ list(other.train_dataset.indices), list(self.datamodule.train_dataset.indices)+ )+ self.assertEqual(+ set(other.train_dataset.indices) & set(other.val_dataset.indices), set()+ )++ def test_the_training_loader_shuffles_and_drops_the_short_batch(self) -> None:+ loader = self.datamodule.train_dataloader()+ self.assertTrue(loader.drop_last)+ self.assertIsInstance(loader.sampler, torch.utils.data.RandomSampler)+ # 750 // 8 = 93 full batches; the remaining 6 samples are dropped.+ self.assertEqual(len(loader), 93)++ def test_the_validation_loader_keeps_order_and_every_sample(self) -> None:+ loader = self.datamodule.val_dataloader()+ self.assertIsInstance(loader.sampler, torch.utils.data.SequentialSampler)+ self.assertFalse(loader.drop_last)+ # ceil(250 / 8) = 32 batches, so nothing is silently discarded.+ self.assertEqual(len(loader), 32)++ def test_a_batch_has_the_declared_shape_and_dtypes(self) -> None:+ samples, labels = next(iter(self.datamodule.train_dataloader()))+ self.assertEqual(tuple(samples.shape), (8, 3, 224, 224))+ self.assertEqual(tuple(labels.shape), (8,))+ self.assertEqual(samples.dtype, torch.float32)+ self.assertEqual(labels.dtype, torch.int64)+ self.assertTrue(bool(((labels >= 0) & (labels < 10)).all()))++ def test_a_different_ratio_moves_the_boundary(self) -> None:+ datamodule = template_datamodule.TemplateDataModule(+ data_dir="./data", batch_size=32, num_workers=0, train_val_split=0.6+ )+ datamodule.setup(stage="fit")+ self.assertEqual(len(datamodule.train_dataset), 600)+ self.assertEqual(len(datamodule.val_dataset), 400)++ def test_the_test_and_predict_stages_build_their_own_datasets(self) -> None:+ datamodule = template_datamodule.TemplateDataModule(+ data_dir="./data", batch_size=64, num_workers=0+ )+ datamodule.setup(stage="test")+ self.assertEqual(len(datamodule.test_dataset), 1000)+ self.assertIsNone(datamodule.predict_dataset)+ datamodule.setup(stage="predict")+ self.assertEqual(len(datamodule.predict_dataset), 1000)+ self.assertEqual(len(datamodule.test_dataloader()), 16)++ def test_the_checkpointed_state_round_trips(self) -> None:+ datamodule = template_datamodule.TemplateDataModule(train_val_split=0.8)+ self.assertEqual(datamodule.state_dict(), {"train_val_split": 0.8})+ datamodule.load_state_dict({"train_val_split": 0.5})+ self.assertEqual(datamodule.hparams.train_val_split, 0.5)+ self.assertEqual(datamodule.state_dict(), {"train_val_split": 0.5})++ def test_teardown_releases_only_the_stage_it_was_given(self) -> None:+ datamodule = template_datamodule.TemplateDataModule(num_workers=0)+ datamodule.setup(stage="test")+ datamodule.teardown(stage="predict")+ self.assertIsNotNone(datamodule.test_dataset)+ datamodule.teardown(stage="test")+ self.assertIsNone(datamodule.test_dataset)++ def test_a_transform_is_applied_to_every_sample(self) -> None:+ dataset = template_datamodule.CustomDataset(+ "./data", transform=lambda sample: torch.zeros_like(sample)+ )+ sample, label = dataset[0]+ self.assertTrue(bool((sample == 0).all()))+ # The label is never passed through the transform.+ self.assertEqual(label.dtype, torch.int64)+ self.assertEqual(len(dataset), 1000)+++class TrainerConfigurationTests(unittest.TestCase):+ def test_the_basic_trainer_runs_ten_epochs_on_whatever_is_available(self) -> None:+ trainer = quick_trainer_setup.basic_trainer()+ self.assertEqual(trainer.max_epochs, 10)+ self.assertGreaterEqual(trainer.num_devices, 1)++ def test_the_debug_trainer_pins_itself_to_the_cpu(self) -> None:+ # Debugging on an accelerator hides the errors you are debugging, and+ # fast_dev_run is what makes it a debug configuration at all.+ from lightning.pytorch.accelerators import CPUAccelerator++ trainer = quick_trainer_setup.debug_trainer()+ self.assertTrue(trainer.fast_dev_run)+ self.assertIsInstance(trainer.accelerator, CPUAccelerator)+ self.assertEqual(trainer.log_every_n_steps, 1)++ def test_the_tuning_trainer_writes_nothing_and_halves_the_data(self) -> None:+ trainer = quick_trainer_setup.hyperparameter_tuning_trainer(max_epochs=5)+ self.assertEqual(trainer.max_epochs, 5)+ self.assertEqual(trainer.checkpoint_callbacks, [])+ self.assertIsNone(trainer.logger)+ self.assertEqual(trainer.limit_train_batches, 0.5)+ self.assertEqual(trainer.limit_val_batches, 0.5)++ def test_the_overfit_trainer_restricts_itself_to_the_requested_batches(self) -> None:+ trainer = quick_trainer_setup.overfit_test_trainer(num_batches=3)+ self.assertEqual(trainer.overfit_batches, 3)+ self.assertEqual(trainer.max_epochs, 100)++ def test_the_production_trainer_checkpoints_stops_early_and_tracks_the_rate(self) -> None:+ trainer = build_or_skip(self, quick_trainer_setup.production_single_gpu_trainer)+ self.assertEqual(trainer.precision, "16-mixed")+ self.assertEqual(trainer.gradient_clip_val, 1.0)+ kinds = {type(callback) for callback in trainer.callbacks}+ self.assertLessEqual(+ {ModelCheckpoint, EarlyStopping, LearningRateMonitor}, kinds+ )+ checkpointer = trainer.checkpoint_callbacks[0]+ self.assertEqual(checkpointer.monitor, "val_loss")+ self.assertEqual(checkpointer.save_top_k, 3)++ def test_the_time_limited_trainer_is_a_valid_checkpoint_configuration(self) -> None:+ # The regression: save_top_k=3 with monitor=None made this function+ # raise on every machine, GPU or not.+ trainer = build_or_skip(+ self, quick_trainer_setup.time_limited_trainer, max_time_hours=1.0+ )+ checkpointer = trainer.checkpoint_callbacks[0]+ self.assertEqual(checkpointer.save_top_k, 3)+ self.assertIsNotNone(checkpointer.monitor)+ self.assertTrue(checkpointer.save_last)++ def test_the_reproducible_trainer_seeds_and_pins_full_precision(self) -> None:+ trainer = build_or_skip(self, quick_trainer_setup.reproducible_trainer, seed=123)+ # seed_everything writes the seed where workers can read it back.+ import os++ self.assertEqual(os.environ.get("PL_GLOBAL_SEED"), "123")+ self.assertEqual(trainer.precision, "32-true")++ @unittest.skipUnless(CUDA_DEVICES >= 4, "DDP over 4 CUDA devices is unavailable")+ def test_the_ddp_trainer_shards_across_the_requested_gpus(self) -> None:+ from lightning.pytorch.strategies import DDPStrategy++ trainer = quick_trainer_setup.multi_gpu_ddp_trainer(num_gpus=4)+ self.assertIsInstance(trainer.strategy, DDPStrategy)+ self.assertEqual(trainer.num_devices, 4)++ @unittest.skipUnless(CUDA_DEVICES >= 8, "FSDP over 8 CUDA devices is unavailable")+ def test_the_fsdp_trainer_uses_bfloat16_and_accumulates(self) -> None:+ from lightning.pytorch.strategies import FSDPStrategy++ trainer = quick_trainer_setup.large_model_fsdp_trainer(num_gpus=8)+ self.assertIsInstance(trainer.strategy, FSDPStrategy)+ self.assertEqual(trainer.precision, "bf16-mixed")+ self.assertEqual(trainer.accumulate_grad_batches, 4)++ def test_the_deepspeed_trainer_selects_the_requested_stage(self) -> None:+ pytest.importorskip("deepspeed", reason="deepspeed is not installable here")+ if CUDA_DEVICES < 8:+ self.skipTest("DeepSpeed stage 3 needs 8 CUDA devices")+ trainer = quick_trainer_setup.deepspeed_trainer(stage=3)+ self.assertEqual(trainer.accumulate_grad_batches, 4)+++class TrainingLoopTests(unittest.TestCase):+ """One short CPU fit: the templates have to compose, not converge."""++ @classmethod+ def setUpClass(cls) -> None:+ torch.manual_seed(0)+ features = torch.randn(24, 784)+ labels = torch.randint(0, 10, (24,))+ cls.loader = DataLoader(TensorDataset(features, labels), batch_size=8)+ cls.module = template_lightning_module.TemplateLightningModule(+ learning_rate=0.01, hidden_dim=16, dropout=0.0+ )+ cls._directory = tempfile.TemporaryDirectory()+ cls.trainer = L.Trainer(+ max_epochs=1,+ accelerator="cpu",+ devices=1,+ logger=False,+ enable_checkpointing=False,+ enable_progress_bar=False,+ enable_model_summary=False,+ default_root_dir=cls._directory.name,+ )+ cls.trainer.fit(cls.module, cls.loader, cls.loader)+ # Snapshot now: a later trainer.test() or .predict() replaces+ # logged_metrics with that stage's own values.+ cls.fit_metrics = dict(cls.trainer.logged_metrics)++ @classmethod+ def tearDownClass(cls) -> None:+ cls._directory.cleanup()++ def test_the_fit_logs_the_metrics_the_template_documents(self) -> None:+ logged = set(self.fit_metrics)+ self.assertIn("val/loss", logged)+ self.assertIn("val/acc", logged)+ self.assertIn("learning_rate", logged)+ self.assertLessEqual({"train/loss_step", "train/loss_epoch"}, logged)++ def test_the_logged_learning_rate_is_the_configured_one(self) -> None:+ self.assertAlmostEqual(+ float(self.fit_metrics["learning_rate"]), 0.01, places=6+ )++ def test_the_losses_are_finite_and_the_accuracies_are_proportions(self) -> None:+ for name, value in self.fit_metrics.items():+ with self.subTest(metric=name):+ self.assertTrue(torch.isfinite(torch.as_tensor(value)))+ if name.endswith("acc"):+ self.assertGreaterEqual(float(value), 0.0)+ self.assertLessEqual(float(value), 1.0)++ def test_a_test_pass_reports_its_own_metrics(self) -> None:+ results = self.trainer.test(self.module, self.loader, verbose=False)+ self.assertEqual(set(results[0]), {"test/loss", "test/acc"})++ def test_prediction_returns_one_class_index_per_sample(self) -> None:+ predictions = self.trainer.predict(self.module, self.loader)+ self.assertEqual(sum(len(batch) for batch in predictions), 24)+ for batch in predictions:+ self.assertEqual(batch.dtype, torch.int64)+ self.assertTrue(bool(((batch >= 0) & (batch < 10)).all()))++ def test_training_moved_the_weights(self) -> None:+ # A fit that leaves every parameter untouched has not trained.+ fresh = template_lightning_module.TemplateLightningModule(+ learning_rate=0.01, hidden_dim=16, dropout=0.0+ )+ trained = dict(self.module.named_parameters())+ self.assertTrue(+ any(+ not torch.allclose(value, trained[name])+ for name, value in fresh.named_parameters()+ )+ )+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/qiskit/test_scripts.py b/tests/qiskit/test_scripts.pynew file mode 100644index 00000000..b30d2ade--- /dev/null+++ b/tests/qiskit/test_scripts.py@@ -0,0 +1,385 @@+"""Tests for the Qiskit environment, primitive, and backend-inspection scripts.++Three failure modes are worth guarding here. First, `run_local_primitives`+claims a specific piece of quantum mechanics: `ry(theta)` then `cx` prepares+cos(theta/2)|00> + sin(theta/2)|11>, so the sampler must only ever see `00` and+`11`, and the estimator of `1.0*ZI + 0.5*XX` must return cos(theta) ++0.5*sin(theta). Those are values known before the code runs, and at+theta = pi/2 the state is the Bell state, whose measurement distribution is+textbook. Second, `check_environment` is the script an agent trusts to decide+whether the environment is usable, so both directions matter -- a healthy+install must report `ok`, and a version drift must land in `warnings` normally+but in `errors` under `--strict`. Third, `inspect_runtime` promises to read a+backend and never submit a job; it is checked against a fake five-qubit linear+device, whose coupling map and gate set are known by construction.+"""++from __future__ import annotations++import json+import math+import sys+import unittest+from importlib import metadata+from pathlib import Path++import pytest++import skill_contract++SKILL_ROOT = Path(__file__).resolve().parents[2] / "skills" / "qiskit"+SCRIPTS = SKILL_ROOT / "scripts"+sys.path.insert(0, str(SCRIPTS))++pytest.importorskip("qiskit", reason="qiskit scripts need qiskit")+pytest.importorskip("numpy", reason="qiskit scripts need numpy")++import check_environment # noqa: E402+import inspect_runtime # noqa: E402+import run_local_primitives # noqa: E402++CliHelpTests = skill_contract.cli.help_test_case(SKILL_ROOT)+++def installed(distribution: str) -> str | None:+ """The installed version, read independently of the script under test."""+ try:+ return metadata.version(distribution)+ except metadata.PackageNotFoundError:+ return None+++class ImportProbeTests(unittest.TestCase):+ def test_a_distribution_that_is_not_installed_has_no_version(self) -> None:+ self.assertIsNone(check_environment.installed_version("no-such-distribution"))++ def test_an_installed_distribution_reports_its_version(self) -> None:+ self.assertEqual(check_environment.installed_version("qiskit"), installed("qiskit"))++ def test_a_missing_module_is_reported_with_the_import_error(self) -> None:+ status = check_environment.import_status("no_such_module_at_all")+ self.assertFalse(status["ok"])+ self.assertIsNone(status["module_file"])+ self.assertIn("ModuleNotFoundError", status["error"])++ def test_an_importable_module_reports_where_it_came_from(self) -> None:+ # The module file is what distinguishes "installed" from "importable":+ # a broken optional environment must be nameable, not just falsy.+ status = check_environment.import_status("qiskit")+ self.assertTrue(status["ok"])+ self.assertIsNone(status["error"])+ self.assertTrue(status["module_file"].endswith("__init__.py"))+++class EnvironmentReportTests(unittest.TestCase):+ def setUp(self) -> None:+ self.report, self.errors, self.warnings = check_environment.collect_report(+ require_runtime=False, require_aer=False, strict=False+ )++ def test_qiskit_alone_is_required_by_default(self) -> None:+ required = {+ name+ for name, details in self.report["packages"].items()+ if details["required"]+ }+ self.assertEqual(required, {"qiskit"})++ def test_the_optional_extras_become_required_on_request(self) -> None:+ report, _, _ = check_environment.collect_report(+ require_runtime=True, require_aer=True, strict=False+ )+ required = {+ name for name, details in report["packages"].items() if details["required"]+ }+ self.assertEqual(required, {"qiskit", "qiskit-ibm-runtime", "qiskit-aer"})++ def test_the_core_api_smoke_check_passes_on_a_working_install(self) -> None:+ # This is the whole point of the script: the imports it exercises are+ # the ones every documented workflow starts from.+ self.assertTrue(self.report["core_api_smoke_check"]["ok"])+ self.assertIsNone(self.report["core_api_smoke_check"]["error"])++ def test_ok_is_exactly_the_absence_of_errors(self) -> None:+ # main() turns this into the process exit code.+ self.assertEqual(self.report["ok"], not self.errors)++ def test_a_healthy_environment_reports_no_errors(self) -> None:+ self.assertEqual(self.errors, [])++ def test_installed_versions_are_read_from_the_metadata(self) -> None:+ for name, details in self.report["packages"].items():+ with self.subTest(distribution=name):+ self.assertEqual(details["installed_version"], installed(name))++ def test_version_drift_is_a_warning_but_an_error_under_strict(self) -> None:+ # Expectations are derived from importlib.metadata and the script's own+ # published baseline, not from the report being checked.+ drifted = {+ name: (installed(name), verified)+ for name, verified in check_environment.VERIFIED_VERSIONS.items()+ if installed(name) is not None and installed(name) != verified+ }+ strict_report, strict_errors, strict_warnings = check_environment.collect_report(+ require_runtime=True, require_aer=True, strict=True+ )+ for name, (current, verified) in drifted.items():+ message = (+ f"{name}=={current} differs from the verified baseline {verified}."+ )+ with self.subTest(distribution=name):+ self.assertFalse(+ self.report["packages"][name]["version_matches_verified"]+ )+ self.assertIn(message, self.warnings)+ self.assertNotIn(message, self.errors)+ if name in {"qiskit", "qiskit-ibm-runtime", "qiskit-aer"}:+ self.assertIn(message, strict_errors)+ self.assertNotIn(message, strict_warnings)+ for name, verified in check_environment.VERIFIED_VERSIONS.items():+ if name not in drifted and installed(name) is not None:+ with self.subTest(distribution=name, drift=False):+ self.assertTrue(+ self.report["packages"][name]["version_matches_verified"]+ )+ self.assertFalse(+ any(name in warning for warning in strict_warnings)+ )++ def test_a_clean_namespace_reports_no_legacy_terra(self) -> None:+ # Mixing qiskit-terra with qiskit 2.x is unrecoverable, so the script+ # must say so; with no terra installed the field stays empty.+ self.assertIsNone(installed("qiskit-terra"))+ self.assertIsNone(self.report["legacy_qiskit_terra"])+ self.assertFalse(any("terra" in error for error in self.errors))++ def test_the_report_survives_json_serialisation(self) -> None:+ # --json is the machine-readable contract, so every value has to be+ # JSON-safe; an exception object smuggled into it would break it.+ round_tripped = json.loads(json.dumps(self.report, sort_keys=True))+ self.assertEqual(round_tripped["packages"].keys(), self.report["packages"].keys())+++class ShotAndAngleValidationTests(unittest.TestCase):+ def test_a_shot_count_inside_the_documented_range_is_accepted(self) -> None:+ self.assertEqual(run_local_primitives.positive_bounded_shots("1"), 1)+ self.assertEqual(+ run_local_primitives.positive_bounded_shots(str(run_local_primitives.MAX_SHOTS)),+ run_local_primitives.MAX_SHOTS,+ )++ def test_shot_counts_outside_the_range_are_rejected(self) -> None:+ import argparse++ for value in ("0", "-1", str(run_local_primitives.MAX_SHOTS + 1)):+ with self.subTest(shots=value):+ with self.assertRaises(argparse.ArgumentTypeError):+ run_local_primitives.positive_bounded_shots(value)++ def test_a_finite_angle_is_accepted_and_an_infinite_one_is_not(self) -> None:+ import argparse++ self.assertEqual(run_local_primitives.finite_float("-0.5"), -0.5)+ for value in ("inf", "-inf", "nan"):+ with self.subTest(theta=value):+ with self.assertRaises(argparse.ArgumentTypeError):+ run_local_primitives.finite_float(value)+++class LocalPrimitiveWorkflowTests(unittest.TestCase):+ def test_at_theta_pi_over_two_the_circuit_is_a_bell_state(self) -> None:+ # ry(pi/2) then cx prepares (|00> + |11>)/sqrt(2). No other basis state+ # has any amplitude, so no other bitstring can ever be sampled.+ result = run_local_primitives.run_workflow(shots=2048, seed=11, theta_value=math.pi / 2)+ self.assertEqual(set(result["sampler"]["counts"]), {"00", "11"})++ def test_the_estimator_reproduces_the_analytic_expectation(self) -> None:+ # <ZI> = cos(theta) and <XX> = sin(theta) for that state, so the+ # observable 1.0*ZI + 0.5*XX has expectation cos + 0.5*sin exactly.+ for theta in (0.0, 0.7, math.pi / 2, math.pi):+ with self.subTest(theta=theta):+ result = run_local_primitives.run_workflow(+ shots=64, seed=3, theta_value=theta+ )+ estimator = result["estimator"]+ self.assertAlmostEqual(+ estimator["expectation_value"],+ math.cos(theta) + 0.5 * math.sin(theta),+ places=10,+ )+ self.assertAlmostEqual(+ estimator["analytic_expectation"],+ math.cos(theta) + 0.5 * math.sin(theta),+ places=12,+ )+ self.assertLess(estimator["absolute_error"], 1e-9)++ def test_a_zero_angle_leaves_both_qubits_in_the_ground_state(self) -> None:+ result = run_local_primitives.run_workflow(shots=256, seed=5, theta_value=0.0)+ self.assertEqual(result["sampler"]["counts"], {"00": 256})+ self.assertEqual(result["sampler"]["probabilities"], {"00": 1.0})+ self.assertAlmostEqual(result["estimator"]["expectation_value"], 1.0, places=12)++ def test_a_pi_angle_flips_both_qubits(self) -> None:+ # ry(pi)|0> = |1> up to sign, and cx then flips the second qubit.+ result = run_local_primitives.run_workflow(shots=256, seed=5, theta_value=math.pi)+ self.assertEqual(result["sampler"]["counts"], {"11": 256})+ self.assertAlmostEqual(result["estimator"]["expectation_value"], -1.0, places=12)++ def test_every_requested_shot_is_accounted_for(self) -> None:+ result = run_local_primitives.run_workflow(shots=777, seed=2, theta_value=1.0)+ self.assertEqual(sum(result["sampler"]["counts"].values()), 777)+ self.assertAlmostEqual(sum(result["sampler"]["probabilities"].values()), 1.0)++ def test_the_sampled_frequencies_match_the_analytic_probabilities(self) -> None:+ theta = 1.0+ result = run_local_primitives.run_workflow(shots=20000, seed=7, theta_value=theta)+ expected = result["sampler"]["expected_probabilities"]+ self.assertAlmostEqual(expected["00"], math.cos(theta / 2) ** 2, places=12)+ self.assertAlmostEqual(expected["11"], math.sin(theta / 2) ** 2, places=12)+ for bitstring, probability in result["sampler"]["probabilities"].items():+ with self.subTest(bitstring=bitstring):+ # 20k shots: three standard errors is under 0.011.+ self.assertAlmostEqual(probability, expected[bitstring], delta=0.02)++ def test_the_same_seed_reproduces_the_same_counts(self) -> None:+ first = run_local_primitives.run_workflow(shots=512, seed=42, theta_value=0.9)+ second = run_local_primitives.run_workflow(shots=512, seed=42, theta_value=0.9)+ self.assertEqual(first["sampler"]["counts"], second["sampler"]["counts"])++ def test_the_reported_parameter_order_is_the_circuit_binding_order(self) -> None:+ # Values are bound positionally, so a wrong order silently runs the+ # wrong circuit.+ result = run_local_primitives.run_workflow(shots=16, seed=1, theta_value=0.3)+ self.assertEqual(result["parameter_order"], ["theta"])+ self.assertEqual(result["theta"], 0.3)+++class QubitCountValidationTests(unittest.TestCase):+ def test_a_plausible_qubit_floor_is_accepted(self) -> None:+ self.assertEqual(inspect_runtime.positive_qubits("5"), 5)+ self.assertEqual(inspect_runtime.positive_qubits("10000"), 10_000)++ def test_an_implausible_qubit_floor_is_rejected(self) -> None:+ import argparse++ for value in ("0", "-3", "10001"):+ with self.subTest(qubits=value):+ with self.assertRaises(argparse.ArgumentTypeError):+ inspect_runtime.positive_qubits(value)++ def test_an_absent_distribution_reports_no_version(self) -> None:+ self.assertIsNone(inspect_runtime.distribution_version("no-such-distribution"))+ self.assertEqual(+ inspect_runtime.distribution_version("qiskit"), installed("qiskit")+ )+++class RecordingService:+ """A stand-in for QiskitRuntimeService that records how it was called."""++ def __init__(self) -> None:+ self.calls: list[tuple[str, dict]] = []++ def backend(self, name, **kwargs):+ self.calls.append(("backend", {"name": name, **kwargs}))+ return f"named:{name}"++ def least_busy(self, **kwargs):+ self.calls.append(("least_busy", kwargs))+ return "least_busy"+++class BackendSelectionTests(unittest.TestCase):+ def test_a_named_backend_is_fetched_by_name(self) -> None:+ service = RecordingService()+ selected = inspect_runtime.select_backend(+ service, "ibm_torino", min_qubits=5, use_fractional_gates=None+ )+ self.assertEqual(selected, "named:ibm_torino")+ self.assertEqual(service.calls, [("backend", {"name": "ibm_torino"})])++ def test_without_a_name_the_least_busy_real_device_is_selected(self) -> None:+ service = RecordingService()+ selected = inspect_runtime.select_backend(+ service, None, min_qubits=27, use_fractional_gates=None+ )+ self.assertEqual(selected, "least_busy")+ self.assertEqual(+ service.calls,+ [+ (+ "least_busy",+ {"operational": True, "simulator": False, "min_num_qubits": 27},+ )+ ],+ )++ def test_the_fractional_gate_flag_is_forwarded_only_when_it_is_set(self) -> None:+ # None must mean "use the service default", not "disable" -- passing+ # use_fractional_gates=False changes which target you get back.+ for requested in (True, False):+ with self.subTest(fractional=requested):+ service = RecordingService()+ inspect_runtime.select_backend(+ service, "ibm_torino", min_qubits=5, use_fractional_gates=requested+ )+ self.assertEqual(+ service.calls[0][1],+ {"name": "ibm_torino", "use_fractional_gates": requested},+ )+++class BackendInspectionTests(unittest.TestCase):+ """Checked against a fake device whose topology is known by construction."""++ @classmethod+ def setUpClass(cls) -> None:+ fake_provider = pytest.importorskip(+ "qiskit_ibm_runtime.fake_provider",+ reason="inspect_runtime needs qiskit-ibm-runtime",+ )+ cls.backend = fake_provider.FakeManilaV2()+ cls.report = inspect_runtime.inspect_backend(cls.backend)++ def test_inspecting_a_backend_submits_no_jobs(self) -> None:+ # The script's central promise: it reads a target, it never queues work.+ self.assertEqual(self.report["submitted_jobs"], 0)++ def test_the_backend_identity_is_reported(self) -> None:+ self.assertEqual(self.report["backend"]["name"], "fake_manila")+ self.assertEqual(self.report["backend"]["num_qubits"], 5)++ def test_a_five_qubit_line_has_eight_directed_coupling_edges(self) -> None:+ # Manila is a linear chain 0-1-2-3-4: four links, both directions.+ self.assertEqual(self.report["target"]["coupling_edge_count"], 8)+ edges = {tuple(edge) for edge in self.report["target"]["coupling_edges"]}+ self.assertEqual(+ edges,+ {(0, 1), (1, 0), (1, 2), (2, 1), (2, 3), (3, 2), (3, 4), (4, 3)},+ )++ def test_the_reported_basis_gates_are_the_targets_own(self) -> None:+ self.assertEqual(+ self.report["target"]["operation_names"],+ sorted(self.backend.operation_names),+ )++ def test_control_flow_support_is_reported_from_the_target(self) -> None:+ exposed = set(self.report["target"]["control_flow_operations"])+ self.assertLessEqual(exposed, {"if_else", "while_loop", "for_loop", "switch_case", "store"})+ self.assertEqual(exposed, {"for_loop", "if_else", "switch_case"} & set(self.backend.operation_names))++ def test_fractional_gates_are_not_claimed_on_a_backend_without_them(self) -> None:+ # Manila's basis is rz/sx/x/cx, so neither rx nor rzz is present and the+ # report must not advertise fractional-gate support.+ self.assertNotIn("rx", self.backend.operation_names)+ self.assertEqual(self.report["target"]["fractional_gate_candidates"], [])++ def test_the_report_survives_json_serialisation(self) -> None:+ round_tripped = json.loads(json.dumps(self.report, sort_keys=True))+ self.assertEqual(round_tripped["backend"]["num_qubits"], 5)+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/qutip/test_qutip_graphics.py b/tests/qutip/test_qutip_graphics.pyindex a7a5f507..1a0202c4 100644--- a/tests/qutip/test_qutip_graphics.py+++ b/tests/qutip/test_qutip_graphics.py@@ -4,7 +4,12 @@ from __future__ import annotationsimport unittest-import matplotlib+import pytest++# Guarded so a bare project-environment run skips cleanly instead of failing+# collection; the real run is `tests/run_all.py --isolated qutip`.+matplotlib = pytest.importorskip("matplotlib", reason="qutip graphics need matplotlib")+pytest.importorskip("qutip", reason="qutip needs qutip")matplotlib.use("Agg")diff --git a/tests/qutip/test_qutip_synthetic.py b/tests/qutip/test_qutip_synthetic.pyindex e0d92f20..54c6ceea 100644--- a/tests/qutip/test_qutip_synthetic.py+++ b/tests/qutip/test_qutip_synthetic.py@@ -7,9 +7,14 @@ import jsonimport mathimport sysimport unittest++import pytestfrom pathlib import Pathimport numpy as np+# Guarded so a bare project-environment run skips cleanly instead of failing+# collection; the real run is `tests/run_all.py --isolated qutip`.+pytest.importorskip("qutip", reason="qutip needs qutip")import qutipdiff --git a/tests/qutip/test_static.py b/tests/qutip/test_static.pyindex 7b3624fe..8b2861f7 100644--- a/tests/qutip/test_static.py+++ b/tests/qutip/test_static.py@@ -43,7 +43,7 @@ class DocumentationTests(unittest.TestCase):self.assertIn("\ncompatibility:", text)self.assertRegex(text,- r"\nmetadata:\n version: \"1\.1\"\n skill-author:"+ r"\nmetadata:\n version: \"\d+\.\d+\"\n skill-author:"r".*\n last-reviewed: \"2026-07-23\"",)diff --git a/tests/rdkit/test_scripts.py b/tests/rdkit/test_scripts.pynew file mode 100644index 00000000..a60e0e83--- /dev/null+++ b/tests/rdkit/test_scripts.py@@ -0,0 +1,273 @@+"""Tests for the RDKit cheminformatics helpers.++Every SMARTS pattern the skill ships is a claim about chemistry, and a pattern+that silently matches nothing is the failure mode: the filter reports "0 hits"+and looks like it worked. So the catalogue tests compile every pattern and then+prove each library actually matches a molecule containing that group.++Property calculation is checked against values that are true by definition --+benzene has one aromatic ring and no rotatable bonds, aspirin's formula is+C9H8O4 -- rather than against whatever RDKit currently returns.+"""++from __future__ import annotations++import sys+import tempfile+import unittest+from pathlib import Path++import pytest++import skill_contract++SKILL_ROOT = Path(__file__).resolve().parents[2] / "skills" / "rdkit"+SCRIPTS = SKILL_ROOT / "scripts"+sys.path.insert(0, str(SCRIPTS))++pytest.importorskip("rdkit", reason="rdkit skill needs rdkit")++from rdkit import Chem # noqa: E402++import molecular_properties # noqa: E402+import similarity_search # noqa: E402+import substructure_filter # noqa: E402++CliHelpTests = skill_contract.cli.help_test_case(SKILL_ROOT)++ASPIRIN = "CC(=O)OC1=CC=CC=C1C(=O)O"+CAFFEINE = "CN1C=NC2=C1C(=O)N(C)C(=O)N2C"+BENZENE = "c1ccccc1"+ETHANOL = "CCO"+++class PatternLibraryTests(unittest.TestCase):+ def test_every_shipped_smarts_pattern_compiles(self) -> None:+ # Chem.MolFromSmarts returns None rather than raising, so a typo would+ # silently disable the pattern.+ for library, patterns in substructure_filter.PATTERN_LIBRARIES.items():+ for name, smarts in patterns.items():+ with self.subTest(library=library, pattern=name):+ self.assertIsNotNone(+ Chem.MolFromSmarts(smarts), f"{name}: {smarts!r}"+ )++ def test_the_documented_libraries_are_all_present_and_non_empty(self) -> None:+ libraries = substructure_filter.PATTERN_LIBRARIES+ self.assertEqual(+ set(libraries), {"functional-groups", "rings", "pains", "privileged"}+ )+ for name, patterns in libraries.items():+ with self.subTest(library=name):+ self.assertTrue(patterns)++ def test_representative_patterns_match_the_chemistry_they_name(self) -> None:+ cases = [+ ("functional-groups", "carboxylic_acid", "CC(=O)O"),+ ("functional-groups", "alcohol", ETHANOL),+ ("functional-groups", "nitrile", "CC#N"),+ ("rings", "benzene", BENZENE),+ ("rings", "pyridine", "c1ccncc1"),+ ("privileged", "piperidine", "C1CCNCC1"),+ ("pains", "catechol", "Oc1ccccc1O"),+ ]+ for library, name, smiles in cases:+ with self.subTest(pattern=name):+ query = Chem.MolFromSmarts(+ substructure_filter.PATTERN_LIBRARIES[library][name]+ )+ molecule = Chem.MolFromSmiles(smiles)+ self.assertIsNotNone(molecule, smiles)+ self.assertTrue(+ molecule.HasSubstructMatch(query), f"{name} did not match {smiles}"+ )++ def test_a_pattern_does_not_match_a_molecule_that_lacks_it(self) -> None:+ benzene = Chem.MolFromSmiles(BENZENE)+ acid = Chem.MolFromSmarts(+ substructure_filter.PATTERN_LIBRARIES["functional-groups"]["carboxylic_acid"]+ )+ self.assertFalse(benzene.HasSubstructMatch(acid))+++class QueryTests(unittest.TestCase):+ def test_a_smarts_string_is_compiled(self) -> None:+ self.assertIsNotNone(substructure_filter.create_pattern_query("[OH][C]"))++ def test_a_plain_smiles_string_is_accepted_as_a_fallback(self) -> None:+ # SMARTS first, SMILES second -- so a user can paste either.+ self.assertIsNotNone(substructure_filter.create_pattern_query("c1ccccc1"))++ def test_an_uninterpretable_pattern_is_refused(self) -> None:+ self.assertIsNone(substructure_filter.create_pattern_query("!!not a pattern!!"))+++class FilterTests(unittest.TestCase):+ """`filter_molecules` takes (name, compiled query) pairs, not raw strings."""++ def setUp(self) -> None:+ self.molecules = [+ Chem.MolFromSmiles(smiles) for smiles in (ASPIRIN, BENZENE, ETHANOL, CAFFEINE)+ ]+ for molecule, name in zip(+ self.molecules, ("aspirin", "benzene", "ethanol", "caffeine")+ ):+ molecule.SetProp("_Name", name)++ @staticmethod+ def pattern(name: str, smarts: str) -> tuple:+ return (name, substructure_filter.create_pattern_query(smarts))++ def _names(self, molecules) -> set:+ return {molecule.GetProp("_Name") for molecule in molecules}++ def test_an_include_pattern_keeps_only_matching_molecules(self) -> None:+ kept, _ = substructure_filter.filter_molecules(+ self.molecules, include_patterns=[self.pattern("benzene", "c1ccccc1")]+ )+ self.assertEqual(self._names(kept), {"aspirin", "benzene"})++ def test_an_exclude_pattern_removes_matching_molecules(self) -> None:+ kept, _ = substructure_filter.filter_molecules(+ self.molecules, exclude_patterns=[self.pattern("benzene", "c1ccccc1")]+ )+ self.assertEqual(self._names(kept), {"ethanol", "caffeine"})++ def test_exclusion_wins_over_inclusion(self) -> None:+ kept, _ = substructure_filter.filter_molecules(+ self.molecules,+ include_patterns=[self.pattern("benzene", "c1ccccc1")],+ exclude_patterns=[self.pattern("acid", "C(=O)[OH]")],+ )+ self.assertEqual(self._names(kept), {"benzene"})++ def test_no_patterns_keeps_everything(self) -> None:+ kept, _ = substructure_filter.filter_molecules(self.molecules)+ self.assertEqual(len(kept), 4)++ def test_match_all_include_requires_every_pattern(self) -> None:+ patterns = [+ self.pattern("benzene", "c1ccccc1"),+ self.pattern("acid", "C(=O)[OH]"),+ ]+ any_match, _ = substructure_filter.filter_molecules(+ self.molecules, include_patterns=patterns+ )+ all_match, _ = substructure_filter.filter_molecules(+ self.molecules, include_patterns=patterns, match_all_include=True+ )+ self.assertEqual(self._names(any_match), {"aspirin", "benzene"})+ self.assertEqual(self._names(all_match), {"aspirin"})++ def test_the_report_records_a_status_for_every_molecule(self) -> None:+ _, report = substructure_filter.filter_molecules(+ self.molecules,+ include_patterns=[self.pattern("benzene", "c1ccccc1")],+ exclude_patterns=[self.pattern("acid", "C(=O)[OH]")],+ )+ self.assertEqual(len(report), 4)+ statuses = {entry["status"] for entry in report}+ self.assertEqual(statuses, {"included", "excluded", "no_match"})++ def test_unparseable_molecules_are_skipped_rather_than_crashing(self) -> None:+ kept, report = substructure_filter.filter_molecules(+ [None, *self.molecules]+ )+ self.assertEqual(len(kept), 4)+ self.assertEqual(len(report), 4)+++class PropertyTests(unittest.TestCase):+ def test_benzene_has_one_aromatic_ring_and_no_rotatable_bonds(self) -> None:+ properties = molecular_properties.calculate_properties(+ Chem.MolFromSmiles(BENZENE)+ )+ self.assertEqual(properties["Aromatic_Rings"], 1)+ self.assertEqual(properties["Rotatable_Bonds"], 0)+ self.assertEqual(properties["Molecular_Formula"], "C6H6")++ def test_aspirin_reports_its_formula_and_hydrogen_bonding(self) -> None:+ properties = molecular_properties.calculate_properties(+ Chem.MolFromSmiles(ASPIRIN)+ )+ self.assertEqual(properties["Molecular_Formula"], "C9H8O4")+ self.assertEqual(properties["HBD"], 1) # the carboxylic acid OH+ self.assertGreaterEqual(properties["HBA"], 3)+ self.assertAlmostEqual(properties["MW"], 180.16, delta=0.1)++ def test_heavier_molecules_have_larger_molecular_weight(self) -> None:+ light = molecular_properties.calculate_properties(Chem.MolFromSmiles(ETHANOL))+ heavy = molecular_properties.calculate_properties(Chem.MolFromSmiles(CAFFEINE))+ self.assertLess(light["MW"], heavy["MW"])++ def test_an_unparseable_smiles_is_reported_rather_than_crashing(self) -> None:+ result = molecular_properties.process_single_molecule("not-a-smiles")+ self.assertFalse(result)+++class FingerprintTests(unittest.TestCase):+ def setUp(self) -> None:+ self.aspirin = Chem.MolFromSmiles(ASPIRIN)+ self.caffeine = Chem.MolFromSmiles(CAFFEINE)++ def test_every_advertised_method_produces_a_fingerprint(self) -> None:+ for method in similarity_search.FINGERPRINT_METHODS:+ with self.subTest(method=method):+ self.assertIsNotNone(+ similarity_search.generate_fingerprint(self.aspirin, method)+ )++ def test_the_method_name_is_case_insensitive(self) -> None:+ lower = similarity_search.generate_fingerprint(self.aspirin, "morgan")+ upper = similarity_search.generate_fingerprint(self.aspirin, "MORGAN")+ self.assertEqual(list(lower), list(upper))++ def test_an_unknown_method_is_refused_by_name(self) -> None:+ with self.assertRaisesRegex(ValueError, "Unknown fingerprint method: ecfp99"):+ similarity_search.generate_fingerprint(self.aspirin, "ecfp99")++ def test_a_null_molecule_yields_no_fingerprint(self) -> None:+ self.assertIsNone(similarity_search.generate_fingerprint(None))++ def test_a_molecule_is_maximally_similar_to_itself(self) -> None:+ from rdkit import DataStructs++ first = similarity_search.generate_fingerprint(self.aspirin)+ second = similarity_search.generate_fingerprint(self.aspirin)+ self.assertAlmostEqual(+ DataStructs.TanimotoSimilarity(first, second), 1.0, places=9+ )++ def test_different_molecules_are_less_similar_than_identical_ones(self) -> None:+ from rdkit import DataStructs++ aspirin = similarity_search.generate_fingerprint(self.aspirin)+ caffeine = similarity_search.generate_fingerprint(self.caffeine)+ self.assertLess(DataStructs.TanimotoSimilarity(aspirin, caffeine), 1.0)++ def test_the_bit_size_is_honoured(self) -> None:+ small = similarity_search.generate_fingerprint(self.aspirin, "morgan", n_bits=512)+ self.assertEqual(len(small), 512)+++class MoleculeLoadingTests(unittest.TestCase):+ def test_a_smiles_file_is_read(self) -> None:+ with tempfile.TemporaryDirectory() as directory:+ path = Path(directory) / "molecules.smi"+ path.write_text(f"{ASPIRIN} aspirin\n{BENZENE} benzene\n", encoding="utf-8")+ molecules = similarity_search.load_molecules(str(path))+ self.assertEqual(len(molecules), 2)++ def test_an_unreadable_line_does_not_abort_the_whole_file(self) -> None:+ with tempfile.TemporaryDirectory() as directory:+ path = Path(directory) / "molecules.smi"+ path.write_text(+ f"{ASPIRIN} aspirin\nnot-a-smiles junk\n{BENZENE} benzene\n",+ encoding="utf-8",+ )+ molecules = similarity_search.load_molecules(str(path))+ self.assertEqual(len(molecules), 2)+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/research-lookup/test_research_lookup.py b/tests/research-lookup/test_research_lookup.pyindex dd555c99..218a7313 100644--- a/tests/research-lookup/test_research_lookup.py+++ b/tests/research-lookup/test_research_lookup.py@@ -24,6 +24,8 @@ from research_lookup import ( # noqa: E402build_parser,)+import skill_contract+def source(index: int,@@ -376,5 +378,10 @@ class PacketTests(unittest.TestCase):self.assertIn("https://pubmed.ncbi.nlm.nih.gov/12345678", urls)+# 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(SCRIPT_DIR.parent)+if __name__ == "__main__":unittest.main()diff --git a/tests/run_all.py b/tests/run_all.pyindex 550f586e..35e6fa78 100644--- a/tests/run_all.py+++ b/tests/run_all.py@@ -8,6 +8,10 @@ directories share top-level module names (see tests/conftest.py).python tests/run_all.py qutip pydicom # only the named skillspython tests/run_all.py -- -x --tb=long # pass extra args to pytest+A full run starts with `tests/_meta`, the repo-wide guard that checks every+skill against the shared structural contract and fails if a skill ships+`scripts/` without a suite here. Naming skills explicitly skips it.+With `--isolated`, each suite instead runs in a throwaway `uv` environmentbuilt from that skill's entry in tests/skill-requirements.toml:@@ -41,10 +45,13 @@ NO_TESTS_COLLECTED = 5def discover(names: list[str]) -> list[Path]:+ # Underscore-prefixed directories are infrastructure, not skills:+ # `_contract/` is the shared library and `_meta/` is the repo-wide guard,+ # run separately by `run_meta()` because it spans every skill at once.available = sorted(pathfor path in TESTS_DIR.iterdir()- if path.is_dir() and not path.name.startswith((".", "__"))+ if path.is_dir() and not path.name.startswith((".", "_")))if not names:return available@@ -82,6 +89,22 @@ def isolated_command(return [*command, "python", "-m", "pytest", target, *pytest_args]+def run_meta(pytest_args: list[str]) -> int:+ """Run the repo-wide guard in this interpreter, before any skill suite.++ `tests/_meta` spans every skill at once -- it is what enforces that a skill+ shipping `scripts/` has a suite here at all -- so it cannot be one of the+ per-skill processes. It imports no skill code and needs no scientific+ packages, so it always runs in the project environment, never an isolated+ one.+ """+ print("\n=== _meta " + "=" * 55)+ completed = subprocess.run(+ [sys.executable, "-m", "pytest", "tests/_meta", *pytest_args], cwd=REPO_ROOT+ )+ return completed.returncode++def main(argv: list[str]) -> int:isolated = "--isolated" in argvargv = [argument for argument in argv if argument != "--isolated"]@@ -102,6 +125,12 @@ def main(argv: list[str]) -> int:suites = discover(names)results: dict[str, int] = {}++ # Only on a full run: when the caller named skills they want those skills,+ # not a repo-wide audit.+ if not names:+ results["_meta"] = run_meta(pytest_args)+for suite in suites:print(f"\n=== {suite.name} " + "=" * max(0, 60 - len(suite.name)))target = str(suite.relative_to(REPO_ROOT))diff --git a/tests/scanpy/test_scripts.py b/tests/scanpy/test_scripts.pynew file mode 100644index 00000000..cacbba81--- /dev/null+++ b/tests/scanpy/test_scripts.py@@ -0,0 +1,221 @@+"""Tests for the scanpy pipeline scripts.++Fifteen scripts share one `_common.py`, and that shared layer is where a+mistake propagates everywhere: a format dispatched to the wrong reader, an+output written without its parent directory, a summary that omits the+embeddings a later step depends on. So the tests concentrate there, driving+real `.h5ad` round trips through a small synthetic AnnData.++The per-script tests are deliberately shallow -- they check that each CLI+parses its arguments and refuses a missing input rather than running a full+clustering pipeline, which would take minutes and prove little about the code.+"""++from __future__ import annotations++import subprocess+import sys+import tempfile+import unittest+from pathlib import Path++import pytest++import skill_contract++SKILL_ROOT = Path(__file__).resolve().parents[2] / "skills" / "scanpy"+SCRIPTS = SKILL_ROOT / "scripts"+sys.path.insert(0, str(SCRIPTS))++np = pytest.importorskip("numpy", reason="scanpy scripts need numpy")+pytest.importorskip("scanpy", reason="scanpy skill needs scanpy")+import anndata as ad # noqa: E402++import _common # noqa: E402++CliHelpTests = skill_contract.cli.help_test_case(SKILL_ROOT)+++def synthetic(n_obs: int = 20, n_vars: int = 10):+ rng = np.random.default_rng(4)+ counts = rng.poisson(3, size=(n_obs, n_vars)).astype("float32")+ adata = ad.AnnData(counts)+ adata.obs_names = [f"cell{i}" for i in range(n_obs)]+ adata.var_names = [f"Gene{i}" for i in range(n_vars)]+ return adata+++class SharedIoTestCase(unittest.TestCase):+ def setUp(self) -> None:+ self._temporary = tempfile.TemporaryDirectory()+ self.addCleanup(self._temporary.cleanup)+ self.root = Path(self._temporary.name)+++class RoundTripTests(SharedIoTestCase):+ def test_an_h5ad_round_trips_through_save_and_load(self) -> None:+ original = synthetic()+ path = self.root / "data.h5ad"+ _common.save_anndata(original, str(path))++ self.assertTrue(path.is_file())+ reloaded = _common.load_anndata(str(path))+ self.assertEqual(reloaded.shape, original.shape)+ self.assertEqual(list(reloaded.var_names), list(original.var_names))+ np.testing.assert_allclose(reloaded.X, original.X)++ def test_saving_creates_the_parent_directory(self) -> None:+ # Pipelines write to results/step3/out.h5ad before that tree exists.+ path = self.root / "results" / "step3" / "out.h5ad"+ _common.save_anndata(synthetic(), str(path))+ self.assertTrue(path.is_file())++ def test_a_csv_is_dispatched_to_the_csv_reader(self) -> None:+ path = self.root / "counts.csv"+ path.write_text("Gene1,Gene2\n1,2\n3,4\n", encoding="utf-8")+ loaded = _common.load_anndata(str(path))+ self.assertEqual(loaded.shape[1], 2)++ def test_a_missing_input_exits_with_a_message(self) -> None:+ # `die` prints to stderr and exits with a code, so check both.+ import io+ from contextlib import redirect_stderr++ stderr = io.StringIO()+ with redirect_stderr(stderr):+ with self.assertRaises(SystemExit) as raised:+ _common.load_anndata(str(self.root / "absent.h5ad"))+ self.assertEqual(raised.exception.code, 1)+ self.assertIn("input not found", stderr.getvalue())++ def test_an_unrecognised_extension_exits_rather_than_guessing(self) -> None:+ import io+ from contextlib import redirect_stderr++ path = self.root / "counts.parquet"+ path.write_bytes(b"")+ stderr = io.StringIO()+ with redirect_stderr(stderr):+ with self.assertRaises(SystemExit):+ _common.load_anndata(str(path))+ self.assertIn("unrecognized input format", stderr.getvalue())++ def test_the_extension_check_is_case_insensitive(self) -> None:+ original = synthetic()+ path = self.root / "DATA.H5AD"+ original.write_h5ad(path)+ self.assertEqual(_common.load_anndata(str(path)).shape, original.shape)+++class SummaryTests(unittest.TestCase):+ def test_the_summary_leads_with_the_matrix_shape(self) -> None:+ summary = _common.summarize(synthetic(n_obs=42, n_vars=7))+ self.assertTrue(summary.startswith("42 cells x 7 genes"))++ def test_annotations_and_embeddings_are_listed(self) -> None:+ adata = synthetic()+ adata.obs["leiden"] = ["0"] * adata.n_obs+ adata.obsm["X_pca"] = np.zeros((adata.n_obs, 2))+ adata.layers["counts"] = adata.X.copy()++ summary = _common.summarize(adata)+ self.assertIn("obs: leiden", summary)+ self.assertIn("obsm: X_pca", summary)+ self.assertIn("layers: counts", summary)++ def test_a_bare_matrix_summarises_to_one_line(self) -> None:+ # anndata >= 0.13 reports an unnamed `None` key on `.layers` standing+ # for X, which must not be rendered as a layer (and must not raise).+ self.assertEqual(len(_common.summarize(synthetic()).splitlines()), 1)++ def test_the_unnamed_x_layer_is_never_listed(self) -> None:+ adata = synthetic()+ self.assertIn(None, list(adata.layers.keys()))+ self.assertNotIn("layers:", _common.summarize(adata))++ def test_the_obs_listing_is_capped(self) -> None:+ # A dataset with hundreds of obs columns must not print all of them.+ adata = synthetic()+ for index in range(50):+ adata.obs[f"column{index}"] = 0+ obs_line = [+ line for line in _common.summarize(adata).splitlines()+ if line.startswith("obs:")+ ][0]+ self.assertEqual(len(obs_line.removeprefix("obs: ").split(", ")), 20)+++class ArgumentTests(unittest.TestCase):+ def test_the_shared_io_arguments_are_attached(self) -> None:+ import argparse++ parser = _common.add_io_args(argparse.ArgumentParser())+ args = parser.parse_args(["input.h5ad"])+ self.assertEqual(args.input, "input.h5ad")+ self.assertEqual(args.figdir, "figures")+ self.assertIsNone(args.output)++ def test_a_default_output_is_advertised_in_the_help(self) -> None:+ import argparse++ parser = _common.add_io_args(+ argparse.ArgumentParser(), default_output="processed.h5ad"+ )+ self.assertEqual(parser.parse_args(["in.h5ad"]).output, "processed.h5ad")+ self.assertIn("processed.h5ad", parser.format_help())++ def test_the_output_flag_overrides_the_default(self) -> None:+ import argparse++ parser = _common.add_io_args(argparse.ArgumentParser(), default_output="d.h5ad")+ self.assertEqual(+ parser.parse_args(["in.h5ad", "-o", "mine.h5ad"]).output, "mine.h5ad"+ )+++class ConfigurationTests(unittest.TestCase):+ def test_configuring_scanpy_creates_the_figure_directory(self) -> None:+ with tempfile.TemporaryDirectory() as directory:+ figures = Path(directory) / "figures"+ _common.configure_scanpy(figdir=str(figures))+ self.assertTrue(figures.is_dir())++ def test_the_dpi_and_verbosity_reach_scanpy(self) -> None:+ import scanpy as sc++ with tempfile.TemporaryDirectory() as directory:+ _common.configure_scanpy(figdir=directory, dpi=77, verbosity=0)+ self.assertEqual(sc.settings.verbosity, 0)+++class PipelineCliTests(unittest.TestCase):+ """Every script refuses a missing input instead of failing deep inside."""++ def setUp(self) -> None:+ self._temporary = tempfile.TemporaryDirectory()+ self.addCleanup(self._temporary.cleanup)+ self.root = Path(self._temporary.name)++ def test_each_cli_reports_a_missing_input_cleanly(self) -> None:+ scripts = [+ path+ for path in sorted(SCRIPTS.glob("*.py"))+ if path.name not in {"_common.py", "run_pipeline.py"}+ ]+ self.assertTrue(scripts)+ for script in scripts:+ with self.subTest(script=script.name):+ result = subprocess.run(+ [sys.executable, str(script), str(self.root / "absent.h5ad")],+ capture_output=True,+ text=True,+ timeout=300,+ cwd=self.root,+ )+ self.assertNotEqual(result.returncode, 0, f"{script.name} accepted it")+ combined = result.stdout + result.stderr+ self.assertNotIn("Traceback", combined, script.name)+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/scholar-evaluation/test_scripts.py b/tests/scholar-evaluation/test_scripts.pyindex 5d5fa994..d6658e62 100644--- a/tests/scholar-evaluation/test_scripts.py+++ b/tests/scholar-evaluation/test_scripts.py@@ -3,9 +3,7 @@from __future__ import annotationsimport ast-import copyimport json-import reimport sysimport tempfileimport unittest@@ -117,26 +115,11 @@ class StaticSafetyTests(unittest.TestCase):def test_skill_is_versioned_and_under_500_lines(self) -> None:text = (SKILL_ROOT / "SKILL.md").read_text(encoding="utf-8")self.assertLess(len(text.splitlines()), 500)- self.assertIn('metadata:\n version: "2.1"', text)+ self.assertRegex(text, r'\nmetadata:\n version: "\d+\.\d+"\n')self.assertIn("license: MIT", text)self.assertIn("compatibility:", text)self.assertNotIn("OPENROUTER", text)- def test_documented_local_paths_exist(self) -> None:- pattern = re.compile(- r"`((?:assets|references|scripts)/[A-Za-z0-9_.-]+)`"- )- documents = [- SKILL_ROOT / "SKILL.md",- *sorted((SKILL_ROOT / "references").glob("*.md")),- ]- missing = []- for document in documents:- for relative in pattern.findall(document.read_text(encoding="utf-8")):- if not (SKILL_ROOT / relative).is_file():- missing.append(f"{document.name}:{relative}")- self.assertEqual(missing, [])-def test_expected_assets_only(self) -> None:expected = {"evaluation_template.json",@@ -148,14 +131,6 @@ class StaticSafetyTests(unittest.TestCase):actual = {path.name for path in ASSETS.iterdir() if path.is_file()}self.assertEqual(actual, expected)- def test_no_bytecode_artifacts(self) -> None:- artifacts = [- path- for path in SKILL_ROOT.rglob("*")- if path.suffix in {".pyc", ".pyo"}- ]- self.assertEqual(artifacts, [])-def test_all_script_help_is_dependency_free(self) -> None:modules = (calculate_scores,diff --git a/tests/scientific-brainstorming/test_scripts.py b/tests/scientific-brainstorming/test_scripts.pyindex 045ade31..f50a2909 100644--- a/tests/scientific-brainstorming/test_scripts.py+++ b/tests/scientific-brainstorming/test_scripts.py@@ -18,6 +18,8 @@ import session_scaffoldimport validate_registerfrom _common import MAX_INPUT_BYTES, CliError, read_json, write_json+import skill_contract+def populated_register() -> dict:"""Return a small valid synthetic register."""@@ -274,5 +276,10 @@ class MatrixTests(unittest.TestCase):evaluate_matrix.load_scores(str(scores), criteria)+# 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(SKILL_ROOT)+if __name__ == "__main__":unittest.main()diff --git a/tests/scientific-schematics/test_scripts.py b/tests/scientific-schematics/test_scripts.pynew file mode 100644index 00000000..db10e79b--- /dev/null+++ b/tests/scientific-schematics/test_scripts.py@@ -0,0 +1,77 @@+"""Tests for the scientific-schematics generator.++The environment-allowlist and CLI behaviour live in the shared contract, since+`latex-posters` and `literature-review` ship byte-identical copies of both+scripts. What is specific to this skill is its bundled `example_usage.sh` and+the document-type quality thresholds the CLI advertises.+"""++from __future__ import annotations++import subprocess+import sys+import unittest+from pathlib import Path++import skill_contract++SKILL_ROOT = Path(__file__).resolve().parents[2] / "skills" / "scientific-schematics"+SCRIPTS = SKILL_ROOT / "scripts"+sys.path.insert(0, str(SCRIPTS))++SchematicTests = skill_contract.schematic.schematic_test_case(SKILL_ROOT)+CliHelpTests = skill_contract.cli.help_test_case(SKILL_ROOT)+++class DocumentTypeTests(unittest.TestCase):+ def test_every_advertised_document_type_is_an_accepted_choice(self) -> None:+ # The help epilogue lists thresholds per document type; a type named+ # there but absent from `choices` fails only at the user's keyboard.+ result = skill_contract.cli.run_help(SCRIPTS / "generate_schematic.py")+ self.assertEqual(result.returncode, 0, result.stderr)+ help_text = result.stdout++ source = (SCRIPTS / "generate_schematic.py").read_text(encoding="utf-8")+ for document_type in (+ "journal", "conference", "poster", "presentation",+ "thesis", "grant", "preprint", "report", "default",+ ):+ with self.subTest(document_type=document_type):+ self.assertIn(document_type, help_text)+ self.assertIn(f'"{document_type}"', source)++ def test_the_output_flag_is_required(self) -> None:+ result = subprocess.run(+ [sys.executable, str(SCRIPTS / "generate_schematic.py"), "a diagram"],+ capture_output=True,+ text=True,+ timeout=60,+ )+ self.assertNotEqual(result.returncode, 0)+ self.assertIn("--output", result.stderr)+++class ExampleScriptTests(unittest.TestCase):+ def test_the_bundled_example_is_executable_shell(self) -> None:+ example = SCRIPTS / "example_usage.sh"+ self.assertTrue(example.is_file())+ self.assertTrue(example.stat().st_mode & 0o111, "not executable")+ self.assertTrue(+ example.read_text(encoding="utf-8").startswith("#!"), "no shebang"+ )+ syntax = subprocess.run(+ ["bash", "-n", str(example)], capture_output=True, text=True, timeout=30+ )+ self.assertEqual(syntax.returncode, 0, syntax.stderr)++ def test_the_example_only_invokes_scripts_the_skill_ships(self) -> None:+ text = (SCRIPTS / "example_usage.sh").read_text(encoding="utf-8")+ for token in text.split():+ if token.endswith(".py"):+ with self.subTest(script=token):+ name = Path(token).name+ self.assertTrue((SCRIPTS / name).is_file(), f"{name} is not shipped")+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/scientific-slides/test_scripts.py b/tests/scientific-slides/test_scripts.pynew file mode 100644index 00000000..6792890a--- /dev/null+++ b/tests/scientific-slides/test_scripts.py@@ -0,0 +1,984 @@+"""Tests for the scientific-slides tooling.++`generate_schematic.py` and `generate_schematic_ai.py` are byte-identical to the+copies in four other skills, so their behaviour comes from the shared contract+(`skill_contract.schematic`) rather than being re-tested here. What is specific+to this skill is the slide pipeline, and each group of tests below guards one way+it fails quietly:++* `validate_presentation.py` is the gate before a talk is delivered. Its slide+ budget is checked in both directions -- a deck inside the range must be+ reported as fine, one outside it must be warned about -- and against the+ one-slide-per-minute rule its own `assets/timing_guidelines.md` documents. The+ PDF path is driven with real two-page PDFs whose 16:9 and 4:3 geometry is known+ by construction, which is also what caught a bug: the script imported the+ retired `PyPDF2` only, so with the maintained `pypdf` installed every PDF check+ silently degraded to "not installed".+* `pdf_to_images.py` converts at a requested DPI. 144 DPI on a 720-point page is+ 1440 pixels, so the zoom arithmetic is checked against the rendered size rather+ than assumed.+* `slides_to_pdf.py` decides slide *order* from filenames, so `02` must land+ before `10`; a lexicographic sort would silently reorder a talk.+* The AI scripts are exercised without touching the network: the OpenRouter+ request is mocked, and what is asserted is the quality-threshold decision, the+ response parsing, the retry loop, and that the API key travels in the child's+ environment rather than on its command line.+"""++from __future__ import annotations++import base64+import contextlib+import io+import os+import subprocess+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" / "scientific-slides"+SCRIPTS = SKILL_ROOT / "scripts"+sys.path.insert(0, str(SCRIPTS))++# `slides_to_pdf` exits at import time when Pillow is missing, so the guard has+# to come first: without it a bare environment turns a skip into a collection+# error for the whole module.+Image = pytest.importorskip("PIL.Image", reason="the slide scripts need Pillow")++import generate_slide_image # noqa: E402 (standard library only)+import pdf_to_images # noqa: E402+import slides_to_pdf # noqa: E402+import validate_presentation # noqa: E402++SchematicTests = skill_contract.schematic.schematic_test_case(SKILL_ROOT)+CliHelpTests = skill_contract.cli.help_test_case(SKILL_ROOT)+++def child_environment() -> dict[str, str]:+ """This process's environment minus any real OpenRouter credential."""+ environment = {**os.environ, "PYTHONDONTWRITEBYTECODE": "1"}+ environment.pop("OPENROUTER_API_KEY", None)+ return environment+++class TemporaryDirectoryTestCase(unittest.TestCase):+ def setUp(self) -> None:+ self._temporary = tempfile.TemporaryDirectory()+ self.addCleanup(self._temporary.cleanup)+ self.root = Path(self._temporary.name)++ def deck(self, pages: int = 2, size: tuple[int, int] = (1280, 720)) -> Path:+ """A PDF of `pages` blank slides, one point per pixel at 72 dpi."""+ images = [Image.new("RGB", size, (255, 255, 255)) for _ in range(pages)]+ path = self.root / f"deck_{pages}_{size[0]}x{size[1]}.pdf"+ images[0].save(+ path, "PDF", resolution=72, save_all=True, append_images=images[1:]+ )+ return path++ #: Fill colour per image mode -- Pillow wants a scalar for single-band modes.+ FILL = {"RGB": (200, 200, 200), "RGBA": (200, 200, 200, 255), "L": 200, "P": 200}++ def image(self, name: str, size: tuple[int, int] = (320, 180), mode="RGB") -> Path:+ path = self.root / name+ path.parent.mkdir(parents=True, exist_ok=True)+ Image.new(mode, size, self.FILL[mode]).save(path)+ return path+++def validated(path, duration=None) -> dict:+ validator = validate_presentation.PresentationValidator(str(path), duration)+ with contextlib.redirect_stdout(io.StringIO()):+ return validator.validate()+++class SlideBudgetTests(unittest.TestCase):+ GUIDELINES = validate_presentation.PresentationValidator.SLIDE_GUIDELINES++ def counted(self, slides: int, duration: int) -> dict:+ validator = validate_presentation.PresentationValidator("talk.pdf", duration)+ validator._check_slide_count(slides)+ return {"info": validator.info, "warnings": validator.warnings}++ def test_every_duration_brackets_its_recommendation(self) -> None:+ for duration, (minimum, recommended, maximum) in self.GUIDELINES.items():+ with self.subTest(duration=duration):+ self.assertLess(minimum, recommended)+ self.assertLess(recommended, maximum)++ def test_the_budget_grows_with_the_talk_length(self) -> None:+ recommended = [self.GUIDELINES[key][1] for key in sorted(self.GUIDELINES)]+ self.assertEqual(recommended, sorted(recommended))++ def test_the_recommendations_track_one_slide_per_minute(self) -> None:+ # The rule the skill's own timing_guidelines.md is built on; a table that+ # drifted far from it would contradict the guidance it ships with.+ for duration, (_, recommended, _) in self.GUIDELINES.items():+ with self.subTest(duration=duration):+ self.assertGreaterEqual(recommended / duration, 0.8)+ self.assertLessEqual(recommended / duration, 1.25)++ def test_the_ranges_overlap_the_shipped_timing_asset(self) -> None:+ # assets/timing_guidelines.md tabulates "Duration | Total Slides"; the+ # validator must not call a deck too long when that table calls it right.+ table = (SKILL_ROOT / "assets" / "timing_guidelines.md").read_text(+ encoding="utf-8"+ )+ import re++ rows = re.findall(r"^\|\s*(\d+)\s*min\s*\|\s*(\d+)-(\d+)", table, re.MULTILINE)+ self.assertTrue(rows, "the timing asset no longer tabulates slide counts")+ for duration, low, high in rows:+ duration, low, high = int(duration), int(low), int(high)+ if duration not in self.GUIDELINES:+ continue+ minimum, _, maximum = self.GUIDELINES[duration]+ with self.subTest(duration=duration):+ self.assertLessEqual(minimum, high)+ self.assertGreaterEqual(maximum, low)++ def test_a_deck_inside_the_range_is_reported_as_fine(self) -> None:+ # 16 slides for a 15-minute talk: squarely inside 13-20.+ result = self.counted(16, 15)+ self.assertEqual(result["warnings"], [])+ self.assertTrue(+ any("within recommended range" in line for line in result["info"])+ )++ def test_too_few_slides_warns_about_the_empty_time(self) -> None:+ result = self.counted(4, 15)+ self.assertTrue(result["warnings"])+ self.assertIn("Fewer slides", result["warnings"][0])++ def test_too_many_slides_warns_about_running_over(self) -> None:+ result = self.counted(40, 15)+ self.assertTrue(result["warnings"])+ self.assertIn("run over time", result["warnings"][0])++ def test_the_boundaries_themselves_are_acceptable(self) -> None:+ minimum, _, maximum = self.GUIDELINES[15]+ for slides in (minimum, maximum):+ with self.subTest(slides=slides):+ self.assertEqual(self.counted(slides, 15)["warnings"], [])++ def test_an_untabulated_duration_borrows_the_nearest_one(self) -> None:+ # 12 minutes is closest to the 10-minute row, and the substitution has+ # to be stated or the numbers look wrong to the user.+ result = self.counted(11, 12)+ self.assertTrue(+ any("guidelines for 10-minute" in line for line in result["info"]),+ result["info"],+ )+++class ValidatorFileTests(TemporaryDirectoryTestCase):+ def test_a_missing_file_is_the_only_thing_reported(self) -> None:+ result = validated(self.root / "absent.pdf")+ self.assertFalse(result["valid"])+ self.assertIn("File not found", result["issues"][0])++ def test_an_unsupported_extension_warns_but_does_not_fail(self) -> None:+ path = self.root / "talk.key"+ path.write_bytes(b"")+ result = validated(path)+ self.assertTrue(result["valid"])+ self.assertTrue(any("Unknown file type" in line for line in result["warnings"]))++ def test_the_file_type_is_recognised_case_insensitively(self) -> None:+ validator = validate_presentation.PresentationValidator("TALK.PDF")+ self.assertEqual(validator.file_type, ".pdf")++ def sized(self, megabytes: float) -> dict:+ path = self.root / f"deck_{megabytes}.pdf"+ with path.open("wb") as handle:+ handle.truncate(int(megabytes * 1024 * 1024)) # sparse, not written+ validator = validate_presentation.PresentationValidator(str(path))+ validator._check_file_size()+ return {"info": validator.info, "warnings": validator.warnings,+ "issues": validator.issues}++ def test_an_ordinary_deck_size_is_only_reported(self) -> None:+ result = self.sized(4)+ self.assertEqual(result["warnings"], [])+ self.assertEqual(result["issues"], [])+ self.assertIn("4.00 MB", result["info"][0])++ def test_a_large_deck_warns_about_sharing_it(self) -> None:+ result = self.sized(60)+ self.assertTrue(result["warnings"])+ self.assertEqual(result["issues"], [])++ def test_an_enormous_deck_is_an_issue_not_a_warning(self) -> None:+ result = self.sized(120)+ self.assertTrue(result["issues"])+ self.assertIn("compressing images", result["issues"][0])+++class ValidatorPdfTests(TemporaryDirectoryTestCase):+ def setUp(self) -> None:+ super().setUp()+ if not validate_presentation.HAS_PDF_READER:+ self.skipTest("neither pypdf nor PyPDF2 is installed")++ def test_a_widescreen_deck_reports_its_page_count_and_ratio(self) -> None:+ # Regression: with only pypdf installed this whole branch used to be+ # skipped, and the validator reported nothing about the deck at all.+ result = validated(self.deck(pages=2, size=(1280, 720)))+ self.assertTrue(result["valid"], result["issues"])+ joined = "\n".join(result["info"])+ self.assertIn("Number of slides: 2", joined)+ self.assertIn("16:9", joined)++ def test_a_four_by_three_deck_is_recognised(self) -> None:+ result = validated(self.deck(pages=1, size=(1024, 768)))+ self.assertIn("4:3", "\n".join(result["info"]))++ def test_an_unusual_aspect_ratio_is_flagged_for_the_venue(self) -> None:+ result = validated(self.deck(pages=1, size=(1000, 1000)))+ self.assertTrue(+ any("Unusual aspect ratio" in line for line in result["warnings"])+ )++ def test_the_slide_dimensions_are_reported_in_inches(self) -> None:+ # 1280 x 720 points at 72 points per inch is 17.8" x 10.0".+ result = validated(self.deck(pages=1, size=(1280, 720)))+ self.assertIn('17.8" × 10.0"', "\n".join(result["info"]))++ def test_the_page_count_is_measured_against_the_duration(self) -> None:+ result = validated(self.deck(pages=2, size=(1280, 720)), duration=15)+ self.assertTrue(any("Fewer slides" in line for line in result["warnings"]))++ def test_a_corrupt_pdf_is_an_issue_rather_than_a_traceback(self) -> None:+ path = self.root / "broken.pdf"+ path.write_bytes(b"%PDF-1.4\nnot really a pdf\n")+ result = validated(path)+ self.assertFalse(result["valid"])+ self.assertIn("Error reading PDF", result["issues"][0])+++class ValidatorLatexTests(TemporaryDirectoryTestCase):+ """The compile step is stubbed: whether pdflatex exists is not the subject."""++ def source(self) -> Path:+ path = self.root / "talk.tex"+ path.write_text("\\documentclass{beamer}\\begin{document}\\end{document}")+ return path++ def test_a_failed_compile_is_an_issue_pointing_at_the_log(self) -> None:+ path = self.source()+ with mock.patch("subprocess.run", side_effect=FileNotFoundError):+ result = validated(path)+ self.assertFalse(result["valid"])+ self.assertIn(".log", result["issues"][0])++ def test_a_successful_compile_folds_in_the_pdf_report(self) -> None:+ if not validate_presentation.HAS_PDF_READER:+ self.skipTest("neither pypdf nor PyPDF2 is installed")+ path = self.source()+ # pdflatex writes talk.pdf beside talk.tex; produce one it can find.+ self.deck(pages=3, size=(1280, 720)).replace(path.with_suffix(".pdf"))+ completed = subprocess.CompletedProcess(args=[], returncode=0)+ with mock.patch("subprocess.run", return_value=completed):+ result = validated(path)+ joined = "\n".join(result["info"])+ self.assertIn("LaTeX compilation: SUCCESS", joined)+ # The merged PDF report is what makes the .tex path useful.+ self.assertIn("Number of slides: 3", joined)++ def test_the_compile_never_enables_shell_escape(self) -> None:+ # Shell escape in a LaTeX source would run arbitrary commands.+ path = self.source()+ with mock.patch("subprocess.run", side_effect=FileNotFoundError) as run:+ validated(path)+ self.assertIn("-no-shell-escape", run.call_args.args[0])+ self.assertIn("-interaction=nonstopmode", run.call_args.args[0])+++class ValidatorPptxTests(TemporaryDirectoryTestCase):+ def setUp(self) -> None:+ super().setUp()+ if not validate_presentation.HAS_PPTX:+ self.skipTest("python-pptx is not installed")++ def build(self, *, font_pt: int, bullets: int) -> Path:+ from pptx import Presentation+ from pptx.util import Inches, Pt++ presentation = Presentation()+ slide = presentation.slides.add_slide(presentation.slide_layouts[6])+ box = slide.shapes.add_textbox(Inches(1), Inches(1), Inches(6), Inches(4))+ frame = box.text_frame+ for index in range(bullets):+ paragraph = frame.paragraphs[0] if index == 0 else frame.add_paragraph()+ run = paragraph.add_run()+ run.text = f"point {index}"+ run.font.size = Pt(font_pt)+ path = self.root / f"deck_{font_pt}_{bullets}.pptx"+ presentation.save(path)+ return path++ def test_a_readable_uncluttered_slide_raises_nothing(self) -> None:+ result = validated(self.build(font_pt=24, bullets=3))+ self.assertTrue(result["valid"])+ self.assertEqual(+ [line for line in result["warnings"] if "text" in line or "bullets" in line],+ [],+ )++ def test_text_below_eighteen_point_is_flagged_with_the_slide_number(self) -> None:+ # 18 pt is the projection floor the skill documents.+ result = validated(self.build(font_pt=12, bullets=2))+ self.assertTrue(+ any("Small text (<18pt)" in line and "[1]" in line+ for line in result["warnings"]),+ result["warnings"],+ )++ def test_eighteen_point_itself_is_acceptable(self) -> None:+ result = validated(self.build(font_pt=18, bullets=2))+ self.assertEqual(+ [line for line in result["warnings"] if "Small text" in line], []+ )++ def test_more_than_six_bullets_is_flagged(self) -> None:+ result = validated(self.build(font_pt=24, bullets=8))+ self.assertTrue(+ any("Many bullets (>6)" in line for line in result["warnings"]),+ result["warnings"],+ )++ def test_six_bullets_is_still_acceptable(self) -> None:+ result = validated(self.build(font_pt=24, bullets=6))+ self.assertEqual(+ [line for line in result["warnings"] if "Many bullets" in line], []+ )++ def test_the_slide_geometry_is_reported(self) -> None:+ result = validated(self.build(font_pt=24, bullets=1))+ # python-pptx's default template is 10" x 7.5", i.e. 4:3.+ self.assertIn('10.0" × 7.5"', "\n".join(result["info"]))+++class PdfToImagesTests(TemporaryDirectoryTestCase):+ def test_only_jpeg_and_png_are_accepted(self) -> None:+ for accepted in ("jpg", "jpeg", "png", "PNG"):+ with self.subTest(format=accepted):+ converter = pdf_to_images.PDFToImagesConverter(+ "deck.pdf", "out/slide", format=accepted+ )+ self.assertEqual(converter.format, accepted.lower())+ for rejected in ("gif", "tiff", "svg"):+ with self.subTest(format=rejected):+ with self.assertRaisesRegex(ValueError, "Unsupported format"):+ pdf_to_images.PDFToImagesConverter(+ "deck.pdf", "out/slide", format=rejected+ )++ def test_a_missing_pdf_is_refused_before_any_conversion(self) -> None:+ converter = pdf_to_images.PDFToImagesConverter(+ str(self.root / "absent.pdf"), str(self.root / "slide")+ )+ with contextlib.redirect_stdout(io.StringIO()):+ with self.assertRaises(FileNotFoundError):+ converter.convert()++ def convert(self, **kwargs):+ if not pdf_to_images.HAS_PYMUPDF:+ self.skipTest("PyMuPDF is not installed")+ source = self.deck(pages=3, size=(1280, 720))+ converter = pdf_to_images.PDFToImagesConverter(+ str(source), str(self.root / "review" / "slide"), **kwargs+ )+ with contextlib.redirect_stdout(io.StringIO()):+ return converter.convert()++ def test_every_page_becomes_one_zero_padded_image(self) -> None:+ produced = self.convert(dpi=72)+ self.assertEqual(+ [path.name for path in produced],+ ["slide-001.jpg", "slide-002.jpg", "slide-003.jpg"],+ )+ for path in produced:+ self.assertTrue(path.is_file())++ def test_the_output_directory_is_created_on_demand(self) -> None:+ produced = self.convert(dpi=72)+ self.assertEqual(produced[0].parent, self.root / "review")++ def test_the_requested_dpi_sets_the_pixel_size(self) -> None:+ # A 720-point-tall slide at 144 dpi is 1440 pixels: zoom = dpi / 72.+ produced = self.convert(dpi=144, format="png")+ with Image.open(produced[0]) as rendered:+ self.assertEqual(rendered.size, (2560, 1440))++ def test_a_page_range_converts_only_those_slides(self) -> None:+ produced = self.convert(dpi=72, first_page=2, last_page=3)+ # 1-indexed and inclusive, and the names keep the original numbering.+ self.assertEqual(+ [path.name for path in produced], ["slide-002.jpg", "slide-003.jpg"]+ )++ def test_the_format_decides_the_encoding_not_just_the_suffix(self) -> None:+ produced = self.convert(dpi=72, format="png")+ with Image.open(produced[0]) as rendered:+ self.assertEqual(rendered.format, "PNG")+++class ImageCollectionTests(TemporaryDirectoryTestCase):+ def test_files_are_ordered_by_name_so_numbering_decides_the_deck(self) -> None:+ # Zero-padded names sort correctly; "10" must not precede "2".+ for name in ("03_methods.png", "01_title.png", "10_end.png", "02_intro.png"):+ self.image(name)+ found = slides_to_pdf.get_image_files([str(self.root)])+ self.assertEqual(+ [path.name for path in found],+ ["01_title.png", "02_intro.png", "03_methods.png", "10_end.png"],+ )++ def test_a_directory_yields_every_supported_image(self) -> None:+ for name in ("a.png", "b.jpg", "c.jpeg", "d.bmp"):+ self.image(name)+ found = slides_to_pdf.get_image_files([str(self.root)])+ self.assertEqual(len(found), 4)++ def test_a_non_image_file_is_skipped_with_a_warning(self) -> None:+ self.image("slide.png")+ notes = self.root / "notes.txt"+ notes.write_text("not a slide")+ stream = io.StringIO()+ with contextlib.redirect_stdout(stream):+ found = slides_to_pdf.get_image_files([str(notes), str(self.root / "slide.png")])+ self.assertEqual([path.name for path in found], ["slide.png"])+ self.assertIn("Skipping non-image", stream.getvalue())++ def test_the_same_file_named_twice_appears_once(self) -> None:+ path = self.image("slide.png")+ found = slides_to_pdf.get_image_files([str(path), str(path)])+ self.assertEqual(len(found), 1)++ def test_a_glob_pattern_is_expanded(self) -> None:+ self.image("s1.png")+ self.image("s2.png")+ self.image("other.jpg")+ found = slides_to_pdf.get_image_files([str(self.root / "s*.png")])+ self.assertEqual([path.name for path in found], ["s1.png", "s2.png"])++ def test_a_path_that_matches_nothing_yields_nothing(self) -> None:+ self.assertEqual(slides_to_pdf.get_image_files([str(self.root / "*.png")]), [])+++class SlidesToPdfTests(TemporaryDirectoryTestCase):+ def combine(self, images, name="talk.pdf", **kwargs):+ destination = self.root / "out" / name+ with contextlib.redirect_stdout(io.StringIO()) as printed:+ ok = slides_to_pdf.combine_images_to_pdf(images, destination, **kwargs)+ return ok, destination, printed.getvalue()++ def page_count(self, path: Path) -> int:+ if validate_presentation.HAS_PDF_READER:+ from validate_presentation import PdfReader++ return len(PdfReader(str(path)).pages)+ self.skipTest("neither pypdf nor PyPDF2 is installed")++ def test_the_slides_become_pages_in_the_order_given(self) -> None:+ images = [self.image(f"slide{index}.png") for index in range(1, 4)]+ ok, destination, _ = self.combine(images)+ self.assertTrue(ok)+ self.assertEqual(self.page_count(destination), 3)++ def test_the_output_directory_is_created(self) -> None:+ ok, destination, _ = self.combine([self.image("slide.png")])+ self.assertTrue(ok)+ self.assertTrue(destination.is_file())++ def test_no_images_is_refused_rather_than_writing_an_empty_pdf(self) -> None:+ ok, destination, printed = self.combine([])+ self.assertFalse(ok)+ self.assertFalse(destination.exists())+ self.assertIn("No image files found", printed)++ def test_a_transparent_slide_is_flattened_onto_white(self) -> None:+ # PDF has no alpha channel; without the flattening step Pillow raises.+ ok, destination, _ = self.combine([self.image("slide.png", mode="RGBA")])+ self.assertTrue(ok)+ self.assertEqual(self.page_count(destination), 1)++ def test_a_greyscale_slide_is_converted_rather_than_rejected(self) -> None:+ ok, _, _ = self.combine([self.image("grey.png", mode="L")], name="grey.pdf")+ self.assertTrue(ok)++ def test_an_unreadable_slide_aborts_instead_of_producing_a_short_deck(self) -> None:+ broken = self.root / "broken.png"+ broken.write_bytes(b"not an image")+ ok, destination, printed = self.combine([self.image("ok.png"), broken])+ self.assertFalse(ok)+ self.assertFalse(destination.exists())+ self.assertIn("Error loading", printed)+++class SlideImageEnvironmentTests(unittest.TestCase):+ """The wrapper hands the credential to the child through the environment."""++ 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 = generate_slide_image.build_subprocess_env(None)+ self.assertEqual(built, {"PATH": "/usr/bin", "HOME": "/home/someone"})++ 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 = generate_slide_image.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 value would look configured and fail deep inside the request.+ 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",+ generate_slide_image.build_subprocess_env(value),+ )++ def test_the_allowlist_carries_no_credential_variables(self) -> None:+ forwarded = " ".join(generate_slide_image.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_matches_the_schematic_wrapper_in_this_skill(self) -> None:+ # Both wrappers in this skill spawn an AI child the same way; a variable+ # added to one and not the other breaks proxies or TLS in half the tools.+ import generate_schematic++ self.assertEqual(+ list(generate_slide_image.FORWARDED_ENV_VARS),+ list(generate_schematic.FORWARDED_ENV_VARS),+ )+++class SlideImageInvocationTests(TemporaryDirectoryTestCase):+ """What the wrapper actually spawns, with the subprocess intercepted."""++ def invoke(self, *arguments):+ completed = subprocess.CompletedProcess(args=[], returncode=0)+ argv = ["generate_slide_image.py", *arguments]+ with mock.patch.object(sys, "argv", argv), \+ mock.patch.dict(os.environ, {"OPENROUTER_API_KEY": "sk-or-test"}), \+ mock.patch("subprocess.run", return_value=completed) as run:+ with contextlib.redirect_stdout(io.StringIO()):+ with self.assertRaises(SystemExit) as raised:+ generate_slide_image.main()+ self.assertEqual(raised.exception.code, 0)+ return run.call_args++ def test_the_generator_script_beside_it_is_what_runs(self) -> None:+ command = self.invoke("a title slide", "-o", str(self.root / "slide.png"))+ self.assertEqual(+ Path(command.args[0][1]).name, "generate_slide_image_ai.py"+ )+ self.assertEqual(command.args[0][0], sys.executable)++ def test_the_credential_never_appears_on_the_command_line(self) -> None:+ command = self.invoke("a slide", "-o", str(self.root / "slide.png"))+ self.assertNotIn("sk-or-test", " ".join(command.args[0]))+ self.assertEqual(command.kwargs["env"]["OPENROUTER_API_KEY"], "sk-or-test")++ def test_the_visual_only_mode_is_forwarded(self) -> None:+ command = self.invoke("a figure", "-o", "f.png", "--visual-only")+ self.assertIn("--visual-only", command.args[0])++ def test_each_attachment_is_forwarded_in_order(self) -> None:+ command = self.invoke(+ "compare these", "-o", "c.png", "--attach", "before.png",+ "--attach", "after.png",+ )+ forwarded = command.args[0]+ self.assertEqual(forwarded.count("--attach"), 2)+ self.assertLess(forwarded.index("before.png"), forwarded.index("after.png"))++ def test_the_iteration_ceiling_is_enforced_by_the_wrapper(self) -> None:+ # Two is the documented maximum; a larger request is clamped, and the+ # default is left implicit rather than passed through.+ self.assertNotIn("--iterations", self.invoke("s", "-o", "s.png").args[0])+ self.assertNotIn(+ "--iterations", self.invoke("s", "-o", "s.png", "--iterations", "5").args[0]+ )+ clamped = self.invoke("s", "-o", "s.png", "--iterations", "1").args[0]+ self.assertEqual(clamped[clamped.index("--iterations") + 1], "1")++ def test_without_a_key_nothing_is_spawned(self) -> None:+ argv = ["generate_slide_image.py", "a slide", "-o", "s.png"]+ with mock.patch.object(sys, "argv", argv), \+ mock.patch.dict(os.environ, {}, clear=True), \+ mock.patch("subprocess.run") as run:+ with contextlib.redirect_stdout(io.StringIO()) as printed:+ with self.assertRaises(SystemExit) as raised:+ generate_slide_image.main()+ self.assertEqual(raised.exception.code, 1)+ self.assertIn("OPENROUTER_API_KEY", printed.getvalue())+ run.assert_not_called()+++class SlideGeneratorTestCase(TemporaryDirectoryTestCase):+ """Base class: an offline SlideImageGenerator with a dummy credential."""++ def setUp(self) -> None:+ super().setUp()+ pytest.importorskip("requests", reason="the AI generator needs requests")+ import generate_slide_image_ai++ self.module = generate_slide_image_ai+ self.generator = generate_slide_image_ai.SlideImageGenerator(+ api_key="sk-or-test"+ )++ @staticmethod+ def data_url(payload: bytes) -> str:+ return "data:image/png;base64," + base64.b64encode(payload).decode()+++class ApiKeyTests(TemporaryDirectoryTestCase):+ def test_a_generator_without_a_credential_refuses_to_start(self) -> None:+ pytest.importorskip("requests", reason="the AI generator needs requests")+ import generate_slide_image_ai++ # Run from an empty directory: the constructor falls back to a .env in+ # the working directory, and this repository has one.+ origin = os.getcwd()+ self.addCleanup(os.chdir, origin)+ os.chdir(self.root)+ with mock.patch.dict(os.environ, {}, clear=True):+ with self.assertRaisesRegex(ValueError, "OPENROUTER_API_KEY"):+ generate_slide_image_ai.SlideImageGenerator()++ def test_the_environment_variable_is_accepted_in_place_of_an_argument(self) -> None:+ pytest.importorskip("requests", reason="the AI generator needs requests")+ import generate_slide_image_ai++ with mock.patch.dict(os.environ, {"OPENROUTER_API_KEY": "sk-or-env"}):+ generator = generate_slide_image_ai.SlideImageGenerator()+ self.assertEqual(generator.api_key, "sk-or-env")+++class GuidelineTests(SlideGeneratorTestCase):+ def test_the_presentation_threshold_is_lower_than_a_paper_figure(self) -> None:+ # Documented as deliberately below the journal/conference bar.+ self.assertEqual(self.module.SlideImageGenerator.QUALITY_THRESHOLD, 6.5)++ def test_a_full_slide_prompt_asks_for_slide_structure(self) -> None:+ guidelines = self.module.SlideImageGenerator.FULL_SLIDE_GUIDELINES+ for requirement in ("16:9", "title", "sans-serif"):+ with self.subTest(requirement=requirement):+ self.assertIn(requirement, guidelines.lower())++ def test_a_visual_only_prompt_does_not_ask_for_slide_furniture(self) -> None:+ # In the PPT workflow the text is added in PowerPoint, so a generated+ # title baked into the image would be duplicated.+ guidelines = self.module.SlideImageGenerator.VISUAL_ONLY_GUIDELINES+ self.assertNotIn("16:9", guidelines)+ self.assertIn("No text unless essential", guidelines)++ def test_the_improved_prompt_carries_the_critique_and_the_right_guidelines(self) -> None:+ for visual_only, expected in (+ (False, self.module.SlideImageGenerator.FULL_SLIDE_GUIDELINES),+ (True, self.module.SlideImageGenerator.VISUAL_ONLY_GUIDELINES),+ ):+ with self.subTest(visual_only=visual_only):+ prompt = self.generator.improve_prompt(+ "a title slide", "the text is too small", 2, visual_only+ )+ self.assertIn("the text is too small", prompt)+ self.assertIn("a title slide", prompt)+ self.assertIn(expected.strip(), prompt)+++class ImageExtractionTests(SlideGeneratorTestCase):+ PAYLOAD = b"\x89PNG\r\n\x1a\n-pretend-this-is-an-image"++ def response(self, message: dict) -> dict:+ return {"choices": [{"message": message}]}++ def test_an_image_in_the_images_field_is_decoded(self) -> None:+ response = self.response(+ {"images": [{"type": "image_url",+ "image_url": {"url": self.data_url(self.PAYLOAD)}}]}+ )+ self.assertEqual(+ self.generator._extract_image_from_response(response), self.PAYLOAD+ )++ def test_wrapped_base64_is_reassembled(self) -> None:+ # Some responses arrive hard-wrapped; the newlines are not data.+ encoded = base64.b64encode(self.PAYLOAD).decode()+ wrapped = "\n".join(encoded[index:index + 8] for index in range(0, len(encoded), 8))+ response = self.response(+ {"images": [{"type": "image_url",+ "image_url": {"url": f"data:image/png;base64,{wrapped}"}}]}+ )+ self.assertEqual(+ self.generator._extract_image_from_response(response), self.PAYLOAD+ )++ def test_an_image_embedded_in_the_content_string_is_found(self) -> None:+ response = self.response(+ {"content": f"Here you go: {self.data_url(self.PAYLOAD)} enjoy"}+ )+ self.assertEqual(+ self.generator._extract_image_from_response(response), self.PAYLOAD+ )++ def test_an_image_in_a_content_block_is_found(self) -> None:+ response = self.response(+ {"content": [+ {"type": "text", "text": "here"},+ {"type": "image_url", "image_url": {"url": self.data_url(self.PAYLOAD)}},+ ]}+ )+ self.assertEqual(+ self.generator._extract_image_from_response(response), self.PAYLOAD+ )++ def test_a_response_with_no_image_yields_none(self) -> None:+ for message in ({}, {"content": "I cannot draw that"}, {"images": []}):+ with self.subTest(message=message):+ self.assertIsNone(+ self.generator._extract_image_from_response(self.response(message))+ )++ def test_a_refusal_with_no_choices_yields_none(self) -> None:+ self.assertIsNone(self.generator._extract_image_from_response({"choices": []}))++ def test_a_truncated_data_url_yields_none_rather_than_raising(self) -> None:+ response = self.response(+ {"images": [{"type": "image_url", "image_url": {"url": "data:image/png"}}]}+ )+ self.assertIsNone(self.generator._extract_image_from_response(response))+++class AttachmentEncodingTests(SlideGeneratorTestCase):+ def test_the_mime_type_follows_the_file_extension(self) -> None:+ expected = {+ "chart.png": "image/png",+ "photo.jpg": "image/jpeg",+ "photo.jpeg": "image/jpeg",+ "loop.gif": "image/gif",+ "shot.webp": "image/webp",+ }+ for name, mime in expected.items():+ with self.subTest(name=name):+ path = self.root / name+ path.write_bytes(b"bytes")+ self.assertTrue(+ self.generator._image_to_base64(str(path)).startswith(+ f"data:{mime};base64,"+ )+ )++ def test_an_unknown_extension_falls_back_to_png(self) -> None:+ path = self.root / "figure.tiff"+ path.write_bytes(b"bytes")+ self.assertTrue(+ self.generator._image_to_base64(str(path)).startswith("data:image/png")+ )++ def test_the_encoded_payload_round_trips(self) -> None:+ path = self.root / "chart.png"+ path.write_bytes(b"\x00\x01\x02payload")+ encoded = self.generator._image_to_base64(str(path)).split(",", 1)[1]+ self.assertEqual(base64.b64decode(encoded), b"\x00\x01\x02payload")+++class ReviewDecisionTests(SlideGeneratorTestCase):+ def setUp(self) -> None:+ super().setUp()+ self.image_path = self.root / "slide.png"+ self.image_path.write_bytes(b"image bytes")++ def review(self, message: dict):+ with mock.patch.object(+ self.generator, "_make_request", return_value={"choices": [{"message": message}]}+ ):+ return self.generator.review_image(str(self.image_path), "a slide", 1)++ def test_a_score_at_the_threshold_is_accepted(self) -> None:+ # 6.5 is the threshold itself, so it must not trigger another round.+ _, score, needs_improvement = self.review(+ {"content": "SCORE: 6.5\nVERDICT: ACCEPTABLE"}+ )+ self.assertEqual(score, 6.5)+ self.assertFalse(needs_improvement)++ def test_a_score_below_the_threshold_asks_for_another_round(self) -> None:+ _, score, needs_improvement = self.review({"content": "SCORE: 6.4"})+ self.assertEqual(score, 6.4)+ self.assertTrue(needs_improvement)++ def test_an_explicit_verdict_overrides_a_high_score(self) -> None:+ # The reviewer's words win: a 9 with NEEDS_IMPROVEMENT is not accepted.+ _, score, needs_improvement = self.review(+ {"content": "SCORE: 9\nVERDICT: NEEDS_IMPROVEMENT"}+ )+ self.assertEqual(score, 9.0)+ self.assertTrue(needs_improvement)++ def test_a_loosely_worded_score_is_still_read(self) -> None:+ _, score, _ = self.review({"content": "Overall quality: 8.5 out of 10"})+ self.assertEqual(score, 8.5)++ def test_an_unscored_review_does_not_block_the_pipeline(self) -> None:+ # No parseable score: assume acceptable rather than loop pointlessly.+ _, score, needs_improvement = self.review({"content": "Looks good to me"})+ self.assertEqual(score, 7.0)+ self.assertFalse(needs_improvement)++ def test_a_review_returned_as_content_blocks_is_flattened(self) -> None:+ critique, score, _ = self.review(+ {"content": [{"type": "text", "text": "SCORE: 6.0"},+ {"type": "text", "text": "ISSUES: crowded"}]}+ )+ self.assertEqual(score, 6.0)+ self.assertIn("crowded", critique)++ def test_a_reasoning_only_reply_is_used_as_the_critique(self) -> None:+ critique, score, _ = self.review({"content": "", "reasoning": "SCORE: 6.0"})+ self.assertEqual(score, 6.0)+ self.assertIn("SCORE", critique)++ def test_a_failed_review_is_not_treated_as_a_bad_image(self) -> None:+ with mock.patch.object(+ self.generator, "_make_request", side_effect=RuntimeError("API down")+ ):+ critique, score, needs_improvement = self.generator.review_image(+ str(self.image_path), "a slide", 1+ )+ self.assertFalse(needs_improvement)+ self.assertEqual(score, 7.0)+ self.assertIn("review skipped", critique)+++class RefinementLoopTests(SlideGeneratorTestCase):+ PAYLOAD = b"first-image"+ BETTER = b"second-image"++ def generate(self, images, reviews, **kwargs):+ destination = self.root / "slides" / "01_title.png"+ with mock.patch.object(self.generator, "generate_image", side_effect=images) as drew, \+ mock.patch.object(self.generator, "review_image", side_effect=reviews):+ with contextlib.redirect_stdout(io.StringIO()):+ results = self.generator.generate_slide(+ "a title slide", str(destination), **kwargs+ )+ return results, destination, drew++ def test_a_good_first_image_stops_early_and_is_written(self) -> None:+ results, destination, drew = self.generate(+ [self.PAYLOAD], [("great", 8.0, False)]+ )+ self.assertTrue(results["success"])+ self.assertTrue(results["early_stop"])+ self.assertEqual(results["final_score"], 8.0)+ self.assertEqual(len(results["iterations"]), 1)+ self.assertEqual(drew.call_count, 1)+ # The bytes on disk are the ones that passed review.+ self.assertEqual(destination.read_bytes(), self.PAYLOAD)++ def test_a_weak_image_is_regenerated_from_an_improved_prompt(self) -> None:+ results, destination, drew = self.generate(+ [self.PAYLOAD, self.BETTER],+ [("text too small", 5.0, True), ("better", 7.5, False)],+ )+ self.assertTrue(results["success"])+ self.assertEqual(len(results["iterations"]), 2)+ self.assertEqual(destination.read_bytes(), self.BETTER)+ # The second prompt must carry the first critique, or the retry is blind.+ second_prompt = drew.call_args_list[1].args[0]+ self.assertIn("text too small", second_prompt)++ def test_the_iteration_ceiling_still_keeps_the_last_image(self) -> None:+ results, destination, drew = self.generate(+ [self.PAYLOAD, self.BETTER],+ [("bad", 3.0, True), ("still bad", 4.0, True)],+ iterations=2,+ )+ self.assertEqual(drew.call_count, 2)+ self.assertFalse(results["early_stop"])+ # Better to hand back the best effort than nothing at all.+ self.assertTrue(results["success"])+ self.assertEqual(destination.read_bytes(), self.BETTER)++ def test_a_failed_generation_writes_no_file_and_reports_failure(self) -> None:+ results, destination, _ = self.generate([None, None], [])+ self.assertFalse(results["success"])+ self.assertIsNone(results["final_image"])+ self.assertFalse(destination.exists())+ self.assertTrue(all(not step["success"] for step in results["iterations"]))++ def test_the_mode_and_threshold_are_recorded_in_the_results(self) -> None:+ results, _, _ = self.generate(+ [self.PAYLOAD], [("fine", 7.0, False)], visual_only=True+ )+ self.assertEqual(results["mode"], "visual_only")+ self.assertEqual(results["quality_threshold"], 6.5)+ self.assertEqual(results["user_prompt"], "a title slide")+++class AiCliValidationTests(TemporaryDirectoryTestCase):+ """Argument validation happens before any request is made."""++ def invoke(self, *arguments, key="sk-or-test"):+ environment = child_environment()+ if key is not None:+ environment["OPENROUTER_API_KEY"] = key+ return subprocess.run(+ [sys.executable, str(SCRIPTS / "generate_slide_image_ai.py"), *arguments],+ capture_output=True,+ text=True,+ timeout=120,+ env=environment,+ )++ def test_more_iterations_than_allowed_is_refused(self) -> None:+ result = self.invoke(+ "a slide", "-o", str(self.root / "s.png"), "--iterations", "3"+ )+ self.assertEqual(result.returncode, 1)+ self.assertIn("between 1 and 2", result.stdout)+ self.assertFalse((self.root / "s.png").exists())++ def test_zero_iterations_is_refused(self) -> None:+ result = self.invoke(+ "a slide", "-o", str(self.root / "s.png"), "--iterations", "0"+ )+ self.assertEqual(result.returncode, 1)+ self.assertIn("between 1 and 2", result.stdout)++ def test_a_missing_attachment_is_named_before_any_request(self) -> None:+ result = self.invoke(+ "a slide", "-o", str(self.root / "s.png"),+ "--attach", str(self.root / "absent.png"),+ )+ self.assertEqual(result.returncode, 1)+ self.assertIn("Attachment file not found", result.stdout)++ def test_a_missing_credential_is_reported_without_a_traceback(self) -> None:+ result = self.invoke("a slide", "-o", str(self.root / "s.png"), key=None)+ self.assertEqual(result.returncode, 1)+ self.assertIn("OPENROUTER_API_KEY", result.stdout)+ self.assertNotIn("Traceback", result.stderr)+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/scientific-visualization/test_scripts.py b/tests/scientific-visualization/test_scripts.pyindex 82a0c0ca..1afa30ef 100644--- a/tests/scientific-visualization/test_scripts.py+++ b/tests/scientific-visualization/test_scripts.py@@ -24,6 +24,8 @@ import image_metadata # noqa: E402import palette_audit # noqa: E402import style_presets # noqa: E402+import skill_contract+class CommonSafetyTests(unittest.TestCase):def test_json_output_is_private_and_refuses_overwrite(self) -> None:@@ -341,5 +343,10 @@ class ExportTests(unittest.TestCase):plt.close(fig)+# 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(SKILL_ROOT)+if __name__ == "__main__":unittest.main()diff --git a/tests/scientific-writing/test_scripts.py b/tests/scientific-writing/test_scripts.pyindex 2b5c9b7c..081299a9 100644--- a/tests/scientific-writing/test_scripts.py+++ b/tests/scientific-writing/test_scripts.py@@ -31,6 +31,8 @@ from synthetic_manuscript import (valid_source_manifest,)+import skill_contract+class ScriptTests(unittest.TestCase):def write_json(self, directory: Path, name: str, value: object) -> Path:@@ -214,5 +216,10 @@ class ScriptTests(unittest.TestCase):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()diff --git a/tests/scientific-writing/test_static.py b/tests/scientific-writing/test_static.pyindex 3b4af893..6693506f 100644--- a/tests/scientific-writing/test_static.py+++ b/tests/scientific-writing/test_static.py@@ -20,7 +20,7 @@ class StaticTests(unittest.TestCase):text = (ROOT / "SKILL.md").read_text(encoding="utf-8")self.assertLess(len(text.splitlines()), 500)self.assertTrue(text.startswith("---\n"))- self.assertIn(' version: "2.0"', text)+ self.assertRegex(text, r'\n version: "\d+\.\d+"\n')self.assertIn("license: MIT", text)self.assertIn("compatibility:", text)self.assertNotIn("required_environment_variables", text)diff --git a/tests/scikit-learn/test_scripts.py b/tests/scikit-learn/test_scripts.pynew file mode 100644index 00000000..a6ba7d28--- /dev/null+++ b/tests/scikit-learn/test_scripts.py@@ -0,0 +1,262 @@+"""Tests for the scikit-learn pipeline and clustering templates.++The value of `create_preprocessing_pipeline` is that it fits its imputer and+scaler *inside* a Pipeline, so cross-validation never lets test-fold statistics+reach the training fold. That is the leak these templates exist to prevent, and+it is what the tests check: the preprocessor is a ColumnTransformer that must+be fitted before it can transform, unseen categories survive, and the whole+thing composes into a single estimator.++Clustering is checked against data with a known answer -- three well-separated+blobs -- so "found 3 clusters" means something.+"""++from __future__ import annotations++import os+import sys+import tempfile+import unittest+from pathlib import Path++import pytest++import skill_contract++SKILL_ROOT = Path(__file__).resolve().parents[2] / "skills" / "scikit-learn"+SCRIPTS = SKILL_ROOT / "scripts"+sys.path.insert(0, str(SCRIPTS))++np = pytest.importorskip("numpy", reason="scikit-learn scripts need numpy")+pd = pytest.importorskip("pandas", reason="scikit-learn scripts need pandas")+sklearn = pytest.importorskip("sklearn", reason="scikit-learn scripts need sklearn")+matplotlib = pytest.importorskip("matplotlib", reason="clustering_analysis plots")+matplotlib.use("Agg")++from sklearn.datasets import make_blobs # noqa: E402+from sklearn.exceptions import NotFittedError # noqa: E402++import classification_pipeline # noqa: E402+import clustering_analysis # noqa: E402+++def mixed_frame(n: int = 60) -> pd.DataFrame:+ rng = np.random.default_rng(7)+ return pd.DataFrame(+ {+ "age": rng.normal(50, 10, n),+ "score": rng.normal(0, 1, n),+ "city": rng.choice(["london", "paris", "berlin"], n),+ "grade": rng.choice(["a", "b"], n),+ }+ )+++NUMERIC = ["age", "score"]+CATEGORICAL = ["city", "grade"]+++class PreprocessingPipelineTests(unittest.TestCase):+ def setUp(self) -> None:+ self.frame = mixed_frame()+ self.preprocessor = classification_pipeline.create_preprocessing_pipeline(+ NUMERIC, CATEGORICAL+ )++ def test_it_returns_an_unfitted_column_transformer(self) -> None:+ from sklearn.compose import ColumnTransformer++ self.assertIsInstance(self.preprocessor, ColumnTransformer)+ # Unfitted: statistics can only come from data it is later shown, which+ # is what keeps the test fold out of the training fold.+ with self.assertRaises(NotFittedError):+ self.preprocessor.transform(self.frame)++ def test_numeric_columns_are_imputed_and_standardised(self) -> None:+ frame = self.frame.copy()+ frame.loc[0, "age"] = np.nan+ transformed = self.preprocessor.fit_transform(frame)++ self.assertFalse(np.isnan(transformed).any(), "NaNs survived imputation")+ # The two numeric columns come first and are standardised.+ numeric_block = transformed[:, : len(NUMERIC)]+ np.testing.assert_allclose(numeric_block.mean(axis=0), 0, atol=1e-9)+ np.testing.assert_allclose(numeric_block.std(axis=0), 1, atol=1e-9)++ def test_categorical_columns_become_one_hot_indicators(self) -> None:+ transformed = self.preprocessor.fit_transform(self.frame)+ # 2 numeric + 3 cities + 2 grades+ self.assertEqual(transformed.shape, (len(self.frame), 2 + 3 + 2))+ categorical_block = transformed[:, len(NUMERIC):]+ self.assertTrue(set(np.unique(categorical_block)) <= {0.0, 1.0})++ def test_an_unseen_category_does_not_raise_at_transform_time(self) -> None:+ # handle_unknown='ignore' -- a category that appears only in the test+ # fold must not blow up the whole cross-validation run.+ self.preprocessor.fit(self.frame)+ unseen = self.frame.iloc[:3].copy()+ unseen["city"] = "tokyo"+ transformed = self.preprocessor.transform(unseen)+ self.assertEqual(transformed.shape[1], 2 + 3 + 2)+ # The unknown category encodes as all-zero indicators.+ np.testing.assert_allclose(transformed[:, 2:5], 0)++ def test_a_missing_categorical_value_is_filled_rather_than_dropped(self) -> None:+ frame = self.frame.copy()+ frame.loc[0, "city"] = None+ transformed = self.preprocessor.fit_transform(frame)+ self.assertEqual(len(transformed), len(frame))++ def test_it_can_be_composed_into_a_single_estimator(self) -> None:+ from sklearn.linear_model import LogisticRegression+ from sklearn.pipeline import Pipeline++ rng = np.random.default_rng(3)+ target = rng.integers(0, 2, len(self.frame))+ model = Pipeline(+ [("prep", self.preprocessor), ("clf", LogisticRegression(max_iter=500))]+ )+ model.fit(self.frame, target)+ self.assertEqual(len(model.predict(self.frame)), len(self.frame))++ def test_columns_outside_the_two_lists_are_dropped(self) -> None:+ frame = self.frame.copy()+ frame["notes"] = "ignore me"+ transformed = self.preprocessor.fit_transform(frame)+ self.assertEqual(transformed.shape[1], 2 + 3 + 2)+++class ClusteringPreprocessTests(unittest.TestCase):+ def setUp(self) -> None:+ self.features, self.labels = make_blobs(+ n_samples=150, centers=3, n_features=4, random_state=11, cluster_std=0.6+ )++ def test_scaling_standardises_every_feature(self) -> None:+ processed = clustering_analysis.preprocess_for_clustering(self.features)+ np.testing.assert_allclose(processed.mean(axis=0), 0, atol=1e-9)+ np.testing.assert_allclose(processed.std(axis=0), 1, atol=1e-9)++ def test_scaling_can_be_turned_off(self) -> None:+ processed = clustering_analysis.preprocess_for_clustering(+ self.features, scale=False+ )+ np.testing.assert_allclose(processed, self.features)++ def test_pca_reduces_to_the_requested_number_of_components(self) -> None:+ processed = clustering_analysis.preprocess_for_clustering(+ self.features, pca_components=2+ )+ self.assertEqual(processed.shape, (150, 2))++ def test_the_input_matrix_is_not_mutated(self) -> None:+ before = self.features.copy()+ clustering_analysis.preprocess_for_clustering(self.features)+ np.testing.assert_allclose(self.features, before)+++class ScratchDirectoryTestCase(unittest.TestCase):+ """Run inside a temporary cwd.++ `find_optimal_k_kmeans` and `visualize_clusters` call `plt.savefig` with a+ bare filename, so they write into the current working directory -- which is+ the repository root when pytest runs. Without this the suite litters the+ checkout with clustering_optimization.png and clustering_results.png.+ """++ def setUp(self) -> None:+ self._origin = Path.cwd()+ self._scratch = tempfile.TemporaryDirectory()+ os.chdir(self._scratch.name)+ self.addCleanup(self._scratch.cleanup)+ self.addCleanup(os.chdir, self._origin)+++class OptimalKTests(ScratchDirectoryTestCase):+ def setUp(self) -> None:+ super().setUp()+ features, _ = make_blobs(+ n_samples=180, centers=3, n_features=3, random_state=5, cluster_std=0.5+ )+ self.features = clustering_analysis.preprocess_for_clustering(features)++ def test_three_well_separated_blobs_are_found(self) -> None:+ # A silhouette search that cannot recover an obvious k=3 is not usable.+ result = clustering_analysis.find_optimal_k_kmeans(+ self.features, k_range=range(2, 7)+ )+ self.assertIsNotNone(result)+ flattened = str(result)+ self.assertIn("3", flattened)++ def test_the_search_covers_every_k_it_was_given(self) -> None:+ result = clustering_analysis.find_optimal_k_kmeans(+ self.features, k_range=range(2, 5)+ )+ # Whatever the container, it must carry one score per candidate k.+ if isinstance(result, dict):+ for value in result.values():+ if isinstance(value, (list, tuple, np.ndarray)) and len(value) > 1:+ self.assertEqual(len(value), 3)+ break+++class AlgorithmComparisonTests(unittest.TestCase):+ def setUp(self) -> None:+ features, self.truth = make_blobs(+ n_samples=150, centers=3, n_features=3, random_state=9, cluster_std=0.5+ )+ self.features = clustering_analysis.preprocess_for_clustering(features)++ def test_several_algorithms_are_compared(self) -> None:+ results = clustering_analysis.compare_clustering_algorithms(+ self.features, n_clusters=3+ )+ self.assertIsInstance(results, dict)+ self.assertGreater(len(results), 1)++ def test_kmeans_recovers_the_planted_structure(self) -> None:+ from sklearn.metrics import adjusted_rand_score++ results = clustering_analysis.compare_clustering_algorithms(+ self.features, n_clusters=3+ )+ kmeans = next(+ (value for name, value in results.items() if "means" in name.lower()), None+ )+ self.assertIsNotNone(kmeans, f"no K-Means entry in {sorted(results)}")++ labels = kmeans.get("labels") if isinstance(kmeans, dict) else None+ if labels is not None:+ self.assertGreater(adjusted_rand_score(self.truth, labels), 0.9)+++class EndToEndTests(ScratchDirectoryTestCase):+ def setUp(self) -> None:+ super().setUp()+ self.addCleanup(lambda: __import__("matplotlib.pyplot", fromlist=["close"]).close("all"))++ def test_the_full_clustering_analysis_runs(self) -> None:+ features, truth = make_blobs(+ n_samples=120, centers=3, n_features=3, random_state=13, cluster_std=0.6+ )+ result = clustering_analysis.complete_clustering_analysis(+ features, true_labels=truth+ )+ self.assertIsNotNone(result)++ def test_the_classification_pipeline_trains_and_scores(self) -> None:+ frame = mixed_frame(120)+ rng = np.random.default_rng(4)+ # A learnable target so the run exercises a real fit, not noise.+ target = (frame["age"] > frame["age"].median()).astype(int).to_numpy().copy()+ target[rng.choice(len(target), 6, replace=False)] ^= 1++ result = classification_pipeline.train_and_evaluate_model(+ frame, target, NUMERIC, CATEGORICAL, random_state=0+ )+ self.assertIsNotNone(result)+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/scikit-survival/test_scripts.py b/tests/scikit-survival/test_scripts.pyindex 222e1fe8..81b47126 100644--- a/tests/scikit-survival/test_scripts.py+++ b/tests/scikit-survival/test_scripts.py@@ -9,6 +9,8 @@ import statimport sysimport tempfileimport unittest++import pytestfrom pathlib import Path@@ -16,6 +18,10 @@ SKILL_ROOT = Path(__file__).resolve().parents[2] / "skills" / "scikit-survival"SCRIPTS = SKILL_ROOT / "scripts"sys.path.insert(0, str(SCRIPTS))+# Guarded so a bare project-environment run skips cleanly instead of failing+# collection; the real run is `tests/run_all.py --isolated scikit-survival`.+pytest.importorskip("sksurv", reason="scikit-survival needs scikit-survival")+import _common # noqa: E402import competing_risk_cif # noqa: E402import evaluate_survival_metrics # noqa: E402diff --git a/tests/scvelo/test_scripts.py b/tests/scvelo/test_scripts.pynew file mode 100644index 00000000..25ccfcfd--- /dev/null+++ b/tests/scvelo/test_scripts.py@@ -0,0 +1,404 @@+"""Tests for the scVelo RNA velocity workflow.++`run_velocity_analysis` is one long pipeline, so the tests split it in two by+what can go wrong:++* The preprocessing and estimation steps run for real, on a synthetic AnnData of+ 60 cells x 40 genes built here rather than downloaded. That is what caught the+ bug this suite now guards: scVelo 0.3 removed `n_top_genes` from+ `filter_and_normalize()`, so the shipped call raised TypeError on the first+ step of every run. Selecting 15 of 40 genes is checked by construction.+* The step ordering is checked with recording stubs in place of `scv.tl.*`,+ because which steps run is the script's own decision: the dynamical model must+ recover dynamics *before* estimating velocity, latent time and the driver-gene+ heatmap belong to that mode alone, and gene ranking is conditional on the+ grouping column existing. The stubs also fix the confidence values, so the+ printed summary statistics are checked against hand-computed numbers.++`mode="deterministic"` drives the real run: with scvelo 0.3.4, `mode="stochastic"`+fails inside the generalized least-squares solver on NumPy >= 2 and the dynamical+model fails inside `pandas.unique` on pandas >= 3, both upstream. The plotting+calls are stubbed for the same reason -- `scv.pl.scatter` on a numeric `.obs`+column raises under pandas 3 -- and stubbing them lets the tests assert which+figures the workflow asks for, which is the part the skill owns.++`load_from_loom` is not covered: it needs a velocyto `.loom` file plus loompy,+and its second branch needs leidenalg, none of which this environment carries.+Neither the `--help` nor the demo contract applies -- the script parses no+arguments, and its `__main__` block downloads the pancreas dataset.+"""++from __future__ import annotations++import contextlib+import io+import sys+import tempfile+import unittest+from pathlib import Path+from unittest import mock++import pytest++SKILL_ROOT = Path(__file__).resolve().parents[2] / "skills" / "scvelo"+SCRIPTS = SKILL_ROOT / "scripts"+sys.path.insert(0, str(SCRIPTS))++matplotlib = pytest.importorskip("matplotlib", reason="scvelo workflow plots")+matplotlib.use("Agg") # never open a window, even if a real plot slips through++np = pytest.importorskip("numpy", reason="scvelo workflow needs numpy")+pytest.importorskip("scvelo", reason="scvelo skill needs scvelo")+pytest.importorskip("scanpy", reason="scvelo workflow needs scanpy")++import anndata as ad # noqa: E402+import scvelo as scv # noqa: E402++import rna_velocity_workflow as workflow # noqa: E402++N_OBS = 60+N_VARS = 40+#: Cells with a velocity confidence above this are counted in the summary.+HIGH_CONFIDENCE = 0.7+++def synthetic(n_obs: int = N_OBS, n_vars: int = N_VARS, seed: int = 0):+ """A minimal AnnData shaped like velocyto output: counts in both layers.++ Counts are drawn high enough (Poisson 8 spliced, 4 unspliced) that no gene+ is dropped by the workflow's `min_shared_counts=20` filter, so the gene+ count after preprocessing is decided by `n_top_genes` alone.+ """+ rng = np.random.default_rng(seed)+ spliced = rng.poisson(8, size=(n_obs, n_vars)).astype("float32")+ unspliced = rng.poisson(4, size=(n_obs, n_vars)).astype("float32")++ adata = ad.AnnData(spliced.copy())+ adata.layers["spliced"] = spliced+ adata.layers["unspliced"] = unspliced+ adata.obs_names = [f"cell{index}" for index in range(n_obs)]+ adata.var_names = [f"Gene{index}" for index in range(n_vars)]+ half = n_obs // 2+ adata.obs["clusters"] = (["alpha"] * half + ["beta"] * (n_obs - half))+ adata.obs["clusters"] = adata.obs["clusters"].astype("category")+ adata.obsm["X_umap"] = rng.normal(size=(n_obs, 2))+ return adata+++class FigureRecorder:+ """Replacement for the `scv.pl` functions: records instead of rendering."""++ def __init__(self) -> None:+ self.calls: list[tuple[str, dict]] = []++ def stub(self, name: str):+ def record(adata=None, *args, **kwargs):+ self.calls.append((name, kwargs))++ return record++ def install(self, test: unittest.TestCase) -> None:+ for name in (+ "velocity_embedding_stream",+ "velocity_embedding",+ "scatter",+ "heatmap",+ ):+ patcher = mock.patch.object(scv.pl, name, self.stub(name))+ patcher.start()+ test.addCleanup(patcher.stop)++ @property+ def names(self) -> list[str]:+ return [name for name, _ in self.calls]++ @property+ def saved(self) -> list[str]:+ return [kwargs["save"] for _, kwargs in self.calls if "save" in kwargs]++ def kwargs_for(self, name: str) -> dict:+ for recorded, kwargs in self.calls:+ if recorded == name:+ return kwargs+ raise AssertionError(f"{name} was never called")+++class LayerRequirementTests(unittest.TestCase):+ """Velocity is impossible without both layers, so the guard fires early."""++ def setUp(self) -> None:+ self._temporary = tempfile.TemporaryDirectory()+ self.addCleanup(self._temporary.cleanup)+ self.output = str(Path(self._temporary.name) / "out")++ def run_on(self, adata):+ with contextlib.redirect_stdout(io.StringIO()):+ workflow.run_velocity_analysis(adata, output_dir=self.output)++ def test_a_missing_spliced_layer_is_refused_before_any_work(self) -> None:+ adata = synthetic()+ del adata.layers["spliced"]+ with self.assertRaisesRegex(AssertionError, "spliced"):+ self.run_on(adata)++ def test_a_missing_unspliced_layer_is_refused(self) -> None:+ adata = synthetic()+ del adata.layers["unspliced"]+ with self.assertRaisesRegex(AssertionError, "unspliced"):+ self.run_on(adata)++ def test_the_message_names_the_tool_that_produces_the_layers(self) -> None:+ adata = synthetic()+ del adata.layers["spliced"]+ with self.assertRaisesRegex(AssertionError, "velocyto"):+ self.run_on(adata)+++class VelocityRunTests(unittest.TestCase):+ """One real run of the pipeline, inspected from several angles."""++ N_TOP_GENES = 15++ @classmethod+ def setUpClass(cls) -> None:+ cls._temporary = tempfile.TemporaryDirectory()+ cls.addClassCleanup(cls._temporary.cleanup)+ # A nested path the workflow has to create itself.+ cls.output = Path(cls._temporary.name) / "results" / "velocity"++ cls.figures = FigureRecorder()+ cls._patchers = [+ mock.patch.object(scv.pl, name, cls.figures.stub(name))+ for name in (+ "velocity_embedding_stream",+ "velocity_embedding",+ "scatter",+ "heatmap",+ )+ ]+ for patcher in cls._patchers:+ patcher.start()+ cls.addClassCleanup(+ lambda: [patcher.stop() for patcher in cls._patchers]+ )++ stream = io.StringIO()+ with contextlib.redirect_stdout(stream):+ cls.input = synthetic()+ cls.adata = workflow.run_velocity_analysis(+ cls.input,+ groupby="clusters",+ n_top_genes=cls.N_TOP_GENES,+ n_neighbors=15,+ mode="deterministic",+ output_dir=str(cls.output),+ )+ cls.printed = stream.getvalue()++ def test_the_input_object_is_annotated_in_place(self) -> None:+ self.assertIs(self.adata, self.input)++ def test_the_gene_set_is_narrowed_to_the_requested_top_genes(self) -> None:+ # 40 genes in, 15 requested: the count is decided by the HVG step, which+ # is exactly what the scVelo 0.3 preprocessing change moved to Scanpy.+ self.assertEqual(self.adata.n_vars, self.N_TOP_GENES)+ self.assertEqual(self.adata.n_obs, N_OBS)++ def test_the_moments_and_velocity_layers_are_added(self) -> None:+ for layer in ("Ms", "Mu", "velocity"):+ with self.subTest(layer=layer):+ self.assertIn(layer, self.adata.layers)++ def test_at_least_one_gene_has_a_usable_velocity(self) -> None:+ # Genes scVelo rejects are left as NaN; an all-NaN layer would mean the+ # run produced nothing to plot or rank.+ velocity = np.asarray(self.adata.layers["velocity"])+ self.assertTrue(np.isfinite(velocity).any())++ def test_the_downstream_per_cell_annotations_are_present(self) -> None:+ for column in ("velocity_confidence", "velocity_pseudotime", "velocity_length"):+ with self.subTest(column=column):+ self.assertIn(column, self.adata.obs)++ def test_the_confidences_stay_inside_their_definition(self) -> None:+ # velocity_confidence is a cosine correlation, so it cannot leave [-1, 1].+ confidence = self.adata.obs["velocity_confidence"].to_numpy()+ self.assertGreaterEqual(np.nanmin(confidence), -1.0)+ self.assertLessEqual(np.nanmax(confidence), 1.0)++ def test_driver_genes_are_ranked_because_the_grouping_column_exists(self) -> None:+ self.assertIn("rank_velocity_genes", self.adata.uns)++ def test_a_non_dynamical_run_skips_the_dynamical_only_results(self) -> None:+ self.assertNotIn("latent_time", self.adata.obs)+ self.assertNotIn("fit_likelihood", self.adata.var)++ def test_the_annotated_object_round_trips_through_the_saved_h5ad(self) -> None:+ saved = self.output / "adata_velocity.h5ad"+ self.assertTrue(saved.is_file())+ reloaded = ad.read_h5ad(saved)+ self.assertEqual(reloaded.shape, self.adata.shape)+ self.assertIn("velocity", reloaded.layers)+ self.assertIn("velocity_pseudotime", reloaded.obs)++ def test_the_four_always_on_figures_are_requested(self) -> None:+ # Stream plot, arrow plot, pseudotime, and the speed/coherence pair.+ self.assertEqual(+ self.figures.names,+ [+ "velocity_embedding_stream",+ "velocity_embedding",+ "scatter",+ "scatter",+ ],+ )++ def test_the_embedding_figures_use_the_umap_basis_and_the_grouping(self) -> None:+ stream = self.figures.kwargs_for("velocity_embedding_stream")+ self.assertEqual(stream["basis"], "umap")+ self.assertEqual(stream["color"], "clusters")++ def test_every_figure_is_written_inside_the_output_directory(self) -> None:+ self.assertEqual(len(self.figures.saved), 4)+ for path in self.figures.saved:+ with self.subTest(path=path):+ self.assertTrue(path.startswith(str(self.output)))++ def test_the_summary_reports_the_cell_and_gene_counts_it_finished_with(self) -> None:+ self.assertIn(f"Cells: {N_OBS}", self.printed)+ self.assertIn(f"Velocity genes: {self.N_TOP_GENES}", self.printed)+ self.assertIn("Velocity model: deterministic", self.printed)+++class StepOrderTests(unittest.TestCase):+ """Which scVelo steps run, in what order, is the script's own logic."""++ def setUp(self) -> None:+ self._temporary = tempfile.TemporaryDirectory()+ self.addCleanup(self._temporary.cleanup)+ self.output = Path(self._temporary.name) / "out"++ self.figures = FigureRecorder()+ self.figures.install(self)+ self.steps: list[str] = []++ def record(name, effect=None):+ def stub(adata, *args, **kwargs):+ self.steps.append(name)+ if effect is not None:+ effect(adata)++ return stub++ def add_velocity(adata):+ adata.layers["velocity"] = np.zeros(adata.shape, dtype="float32")++ def add_confidence(adata):+ # Half the cells at 0.9 and half at 0.5: mean 0.700, and exactly+ # half above the 0.7 high-confidence cut used by the summary.+ half = adata.n_obs // 2+ adata.obs["velocity_confidence"] = [0.9] * half + [0.5] * (+ adata.n_obs - half+ )+ adata.obs["velocity_length"] = np.ones(adata.n_obs)++ def add_fits(adata):+ adata.var["fit_likelihood"] = np.linspace(0.05, 0.95, adata.n_vars)++ def add_pseudotime(adata):+ adata.obs["velocity_pseudotime"] = np.linspace(0, 1, adata.n_obs)++ def add_latent_time(adata):+ adata.obs["latent_time"] = np.linspace(0, 1, adata.n_obs)++ for name, effect in (+ ("recover_dynamics", add_fits),+ ("velocity", add_velocity),+ ("velocity_graph", None),+ ("velocity_confidence", add_confidence),+ ("velocity_pseudotime", add_pseudotime),+ ("latent_time", add_latent_time),+ ("rank_velocity_genes", None),+ ):+ patcher = mock.patch.object(scv.tl, name, record(name, effect))+ patcher.start()+ self.addCleanup(patcher.stop)++ def analyse(self, **kwargs) -> str:+ stream = io.StringIO()+ with contextlib.redirect_stdout(stream):+ workflow.run_velocity_analysis(+ synthetic(),+ n_top_genes=15,+ n_neighbors=15,+ output_dir=str(self.output),+ **kwargs,+ )+ return stream.getvalue()++ def test_the_dynamical_model_recovers_dynamics_before_estimating(self) -> None:+ # Reversed, `velocity(mode="dynamical")` has no fitted parameters to use.+ self.analyse(groupby="clusters", mode="dynamical")+ self.assertLess(+ self.steps.index("recover_dynamics"), self.steps.index("velocity")+ )++ def test_the_dynamical_model_adds_latent_time_and_the_driver_heatmap(self) -> None:+ self.analyse(groupby="clusters", mode="dynamical")+ self.assertIn("latent_time", self.steps)+ self.assertIn("heatmap", self.figures.names)+ self.assertTrue(+ any("latent_time" in path for path in self.figures.saved),+ "the latent-time figure was not requested",+ )++ def test_a_stochastic_run_skips_the_dynamical_only_steps(self) -> None:+ self.analyse(groupby="clusters", mode="stochastic")+ # Fitting dynamics is the expensive part; the fast mode must not pay it.+ self.assertNotIn("recover_dynamics", self.steps)+ self.assertNotIn("latent_time", self.steps)+ self.assertNotIn("heatmap", self.figures.names)++ def test_gene_ranking_needs_the_grouping_column(self) -> None:+ self.analyse(groupby="clusters", mode="stochastic")+ self.assertIn("rank_velocity_genes", self.steps)++ def test_an_absent_grouping_column_skips_ranking_instead_of_failing(self) -> None:+ self.analyse(groupby="cell_type_not_present", mode="stochastic")+ self.assertNotIn("rank_velocity_genes", self.steps)++ def test_the_summary_statistics_are_computed_over_the_confidences(self) -> None:+ printed = self.analyse(groupby="clusters", mode="stochastic")+ # 30 cells at 0.9 and 30 at 0.5: mean 0.700, half above 0.7.+ self.assertIn("Mean velocity confidence: 0.700", printed)+ self.assertIn(+ f"High-confidence cells (>{HIGH_CONFIDENCE}): {N_OBS // 2} (50.0%)",+ printed,+ )++ def test_the_output_directory_is_created_before_anything_is_written(self) -> None:+ self.assertFalse(self.output.exists())+ self.analyse(groupby="clusters", mode="stochastic")+ self.assertTrue((self.output / "adata_velocity.h5ad").is_file())+++class ModeValidationTests(unittest.TestCase):+ def test_an_unknown_mode_is_rejected_by_scvelo(self) -> None:+ # The script forwards `mode` verbatim, so a typo must surface as an+ # error naming the allowed estimators rather than as silent nonsense.+ adata = synthetic()+ with tempfile.TemporaryDirectory() as directory:+ with contextlib.redirect_stdout(io.StringIO()):+ with self.assertRaisesRegex(ValueError, "deterministic"):+ workflow.run_velocity_analysis(+ adata,+ groupby="clusters",+ n_top_genes=15,+ n_neighbors=15,+ mode="stochastik",+ output_dir=directory,+ )+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/shap/test_scripts.py b/tests/shap/test_scripts.pynew file mode 100644index 00000000..3e27aaf3--- /dev/null+++ b/tests/shap/test_scripts.py@@ -0,0 +1,342 @@+"""Tests for the SHAP tabular report generator.++The report's one substantive claim is additivity: with an interventional+TreeExplainer in probability space, a row's base value plus its SHAP values must+reconstruct the model's predicted probability for that row. That identity is a+theorem about Shapley values, not a property of this code, which makes it the+right thing to assert -- and the script itself validates it, so the tests check+that the validation is real by verifying the reconstruction independently.++The rest guards the parts that silently produce a wrong report rather than+crashing: `select_output` picking the wrong class slice out of a+(samples, features, outputs) array, the CLI's numeric bounds accepting a zero+background, `save_axis` leaking figures, and the exported CSVs disagreeing with+the values they were built from.+"""++from __future__ import annotations++import argparse+import json+import subprocess+import sys+import tempfile+import unittest+from pathlib import Path++import pytest++import skill_contract++SKILL_ROOT = Path(__file__).resolve().parents[2] / "skills" / "shap"+SCRIPTS = SKILL_ROOT / "scripts"+sys.path.insert(0, str(SCRIPTS))++np = pytest.importorskip("numpy", reason="shap scripts need numpy")+pd = pytest.importorskip("pandas", reason="shap scripts need pandas")+shap = pytest.importorskip("shap", reason="shap scripts need shap")+pytest.importorskip("sklearn", reason="shap scripts need scikit-learn")+matplotlib = pytest.importorskip("matplotlib", reason="the report exports figures")+matplotlib.use("Agg")++import matplotlib.pyplot as plt # noqa: E402+from sklearn.datasets import load_breast_cancer # noqa: E402+from sklearn.ensemble import RandomForestClassifier # noqa: E402++import tabular_report # noqa: E402++CliHelpTests = skill_contract.cli.help_test_case(SKILL_ROOT)++REPORT = SCRIPTS / "tabular_report.py"+++class ArgumentBoundTests(unittest.TestCase):+ def test_a_positive_integer_is_accepted_and_zero_is_not(self) -> None:+ # --background-size 0 would build an empty background, which makes every+ # SHAP value meaningless rather than merely wrong.+ self.assertEqual(tabular_report.positive_int("3"), 3)+ for value in ("0", "-2"):+ with self.subTest(value=value):+ with self.assertRaises(argparse.ArgumentTypeError):+ tabular_report.positive_int(value)++ def test_zero_is_a_valid_class_index_but_a_negative_one_is_not(self) -> None:+ self.assertEqual(tabular_report.nonnegative_int("0"), 0)+ with self.assertRaises(argparse.ArgumentTypeError):+ tabular_report.nonnegative_int("-1")++ def test_tolerances_must_be_strictly_positive(self) -> None:+ self.assertEqual(tabular_report.positive_float("1e-6"), 1e-6)+ for value in ("0", "-1e-6"):+ with self.subTest(value=value):+ with self.assertRaises(argparse.ArgumentTypeError):+ tabular_report.positive_float(value)+++class SingleOutputStub:+ """Stands in for an Explanation whose values have the given shape."""++ def __init__(self, shape: tuple[int, ...]) -> None:+ self.values = np.zeros(shape)+++class OutputSelectionTests(unittest.TestCase):+ def test_a_two_dimensional_explanation_is_returned_unchanged_for_class_zero(self) -> None:+ stub = SingleOutputStub((4, 3))+ self.assertIs(tabular_report.select_output(stub, 0), stub)++ def test_a_two_dimensional_explanation_rejects_any_other_class(self) -> None:+ with self.assertRaisesRegex(ValueError, "produced one output"):+ tabular_report.select_output(SingleOutputStub((4, 3)), 1)++ def test_an_unexpected_rank_names_the_shape_it_got(self) -> None:+ with self.assertRaisesRegex(ValueError, r"received \(4,\)"):+ tabular_report.select_output(SingleOutputStub((4,)), 0)+ with self.assertRaisesRegex(ValueError, r"received \(2, 3, 4, 5\)"):+ tabular_report.select_output(SingleOutputStub((2, 3, 4, 5)), 0)++ def test_a_class_index_past_the_last_output_is_rejected(self) -> None:+ with self.assertRaisesRegex(ValueError, "outside 2 outputs"):+ tabular_report.select_output(SingleOutputStub((4, 3, 2)), 2)++ def test_output_names_fall_back_to_a_positional_label(self) -> None:+ explanation = shap.Explanation(+ values=np.zeros((2, 3)), base_values=np.zeros(2), output_names=None+ )+ self.assertEqual(tabular_report.output_name(explanation, 1), "class_1")++ def test_a_named_output_keeps_its_name(self) -> None:+ explanation = shap.Explanation(+ values=np.zeros((2, 3)), base_values=np.zeros(2), output_names="malignant"+ )+ self.assertEqual(tabular_report.output_name(explanation, 0), "malignant")+++class ExplanationTests(unittest.TestCase):+ """One small interventional TreeExplainer, reused across the assertions."""++ @classmethod+ def setUpClass(cls) -> None:+ frame, target = load_breast_cancer(as_frame=True, return_X_y=True)+ cls.features = frame.iloc[:120, :6]+ cls.model = RandomForestClassifier(+ n_estimators=20, min_samples_leaf=3, random_state=0+ ).fit(cls.features, target.iloc[:120])+ background = shap.sample(cls.features, 20, random_state=0)+ explainer = shap.TreeExplainer(+ cls.model,+ data=background,+ feature_perturbation="interventional",+ model_output="probability",+ )+ cls.explained = cls.features.iloc[:10]+ cls.all_outputs = explainer(cls.explained)++ def test_the_explainer_produces_one_slice_per_class(self) -> None:+ self.assertEqual(+ np.shape(self.all_outputs.values), (10, 6, len(self.model.classes_))+ )++ def test_selecting_a_class_takes_that_slice_and_no_other(self) -> None:+ for class_index in range(len(self.model.classes_)):+ with self.subTest(class_index=class_index):+ selected = tabular_report.select_output(self.all_outputs, class_index)+ np.testing.assert_allclose(+ np.asarray(selected.values),+ np.asarray(self.all_outputs.values)[:, :, class_index],+ )+ self.assertEqual(np.shape(selected.base_values), (10,))++ def test_shap_values_reconstruct_the_predicted_probability(self) -> None:+ # The defining property: base value + contributions = model output. The+ # script asserts this with np.testing.assert_allclose; here the target+ # is recomputed from predict_proba so the check is independent.+ for class_index in range(len(self.model.classes_)):+ with self.subTest(class_index=class_index):+ selected = tabular_report.select_output(self.all_outputs, class_index)+ reconstructed = np.asarray(selected.base_values, dtype=float) + np.asarray(+ selected.values, dtype=float+ ).sum(axis=1)+ predicted = self.model.predict_proba(self.explained)[:, class_index]+ np.testing.assert_allclose(reconstructed, predicted, rtol=1e-5, atol=1e-6)++ def test_the_two_class_slices_are_mirror_images(self) -> None:+ # Binary probabilities sum to one, so each feature's contribution to+ # class 1 must be the negative of its contribution to class 0.+ values = np.asarray(self.all_outputs.values, dtype=float)+ np.testing.assert_allclose(values[:, :, 0], -values[:, :, 1], atol=1e-9)++ def test_the_base_value_is_the_background_mean_prediction(self) -> None:+ # With an interventional masker the base value is the model's average+ # output over the background sample, and it is identical for every row.+ selected = tabular_report.select_output(self.all_outputs, 1)+ base_values = np.asarray(selected.base_values, dtype=float)+ np.testing.assert_allclose(base_values, base_values[0])+ background = shap.sample(self.features, 20, random_state=0)+ self.assertAlmostEqual(+ float(base_values[0]),+ float(self.model.predict_proba(background)[:, 1].mean()),+ places=5,+ )+++class FigureExportTests(unittest.TestCase):+ def setUp(self) -> None:+ self.addCleanup(plt.close, "all")++ def test_saving_an_axis_writes_a_file_and_leaves_no_open_figure(self) -> None:+ # A report that exports four figures without closing them exhausts+ # matplotlib's figure warning threshold and leaks memory.+ figure, axis = plt.subplots()+ axis.plot([0, 1], [0, 1])+ with tempfile.TemporaryDirectory() as directory:+ path = Path(directory) / "figure.png"+ tabular_report.save_axis(axis, path)+ self.assertGreater(path.stat().st_size, 0)+ self.assertEqual(plt.get_fignums(), [])++ def test_a_missing_axis_falls_back_to_the_current_figure(self) -> None:+ # Some shap.plots helpers return None and draw into gcf().+ plt.figure()+ with tempfile.TemporaryDirectory() as directory:+ path = Path(directory) / "current.png"+ tabular_report.save_axis(None, path)+ self.assertGreater(path.stat().st_size, 0)+ self.assertEqual(plt.get_fignums(), [])+++class ReportRunTests(unittest.TestCase):+ """One end-to-end CLI run, shared by the assertions about its output."""++ @classmethod+ def setUpClass(cls) -> None:+ cls._directory = tempfile.TemporaryDirectory()+ cls.output = Path(cls._directory.name) / "report"+ completed = subprocess.run(+ [+ sys.executable, str(REPORT),+ "--output-dir", str(cls.output),+ "--background-size", "20",+ "--explain-size", "12",+ "--max-display", "5",+ "--seed", "3",+ ],+ capture_output=True,+ text=True,+ timeout=600,+ )+ if completed.returncode != 0:+ raise AssertionError(+ f"tabular_report.py exited {completed.returncode}:\n{completed.stderr}"+ )+ cls.stdout = completed.stdout+ cls.metadata = json.loads((cls.output / "metadata.json").read_text())++ @classmethod+ def tearDownClass(cls) -> None:+ cls._directory.cleanup()++ def test_every_documented_artefact_is_written(self) -> None:+ expected = {+ "bar.png",+ "beeswarm.png",+ "feature_importance.csv",+ "first_row_contributions.csv",+ "metadata.json",+ "prediction_reconstruction.csv",+ "scatter-top-feature.png",+ "waterfall-first-row.png",+ }+ self.assertEqual({path.name for path in self.output.iterdir()}, expected)+ for path in self.output.iterdir():+ with self.subTest(artefact=path.name):+ self.assertGreater(path.stat().st_size, 0)++ def test_the_metadata_records_the_run_it_actually_did(self) -> None:+ self.assertEqual(self.metadata["seed"], 3)+ self.assertEqual(self.metadata["background_rows"], 20)+ self.assertEqual(self.metadata["explained_rows"], 12)+ # Breast cancer ships 30 features and 2 classes.+ self.assertEqual(self.metadata["feature_count"], 30)+ self.assertEqual(self.metadata["all_output_shape"], [12, 30, 2])+ self.assertEqual(self.metadata["selected_output_shape"], [12, 30])+ self.assertEqual(self.metadata["output_units"], "class probability")+ self.assertEqual(self.metadata["feature_perturbation"], "interventional")++ def test_the_additivity_error_is_inside_the_tolerance_it_reports(self) -> None:+ self.assertLess(+ self.metadata["max_abs_additivity_error"],+ self.metadata["additivity_atol"] + self.metadata["additivity_rtol"],+ )++ def test_the_reconstruction_csv_adds_up_row_by_row(self) -> None:+ frame = pd.read_csv(self.output / "prediction_reconstruction.csv")+ self.assertEqual(len(frame), 12)+ np.testing.assert_allclose(+ frame["reconstructed_output"], frame["prediction"], atol=1e-6+ )+ np.testing.assert_allclose(+ frame["reconstruction_error"],+ frame["reconstructed_output"] - frame["prediction"],+ atol=1e-12,+ )+ # Probability-space output: every prediction is a probability.+ self.assertTrue(((frame["prediction"] >= 0) & (frame["prediction"] <= 1)).all())++ def test_the_importance_table_is_ranked_by_mean_absolute_shap(self) -> None:+ frame = pd.read_csv(self.output / "feature_importance.csv")+ self.assertEqual(len(frame), 30)+ self.assertTrue(frame["mean_abs_shap"].is_monotonic_decreasing)+ self.assertTrue((frame["mean_abs_shap"] >= 0).all())+ # The signed mean can never exceed the absolute mean in magnitude.+ self.assertTrue((frame["mean_signed_shap"].abs() <= frame["mean_abs_shap"] + 1e-12).all())+ self.assertEqual(frame.loc[0, "feature"], self.metadata["top_feature"])++ def test_the_first_row_breakdown_is_ordered_by_contribution_size(self) -> None:+ frame = pd.read_csv(self.output / "first_row_contributions.csv")+ self.assertEqual(len(frame), 30)+ self.assertTrue(frame["shap_value"].abs().is_monotonic_decreasing)+ # Those contributions are the ones that reconstruct row 0's prediction.+ reconstruction = pd.read_csv(self.output / "prediction_reconstruction.csv")+ self.assertAlmostEqual(+ float(reconstruction.loc[0, "base_value"] + frame["shap_value"].sum()),+ float(reconstruction.loc[0, "prediction"]),+ places=5,+ )++ def test_the_run_prints_its_metadata_and_where_it_wrote(self) -> None:+ self.assertIn("shap_version", self.stdout)+ self.assertIn(str(self.output.resolve()), self.stdout)+++class ReportFailureTests(unittest.TestCase):+ def test_a_class_index_outside_the_model_is_rejected_before_any_work(self) -> None:+ with tempfile.TemporaryDirectory() as directory:+ completed = subprocess.run(+ [+ sys.executable, str(REPORT),+ "--output-dir", directory,+ "--class-index", "7",+ "--background-size", "5",+ "--explain-size", "5",+ ],+ capture_output=True,+ text=True,+ timeout=600,+ )+ self.assertNotEqual(completed.returncode, 0)+ self.assertIn("--class-index 7 is outside model classes", completed.stderr)++ def test_a_negative_background_size_is_refused_by_the_parser(self) -> None:+ completed = subprocess.run(+ [sys.executable, str(REPORT), "--background-size", "-1"],+ capture_output=True,+ text=True,+ timeout=120,+ )+ self.assertEqual(completed.returncode, 2)+ self.assertIn("greater than zero", completed.stderr)+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/simpy/test_scripts.py b/tests/simpy/test_scripts.pyindex f76f7374..f0faecdb 100644--- a/tests/simpy/test_scripts.py+++ b/tests/simpy/test_scripts.py@@ -11,8 +11,13 @@ import subprocessimport sysimport tempfileimport unittest++import pytestfrom pathlib import Path+# Guarded so a bare project-environment run skips cleanly instead of failing+# collection; the real run is `tests/run_all.py --isolated simpy`.+pytest.importorskip("simpy", reason="simpy needs simpy")import simpydiff --git a/tests/skill-requirements.toml b/tests/skill-requirements.tomlindex b55975b6..da21b63e 100644--- a/tests/skill-requirements.toml+++ b/tests/skill-requirements.toml@@ -173,6 +173,9 @@ packages = ["numpy", "pandas", "pyDOE3"][skills.iso-standards-readiness]packages = []+[skills.analytical-method-validation]+packages = []+[skills.clinical-decision-support]packages = []@@ -464,7 +467,11 @@ packages = ["pysam"]packages = ["bioservices", "biopython", "networkx", "pandas"][skills.gget]-packages = ["gget", "matplotlib", "numpy", "pandas", "scanpy"]+# scanpy is pinned forward deliberately. Unpinned, the resolver walks it back to+# 1.9.8, whose numba 0.53.1 needs llvmlite 0.36.0, which cannot build on 3.13 --+# so the whole environment fails before a single test runs. >=1.10 is also what+# gget's own cellxgene extra requires.+packages = ["gget", "matplotlib", "numpy", "pandas", "scanpy>=1.10"][skills.scikit-bio]packages = ["scikit-bio", "biom-format", "tables", "matplotlib", "numpy", "pandas", "seaborn"]@@ -534,14 +541,22 @@ packages = ["pyopenms", "matplotlib", "numpy", "pandas"]packages = ["mdanalysis", "openmm", "matplotlib", "numpy", "pandas", "scipy"][skills.pymatgen]-packages = ["pymatgen", "pymatgen-core", "mp-api"]+# Pinned to the skill's own "Verified snapshot (2026-07-23)", which its+# `_common.py` enforces before any network execution. Left unpinned, a new+# pymatgen-core release makes the suite fail on the snapshot check -- and+# loosening that check would throw away the guarantee it exists to make. When+# the skill re-verifies against newer releases, update both together.+packages = ["pymatgen==2026.5.4", "pymatgen-core==2026.7.16", "mp-api==0.46.4"][skills.rowan]packages = ["rowan-python", "rdkit", "pandas"][skills.deepchem]python = "3.11"-packages = ["deepchem", "numpy", "scikit-learn"]+# torch is what the skill's own `compatibility` line and the `deepchem[torch]`+# install command require: without a backend, dc.models.GCNModel and friends do+# not exist, so no model path is reachable at all.+packages = ["deepchem", "torch", "numpy", "scikit-learn"][skills.pytdc]python = "3.11"diff --git a/tests/stable-baselines3/test_scripts.py b/tests/stable-baselines3/test_scripts.pynew file mode 100644index 00000000..fa11c5cf--- /dev/null+++ b/tests/stable-baselines3/test_scripts.py@@ -0,0 +1,415 @@+"""Tests for the Stable-Baselines3 environment, training, and evaluation templates.++`custom_env_template` is the piece with real logic, and all of it is checkable+against values fixed by the template's own docstring: action 0 moves up, the+reward is 1.0 on reaching the goal and -0.1 times the Euclidean distance+otherwise, positions clip at the grid edge, and the registered environment+truncates at 100 steps. Those are the numbers a user copies and then relies on,+so a transposed direction table or a sign flip in the reward must fail here.++The environment also has to satisfy SB3's `check_env`, and that is asserted in+both directions: the template passes with no warnings, while a subclass that+returns float64 observations against a float32 `Box` is rejected -- otherwise+"check_env passed" would prove only that the checker was called.++The training and evaluation templates are thin wrappers over SB3, so they are+covered by one small end-to-end run each: a real (tiny) PPO fit through+`train_agent`, driven in a subprocess because it hardcodes `SubprocVecEnv`, and+`evaluate_agent` loading the saved model back.+"""++from __future__ import annotations++import contextlib+import io+import subprocess+import sys+import tempfile+import textwrap+import unittest+import warnings+from pathlib import Path++import pytest++import skill_contract++SKILL_ROOT = Path(__file__).resolve().parents[2] / "skills" / "stable-baselines3"+SCRIPTS = SKILL_ROOT / "scripts"+sys.path.insert(0, str(SCRIPTS))++np = pytest.importorskip("numpy", reason="the templates need numpy")+gym = pytest.importorskip("gymnasium", reason="the templates need gymnasium")+pytest.importorskip("torch", reason="stable-baselines3 needs torch")+pytest.importorskip("stable_baselines3", reason="the templates need stable-baselines3")++from stable_baselines3 import PPO # noqa: E402+from stable_baselines3.common.env_checker import check_env # noqa: E402++import custom_env_template # noqa: E402+import evaluate_agent # noqa: E402+import train_rl_agent # noqa: E402++# Only `custom_env_template` has a runnable demo: its `__main__` block validates+# the environment and returns. `train_rl_agent`'s trains for 100k timesteps and+# `evaluate_agent`'s loads a checkpoint that does not exist in a clean checkout,+# so neither can be run as documentation; both are covered by the tests below.+DemoBlockTests = skill_contract.cli.demo_test_case(+ SKILL_ROOT, ("custom_env_template.py",)+)++#: Direction table from the template's own step() docstring.+MOVES = {0: (-1, 0), 1: (1, 0), 2: (0, -1), 3: (0, 1)}+++def placed_env(agent, goal, grid_size=5, render_mode=None):+ """A reset environment with the agent and goal pinned where we want them."""+ env = custom_env_template.CustomEnv(grid_size=grid_size, render_mode=render_mode)+ env.reset(seed=0)+ env._agent_position = np.array(agent)+ env._goal_position = np.array(goal)+ return env+++class SpaceDefinitionTests(unittest.TestCase):+ def test_the_action_space_is_the_four_documented_moves(self) -> None:+ self.assertEqual(custom_env_template.CustomEnv().action_space.n, 4)++ def test_the_observation_box_spans_the_grid_and_is_float32(self) -> None:+ # SB3 expects float32 observations; float64 silently costs a conversion+ # warning at best and a space mismatch at worst.+ for grid_size in (3, 5, 8):+ with self.subTest(grid_size=grid_size):+ space = custom_env_template.CustomEnv(grid_size=grid_size).observation_space+ self.assertEqual(space.shape, (2,))+ self.assertEqual(space.dtype, np.float32)+ np.testing.assert_allclose(space.low, [0.0, 0.0])+ np.testing.assert_allclose(space.high, [grid_size - 1] * 2)++ def test_the_metadata_declares_the_render_modes_it_implements(self) -> None:+ self.assertEqual(+ custom_env_template.CustomEnv.metadata["render_modes"],+ ["human", "rgb_array"],+ )+++class ResetTests(unittest.TestCase):+ def test_the_same_seed_gives_the_same_starting_layout(self) -> None:+ first, first_info = custom_env_template.CustomEnv().reset(seed=17)+ second, second_info = custom_env_template.CustomEnv().reset(seed=17)+ np.testing.assert_array_equal(first, second)+ np.testing.assert_array_equal(+ first_info["goal_position"], second_info["goal_position"]+ )++ def test_different_seeds_give_different_layouts(self) -> None:+ layouts = {+ tuple(custom_env_template.CustomEnv().reset(seed=seed)[0])+ for seed in range(30)+ }+ self.assertGreater(len(layouts), 1)++ def test_the_goal_never_starts_on_the_agent(self) -> None:+ # reset() loops until they differ; otherwise the episode would be over+ # before it began.+ for seed in range(50):+ with self.subTest(seed=seed):+ _, info = custom_env_template.CustomEnv(grid_size=2).reset(seed=seed)+ self.assertFalse(+ np.array_equal(info["agent_position"], info["goal_position"])+ )++ def test_the_observation_is_the_agent_position_and_lies_in_the_space(self) -> None:+ env = custom_env_template.CustomEnv()+ observation, info = env.reset(seed=3)+ self.assertTrue(env.observation_space.contains(observation))+ np.testing.assert_allclose(observation, info["agent_position"])++ def test_the_info_distance_is_the_euclidean_distance_to_the_goal(self) -> None:+ env = placed_env(agent=(0, 0), goal=(3, 4))+ info = env._get_info()+ # 3-4-5 triangle.+ self.assertAlmostEqual(info["distance_to_goal"], 5.0)+++class StepTests(unittest.TestCase):+ def test_each_action_moves_one_cell_in_its_documented_direction(self) -> None:+ for action, (row_delta, column_delta) in MOVES.items():+ with self.subTest(action=action):+ env = placed_env(agent=(2, 2), goal=(4, 4))+ observation, _, terminated, truncated, _ = env.step(action)+ np.testing.assert_allclose(+ observation, [2 + row_delta, 2 + column_delta]+ )+ self.assertFalse(terminated)+ self.assertFalse(truncated)++ def test_moves_are_clipped_at_every_edge(self) -> None:+ # Walking into a wall must be a no-op, not an out-of-space observation.+ cases = [((0, 0), 0, (0, 0)), ((0, 0), 2, (0, 0)), ((4, 4), 1, (4, 4)), ((4, 4), 3, (4, 4))]+ for start, action, expected in cases:+ with self.subTest(start=start, action=action):+ env = placed_env(agent=start, goal=(2, 2))+ observation, _, _, _, _ = env.step(action)+ np.testing.assert_allclose(observation, expected)+ self.assertTrue(env.observation_space.contains(observation))++ def test_reaching_the_goal_pays_one_and_terminates(self) -> None:+ env = placed_env(agent=(4, 3), goal=(4, 4))+ _, reward, terminated, truncated, _ = env.step(3)+ self.assertEqual(reward, 1.0)+ self.assertTrue(terminated)+ self.assertFalse(truncated)++ def test_not_reaching_the_goal_costs_a_tenth_of_the_distance(self) -> None:+ # From (2, 2) moving up lands on (1, 2); the goal at (4, 4) is then+ # sqrt(9 + 4) = 3.6055... away, so the reward is -0.36055...+ env = placed_env(agent=(2, 2), goal=(4, 4))+ _, reward, _, _, info = env.step(0)+ self.assertAlmostEqual(reward, -0.1 * np.sqrt(13.0))+ self.assertAlmostEqual(reward, -0.1 * info["distance_to_goal"])++ def test_the_step_penalty_shrinks_as_the_agent_closes_in(self) -> None:+ far = placed_env(agent=(0, 0), goal=(4, 4)).step(1)[1]+ near = placed_env(agent=(3, 4), goal=(4, 4)).step(2)[1]+ self.assertLess(far, near)++ def test_the_raw_environment_never_truncates_on_its_own(self) -> None:+ # The template says the time limit comes from registration, not step().+ env = placed_env(agent=(0, 0), goal=(4, 4))+ for _ in range(50):+ _, _, terminated, truncated, _ = env.step(1)+ self.assertFalse(truncated)+ if terminated:+ break+++class RegistrationTests(unittest.TestCase):+ def test_the_environment_is_registered_under_its_documented_id(self) -> None:+ self.assertIn("CustomEnv-v0", gym.registry)++ def test_gym_make_applies_the_hundred_step_time_limit(self) -> None:+ made = gym.make("CustomEnv-v0")+ self.assertEqual(made.spec.max_episode_steps, 100)++ def test_an_episode_that_never_reaches_the_goal_truncates_at_one_hundred(self) -> None:+ # Park the agent in the top row and keep pressing up: it can never reach+ # a goal in the bottom-right corner, so only the time limit ends this.+ made = gym.make("CustomEnv-v0")+ made.reset(seed=0)+ made.unwrapped._agent_position = np.array([0, 0])+ made.unwrapped._goal_position = np.array([4, 4])+ steps = 0+ while True:+ _, _, terminated, truncated, _ = made.step(0)+ steps += 1+ self.assertFalse(terminated)+ if truncated:+ break+ self.assertLess(steps, 100)+ self.assertEqual(steps, 100)+++class EnvCheckerTests(unittest.TestCase):+ def test_the_template_passes_sb3s_checker_without_warnings(self) -> None:+ with warnings.catch_warnings(record=True) as caught:+ warnings.simplefilter("always")+ check_env(custom_env_template.CustomEnv(), warn=True)+ self.assertEqual([str(warning.message) for warning in caught], [])++ def test_the_checker_rejects_an_observation_outside_the_declared_space(self) -> None:+ # The other direction: without this, "check_env passed" would only prove+ # the checker ran.+ class WrongDtypeEnv(custom_env_template.CustomEnv):+ def _get_obs(self):+ return self._agent_position.astype(np.float64)++ with self.assertRaises(AssertionError):+ check_env(WrongDtypeEnv(), warn=True)++ def test_the_validate_helper_runs_the_checker_on_the_template(self) -> None:+ # The helper is what the demo block calls; it must not print a failure.+ stream = io.StringIO()+ with contextlib.redirect_stdout(stream):+ custom_env_template.validate_environment()+ self.assertIn("validation passed", stream.getvalue())+++class RenderTests(unittest.TestCase):+ def test_human_rendering_draws_the_agent_and_the_goal(self) -> None:+ env = placed_env(agent=(0, 0), goal=(2, 2), grid_size=3, render_mode="human")+ stream = io.StringIO()+ with contextlib.redirect_stdout(stream):+ env.render()+ drawn = stream.getvalue()+ self.assertIn("A", drawn)+ self.assertIn("G", drawn)+ self.assertEqual(drawn.count("A"), 1)++ def test_rgb_rendering_returns_a_fifty_pixel_cell_canvas(self) -> None:+ env = placed_env(agent=(0, 0), goal=(2, 2), grid_size=3, render_mode="rgb_array")+ frame = env.render()+ self.assertEqual(frame.shape, (150, 150, 3))+ self.assertEqual(frame.dtype, np.uint8)++ def test_rendering_is_a_no_op_when_no_mode_was_requested(self) -> None:+ env = placed_env(agent=(0, 0), goal=(2, 2), render_mode=None)+ self.assertIsNone(env.render())+++def train_tiny_agent(directory: Path) -> Path:+ """A two-rollout PPO on CartPole, saved to disk. Not a competent policy."""+ model = PPO(+ "MlpPolicy",+ "CartPole-v1",+ n_steps=64,+ batch_size=32,+ n_epochs=1,+ seed=0,+ verbose=0,+ )+ model.learn(total_timesteps=128)+ path = directory / "tiny_model"+ model.save(str(path))+ return path+++class EvaluationTests(unittest.TestCase):+ @classmethod+ def setUpClass(cls) -> None:+ cls._directory = tempfile.TemporaryDirectory()+ cls.model_path = train_tiny_agent(Path(cls._directory.name))++ @classmethod+ def tearDownClass(cls) -> None:+ cls._directory.cleanup()++ def test_evaluation_returns_a_mean_and_a_non_negative_spread(self) -> None:+ mean, deviation = evaluate_agent.evaluate_agent(+ str(self.model_path), env_id="CartPole-v1", n_eval_episodes=3+ )+ self.assertIsInstance(float(mean), float)+ self.assertGreaterEqual(deviation, 0.0)+ # CartPole-v1 pays 1 per surviving step and caps at 500.+ self.assertGreater(mean, 0.0)+ self.assertLessEqual(mean, 500.0)++ def test_the_score_is_an_average_of_whole_cartpole_episodes(self) -> None:+ # CartPole pays exactly 1 per surviving step, so the mean of n episodes+ # is a multiple of 1/n. The helper takes no seed, so the value itself+ # varies between calls -- its arithmetic must not.+ mean, _ = evaluate_agent.evaluate_agent(+ str(self.model_path), env_id="CartPole-v1", n_eval_episodes=4+ )+ self.assertAlmostEqual((mean * 4) % 1.0, 0.0, places=9)+ self.assertGreaterEqual(mean, 1.0)++ def test_a_single_episode_has_no_spread(self) -> None:+ _, deviation = evaluate_agent.evaluate_agent(+ str(self.model_path), env_id="CartPole-v1", n_eval_episodes=1+ )+ self.assertEqual(deviation, 0.0)++ def test_a_missing_normalisation_file_is_ignored_rather_than_fatal(self) -> None:+ mean, _ = evaluate_agent.evaluate_agent(+ str(self.model_path),+ env_id="CartPole-v1",+ n_eval_episodes=1,+ vec_normalize_path=str(Path(self._directory.name) / "absent.pkl"),+ )+ self.assertGreater(mean, 0.0)++ def test_comparing_models_reports_one_row_per_path(self) -> None:+ # The results are keyed by path, so the same checkpoint twice collapses+ # to one entry rather than silently overwriting a different model's row.+ results = evaluate_agent.compare_models(+ [str(self.model_path), str(self.model_path)],+ env_id="CartPole-v1",+ n_eval_episodes=2,+ )+ self.assertEqual(set(results), {str(self.model_path)})+ entry = results[str(self.model_path)]+ self.assertEqual(set(entry), {"mean", "std"})+ self.assertGreater(entry["mean"], 0.0)+ self.assertLessEqual(entry["mean"], 500.0)+ self.assertGreaterEqual(entry["std"], 0.0)++ def test_loading_a_model_that_does_not_exist_fails_loudly(self) -> None:+ with self.assertRaises((FileNotFoundError, ValueError)):+ evaluate_agent.evaluate_agent(+ str(Path(self._directory.name) / "nothing"), env_id="CartPole-v1"+ )+++DRIVER = """+import json, sys+sys.path.insert(0, {scripts!r})+import train_rl_agent++if __name__ == "__main__":+ model = train_rl_agent.train_agent(+ env_id="CartPole-v1",+ n_envs=2,+ total_timesteps=16,+ eval_freq=10 ** 9,+ save_freq=10 ** 9,+ log_dir={logs!r},+ save_path={models!r},+ )+ print("TIMESTEPS", model.num_timesteps)+"""+++class TrainingPipelineTests(unittest.TestCase):+ """One real (tiny) run of the training template, end to end."""++ def test_the_template_trains_and_saves_a_loadable_model(self) -> None:+ with tempfile.TemporaryDirectory() as directory:+ root = Path(directory)+ driver = root / "driver.py"+ # train_agent hardcodes SubprocVecEnv, and spawn/forkserver+ # re-imports the entry module, so it can only be launched from a+ # script guarded by `if __name__ == "__main__"`.+ driver.write_text(+ textwrap.dedent(DRIVER).format(+ scripts=str(SCRIPTS),+ logs=str(root / "logs"),+ models=str(root / "models"),+ )+ )+ completed = subprocess.run(+ [sys.executable, str(driver)],+ capture_output=True,+ text=True,+ timeout=900,+ )+ self.assertEqual(+ completed.returncode, 0, f"driver failed:\n{completed.stderr[-3000:]}"+ )+ self.assertIn("Training complete!", completed.stdout)++ # PPO collects n_steps per environment before it can update, so the+ # 16 requested timesteps become one full rollout.+ reported = int(completed.stdout.split("TIMESTEPS")[1].split()[0])+ self.assertGreaterEqual(reported, 16)++ saved = root / "models" / "final_model.zip"+ self.assertTrue(saved.is_file())+ self.assertTrue((root / "logs" / "eval").is_dir())+ self.assertTrue((root / "models" / "best_model").is_dir())++ # The point of saving is being able to load it again.+ mean, _ = evaluate_agent.evaluate_agent(+ str(root / "models" / "final_model"),+ env_id="CartPole-v1",+ n_eval_episodes=2,+ )+ self.assertGreater(mean, 0.0)+++# `watch_agent` is deliberately untested: it exists to open a+# render_mode="human" window, which needs a display this suite does not have.+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/statistical-analysis/test_scripts.py b/tests/statistical-analysis/test_scripts.pynew file mode 100644index 00000000..36286377--- /dev/null+++ b/tests/statistical-analysis/test_scripts.py@@ -0,0 +1,213 @@+"""Tests for the statistical-analysis assumption checks.++These functions decide whether a parametric test is defensible, so the+assertions are constructed against data whose answer is known by construction:+a normal sample must pass Shapiro-Wilk, a lognormal one must fail; groups drawn+with equal variance must pass Levene, groups with a 10x spread must fail. A+check that quietly returns "assumption met" for skewed data is worse than no+check at all.++Most of these functions default to `plot=True` and draw with matplotlib, so the+suite forces the Agg backend and passes `plot=False` where the parameter exists+(`check_linearity` and `comprehensive_assumption_check` do not take one). These+are numeric assertions, not rendering ones.+"""++from __future__ import annotations++import sys+import unittest+from pathlib import Path++import pytest++import skill_contract++SKILL_ROOT = Path(__file__).resolve().parents[2] / "skills" / "statistical-analysis"+SCRIPTS = SKILL_ROOT / "scripts"+sys.path.insert(0, str(SCRIPTS))++np = pytest.importorskip("numpy", reason="statistical-analysis needs numpy")+pd = pytest.importorskip("pandas", reason="statistical-analysis needs pandas")+pytest.importorskip("scipy", reason="statistical-analysis needs scipy")+matplotlib = pytest.importorskip("matplotlib", reason="assumption_checks imports matplotlib")+matplotlib.use("Agg")++import assumption_checks # noqa: E402++RNG = np.random.default_rng(20260727)+NORMAL = RNG.normal(0, 1, 300)+SKEWED = RNG.lognormal(0, 1, 300)+++class NormalityTests(unittest.TestCase):+ def test_a_normal_sample_is_reported_as_normal(self) -> None:+ result = assumption_checks.check_normality(NORMAL, plot=False)+ self.assertTrue(result["is_normal"])+ self.assertGreater(result["p_value"], 0.05)++ def test_a_lognormal_sample_is_reported_as_non_normal(self) -> None:+ result = assumption_checks.check_normality(SKEWED, plot=False)+ self.assertFalse(result["is_normal"])+ self.assertLess(result["p_value"], 0.05)++ def test_the_verdict_follows_the_supplied_alpha(self) -> None:+ # Same data, stricter threshold: the decision must move with alpha+ # rather than being hardcoded at .05.+ borderline = RNG.normal(0, 1, 300)+ lenient = assumption_checks.check_normality(borderline, alpha=1e-9, plot=False)+ self.assertTrue(lenient["is_normal"])+ strict = assumption_checks.check_normality(borderline, alpha=0.999, plot=False)+ self.assertFalse(strict["is_normal"])++ def test_the_result_carries_the_test_name_and_a_recommendation(self) -> None:+ normal = assumption_checks.check_normality(NORMAL, plot=False)+ self.assertEqual(normal["test"], "Shapiro-Wilk")+ self.assertEqual(normal["n"], len(NORMAL))+ self.assertIn("parametric", normal["recommendation"])++ skewed = assumption_checks.check_normality(SKEWED, plot=False)+ self.assertIn("non-parametric", skewed["recommendation"])++ def test_lists_and_series_are_accepted_as_well_as_arrays(self) -> None:+ for data in (list(NORMAL), pd.Series(NORMAL), NORMAL):+ with self.subTest(kind=type(data).__name__):+ self.assertTrue(+ assumption_checks.check_normality(data, plot=False)["is_normal"]+ )+++class PerGroupNormalityTests(unittest.TestCase):+ def setUp(self) -> None:+ self.frame = pd.DataFrame(+ {+ "value": np.concatenate([RNG.normal(0, 1, 200), RNG.lognormal(0, 1, 200)]),+ "group": ["normal"] * 200 + ["skewed"] * 200,+ }+ )++ def test_each_group_gets_its_own_verdict(self) -> None:+ result = assumption_checks.check_normality_per_group(+ self.frame, "value", "group", plot=False+ )+ self.assertEqual(len(result), 2)+ verdicts = dict(zip(result["Group"], result["Normal"]))+ self.assertEqual(verdicts["normal"], "Yes")+ self.assertEqual(verdicts["skewed"], "No")++ def test_the_result_is_a_frame_with_one_row_and_an_n_per_group(self) -> None:+ result = assumption_checks.check_normality_per_group(+ self.frame, "value", "group", plot=False+ )+ self.assertIsInstance(result, pd.DataFrame)+ self.assertEqual(set(result["Group"]), {"normal", "skewed"})+ self.assertEqual(list(result["N"]), [200, 200])+++class VarianceTests(unittest.TestCase):+ def _frame(self, spread: float) -> pd.DataFrame:+ return pd.DataFrame(+ {+ "value": np.concatenate(+ [RNG.normal(0, 1, 200), RNG.normal(0, spread, 200)]+ ),+ "group": ["a"] * 200 + ["b"] * 200,+ }+ )++ def test_equal_variances_pass_levene(self) -> None:+ result = assumption_checks.check_homogeneity_of_variance(+ self._frame(1.0), "value", "group", plot=False+ )+ self.assertTrue(result["is_homogeneous"])++ def test_a_tenfold_spread_difference_fails_levene(self) -> None:+ result = assumption_checks.check_homogeneity_of_variance(+ self._frame(10.0), "value", "group", plot=False+ )+ self.assertFalse(result["is_homogeneous"])+ self.assertLess(result["p_value"], 0.05)++ def test_more_than_two_groups_are_supported(self) -> None:+ frame = pd.DataFrame(+ {+ "value": np.concatenate([RNG.normal(0, 1, 100) for _ in range(3)]),+ "group": ["a"] * 100 + ["b"] * 100 + ["c"] * 100,+ }+ )+ result = assumption_checks.check_homogeneity_of_variance(+ frame, "value", "group", plot=False+ )+ self.assertTrue(result["is_homogeneous"])+++class OutlierTests(unittest.TestCase):+ def test_the_iqr_method_finds_a_planted_extreme_value(self) -> None:+ data = np.concatenate([RNG.normal(0, 1, 200), [50.0]])+ result = assumption_checks.detect_outliers(data, method="iqr", plot=False)+ self.assertGreaterEqual(result["n_outliers"], 1)++ def test_the_zscore_method_finds_the_same_value(self) -> None:+ data = np.concatenate([RNG.normal(0, 1, 200), [50.0]])+ result = assumption_checks.detect_outliers(data, method="zscore", plot=False)+ self.assertGreaterEqual(result["n_outliers"], 1)++ def test_a_higher_threshold_flags_fewer_points(self) -> None:+ data = np.concatenate([RNG.normal(0, 1, 300), [6.0, 8.0, 12.0]])+ mild = assumption_checks.detect_outliers(+ data, method="iqr", threshold=1.5, plot=False+ )+ extreme = assumption_checks.detect_outliers(+ data, method="iqr", threshold=3.0, plot=False+ )+ self.assertGreaterEqual(mild["n_outliers"], extreme["n_outliers"])++ def test_clean_data_yields_no_extreme_outliers(self) -> None:+ result = assumption_checks.detect_outliers(+ RNG.normal(0, 1, 200), method="zscore", threshold=5.0, plot=False+ )+ self.assertEqual(result["n_outliers"], 0)++ def test_the_reported_percentage_matches_the_count(self) -> None:+ data = np.concatenate([RNG.normal(0, 1, 99), [50.0]])+ result = assumption_checks.detect_outliers(data, method="zscore", plot=False)+ self.assertAlmostEqual(+ result["pct_outliers"], 100 * result["n_outliers"] / len(data), places=6+ )+++class LinearityTests(unittest.TestCase):+ def test_a_straight_line_relationship_is_reported_as_linear(self) -> None:+ x = np.linspace(0, 10, 200)+ y = 3 * x + RNG.normal(0, 0.1, 200)+ result = assumption_checks.check_linearity(x, y)+ self.assertGreater(abs(result["r"]), 0.99)++ def test_a_quadratic_relationship_is_distinguished_from_a_linear_one(self) -> None:+ x = np.linspace(-5, 5, 200)+ linear = assumption_checks.check_linearity(+ x, 2 * x + RNG.normal(0, 0.1, 200)+ )+ curved = assumption_checks.check_linearity(+ x, x**2 + RNG.normal(0, 0.1, 200)+ )+ self.assertGreater(abs(linear["r"]), abs(curved["r"]))+++class ComprehensiveCheckTests(unittest.TestCase):+ def test_the_combined_check_reports_on_every_assumption(self) -> None:+ frame = pd.DataFrame(+ {+ "value": np.concatenate([RNG.normal(0, 1, 100), RNG.normal(1, 1, 100)]),+ "group": ["a"] * 100 + ["b"] * 100,+ }+ )+ result = assumption_checks.comprehensive_assumption_check(+ frame, "value", "group"+ )+ self.assertIsInstance(result, dict)+ self.assertTrue(result)+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/statistical-power/test_scripts.py b/tests/statistical-power/test_scripts.pynew file mode 100644index 00000000..9850fa08--- /dev/null+++ b/tests/statistical-power/test_scripts.py@@ -0,0 +1,331 @@+"""Tests for the statistical-power calculators.++Power analysis is a place where a plausible-looking wrong answer costs real+money and real subjects, so these tests check numbers against values that can+be verified independently rather than against whatever the code happens to+return. Cohen's canonical results are the anchors: a two-sample t-test with+d = 0.5 at 80% power needs 64 per group, and Pearson r = 0.30 at 80% power+needs 85.++The three entry points (`sample_size`, `power`, `mde`) solve the same+relationship for different unknowns, so the strongest assertions are the+round trips -- feed one's output to another and you must land back where you+started.+"""++from __future__ import annotations++import math+import sys+import tempfile+import unittest+from pathlib import Path++import pytest++import skill_contract++SKILL_ROOT = Path(__file__).resolve().parents[2] / "skills" / "statistical-power"+SCRIPTS = SKILL_ROOT / "scripts"+sys.path.insert(0, str(SCRIPTS))++pytest.importorskip("numpy", reason="statistical-power needs numpy")+pytest.importorskip("scipy", reason="statistical-power needs scipy")+pytest.importorskip("statsmodels", reason="statistical-power needs statsmodels")++import power as power_module # noqa: E402+import simulate_power # noqa: E402++DemoBlockTests = skill_contract.cli.demo_test_case(SKILL_ROOT, ("power.py",))+++class SampleSizeTests(unittest.TestCase):+ def test_two_sample_t_test_matches_cohens_canonical_value(self) -> None:+ # Cohen (1988): d = 0.5, alpha = .05 two-sided, power = .80 -> 64/group.+ self.assertEqual(+ power_module.sample_size("t_ind", effect_size=0.5, power=0.80), 64+ )++ def test_correlation_matches_the_published_value(self) -> None:+ # r = 0.30, alpha = .05 two-sided, power = .80 -> n = 85.+ self.assertEqual(+ power_module.sample_size("correlation", effect_size=0.30, power=0.80), 85+ )++ def test_anova_returns_total_n_not_per_group(self) -> None:+ # f = 0.25, k = 4, power = .80 -> ~180 total (45 per group).+ total = power_module.sample_size(+ "anova", effect_size=0.25, k_groups=4, power=0.80+ )+ self.assertGreater(total, 150)+ self.assertLess(total, 200)++ def test_smaller_effects_need_larger_samples(self) -> None:+ sizes = [+ power_module.sample_size("t_ind", effect_size=d, power=0.80)+ for d in (0.8, 0.5, 0.2)+ ]+ self.assertEqual(sizes, sorted(sizes))++ def test_higher_power_needs_a_larger_sample(self) -> None:+ low = power_module.sample_size("t_ind", effect_size=0.5, power=0.80)+ high = power_module.sample_size("t_ind", effect_size=0.5, power=0.95)+ self.assertGreater(high, low)++ def test_a_one_sided_test_needs_fewer_subjects(self) -> None:+ two = power_module.sample_size("t_ind", effect_size=0.5, power=0.80)+ one = power_module.sample_size(+ "t_ind", effect_size=0.5, power=0.80, alternative="larger"+ )+ self.assertLess(one, two)++ def test_round_up_is_the_default_because_a_fraction_of_a_subject_is_not_a_subject(+ self,+ ) -> None:+ rounded = power_module.sample_size("t_ind", effect_size=0.5, power=0.80)+ exact = power_module.sample_size(+ "t_ind", effect_size=0.5, power=0.80, round_up=False+ )+ self.assertIsInstance(rounded, int)+ self.assertGreaterEqual(rounded, exact)+ self.assertEqual(rounded, math.ceil(exact))++ def test_an_unequal_allocation_ratio_changes_the_first_group(self) -> None:+ balanced = power_module.sample_size("t_ind", effect_size=0.5, power=0.80)+ skewed = power_module.sample_size(+ "t_ind", effect_size=0.5, power=0.80, ratio=2.0+ )+ self.assertLess(skewed, balanced)+++class RequiredArgumentTests(unittest.TestCase):+ def test_each_test_names_the_parameter_it_is_missing(self) -> None:+ cases = [+ ("anova", {"effect_size": 0.25}, "k_groups"),+ ("two_proportions", {"prop1": 0.4}, "prop1= and prop2="),+ ("one_proportion", {"prop1": 0.4}, "prop1= and prop0="),+ ("chi2", {"effect_size": 0.3}, "dof="),+ ("linear_regression", {"effect_size": 0.15}, "df_num="),+ ]+ for test, kwargs, expected in cases:+ with self.subTest(test=test):+ with self.assertRaises(ValueError) as raised:+ power_module.sample_size(test, power=0.80, **kwargs)+ self.assertIn(expected, str(raised.exception))++ def test_an_unknown_test_is_named_in_the_error(self) -> None:+ with self.assertRaisesRegex(ValueError, "unknown test 'wilcoxon'"):+ power_module.sample_size("wilcoxon", effect_size=0.5)++ def test_test_names_are_case_insensitive(self) -> None:+ self.assertEqual(+ power_module.sample_size("T_IND", effect_size=0.5, power=0.80),+ power_module.sample_size("t_ind", effect_size=0.5, power=0.80),+ )++ def test_power_requires_a_sample_size(self) -> None:+ with self.assertRaisesRegex(ValueError, "nobs1=|nobs="):+ power_module.power("t_ind", effect_size=0.5)++ def test_mde_requires_a_sample_size(self) -> None:+ with self.assertRaisesRegex(ValueError, "nobs1=|nobs="):+ power_module.mde("t_ind")+++class PowerTests(unittest.TestCase):+ def test_power_at_the_solved_sample_size_reaches_the_target(self) -> None:+ n = power_module.sample_size("t_ind", effect_size=0.5, power=0.80)+ achieved = power_module.power("t_ind", effect_size=0.5, nobs1=n)+ self.assertGreaterEqual(achieved, 0.80)+ self.assertLess(achieved, 0.82) # rounding up, not wildly over++ def test_power_is_bounded_and_monotone_in_n(self) -> None:+ values = [+ power_module.power("t_ind", effect_size=0.5, nobs1=n)+ for n in (10, 30, 64, 200)+ ]+ self.assertEqual(values, sorted(values))+ self.assertTrue(all(0.0 <= value <= 1.0 for value in values))++ def test_a_zero_effect_has_power_equal_to_alpha(self) -> None:+ # With no true effect, the rejection rate is the type-I error rate.+ self.assertAlmostEqual(+ power_module.power("t_ind", effect_size=0.0, nobs1=100, alpha=0.05),+ 0.05,+ places=3,+ )++ def test_correlation_power_round_trips_with_its_sample_size(self) -> None:+ n = power_module.sample_size("correlation", effect_size=0.30, power=0.80)+ self.assertGreaterEqual(+ power_module.power("correlation", effect_size=0.30, nobs=n), 0.80+ )++ def test_regression_power_is_zero_when_the_model_has_no_residual_df(self) -> None:+ # n - k_total - 1 < 1 means nothing left to test against; report 0+ # rather than raising or returning a nonsense value.+ self.assertEqual(+ power_module.power(+ "linear_regression", effect_size=0.15, nobs=5, df_num=3, k_total=5+ ),+ 0.0,+ )++ def test_two_proportions_power_round_trips(self) -> None:+ n = power_module.sample_size(+ "two_proportions", prop1=0.40, prop2=0.55, power=0.80+ )+ self.assertGreaterEqual(+ power_module.power("two_proportions", prop1=0.40, prop2=0.55, nobs1=n),+ 0.80,+ )+++class MdeTests(unittest.TestCase):+ def test_the_mde_at_a_solved_n_recovers_the_original_effect(self) -> None:+ n = power_module.sample_size("t_ind", effect_size=0.5, power=0.80)+ detectable = power_module.mde("t_ind", nobs1=n, power=0.80)+ self.assertAlmostEqual(detectable, 0.5, delta=0.02)++ def test_a_larger_sample_detects_a_smaller_effect(self) -> None:+ small = power_module.mde("t_ind", nobs1=20, power=0.80)+ large = power_module.mde("t_ind", nobs1=200, power=0.80)+ self.assertLess(large, small)++ def test_correlation_mde_round_trips(self) -> None:+ n = power_module.sample_size("correlation", effect_size=0.30, power=0.80)+ self.assertAlmostEqual(+ power_module.mde("correlation", nobs=n, power=0.80), 0.30, delta=0.01+ )++ def test_regression_mde_round_trips(self) -> None:+ detectable = power_module.mde(+ "linear_regression", nobs=100, df_num=3, k_total=5, power=0.80+ )+ achieved = power_module.power(+ "linear_regression",+ effect_size=detectable,+ nobs=100,+ df_num=3,+ k_total=5,+ )+ self.assertAlmostEqual(achieved, 0.80, delta=0.01)+++class RegressionSolverTests(unittest.TestCase):+ def test_the_sample_size_search_stops_at_the_first_adequate_n(self) -> None:+ n = power_module.sample_size(+ "linear_regression", effect_size=0.15, df_num=3, k_total=5, power=0.80+ )+ at_n = power_module._reg_power(0.15, n, 3, 5, 0.05)+ below = power_module._reg_power(0.15, n - 1, 3, 5, 0.05)+ self.assertGreaterEqual(at_n, 0.80)+ self.assertLess(below, 0.80)++ def test_an_undetectably_small_effect_does_not_loop_forever(self) -> None:+ with self.assertRaisesRegex(RuntimeError, "did not converge"):+ power_module._reg_sample_size(1e-9, 1, 1, 0.05, 0.99)+++class PowerCurveTests(unittest.TestCase):+ def test_the_curve_rises_with_sample_size_and_is_saved(self) -> None:+ import matplotlib++ matplotlib.use("Agg")+ with tempfile.TemporaryDirectory() as directory:+ output = Path(directory) / "curve.png"+ ns, powers = power_module.power_curve(+ "t_ind", effect_size=0.5, n_range=range(10, 110, 10), save=output+ )+ self.assertEqual(len(ns), len(powers))+ self.assertEqual(len(ns), 10)+ self.assertTrue(list(powers) == sorted(powers))+ self.assertTrue(output.is_file())+ self.assertGreater(output.stat().st_size, 0)++ def test_per_group_tests_iterate_the_per_group_n(self) -> None:+ # For t_ind the curve must pass nobs1, so power at n=64 matches the+ # canonical per-group answer rather than a total-n reading.+ _, powers = power_module.power_curve(+ "t_ind", effect_size=0.5, n_range=[64]+ )+ self.assertAlmostEqual(float(powers[0]), 0.80, delta=0.01)+++class SimulationTests(unittest.TestCase):+ def test_wilson_intervals_bracket_the_estimate_and_stay_in_range(self) -> None:+ for successes, trials in ((0, 100), (50, 100), (100, 100), (1, 10)):+ with self.subTest(successes=successes, trials=trials):+ low, high = simulate_power._wilson_ci(successes, trials)+ observed = successes / trials+ self.assertLessEqual(0.0, low)+ self.assertLessEqual(high, 1.0)+ # The bound is clamped to [0, 1], so at p = 1 it lands one ulp+ # short of the observed rate; compare with a float tolerance.+ self.assertLessEqual(low, observed + 1e-12)+ self.assertLessEqual(observed, high + 1e-12)++ def test_a_zero_success_run_still_has_a_positive_upper_bound(self) -> None:+ # The interval must not collapse to (0, 0): "we saw none" is not+ # "it cannot happen".+ low, high = simulate_power._wilson_ci(0, 50)+ self.assertEqual(low, 0.0)+ self.assertGreater(high, 0.0)++ def test_simulation_reproduces_from_its_seed(self) -> None:+ generator = simulate_power.example_two_group_difference(effect=0.5)+ first = simulate_power.simulate_power(generator, n=30, n_sims=200, seed=4)+ second = simulate_power.simulate_power(generator, n=30, n_sims=200, seed=4)+ self.assertEqual(first.power, second.power)++ def test_simulated_power_tracks_the_analytic_answer(self) -> None:+ # The whole point of the simulator is to agree with theory where theory+ # applies, so it can be trusted where theory does not.+ generator = simulate_power.example_two_group_difference(effect=0.5)+ simulated = simulate_power.simulate_power(generator, n=64, n_sims=4000, seed=1)+ analytic = power_module.power("t_ind", effect_size=0.5, nobs1=64)+ self.assertAlmostEqual(simulated.power, analytic, delta=0.04)++ def test_a_null_effect_simulates_to_the_alpha_level(self) -> None:+ generator = simulate_power.example_two_group_difference(effect=0.0)+ estimate = simulate_power.simulate_power(+ generator, n=50, n_sims=4000, alpha=0.05, seed=2+ )+ self.assertAlmostEqual(estimate.power, 0.05, delta=0.02)++ def test_the_estimate_reports_its_own_uncertainty(self) -> None:+ generator = simulate_power.example_two_group_difference(effect=0.5)+ estimate = simulate_power.simulate_power(generator, n=40, n_sims=500, seed=3)+ self.assertLessEqual(estimate.ci_low, estimate.power)+ self.assertLessEqual(estimate.power, estimate.ci_high)+ self.assertEqual(estimate.n_sims, 500)++ def test_the_sample_size_search_returns_an_n_that_meets_the_target(self) -> None:+ generator = simulate_power.example_two_group_difference(effect=0.8)+ found, estimate = simulate_power.find_sample_size(+ generator, target_power=0.80, n_sims=400, hi=200, seed=5, verbose=False+ )+ self.assertIsInstance(found, int)+ self.assertGreaterEqual(estimate.power, 0.80)+ # Bisection returns the smallest adequate n, so one fewer must fall short.+ below = simulate_power.simulate_power(+ generator, n=found - 1, n_sims=400, seed=5+ )+ self.assertLess(below.power, 0.80)++ def test_the_worked_examples_all_produce_a_usable_estimate(self) -> None:+ examples = (+ simulate_power.example_two_group_difference(effect=0.6),+ simulate_power.example_logistic_regression(beta=1.0),+ simulate_power.example_cluster_randomized(effect=0.5),+ )+ for index, generator in enumerate(examples):+ with self.subTest(example=index):+ estimate = simulate_power.simulate_power(+ generator, n=40, n_sims=200, seed=7+ )+ self.assertTrue(0.0 <= estimate.power <= 1.0)+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/timesfm-forecasting/test_scripts.py b/tests/timesfm-forecasting/test_scripts.pynew file mode 100644index 00000000..1dfbe161--- /dev/null+++ b/tests/timesfm-forecasting/test_scripts.py@@ -0,0 +1,693 @@+"""Tests for the TimesFM preflight checker and CSV forecasting driver.++Neither script is exercised against real model weights -- the point of+`check_system.py` is to run *before* a 200M-parameter download, and+`forecast_csv.py` only reaches the network in `load_model()`, which nothing here+calls. What the tests cover instead:++* Thresholds. Every RAM, disk, and Python verdict is produced with the host+ stubbed, so the boundaries are checked against the profile tables rather than+ against whatever this machine happens to have: exactly the minimum warns,+ below it fails, exactly the recommendation passes. A missing package must warn+ and not fail, or the checker would refuse to run on a machine it is being used+ to prepare.+* The batch-size ladder. It must be monotonic in VRAM and RAM -- a swapped tier+ would recommend a larger batch for a smaller GPU -- and a value it cannot+ parse must fall back rather than raise.+* The contract between the two scripts: `forecast_csv` reads+ `recommended_batch_size` out of `SystemReport.to_dict()` and refuses to+ continue when the report fails, so both keys and both paths are asserted.+* Quantile indexing. TimesFM's continuous quantile head returns ten columns --+ the mean followed by the nine deciles -- so the 10th, 50th and 90th+ percentiles live at indices 1, 5 and 9. Off-by-one here mislabels a+ prediction interval, which no shape check would catch, so the test feeds an+ array whose values encode their own index.+"""++from __future__ import annotations++import contextlib+import io+import json+import os+import shutil+import subprocess+import sys+import tempfile+import types+import unittest+from pathlib import Path+from unittest import mock++import pytest++import skill_contract++SKILL_ROOT = Path(__file__).resolve().parents[2] / "skills" / "timesfm-forecasting"+SCRIPTS = SKILL_ROOT / "scripts"+sys.path.insert(0, str(SCRIPTS))++np = pytest.importorskip("numpy", reason="forecast_csv needs numpy")+pd = pytest.importorskip("pandas", reason="forecast_csv needs pandas")++import check_system # noqa: E402+import forecast_csv # noqa: E402++CliHelpTests = skill_contract.cli.help_test_case(SKILL_ROOT)+++def usage(free_gb: float):+ """A `shutil.disk_usage` result with the requested free space."""+ total = int(100 * 1024**3)+ free = int(free_gb * 1024**3)+ return shutil._ntuple_diskusage(total, total - free, free)+++def report_with_gpu(value: str, status: str = "pass") -> check_system.SystemReport:+ report = check_system.SystemReport(model="test")+ report.checks.append(+ check_system.CheckResult(name="GPU", status=status, detail="", value=value)+ )+ return report+++class ModelProfileTests(unittest.TestCase):+ def test_the_three_documented_checkpoints_are_offered(self) -> None:+ self.assertEqual(set(check_system.MODEL_PROFILES), {"v2.5", "v2.0", "v1.0"})++ def test_each_profile_points_at_its_published_hugging_face_repo(self) -> None:+ # A wrong repo id is a 404 at download time, long after the check passed.+ expected = {+ "v2.5": "google/timesfm-2.5-200m-pytorch",+ "v2.0": "google/timesfm-2.0-500m-pytorch",+ "v1.0": "google/timesfm-1.0-200m-pytorch",+ }+ for version, repo in expected.items():+ with self.subTest(version=version):+ self.assertEqual(check_system.MODEL_PROFILES[version]["hf_repo"], repo)++ def test_the_five_hundred_million_model_asks_for_the_most_memory(self) -> None:+ # v2.0 is 500M parameters against 200M for the other two.+ by_ram = {+ version: profile["min_ram_gb"]+ for version, profile in check_system.MODEL_PROFILES.items()+ }+ self.assertEqual(max(by_ram, key=by_ram.get), "v2.0")++ def test_no_profile_recommends_less_than_it_requires(self) -> None:+ for version, profile in check_system.MODEL_PROFILES.items():+ with self.subTest(version=version):+ self.assertLessEqual(profile["min_ram_gb"], profile["recommended_ram_gb"])+ self.assertLessEqual(+ profile["min_vram_gb"], profile["recommended_vram_gb"]+ )+ self.assertGreater(profile["disk_gb"], 0)+++class RamCheckTests(unittest.TestCase):+ PROFILE = check_system.MODEL_PROFILES["v2.0"] # min 8 GB, recommended 16 GB++ def check(self, total: float, available: float = 4.0):+ with mock.patch.object(check_system, "_get_total_ram_gb", return_value=total), \+ mock.patch.object(check_system, "_get_available_ram_gb", return_value=available):+ return check_system.check_ram(self.PROFILE)++ def test_below_the_minimum_fails_and_explains_the_consequence(self) -> None:+ result = self.check(4.0)+ self.assertEqual(result.status, "fail")+ self.assertIn("8 GB", result.detail)++ def test_exactly_the_minimum_warns_rather_than_failing(self) -> None:+ # 8 GB is enough to load the model, just not comfortably.+ self.assertEqual(self.check(8.0).status, "warn")++ def test_just_under_the_recommendation_still_warns(self) -> None:+ result = self.check(15.9)+ self.assertEqual(result.status, "warn")+ self.assertIn("per_core_batch_size", result.detail)++ def test_exactly_the_recommendation_passes(self) -> None:+ self.assertEqual(self.check(16.0).status, "pass")++ def test_the_reported_value_carries_both_totals(self) -> None:+ result = self.check(32.0, available=12.5)+ self.assertIn("32.0 GB", result.value)+ self.assertIn("12.5 GB", result.value)++ def test_the_smaller_model_passes_where_the_larger_one_fails(self) -> None:+ # 4 GB: below v2.0's 8 GB minimum, but at v2.5's recommendation.+ with mock.patch.object(check_system, "_get_total_ram_gb", return_value=4.0), \+ mock.patch.object(check_system, "_get_available_ram_gb", return_value=2.0):+ self.assertEqual(+ check_system.check_ram(check_system.MODEL_PROFILES["v2.5"]).status,+ "pass",+ )+ self.assertEqual(+ check_system.check_ram(check_system.MODEL_PROFILES["v2.0"]).status,+ "fail",+ )+++class DiskCheckTests(unittest.TestCase):+ PROFILE = check_system.MODEL_PROFILES["v2.0"] # 4 GB of weights++ def test_less_free_space_than_the_weights_need_fails(self) -> None:+ with mock.patch("shutil.disk_usage", return_value=usage(1.0)):+ result = check_system.check_disk(self.PROFILE)+ self.assertEqual(result.status, "fail")+ self.assertIn("HF_HOME", result.detail)++ def test_exactly_enough_space_passes(self) -> None:+ with mock.patch("shutil.disk_usage", return_value=usage(4.0)):+ self.assertEqual(check_system.check_disk(self.PROFILE).status, "pass")++ def test_the_cache_directory_is_where_the_space_is_measured(self) -> None:+ # The advice is "set HF_HOME to a larger volume", so that variable has+ # to be what the check actually looks at.+ with tempfile.TemporaryDirectory() as cache:+ with mock.patch.dict(os.environ, {"HF_HOME": cache}), \+ mock.patch("shutil.disk_usage", return_value=usage(50.0)) as measured:+ result = check_system.check_disk(self.PROFILE)+ self.assertIn(cache, result.value)+ self.assertEqual(measured.call_args.args[0], cache)++ def test_an_absent_cache_directory_falls_back_to_the_home_volume(self) -> None:+ missing = str(Path(tempfile.gettempdir()) / "timesfm-cache-does-not-exist")+ with mock.patch.dict(os.environ, {"HF_HOME": missing}), \+ mock.patch("shutil.disk_usage", return_value=usage(50.0)) as measured:+ check_system.check_disk(self.PROFILE)+ self.assertEqual(measured.call_args.args[0], str(Path.home()))+++class PythonCheckTests(unittest.TestCase):+ @staticmethod+ def interpreter(major: int, minor: int):+ return mock.patch.object(sys, "version_info", (major, minor, 0, "final", 0))++ def test_the_documented_minimum_of_three_ten_passes(self) -> None:+ with self.interpreter(3, 10):+ self.assertEqual(check_system.check_python().status, "pass")++ def test_three_nine_fails_and_states_the_requirement(self) -> None:+ with self.interpreter(3, 9):+ result = check_system.check_python()+ self.assertEqual(result.status, "fail")+ self.assertIn(">= 3.10", result.detail)++ def test_a_newer_interpreter_passes(self) -> None:+ with self.interpreter(3, 13):+ self.assertEqual(check_system.check_python().status, "pass")+++class PackageCheckTests(unittest.TestCase):+ def test_an_installed_package_reports_its_version(self) -> None:+ module = types.ModuleType("timesfm_probe_present")+ module.__version__ = "2.5.0"+ with mock.patch.dict(sys.modules, {"timesfm_probe_present": module}):+ result = check_system.check_package("probe", "timesfm_probe_present")+ self.assertEqual(result.status, "pass")+ self.assertIn("2.5.0", result.value)++ def test_a_missing_package_warns_instead_of_failing(self) -> None:+ # The whole point is to run this before installing TimesFM, so a missing+ # package must not make the report fail and block the workflow.+ result = check_system.check_package("timesfm_probe_absent_xyz")+ self.assertEqual(result.status, "warn")+ self.assertIn("uv pip install", result.detail)++ def test_a_package_without_a_version_is_still_installed(self) -> None:+ module = types.ModuleType("timesfm_probe_bare")+ with mock.patch.dict(sys.modules, {"timesfm_probe_bare": module}):+ result = check_system.check_package("probe", "timesfm_probe_bare")+ self.assertEqual(result.status, "pass")+ self.assertIn("unknown", result.value)+++class GpuCheckTests(unittest.TestCase):+ @staticmethod+ def torch_module(*, cuda: bool, mps: bool = False, vram_gb: float = 24.0):+ module = types.ModuleType("torch")+ module.cuda = types.SimpleNamespace(+ is_available=lambda: cuda,+ get_device_name=lambda index: "NVIDIA A10G",+ get_device_properties=lambda index: types.SimpleNamespace(+ total_memory=int(vram_gb * 1024**3)+ ),+ )+ module.backends = types.SimpleNamespace(+ mps=types.SimpleNamespace(is_available=lambda: mps)+ )+ return module++ def test_a_cuda_device_is_reported_with_its_vram(self) -> None:+ with mock.patch.dict(sys.modules, {"torch": self.torch_module(cuda=True, vram_gb=16.0)}):+ result = check_system.check_gpu()+ self.assertEqual(result.status, "pass")+ self.assertIn("NVIDIA A10G", result.value)+ self.assertIn("VRAM: 16.0 GB", result.value)++ def test_apple_silicon_passes_without_a_vram_figure(self) -> None:+ # MPS uses unified memory, so there is no separate VRAM to report.+ with mock.patch.dict(sys.modules, {"torch": self.torch_module(cuda=False, mps=True)}):+ result = check_system.check_gpu()+ self.assertEqual(result.status, "pass")+ self.assertIn("MPS", result.value)+ self.assertNotIn("VRAM", result.value)++ def test_no_accelerator_warns_because_cpu_still_works(self) -> None:+ with mock.patch.dict(sys.modules, {"torch": self.torch_module(cuda=False)}):+ result = check_system.check_gpu()+ self.assertEqual(result.status, "warn")+ self.assertIn("CPU", result.value)++ def test_torch_missing_entirely_warns_rather_than_raising(self) -> None:+ with mock.patch.dict(sys.modules, {"torch": None}):+ result = check_system.check_gpu()+ self.assertEqual(result.status, "warn")+ self.assertIn("torch not installed", result.value)+++class BatchSizeTests(unittest.TestCase):+ def gpu_batch(self, vram_gb: float) -> int:+ return check_system.recommend_batch_size(+ report_with_gpu(f"NVIDIA A100 | VRAM: {vram_gb} GB")+ )++ def cpu_batch(self, ram_gb: float) -> int:+ report = report_with_gpu("None (CPU only)", status="warn")+ with mock.patch.object(check_system, "_get_total_ram_gb", return_value=ram_gb):+ return check_system.recommend_batch_size(report)++ def mps_batch(self, ram_gb: float) -> int:+ report = report_with_gpu("Apple Silicon MPS")+ with mock.patch.object(check_system, "_get_total_ram_gb", return_value=ram_gb):+ return check_system.recommend_batch_size(report)++ def test_the_vram_tiers_are_the_documented_ladder(self) -> None:+ for vram, expected in ((40.0, 256), (24.0, 256), (16.0, 128), (8.0, 64),+ (4.0, 32), (2.0, 16)):+ with self.subTest(vram=vram):+ self.assertEqual(self.gpu_batch(vram), expected)++ def test_each_tier_boundary_is_inclusive_from_below(self) -> None:+ # 23.9 GB must not be treated as a 24 GB card.+ self.assertEqual(self.gpu_batch(23.9), 128)+ self.assertEqual(self.gpu_batch(15.9), 64)+ self.assertEqual(self.gpu_batch(7.9), 32)+ self.assertEqual(self.gpu_batch(3.9), 16)++ def test_the_recommendation_never_decreases_as_vram_grows(self) -> None:+ # A non-monotonic ladder would hand a smaller card the larger batch.+ sizes = [self.gpu_batch(vram) for vram in (1, 4, 8, 16, 24, 80)]+ self.assertEqual(sizes, sorted(sizes))++ def test_an_unparseable_vram_figure_falls_back_to_a_safe_batch(self) -> None:+ report = report_with_gpu("Mystery GPU | VRAM: lots GB")+ self.assertEqual(check_system.recommend_batch_size(report), 32)++ def test_cpu_only_hosts_are_sized_by_system_memory(self) -> None:+ self.assertEqual(self.cpu_batch(64.0), 64)+ self.assertEqual(self.cpu_batch(16.0), 32)+ self.assertEqual(self.cpu_batch(8.0), 8)+ self.assertEqual(self.cpu_batch(4.0), 4)++ def test_cpu_recommendations_never_decrease_as_memory_grows(self) -> None:+ sizes = [self.cpu_batch(ram) for ram in (2, 8, 16, 32, 128)]+ self.assertEqual(sizes, sorted(sizes))++ def test_unified_memory_hosts_are_sized_by_system_memory(self) -> None:+ self.assertEqual(self.mps_batch(64.0), 64)+ self.assertEqual(self.mps_batch(16.0), 32)+ self.assertEqual(self.mps_batch(8.0), 16)++ def test_every_recommendation_is_a_usable_batch_size(self) -> None:+ for vram in (0.5, 4.0, 80.0):+ with self.subTest(vram=vram):+ self.assertGreaterEqual(self.gpu_batch(vram), 1)+++class ReportTests(unittest.TestCase):+ """`run_checks` composes the individual verdicts into one decision."""++ def run_checks(self, *, total_ram=32.0, modules=None, free_gb=100.0,+ model="v2.5"):+ # `modules` is patched into sys.modules, so a value of None stands for+ # "not installed" -- importing it raises ImportError.+ modules = {} if modules is None else modules+ with mock.patch.object(check_system, "_get_total_ram_gb", return_value=total_ram), \+ mock.patch.object(check_system, "_get_available_ram_gb", return_value=total_ram / 2), \+ mock.patch("shutil.disk_usage", return_value=usage(free_gb)), \+ mock.patch.dict(sys.modules, modules):+ return check_system.run_checks(model)++ def test_a_healthy_cpu_host_passes_in_cpu_mode(self) -> None:+ report = self.run_checks(modules={"torch": GpuCheckTests.torch_module(cuda=False)})+ self.assertTrue(report.passed)+ self.assertEqual(report.mode, "cpu")+ self.assertIn("ready", report.verdict)+ self.assertIn(str(report.recommended_batch_size), report.verdict_detail)++ def test_a_cuda_host_is_reported_in_gpu_mode(self) -> None:+ report = self.run_checks(modules={"torch": GpuCheckTests.torch_module(cuda=True)})+ self.assertEqual(report.mode, "gpu")++ def test_an_apple_silicon_host_is_reported_in_mps_mode(self) -> None:+ report = self.run_checks(+ modules={"torch": GpuCheckTests.torch_module(cuda=False, mps=True)}+ )+ self.assertEqual(report.mode, "mps")++ def test_too_little_memory_fails_the_whole_report(self) -> None:+ report = self.run_checks(+ total_ram=1.0,+ modules={"torch": GpuCheckTests.torch_module(cuda=False)},+ )+ self.assertFalse(report.passed)+ self.assertIn("does NOT meet", report.verdict)+ # The detail must name the failing resource, not just say "failed".+ self.assertIn("RAM", report.verdict_detail)++ def test_a_full_disk_fails_the_whole_report(self) -> None:+ report = self.run_checks(+ free_gb=0.5,+ modules={"torch": GpuCheckTests.torch_module(cuda=False)},+ )+ self.assertFalse(report.passed)++ def test_warnings_alone_do_not_fail_the_report(self) -> None:+ # No GPU and no timesfm installed: both warn, and the run may proceed.+ report = self.run_checks(modules={"torch": None, "timesfm": None})+ statuses = {check.name: check.status for check in report.checks}+ self.assertEqual(statuses["GPU"], "warn")+ self.assertTrue(report.passed)++ def test_every_documented_resource_is_checked(self) -> None:+ report = self.run_checks(modules={"torch": GpuCheckTests.torch_module(cuda=False)})+ self.assertEqual(+ [check.name for check in report.checks],+ ["RAM", "GPU", "Disk", "Python", "timesfm", "torch"],+ )++ def test_the_json_report_is_serialisable_and_keeps_its_keys(self) -> None:+ # forecast_csv consumes this dict, and --json is a documented interface.+ report = self.run_checks(modules={"torch": GpuCheckTests.torch_module(cuda=True)})+ payload = json.loads(json.dumps(report.to_dict()))+ self.assertEqual(+ set(payload),+ {"model", "passed", "mode", "recommended_batch_size", "verdict",+ "verdict_detail", "checks"},+ )+ self.assertEqual(set(payload["checks"][0]), {"name", "status", "detail", "value"})++ def test_an_unknown_model_version_is_not_silently_substituted(self) -> None:+ with self.assertRaises(KeyError):+ check_system.run_checks("v9.9")+++class CheckResultFormattingTests(unittest.TestCase):+ def test_each_status_gets_its_own_icon(self) -> None:+ icons = {+ status: check_system.CheckResult(name="x", status=status, detail="").icon+ for status in ("pass", "warn", "fail", "banana")+ }+ self.assertEqual(len(set(icons.values())), 4, icons)++ def test_the_rendered_line_carries_the_name_value_and_status(self) -> None:+ line = str(+ check_system.CheckResult(+ name="RAM", status="warn", detail="tight", value="Total: 8.0 GB"+ )+ )+ self.assertIn("RAM", line)+ self.assertIn("Total: 8.0 GB", line)+ self.assertIn("WARN", line)+++class CommandLineTests(unittest.TestCase):+ """The checker is documented as runnable, so run it -- it touches nothing."""++ def invoke(self, *arguments):+ return subprocess.run(+ [sys.executable, str(SCRIPTS / "check_system.py"), *arguments],+ capture_output=True,+ text=True,+ timeout=180,+ env={**os.environ, "PYTHONDONTWRITEBYTECODE": "1"},+ )++ def test_the_json_output_parses_and_names_the_model(self) -> None:+ result = self.invoke("--model", "v1.0", "--json")+ # Exit code follows the verdict for this host, so only the payload is+ # asserted; a crash would show up as unparseable output.+ payload = json.loads(result.stdout)+ self.assertEqual(payload["model"], "TimesFM 1.0 (200M)")+ self.assertIn(payload["mode"], {"cpu", "gpu", "mps"})+ self.assertGreaterEqual(payload["recommended_batch_size"], 1)++ def test_an_unknown_model_is_rejected_by_the_parser(self) -> None:+ result = self.invoke("--model", "v9.9")+ self.assertNotEqual(result.returncode, 0)+ self.assertIn("invalid choice", result.stderr)++ def test_the_human_report_names_every_check_and_a_verdict(self) -> None:+ result = self.invoke()+ for name in ("RAM", "GPU", "Disk", "Python", "timesfm", "torch"):+ self.assertIn(name, result.stdout)+ self.assertIn("VERDICT", result.stdout)+++class PreflightHandoffTests(unittest.TestCase):+ """`forecast_csv` refuses to load a model the host cannot hold."""++ def test_a_failing_report_stops_the_run(self) -> None:+ report = check_system.SystemReport(+ model="test", verdict_detail="only 1 GB of RAM"+ )+ report.checks.append(+ check_system.CheckResult(name="RAM", status="fail", detail="only 1 GB")+ )+ with mock.patch.object(check_system, "run_checks", return_value=report):+ with contextlib.redirect_stdout(io.StringIO()) as printed:+ with self.assertRaises(SystemExit) as raised:+ forecast_csv.run_preflight()+ self.assertEqual(raised.exception.code, 1)+ # The reason has to reach the user, not just the exit code.+ self.assertIn("only 1 GB of RAM", printed.getvalue())++ def test_a_passing_report_hands_over_the_recommended_batch_size(self) -> None:+ report = check_system.SystemReport(model="test", recommended_batch_size=64)+ report.checks.append(+ check_system.CheckResult(name="RAM", status="pass", detail="fine")+ )+ with mock.patch.object(check_system, "run_checks", return_value=report):+ with contextlib.redirect_stdout(io.StringIO()):+ handed = forecast_csv.run_preflight()+ # The key forecast_csv reads must be the key the report writes.+ self.assertEqual(handed["recommended_batch_size"], 64)+++class CsvLoadingTests(unittest.TestCase):+ def setUp(self) -> None:+ self._temporary = tempfile.TemporaryDirectory()+ self.addCleanup(self._temporary.cleanup)+ self.root = Path(self._temporary.name)++ def write(self, text: str) -> str:+ path = self.root / "series.csv"+ path.write_text(text)+ return str(path)++ def load(self, path, *args):+ with contextlib.redirect_stdout(io.StringIO()) as printed:+ frame, columns, date_column = forecast_csv.load_csv(path, *args)+ return frame, columns, date_column, printed.getvalue()++ def test_numeric_columns_are_detected_and_the_date_column_excluded(self) -> None:+ path = self.write(+ "date,sales,revenue,region\n"+ "2024-01-01,10,100,north\n"+ "2024-01-02,11,110,north\n"+ )+ frame, columns, date_column, _ = self.load(path, "date")+ self.assertEqual(columns, ["sales", "revenue"])+ self.assertEqual(date_column, "date")+ # The date column must be parsed, not left as text, or no frequency can+ # be inferred for the forecast index.+ self.assertTrue(pd.api.types.is_datetime64_any_dtype(frame["date"]))++ def test_a_string_column_is_never_forecast(self) -> None:+ path = self.write("region,sales\nnorth,10\nsouth,12\n")+ _, columns, _, _ = self.load(path)+ self.assertEqual(columns, ["sales"])++ def test_an_explicit_column_list_is_honoured(self) -> None:+ path = self.write("sales,revenue\n10,100\n11,110\n")+ _, columns, _, _ = self.load(path, None, ["revenue"])+ self.assertEqual(columns, ["revenue"])++ def test_a_column_that_does_not_exist_is_dropped_with_a_warning(self) -> None:+ path = self.write("sales\n10\n11\n")+ _, columns, _, printed = self.load(path, None, ["sales", "profit"])+ self.assertEqual(columns, ["sales"])+ self.assertIn("profit", printed)++ def test_a_missing_date_column_is_reported_and_forgotten(self) -> None:+ path = self.write("day,sales\n2024-01-01,10\n")+ _, _, date_column, printed = self.load(path, "date")+ self.assertIsNone(date_column)+ self.assertIn("not found", printed)++ def test_a_csv_with_nothing_numeric_stops_the_run(self) -> None:+ path = self.write("region\nnorth\nsouth\n")+ with contextlib.redirect_stdout(io.StringIO()) as printed:+ with self.assertRaises(SystemExit) as raised:+ forecast_csv.load_csv(path)+ self.assertEqual(raised.exception.code, 1)+ self.assertIn("No numeric columns", printed.getvalue())++ def test_naming_no_columns_at_all_falls_back_to_autodetection(self) -> None:+ path = self.write("sales,revenue\n10,100\n")+ _, columns, _, _ = self.load(path, None, None)+ self.assertEqual(columns, ["sales", "revenue"])+++class ForecastAssemblyTests(unittest.TestCase):+ HORIZON = 4++ class RecordingModel:+ """Stands in for TimesFM: records inputs, returns index-encoded output."""++ def __init__(self, horizon: int) -> None:+ self.horizon = horizon+ self.inputs = None++ def forecast(self, horizon, inputs):+ self.inputs = [np.asarray(series) for series in inputs]+ point = np.zeros((len(inputs), horizon), dtype="float32")+ # quantiles[series, step, q] == q, so any index mix-up is visible.+ quantiles = np.tile(np.arange(10, dtype="float32"), (len(inputs), horizon, 1))+ return point, quantiles++ def setUp(self) -> None:+ self.model = self.RecordingModel(self.HORIZON)+ self.frame = pd.DataFrame(+ {+ "date": pd.date_range("2024-01-01", periods=5, freq="D"),+ "sales": [1.0, 2.0, 3.0, 4.0, 5.0],+ "revenue": [10.0, np.nan, 30.0, 40.0, 50.0],+ }+ )+ with contextlib.redirect_stdout(io.StringIO()):+ self.results = forecast_csv.forecast_series(+ self.model, self.frame, ["sales", "revenue"], self.HORIZON+ )++ def test_each_series_is_forecast_and_keyed_by_its_column(self) -> None:+ self.assertEqual(set(self.results), {"sales", "revenue"})+ for values in self.results.values():+ self.assertEqual(len(values["forecast"]), self.HORIZON)++ def test_the_quantile_columns_map_to_the_documented_percentiles(self) -> None:+ # TimesFM returns [mean, q0.1 ... q0.9], so the 10th, 50th and 90th+ # percentiles are columns 1, 5 and 9.+ band = self.results["sales"]+ self.assertEqual(band["lower_90"], [1.0] * self.HORIZON)+ self.assertEqual(band["lower_80"], [2.0] * self.HORIZON)+ self.assertEqual(band["median"], [5.0] * self.HORIZON)+ self.assertEqual(band["upper_80"], [8.0] * self.HORIZON)+ self.assertEqual(band["upper_90"], [9.0] * self.HORIZON)++ def test_the_bands_are_ordered_from_low_to_high(self) -> None:+ band = self.results["revenue"]+ for lower, upper in (("lower_90", "lower_80"), ("lower_80", "median"),+ ("median", "upper_80"), ("upper_80", "upper_90")):+ with self.subTest(pair=(lower, upper)):+ self.assertLess(band[lower][0], band[upper][0])++ def test_gaps_are_dropped_before_the_series_reaches_the_model(self) -> None:+ # A NaN passed through would poison the whole context window.+ sales, revenue = self.model.inputs+ self.assertEqual(len(sales), 5)+ self.assertEqual(len(revenue), 4)+ self.assertFalse(np.isnan(revenue).any())+ self.assertEqual(revenue.dtype, np.float32)+++class OutputWritingTests(unittest.TestCase):+ HORIZON = 3++ def setUp(self) -> None:+ self._temporary = tempfile.TemporaryDirectory()+ self.addCleanup(self._temporary.cleanup)+ self.root = Path(self._temporary.name)+ self.results = {+ name: {+ "forecast": [1.0, 2.0, 3.0],+ "lower_90": [0.1, 0.2, 0.3],+ "lower_80": [0.2, 0.3, 0.4],+ "median": [1.0, 2.0, 3.0],+ "upper_80": [1.8, 2.8, 3.8],+ "upper_90": [1.9, 2.9, 3.9],+ }+ for name in ("sales", "revenue")+ }++ def write_csv(self, frame, date_column):+ destination = self.root / "forecasts.csv"+ with contextlib.redirect_stdout(io.StringIO()):+ forecast_csv.write_csv_output(+ self.results, str(destination), frame, date_column, self.HORIZON+ )+ return pd.read_csv(destination)++ def test_one_row_per_series_and_step(self) -> None:+ frame = pd.DataFrame({"sales": [1.0, 2.0]})+ written = self.write_csv(frame, None)+ self.assertEqual(len(written), 2 * self.HORIZON)+ self.assertEqual(sorted(written["step"].unique()), [1, 2, 3])+ self.assertEqual(sorted(written["series"].unique()), ["revenue", "sales"])++ def test_without_dates_only_the_step_index_is_written(self) -> None:+ written = self.write_csv(pd.DataFrame({"sales": [1.0, 2.0]}), None)+ self.assertNotIn("date", written.columns)++ def test_a_daily_history_continues_past_its_last_observation(self) -> None:+ # Five daily points ending 2024-01-05, horizon 3: the forecast index is+ # the next three days, not a repeat of the last one.+ frame = pd.DataFrame(+ {"date": pd.date_range("2024-01-01", periods=5, freq="D")}+ )+ written = self.write_csv(frame, "date")+ self.assertEqual(+ list(written[written["series"] == "sales"]["date"]),+ ["2024-01-06", "2024-01-07", "2024-01-08"],+ )++ def test_an_irregular_history_falls_back_to_step_numbers(self) -> None:+ # No frequency can be inferred from unevenly spaced dates, so the+ # writer must not invent one.+ frame = pd.DataFrame(+ {"date": pd.to_datetime(["2024-01-01", "2024-01-03", "2024-01-08"])}+ )+ written = self.write_csv(frame, "date")+ self.assertNotIn("date", written.columns)++ def test_every_band_column_survives_the_round_trip(self) -> None:+ written = self.write_csv(pd.DataFrame({"sales": [1.0]}), None)+ for column in ("forecast", "lower_90", "lower_80", "median",+ "upper_80", "upper_90"):+ self.assertIn(column, written.columns)+ first = written[(written["series"] == "sales") & (written["step"] == 1)]+ self.assertEqual(first["lower_90"].iloc[0], 0.1)++ def test_the_json_output_keeps_the_series_names_and_bands(self) -> None:+ destination = self.root / "forecasts.json"+ with contextlib.redirect_stdout(io.StringIO()):+ forecast_csv.write_json_output(self.results, str(destination))+ payload = json.loads(destination.read_text())+ self.assertEqual(set(payload), {"sales", "revenue"})+ self.assertEqual(payload["sales"]["upper_90"], [1.9, 2.9, 3.9])+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/treatment-plans/test_scripts.py b/tests/treatment-plans/test_scripts.pyindex c74fa5f4..14c2b64a 100644--- a/tests/treatment-plans/test_scripts.py+++ b/tests/treatment-plans/test_scripts.py@@ -316,34 +316,10 @@ class StaticSafetyTests(unittest.TestCase):def test_skill_is_versioned_and_under_500_lines(self) -> None:text = (SKILL_ROOT / "SKILL.md").read_text(encoding="utf-8")self.assertLess(len(text.splitlines()), 500)- self.assertIn("metadata:\n version: \"2.1\"", text)+ self.assertRegex(text, r'\nmetadata:\n version: "\d+\.\d+"\n')self.assertIn("license: MIT", text)self.assertNotIn("OPENROUTER", text)- def test_documented_local_paths_exist(self) -> None:- pattern = re.compile(- r"`((?:assets|references|scripts)/[A-Za-z0-9_.-]+)`"- )- documents = [- SKILL_ROOT / "SKILL.md",- *sorted((SKILL_ROOT / "references").glob("*.md")),- ]- missing = []- for document in documents:- for relative in pattern.findall(document.read_text(encoding="utf-8")):- if not (SKILL_ROOT / relative).is_file():- missing.append(f"{document.name}:{relative}")- self.assertEqual(missing, [])-- def test_no_bytecode_artifacts(self) -> None:- artifacts = [- path- for path in SKILL_ROOT.rglob("*")- if path.suffix in {".pyc", ".pyo"}- or path.name == "__pycache__"- ]- self.assertEqual(artifacts, [])-def test_all_script_help_commands_are_dependency_free(self) -> None:modules = (check_completeness,diff --git a/tests/venue-templates/test_scripts.py b/tests/venue-templates/test_scripts.pynew file mode 100644index 00000000..24703432--- /dev/null+++ b/tests/venue-templates/test_scripts.py@@ -0,0 +1,294 @@+"""Tests for the venue-templates scripts.++The skill's whole claim is that its page limits and template notes are+*verified* against an official source rather than remembered, so the catalogue+tests below are the substantive ones: every preset carries a source URL and a+checked date, every template entry points at a file the skill actually ships,+and no entry silently claims to be an official venue package.++`validate_format` shells out to Poppler, which may not be installed. Its+decision table is pure, so the tests drive that directly and never require the+binary.+"""++from __future__ import annotations++import sys+import tempfile+import unittest+from pathlib import Path++import skill_contract++SKILL_ROOT = Path(__file__).resolve().parents[2] / "skills" / "venue-templates"+SCRIPTS = SKILL_ROOT / "scripts"+ASSETS = SKILL_ROOT / "assets"+sys.path.insert(0, str(SCRIPTS))++import customize_template # noqa: E402+import query_template # noqa: E402+import validate_format # noqa: E402++CliHelpTests = skill_contract.cli.help_test_case(SKILL_ROOT)+++class CatalogueTests(unittest.TestCase):+ """Every catalogued template resolves to a file and carries provenance."""++ def test_every_template_file_is_shipped(self) -> None:+ missing = []+ for category, templates in query_template.TEMPLATES.items():+ for identifier, template in templates.items():+ path = ASSETS / category / template["file"]+ if not path.is_file():+ missing.append(f"{category}/{identifier} -> {template['file']}")+ self.assertEqual(missing, [])++ def test_every_template_declares_status_and_requirements(self) -> None:+ for category, templates in query_template.TEMPLATES.items():+ for identifier, template in templates.items():+ with self.subTest(template=f"{category}/{identifier}"):+ self.assertTrue(template["status"].strip())+ self.assertTrue(template["requirements"].strip())+ self.assertTrue(template["full_name"].strip())++ def test_only_the_poster_scaffold_lacks_an_official_source(self) -> None:+ # A missing source is a deliberate signal -- print_template tells the+ # user to consult event-specific instructions -- so it must stay rare+ # and intentional rather than creeping across the catalogue.+ sourceless = {+ f"{category}/{identifier}"+ for category, templates in query_template.TEMPLATES.items()+ for identifier, template in templates.items()+ if not template["source"]+ }+ self.assertEqual(sourceless, {"posters/beamerposter"})++ def test_checked_date_is_an_iso_day(self) -> None:+ from datetime import date++ self.assertEqual(+ date.fromisoformat(query_template.CHECKED_DATE).isoformat(),+ query_template.CHECKED_DATE,+ )++ def test_template_path_resolves_inside_the_skill(self) -> None:+ path = query_template.template_path("journals", "nature_article.tex")+ self.assertTrue(path.is_file())+ self.assertTrue(path.is_relative_to(SKILL_ROOT))+++class SearchTests(unittest.TestCase):+ def test_unfiltered_search_returns_the_whole_catalogue(self) -> None:+ total = sum(len(group) for group in query_template.TEMPLATES.values())+ self.assertEqual(len(query_template.search_templates()), total)++ def test_type_filter_restricts_to_one_category(self) -> None:+ grants = query_template.search_templates(template_type="grants")+ self.assertEqual({item["category"] for item in grants}, {"grants"})+ self.assertEqual(+ len(query_template.search_templates(template_type="all")),+ len(query_template.search_templates()),+ )++ def test_venue_and_keyword_filters_are_case_insensitive(self) -> None:+ self.assertEqual(+ [item["id"] for item in query_template.search_templates(venue="NeurIPS")],+ ["neurips-2026"],+ )+ elsevier = query_template.search_templates(keyword="ELSARTICLE")+ self.assertEqual(len(elsevier), 3)++ def test_filters_combine_rather_than_widen(self) -> None:+ self.assertEqual(+ query_template.search_templates(venue="nsf", template_type="journals"), []+ )++ def test_unmatched_query_returns_nothing(self) -> None:+ self.assertEqual(query_template.search_templates(venue="no-such-venue"), [])+++class PageCountDecisionTests(unittest.TestCase):+ """The decision table in `page_count_result`, one branch per test."""++ def test_missing_poppler_skips_rather_than_guesses(self) -> None:+ result = validate_format.page_count_result(None, 8, 8, "references")+ self.assertEqual(result["status"], "skip")+ self.assertIn("Poppler", result["message"])++ def test_no_limit_reports_information_only(self) -> None:+ result = validate_format.page_count_result(12, None, None, None)+ self.assertEqual(result["status"], "info")+ self.assertIn("12", result["message"])++ def test_limit_without_a_manual_count_asks_for_one(self) -> None:+ result = validate_format.page_count_result(20, None, 8, "references")+ self.assertEqual(result["status"], "manual")+ self.assertIn("--content-pages", result["message"])+ self.assertIn("references", result["message"])++ def test_content_pages_over_total_pages_fails(self) -> None:+ result = validate_format.page_count_result(5, 9, 9, None)+ self.assertEqual(result["status"], "fail")+ self.assertIn("exceed total", result["message"])++ def test_content_pages_over_the_limit_fails(self) -> None:+ result = validate_format.page_count_result(30, 10, 9, None)+ self.assertEqual(result["status"], "fail")+ self.assertIn("10/9", result["message"])++ def test_within_the_limit_passes(self) -> None:+ result = validate_format.page_count_result(30, 9, 9, None)+ self.assertEqual(result["status"], "pass")+ self.assertIn("9/9", result["message"])++ def test_zero_content_pages_is_accepted_not_treated_as_missing(self) -> None:+ # `if content_pages is None` rather than a falsy check -- 0 pages is a+ # real answer and must not fall through to the "manual" branch.+ result = validate_format.page_count_result(4, 0, 8, None)+ self.assertEqual(result["status"], "pass")+++class FontAndMetadataTests(unittest.TestCase):+ def test_font_result_covers_missing_binary_empty_and_populated(self) -> None:+ self.assertEqual(validate_format.font_result(None)["status"], "skip")+ self.assertEqual(validate_format.font_result([])["status"], "manual")+ populated = validate_format.font_result(["ABCDEF+NimbusRomNo9L"])+ self.assertEqual(populated["status"], "info")+ self.assertIn("does not verify font family", populated["message"])++ def test_metadata_result_flags_identity_fields_for_blind_review(self) -> None:+ self.assertEqual(validate_format.metadata_result(None)["status"], "skip")+ self.assertEqual(validate_format.metadata_result({})["status"], "info")+ leaky = validate_format.metadata_result(+ {"Title": "Our Paper", "Author": "A. Researcher", "Pages": "9"}+ )+ self.assertEqual(leaky["status"], "manual")+ self.assertIn("A. Researcher", leaky["message"])+ self.assertIn("blind-review", leaky["message"])+ # `Pages` is not an identity field and must not be reported as one.+ self.assertNotIn("Pages", leaky["message"])+++class PresetTests(unittest.TestCase):+ def test_every_preset_carries_a_limit_source_and_checked_date(self) -> None:+ from datetime import date++ self.assertTrue(validate_format.PRESETS)+ for venue, preset in validate_format.PRESETS.items():+ with self.subTest(venue=venue):+ self.assertGreater(preset["max_content_pages"], 0)+ self.assertTrue(preset["source"].startswith("https://"))+ self.assertTrue(preset["excluded"].strip())+ date.fromisoformat(preset["checked"])++ def test_preset_names_are_offered_as_cli_choices(self) -> None:+ # --venue uses `choices=sorted(PRESETS)`, so a preset added to the dict+ # is selectable without a second edit; this pins that wiring.+ help_text = SKILL_ROOT.joinpath("scripts/validate_format.py").read_text(+ encoding="utf-8"+ )+ self.assertIn("choices=sorted(PRESETS)", help_text)+++class ReportTests(unittest.TestCase):+ def test_report_records_the_source_and_every_result(self) -> None:+ with tempfile.TemporaryDirectory() as directory:+ report = Path(directory) / "report.txt"+ validate_format.write_report(+ report,+ Path("paper.pdf"),+ "https://icml.cc/",+ "2026-07-20",+ {+ "page-count": {"status": "pass", "message": "8/8"},+ "fonts": {"status": "skip", "message": "no poppler"},+ },+ )+ text = report.read_text(encoding="utf-8")+ self.assertIn("https://icml.cc/", text)+ self.assertIn("PAGE-COUNT", text)+ self.assertIn("Status: pass", text)+ self.assertIn("FONTS", text)+ self.assertIn("2026-07-20", text)++ def test_report_names_an_absent_source_explicitly(self) -> None:+ with tempfile.TemporaryDirectory() as directory:+ report = Path(directory) / "report.txt"+ validate_format.write_report(report, Path("p.pdf"), None, None, {})+ text = report.read_text(encoding="utf-8")+ self.assertIn("Official source: not supplied", text)+ self.assertIn("Preset checked: not applicable", text)+++class CustomizeTests(unittest.TestCase):+ def test_find_template_searches_every_asset_category(self) -> None:+ for filename in (+ "nature_article.tex",+ "beamerposter_academic.tex",+ "nsf_proposal_template.tex",+ ):+ with self.subTest(template=filename):+ self.assertIsNotNone(customize_template.find_template(filename))+ self.assertIsNone(customize_template.find_template("not_a_template.tex"))++ def test_customizing_a_shipped_template_edits_the_title_and_nothing_else(self) -> None:+ # The placeholder patterns end in `[^}]*`, so they are bounded by the+ # closing brace of the LaTeX macro they sit in. Driving a real shipped+ # template is what proves that boundary holds where it matters.+ template = ASSETS / "journals" / "nature_article.tex"+ original = template.read_text(encoding="utf-8")+ with tempfile.TemporaryDirectory() as directory:+ output = Path(directory) / "out.tex"+ customize_template.customize_template(+ template, output, title="Structural Variation in Ancient Genomes"+ )+ text = output.read_text(encoding="utf-8")++ self.assertIn("\\title{Structural Variation in Ancient Genomes}", text)+ self.assertNotIn("Insert Your Title Here", text)+ # Everything outside the \title{...} macro survives untouched.+ self.assertEqual(len(text.splitlines()), len(original.splitlines()))+ self.assertIn("\\documentclass", text)+ self.assertIn("\\end{document}", text)++ def test_replacement_stops_at_the_enclosing_brace(self) -> None:+ with tempfile.TemporaryDirectory() as directory:+ source = Path(directory) / "template.tex"+ source.write_text(+ "\\title{Insert Your Title Here: subtitle}\n"+ "\\author{[email protected]}\n"+ "\\date{today}\n",+ encoding="utf-8",+ )+ output = Path(directory) / "out.tex"+ customize_template.customize_template(+ source, output, title="A Real Title", email="[email protected]"+ )+ text = output.read_text(encoding="utf-8")++ self.assertIn("\\title{A Real Title}", text)+ self.assertIn("\\author{[email protected]}", text)+ self.assertIn("\\date{today}", text)++ def test_template_is_copied_verbatim_when_nothing_matches(self) -> None:+ with tempfile.TemporaryDirectory() as directory:+ source = Path(directory) / "template.tex"+ source.write_text("\\documentclass{article}\n", encoding="utf-8")+ output = Path(directory) / "out.tex"+ customize_template.customize_template(source, output, title="Ignored")+ self.assertEqual(+ output.read_text(encoding="utf-8"), "\\documentclass{article}\n"+ )++ def test_empty_values_never_blank_out_a_placeholder(self) -> None:+ with tempfile.TemporaryDirectory() as directory:+ source = Path(directory) / "template.tex"+ source.write_text("\\title{Insert Your Title Here}\n", encoding="utf-8")+ output = Path(directory) / "out.tex"+ customize_template.customize_template(source, output, title="")+ self.assertIn("Insert Your Title Here", output.read_text(encoding="utf-8"))+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/xlsx/test_scripts.py b/tests/xlsx/test_scripts.pynew file mode 100644index 00000000..64951604--- /dev/null+++ b/tests/xlsx/test_scripts.py@@ -0,0 +1,185 @@+"""Tests for the xlsx skill's recalculation helper.++The shared `office/` tree is covered by the contract. What is specific here is+`recalc`, which drives LibreOffice to recompute formulas -- and the safety+check in front of it.++That check is the interesting part. Recalculating a workbook whose formulas+point at *other* workbooks, when those workbooks are unavailable, replaces+cached values with errors: the recalculation destroys the only copy of the+numbers. `external_links_at_risk` is what stops that, so the tests build real+workbooks with openpyxl and assert on exactly which cells it names.+"""++from __future__ import annotations++import sys+import tempfile+import unittest+import zipfile+from pathlib import Path++import pytest++import skill_contract++SKILL_ROOT = Path(__file__).resolve().parents[2] / "skills" / "xlsx"+SCRIPTS = SKILL_ROOT / "scripts"+sys.path.insert(0, str(SCRIPTS))++openpyxl = pytest.importorskip("openpyxl", reason="xlsx scripts need openpyxl")++import recalc # noqa: E402++OfficeTests = skill_contract.office.office_test_case(SKILL_ROOT)+++class CommandLineTests(unittest.TestCase):+ """`recalc.py` reads `sys.argv` directly, so it has no argparse `--help`."""++ def _run(self, *args: str):+ import os+ import subprocess++ return subprocess.run(+ [sys.executable, str(SCRIPTS / "recalc.py"), *args],+ capture_output=True,+ text=True,+ timeout=120,+ env={**os.environ, "PYTHONDONTWRITEBYTECODE": "1"},+ )++ def test_no_arguments_prints_usage(self) -> None:+ result = self._run()+ self.assertIn("Usage: python recalc.py", result.stdout)+ self.assertNotIn("Traceback", result.stderr)++ def test_the_usage_text_documents_the_force_flag(self) -> None:+ # --force is the escape hatch past the external-link guard; it has to+ # be discoverable or people will not know the guard can be overridden.+ self.assertIn("--force", self._run().stdout)+++class ExternalReferencePatternTests(unittest.TestCase):+ """`EXTERNAL_REF_RE` decides which formulas count as reaching outside."""++ def test_bracketed_workbook_references_match(self) -> None:+ for formula in (+ "=[1]Sheet1!A1",+ "='[1]Some Sheet'!A1",+ "=SUM([2]Data!A1:A9)",+ ):+ with self.subTest(formula=formula):+ self.assertTrue(recalc.EXTERNAL_REF_RE.search(formula), formula)++ def test_ordinary_local_formulas_do_not_match(self) -> None:+ for formula in (+ "=A1+B2",+ "=SUM(Sheet2!A1:A9)",+ "=IF(A1>0,1,0)",+ '=CONCATENATE("[1]",A1)',+ "=INDEX(Table1[Column],1)",+ ):+ with self.subTest(formula=formula):+ self.assertIsNone(recalc.EXTERNAL_REF_RE.search(formula), formula)++ def test_the_reported_location_cap_is_positive(self) -> None:+ self.assertGreater(recalc.MAX_LOCATIONS, 0)+++class WorkbookTestCase(unittest.TestCase):+ def setUp(self) -> None:+ self._temporary = tempfile.TemporaryDirectory()+ self.addCleanup(self._temporary.cleanup)+ self.root = Path(self._temporary.name)++ def workbook(self, name: str = "book.xlsx", **cells) -> Path:+ book = openpyxl.Workbook()+ sheet = book.active+ sheet.title = "Data"+ for coordinate, value in cells.items():+ sheet[coordinate] = value+ path = self.root / name+ book.save(path)+ book.close()+ return path+++class ExternalLinkRiskTests(WorkbookTestCase):+ def test_a_workbook_with_no_external_links_is_never_at_risk(self) -> None:+ path = self.workbook(A1=1, A2=2, A3="=SUM(A1:A2)")+ self.assertEqual(recalc.external_links_at_risk(path), [])++ def test_a_non_workbook_file_is_reported_as_no_risk_rather_than_raising(self) -> None:+ path = self.root / "not-a-workbook.xlsx"+ path.write_bytes(b"definitely not a zip")+ self.assertEqual(recalc.external_links_at_risk(path), [])++ def test_a_missing_file_is_reported_as_no_risk(self) -> None:+ self.assertEqual(+ recalc.external_links_at_risk(self.root / "absent.xlsx"), []+ )++ def test_the_check_reads_the_package_without_modifying_it(self) -> None:+ path = self.workbook(A1=1, A2="=A1*2")+ before = path.read_bytes()+ recalc.external_links_at_risk(path)+ self.assertEqual(path.read_bytes(), before)++ def test_a_workbook_without_the_external_links_part_short_circuits(self) -> None:+ # The function returns early unless xl/externalLinks/ exists, so the+ # common case never pays for two full workbook loads.+ path = self.workbook(A1=1)+ with zipfile.ZipFile(path) as archive:+ self.assertFalse(+ any(name.startswith("xl/externalLinks/") for name in archive.namelist())+ )+ self.assertEqual(recalc.external_links_at_risk(path), [])+++class MacroSetupTests(WorkbookTestCase):+ def test_the_macro_module_is_written_into_the_profile(self) -> None:+ profile = self.root / "profile"+ recalc.setup_libreoffice_macro(profile)+ module = profile / "user" / "basic" / "Standard" / recalc.MACRO_FILENAME+ self.assertTrue(module.is_file(), "macro module was not written")+ self.assertIn("Recalculate", module.read_text(encoding="utf-8"))++ def test_the_macro_xml_is_well_formed(self) -> None:+ import defusedxml.ElementTree as ElementTree++ ElementTree.fromstring(recalc.RECALCULATE_MACRO)++ def test_setup_is_idempotent(self) -> None:+ profile = self.root / "profile"+ recalc.setup_libreoffice_macro(profile)+ first = (profile / "user" / "basic" / "Standard" / recalc.MACRO_FILENAME).read_bytes()+ recalc.setup_libreoffice_macro(profile)+ second = (profile / "user" / "basic" / "Standard" / recalc.MACRO_FILENAME).read_bytes()+ self.assertEqual(first, second)+++class RecalcGuardTests(WorkbookTestCase):+ def test_a_missing_soffice_is_reported_clearly(self) -> None:+ import shutil++ if shutil.which("soffice"):+ self.skipTest("LibreOffice is installed; this asserts the absent path")+ path = self.workbook(A1=1, A2="=A1*2")+ result = recalc.recalc(path)+ self.assertIn("soffice", str(result).lower())++ def test_the_missing_soffice_message_names_libreoffice(self) -> None:+ self.assertIn("LibreOffice", recalc.SOFFICE_MISSING)++ def test_the_timestamp_helper_reports_a_files_mtime(self) -> None:+ path = self.workbook(A1=1)+ self.assertEqual(recalc._stamp(path), recalc._stamp(path))+ self.assertIsNotNone(recalc._stamp(path))++ def test_the_timeout_helper_answers_without_raising(self) -> None:+ self.assertIn(recalc.has_gtimeout(), (True, False))+++if __name__ == "__main__":+ unittest.main()