Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .linkml-reference-validator.yaml
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
cache_dir: publications
download_supplementary_files: true
email: cjmungall@lbl.gov
# Picked up by a bare `linkml-reference-validator` run (no --config) from the
# repo root. publications/ is committed, reviewed evidence: never re-fetch and
# rewrite an entry because its extractor stamp is missing or old.
trust_cached_entries: true
78 changes: 78 additions & 0 deletions conftest.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
"""Repository-wide pytest guard: no test session may write into committed data.

This lives at the repository root, not in ``tests/``, because the root conftest
is loaded for every invocation under the rootdir, including
``pytest --doctest-modules src``, which never loads ``tests/conftest.py``.
"""

import subprocess
from pathlib import Path
from typing import Optional

import pytest

REPO_ROOT = Path(__file__).resolve().parent
# Committed curated data and caches that no test may write to; tests use tmp_path.
PROTECTED_TREES = ("publications", "genes", "reactome")

_status_key = pytest.StashKey[Optional[str]]()
_changes_key = pytest.StashKey[list[str]]()


def _protected_tree_status() -> Optional[str]:
"""Return git's porcelain status of the protected trees, or None without git.

Untracked files are included, so a newly cached ``PMID_*.md`` counts too;
git-ignored files are not. The status lines carry no content hash, so the
comparison is blind to further edits to a file that was already modified
before the session, and it attributes any change made during the session
(an editor save, a concurrent ``just fetch-gene``) to the tests.
"""
try:
result = subprocess.run(
["git", "status", "--porcelain", "--untracked-files=all", "--", *PROTECTED_TREES],
cwd=REPO_ROOT,
capture_output=True,
text=True,
check=True,
)
except (OSError, subprocess.CalledProcessError): # not a git checkout
return None
return result.stdout


def pytest_sessionstart(session):
"""Snapshot the protected trees before any test runs."""
session.config.stash[_status_key] = _protected_tree_status()


def pytest_sessionfinish(session, exitstatus):
"""Fail an otherwise passing run if the protected trees changed during it."""
before = session.config.stash.get(_status_key, None)
if before is None:
return
after = _protected_tree_status()
if after is None or after == before:
return
changed = sorted(set(after.splitlines()) - set(before.splitlines()))
session.config.stash[_changes_key] = changed or [
"(status changed for files already modified before the run)"
]
# Keep more specific outcomes (interrupted, usage error, no tests collected).
if session.exitstatus == pytest.ExitCode.OK:
session.exitstatus = pytest.ExitCode.TESTS_FAILED


def pytest_terminal_summary(terminalreporter):
"""Report protected-tree changes in the summary, next to the final result line."""
changed = terminalreporter.config.stash.get(_changes_key, None)
if not changed:
return
terminalreporter.write_sep(
"=",
"tests modified committed " + "/".join(PROTECTED_TREES) + " (use tmp_path)",
red=True,
bold=True,
)
for line in changed:
terminalreporter.write_line(line, red=True)
12 changes: 10 additions & 2 deletions src/ai_gene_review/etl/gene.py
Original file line number Diff line number Diff line change
Expand Up @@ -623,7 +623,11 @@ def fetch_gene_data(
supporting_entities_backfilled,
) = (
validator.seed_missing_annotations(
yaml_file, goa_file, fetch_titles=fetch_titles
yaml_file,
goa_file,
fetch_titles=fetch_titles,
publications_dir=base_path / "publications",
reactome_dir=base_path / "reactome",
)
)
result["annotations_added"] = added_count
Expand Down Expand Up @@ -1807,7 +1811,11 @@ def fetch_gene_data_ncRNA(
supporting_entities_backfilled,
) = (
validator.seed_missing_annotations(
yaml_file, goa_file, fetch_titles=True
yaml_file,
goa_file,
fetch_titles=True,
publications_dir=base_path / "publications",
reactome_dir=base_path / "reactome",
)
)
result["annotations_added"] = added_count
Expand Down
29 changes: 22 additions & 7 deletions src/ai_gene_review/validation/goa_validator.py
Original file line number Diff line number Diff line change
Expand Up @@ -633,6 +633,8 @@ def seed_missing_annotations(
goa_file: Optional[Path] = None,
output_file: Optional[Path] = None,
fetch_titles: bool = False,
publications_dir: Optional[Path] = None,
reactome_dir: Optional[Path] = None,
) -> Tuple[int, Path, int, int, int]:
"""Seed missing annotations from GOA file into YAML.

Expand All @@ -645,6 +647,10 @@ def seed_missing_annotations(
goa_file: Path to GOA file (if None, derives from yaml_file path)
output_file: Output path (if None, overwrites input file)
fetch_titles: If True, fetch actual titles from PubMed (may be slow)
publications_dir: Publication cache read and written when fetching
titles (default: ``publications`` relative to the working directory)
reactome_dir: Reactome cache read and written when fetching titles
(default: ``reactome`` relative to the working directory)

Returns:
Tuple of (annotations added, output file path, references added,
Expand Down Expand Up @@ -894,8 +900,11 @@ def seeding_key(ann: GOAAnnotation) -> tuple:
if pmid.startswith("PMID:"):
pmid_num = pmid[5:] # Remove 'PMID:' prefix
try:
# Use publications directory for cache
cache_dir = Path("publications")
cache_dir = (
publications_dir
if publications_dir is not None
else Path("publications")
)

# First try to get just the title from cache (fast)
cached_title = get_cached_title(pmid_num, cache_dir)
Expand All @@ -918,7 +927,13 @@ def seeding_key(ann: GOAAnnotation) -> tuple:
title = self._get_go_ref_title(pmid, go_ref_titles)
elif pmid.startswith("Reactome:"):
# Fetch Reactome pathway title
title = self._get_reactome_title(pmid, reactome_titles)
title = self._get_reactome_title(
pmid,
reactome_titles,
reactome_dir
if reactome_dir is not None
else Path("reactome"),
)

new_ref = {
"id": pmid,
Expand Down Expand Up @@ -1113,12 +1128,15 @@ def _is_contributes_to(qualifier: Optional[str], go_aspect: str = "") -> bool:
base = qualifier.replace("NOT|", "").replace("NOT", "").strip("|").strip()
return base == "contributes_to"

def _get_reactome_title(self, reactome_id: str, cache: Dict[str, str]) -> str:
def _get_reactome_title(
self, reactome_id: str, cache: Dict[str, str], cache_dir: Path
) -> str:
"""Fetch Reactome pathway title from Reactome API or cache.

