Files
rarelens/api/tests/conftest.py
T
Kemal Yaylali 07a01715fd feat: redesign around phenotype-driven triage, not variant filtering
A table with filters made the user do the work. Rare disease triage is a different task:
which few variants could explain *this* patient's phenotype, and why. The app now answers
that, and lets a reviewer act on the answer.

Domain
- a case is a proband: a VCF plus the HPO terms observed in the patient (samples -> cases)
- HPO's gene-to-phenotype annotations are loaded as reference data (scripts/load-hpo.py)
- each candidate can be shortlisted or dismissed with a reason and a note

Ranking (app/services/triage.py, 21 tests)
- weighted sum of phenotype match, rarity, consequence severity and the model's score,
  with every component shown next to the candidate
- rarity and consequence filter; phenotype only ranks, because a real diagnosis can sit in
  a gene nobody has annotated yet and filtering on it would hide exactly that case
- ClinVar is deliberately not an input: it appears beside the result as independent
  confirmation, so nothing ranks highly merely because ClinVar already said pathogenic

UI
- the funnel is the headline: variants called -> rare -> coding candidates -> phenotype-matched
- ranked candidates with evidence chips, not a grid of everything; filters are demoted
- a variant panel showing the score breakdown, the matched HPO terms, the raw VEP record and
  links out to Ensembl/gnomAD/ClinVar, with the decision controls
- a printable case report: phenotype, funnel, shortlisted variants with reasons, provenance

API: /cases with phenotypes, /cases/{id}/candidates (funnel + ranked + weights),
/variants/{id}, /variants/{id}/decision, /cases/{id}/report, /phenotypes for the picker.
Scoring moved under the case and now answers 503 with the reason when no model registry is
reachable, instead of a 500.

Verified end to end on a simulated proband (scripts/make-demo-case.sh: real GIAB HG002
background + one real ClinVar 2-star pathogenic NF2 variant). 13 variants called -> 1 coding
candidate, and the planted variant ranks first at 0.80 on phenotype 1.00, rarity 1.00 and
consequence 1.00, with ClinVar agreeing afterwards.

Tests: api 75, ml 18, loader 16, web 27; ruff, mypy, svelte-check, terraform validate, both
kustomize overlays and the Nextflow stub run all clean.
2026-09-12 08:30:44 +01:00

85 lines
2.5 KiB
Python

"""Test bootstrap.
CI provides DATABASE_URL (a Postgres service container). Locally, when it is unset, a throwaway
Postgres is started with `pgserver` so `pytest` needs no Docker. Set REQUIRE_DB=1 to turn a missing
database into a failure instead of a skip (CI does this).
DATABASE_URL must be settled before anything imports `app`, because `app.config.settings` and the
engine in `app.db` are created at import time.
"""
import os
import tempfile
from collections.abc import AsyncIterator, Iterator
from pathlib import Path
from typing import TYPE_CHECKING
import pytest
from httpx import ASGITransport, AsyncClient
if TYPE_CHECKING:
from alembic.config import Config
API_DIR = Path(__file__).resolve().parents[1]
_pg_server = None # keeps the pgserver handle alive for the whole session
def _resolve_database_url() -> str | None:
global _pg_server
if url := os.environ.get("DATABASE_URL"):
return url
try:
import pgserver
except ImportError:
return None
_pg_server = pgserver.get_server(tempfile.mkdtemp(prefix="rarelens-pg-"), cleanup_mode="delete")
socket_dir = _pg_server.get_uri().split("host=", 1)[1]
return f"postgresql+asyncpg://postgres@/postgres?host={socket_dir}"
DATABASE_URL = _resolve_database_url()
if DATABASE_URL:
os.environ["DATABASE_URL"] = DATABASE_URL
@pytest.fixture(scope="session")
def alembic_cfg() -> "Config":
if not DATABASE_URL:
if os.environ.get("REQUIRE_DB"):
pytest.fail("REQUIRE_DB is set but no database is available")
pytest.skip("no DATABASE_URL and pgserver is not installed")
from alembic.config import Config
cfg = Config(str(API_DIR / "alembic.ini"))
cfg.set_main_option("script_location", str(API_DIR / "alembic"))
return cfg
@pytest.fixture(scope="session")
def migrated_db(alembic_cfg: "Config") -> Iterator[None]:
from alembic import command
command.upgrade(alembic_cfg, "head")
yield
@pytest.fixture
async def db(migrated_db: None) -> AsyncIterator[None]:
from sqlalchemy import text
from app.db import engine
async with engine.begin() as conn:
await conn.execute(
text("TRUNCATE cases, case_phenotypes, gene_phenotypes, jobs, variants, "
"predictions, variant_decisions RESTART IDENTITY CASCADE")
)
yield
@pytest.fixture
async def client() -> AsyncIterator[AsyncClient]:
from app.main import app
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as c:
yield c