Args:
reactome_id: The Reactome identifier (e.g., 'Reactome:R-HSA-6785807')
cache: Dictionary to cache fetched titles
cache_dir: Reactome cache directory read and written for the title

Returns:
The title of the Reactome pathway, or a TODO placeholder if not found
Expand All @@ -1136,9 +1154,6 @@ def _get_reactome_title(self, reactome_id: str, cache: Dict[str, str]) -> str:
clean_id = clean_id.split(":", 1)[1].strip()

try:
# Use reactome directory for cache
cache_dir = Path("reactome")

# First try to get just the title from cache (fast)
cached_title = get_cached_title(clean_id, cache_dir)
if cached_title:
Expand Down
8 changes: 6 additions & 2 deletions tests/test_gene_alternative_products_refresh.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,10 @@ def test_fetch_repairs_existing_bag6_note_and_preserves_curated_fields(tmp_path,
monkeypatch.setattr(gene, "fetch_goa_data", lambda accession: goa)
monkeypatch.setattr(gene, "_extract_panther_family_id", lambda text: None)
calls = []
def seed(self, yaml_file, goa_file, fetch_titles=True):
calls.append((yaml_file, goa_file, fetch_titles))
def seed(
self, yaml_file, goa_file, fetch_titles=True, publications_dir=None, reactome_dir=None
):
calls.append((yaml_file, goa_file, fetch_titles, publications_dir, reactome_dir))
return 0, None, 0, 0, 0
monkeypatch.setattr(GOAValidator, "seed_missing_annotations", seed)
result = gene.fetch_gene_data(("human", "BAG6"), base_path=tmp_path, fetch_titles=False)
Expand All @@ -61,6 +63,8 @@ def seed(self, yaml_file, goa_file, fetch_titles=True):
assert second["alternative_product_sequences_repaired"] == 0
assert review.read_bytes() == first_bytes
assert len(calls) == 2 and all(call[2] is False for call in calls)
assert all(call[3] == tmp_path / "publications" for call in calls)
assert all(call[4] == tmp_path / "reactome" for call in calls)
assert (directory / "BAG6-uniprot.txt").read_text() == raw
assert (directory / "BAG6-goa.tsv").read_text() == goa

Expand Down
56 changes: 56 additions & 0 deletions tests/test_goa_validator.py
Original file line number Diff line number Diff line change
Expand Up @@ -851,6 +851,62 @@ def test_seed_missing_annotations_true_noop_preserves_yaml_bytes(tmp_path):
assert yaml_path.read_text() == original


def test_seed_missing_annotations_uses_given_cache_dirs(tmp_path):
"""Title lookups read the given caches, not the repo's publications/ or reactome/.

PMID:12345 and R-CEL-9856612 are also cached in the committed trees with
different titles, so a lookup there would be visible as the wrong title.
"""
validator = GOAValidator()
goa_path = tmp_path / "TEST-goa.tsv"
goa_path.write_text(
"GENE PRODUCT DB\tGENE PRODUCT ID\tSYMBOL\tQUALIFIER\tGO TERM\tGO NAME\t"
"GO ASPECT\tECO ID\tGO EVIDENCE CODE\tREFERENCE\tWITH/FROM\tTAXON ID\t"
"TAXON NAME\tASSIGNED BY\tGENE NAME\tDATE\n"
"UniProtKB\tQ12345\tTEST\tenables\tGO:0001234\ttest function\tMF\t"
"ECO:0000353\tIPI\tPMID:12345\t\tNCBITaxon:9606\tHomo sapiens\t"
"UniProt\tTest protein\t20180515\n"
"UniProtKB\tQ12345\tTEST\tinvolved_in\tGO:0005678\ttest process\tBP\t"
"ECO:0000304\tTAS\tReactome:R-CEL-9856612\t\tNCBITaxon:9606\tHomo sapiens\t"
"Reactome\tTest protein\t20180515\n"
)
yaml_path = tmp_path / "TEST-ai-review.yaml"
yaml_path.write_text(
"id: Q12345\n"
"gene_symbol: TEST\n"
"taxon: {id: 'NCBITaxon:9606', label: Homo sapiens}\n"
"description: Test gene\n"
)
reactome_dir = tmp_path / "reactome"
reactome_dir.mkdir()
(reactome_dir / "R-CEL-9856612.md").write_text(
"---\nstable_id: R-CEL-9856612\n---\n\n# Fixture-only pathway title\n"
)
publications_dir = tmp_path / "publications"
publications_dir.mkdir()
(publications_dir / "PMID_12345.md").write_text(
"---\npmid: '12345'\n---\n\n# Fixture-only cached title\n"
)

_, _, references_added, _, _ = validator.seed_missing_annotations(
yaml_path,
goa_path,
fetch_titles=True,
publications_dir=publications_dir,
reactome_dir=reactome_dir,
)

assert references_added == 2
document = yaml.safe_load(yaml_path.read_text())
titles = {ref["id"]: ref["title"] for ref in document["references"]}
assert titles == {
"PMID:12345": "Fixture-only cached title",
"Reactome:R-CEL-9856612": "Fixture-only pathway title",
}
assert sorted(publications_dir.iterdir()) == [publications_dir / "PMID_12345.md"]
assert sorted(reactome_dir.iterdir()) == [reactome_dir / "R-CEL-9856612.md"]


def test_seed_missing_annotations_noop_writes_requested_output(tmp_path):
"""A no-op seed still writes a separately requested output file."""
validator = GOAValidator()
Expand Down
6 changes: 4 additions & 2 deletions tests/test_publication_etl.py
Original file line number Diff line number Diff line change
Expand Up @@ -163,15 +163,17 @@ def test_extract_pmids_from_empty_yaml():


@pytest.mark.integration
def test_fetch_pubmed_data():
def test_fetch_pubmed_data(tmp_path):
"""Test fetching real data from PubMed.

This test requires network access and is marked as integration.
The cache goes to tmp_path: the default would overwrite the committed
publications/PMID_29727692.md.
"""
# Use a known PMID from CFAP300 literature
pmid = "29727692"

pub = fetch_pubmed_data(pmid)
pub = fetch_pubmed_data(pmid, cache_dir=tmp_path)

assert pub is not None
assert pub.pmid == pmid
Expand Down
9 changes: 9 additions & 0 deletions tests/test_reference_cache_behavior.py
Original file line number Diff line number Diff line change
Expand Up @@ -257,3 +257,12 @@ def test_subprocess_network_guard_is_active_through_wrapper(tmp_path, no_network
assert event in {"socket.connect", "socket.getaddrinfo"}
assert target.startswith("(") and target != "()", attempted.read_text()
assert not (cache_dir / "PMID_1.md").exists()


def test_bare_cli_default_config_trusts_reviewed_cache(monkeypatch):
"""A validator run without --config uses .linkml-reference-validator.yaml."""
from linkml_reference_validator.cli.shared import load_validation_config

monkeypatch.chdir(PROJECT_ROOT)
config = load_validation_config(None, load_custom_sources=False)
assert config.trust_cached_entries is True
Loading