T2: logic tests only over the merged suite; capture tooling removed

PLAN-feature-parity §2.13, P7 rule.
- removed tools/capture_pages.py, tools/capture_pages.mjs, tools/capture_association.py
  — they produced reference fixtures for parity tests that no longer exist.
- removed tests/fixtures/reference/ (cacu, cama, tea ui captures: pages.json,
  responses.json, screenshots) — only the capture tools and two comments read them.
- removed models/tests/recurrence_reference.py — reference-parity helper, unused.
- kept from rebuild, all fast and pure or in-process SQLite: test_cama_recurrence_site,
  test_core_fhir_record, test_core_sources, test_measure_periods, test_patient_search,
  test_promotion_reports, WebApi test_sources and test_users (TestClient on own_platform).
  Already removed in T1: test_tea_association, test_persistance_eeg_study, test_backup,
  test_link_answers, the SQL Server and PostgreSQL source cases (whole platforms or
  external servers).
- tools/load_site.py, synthetic/ and tests/fixtures/synthea stay: they load a demo
  deployment, not tests.
This commit is contained in:
2026-12-01 00:46:19 -06:00
parent 95069151a8
commit 3994877859
29 changed files with 2 additions and 156289 deletions
+1 -1
Submodule WebApp updated: d3c04a5fcf...d8cb6420a4
+1 -1
Submodule models updated: fde57b9074...7751c176f0
Binary file not shown.

Before

Width:  |  Height:  |  Size: 68 KiB

-17
View File
@@ -1,17 +0,0 @@
{
"domain": "cacu",
"web": {
"tag": "isssteleon-cacu197/webapp:local",
"id": "sha256:60954f03649bfa263549cb0f336ee9f7d723c9117ed3aa4d5ef1c9a8c62f6663"
},
"api": {
"tag": "isssteleon-cacu197/webapi:local",
"id": "sha256:446a58a21ef841eff1acbfa6386a48f5482342e9c75cc76465491cecd6462642"
},
"load": [
"cacu.Paciente: 312 le\u00eddas, 312 nuevas, 0 actualizadas, 0 rechazadas",
"cacu.CitologiaCervical: 461 le\u00eddas, 461 nuevas, 0 actualizadas, 0 rechazadas",
"cacu.BiopsiaCervical: 47 le\u00eddas, 47 nuevas, 0 actualizadas, 0 rechazadas",
"cacu.NotaMedica: 349 le\u00eddas, 349 nuevas, 0 actualizadas, 0 rechazadas"
]
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
Binary file not shown.

Before

Width:  |  Height:  |  Size: 300 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 239 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 688 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 139 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 66 KiB

-17
View File
@@ -1,17 +0,0 @@
{
"domain": "cama",
"web": {
"tag": "isssteleon/webapp:cama-dev-3743ea6",
"id": "sha256:604206dad07d8346035bdc3a61a797dc1eb4e0bdd9f2e6cd73c7d19e863d8871"
},
"api": {
"tag": "isssteleon/webapi:cama-dev-3743ea6",
"id": "sha256:8fed1871259111828712104fda899ce8bffb5a6eaa9813195d99dd15315ac7ff"
},
"load": [
"cama.Paciente: 300 le\u00eddas, 300 nuevas, 0 actualizadas, 0 rechazadas",
"cama.Mastografia: 400 le\u00eddas, 400 nuevas, 0 actualizadas, 0 rechazadas",
"cama.BiopsiaMama: 108 le\u00eddas, 108 nuevas, 0 actualizadas, 0 rechazadas",
"cama.NotaMedica: 218 le\u00eddas, 218 nuevas, 0 actualizadas, 0 rechazadas"
]
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
Binary file not shown.

Before

Width:  |  Height:  |  Size: 282 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 333 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 192 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 129 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 68 KiB

-22
View File
@@ -1,22 +0,0 @@
{
"domain": "tea",
"web": {
"tag": "sitio-c/webapp:local",
"id": "sha256:bd04b1af1b32b5800f8963fbec1d7bedd9b1301f58f4f320416c3bda93e97755"
},
"api": {
"tag": "sitio-c/webapi:local",
"id": "sha256:7b6c00696cd833aadf9fa3b2779269bab189e3b62e1caad8463ce68374b5b98f"
},
"load": [
"tea.Pacientes: 200 le\u00eddas, 200 nuevas, 0 actualizadas, 0 rechazadas",
"tea.OrdenesEstudio: 232 le\u00eddas, 232 nuevas, 0 actualizadas, 0 rechazadas",
"tea.Mchat: 216 le\u00eddas, 216 nuevas, 0 actualizadas, 0 rechazadas",
"tea.Ados2: 113 le\u00eddas, 113 nuevas, 0 actualizadas, 0 rechazadas",
"tea.EvaluacionNeuropediatrica: 83 le\u00eddas, 83 nuevas, 0 actualizadas, 0 rechazadas",
"tea.Eeg: 84 le\u00eddas, 84 nuevas, 0 actualizadas, 0 rechazadas",
"tea.RelacionAdos2: 12 le\u00eddas, 12 nuevas, 0 actualizadas, 0 rechazadas",
"tea.RelacionAdos2Paciente: 576 le\u00eddas, 576 nuevas, 0 actualizadas, 0 rechazadas",
"tea.Ados2 (documento): 50 le\u00eddas, 0 nuevas, 50 actualizadas, 0 rechazadas"
]
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
Binary file not shown.

Before

Width:  |  Height:  |  Size: 282 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 296 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 89 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 118 KiB

-173
View File
@@ -1,173 +0,0 @@
"""Capture the old platform's EEG–ADOS-2 association (models/libs/tea, `ados2_association`
0.1.0, its `model.toml` settings) on the TEA reference tables, as the old `relate()` job
built its cohort: every valid EEG with an age, joined to the child's first ADOS-2, with the
z of each metric and zone. Writes tests/fixtures/reference/tea/association.json: the
cohort it was fitted on, the EEGs it scored, and what it gave.
uv run python tools/capture_association.py [OLD_MODELS_DIR]
OLD_MODELS_DIR (default ~/ISSSTELEON-repo/models) is the old models repository, read only:
its code runs here and nothing of it is kept."""
import json
import sys
from pathlib import Path
import pandas as pd
ROOT = Path(__file__).parents[1]
TABLES = ROOT / "tests" / "fixtures" / "reference" / "tea" / "tables"
OUT = ROOT / "tests" / "fixtures" / "reference" / "tea" / "association.json"
BIOMARKERS = {
"PICOS_PAROXISTICOS": "spikes",
"HUSOS_SUENO_N2": "spindles",
"RITMO_POSTERIOR": "posterior_rhythm",
"GRADIENTE_ANTEROPOSTERIOR": "gradient",
}
ZONED = ("spikes", "spindles")
def _load(name: str) -> list[dict]:
return json.loads((TABLES / f"{name}.json").read_text())
def cohort() -> tuple[pd.DataFrame, pd.DataFrame]:
"""(fit, scored) as the old job built them."""
eegs = [e for e in _load("eeg") if e["eeg_valido"] == 1 and e["eeg_edad_meses"] is not None]
ados = sorted(
(a for a in _load("ados2") if a["ado_pac_id"] is not None),
key=lambda a: (a["ado_fecha"] is None, a["ado_fecha"], a["ado_id"]),
)
first: dict = {}
for a in ados:
first.setdefault(a["ado_pac_id"], a)
items = sorted(k.removeprefix("ado_") for k in ados[0] if k.startswith(("ado_sa_", "ado_rrb_")))
rows = []
for e in eegs:
a = first.get(e["eeg_pac_id"])
if a is None:
continue
rows.append(
{
"key": e["eeg_id"],
"pac_id": e["eeg_pac_id"],
"fecha": e["eeg_fecha_estudio"],
"age_months": float(e["eeg_edad_meses"]),
"ados_module": a["ado_modulo"],
"css": a["ado_css"],
**{c: a[f"ado_{c}"] for c in items},
}
)
scored = pd.DataFrame(rows)
keys = set(scored["key"])
values: dict[str, dict[str, float]] = {k: {} for k in keys}
zoned = {}
for m in _load("eeg_metrica"):
biomarker = BIOMARKERS.get(m["met_codigo"])
if biomarker is None or m["met_eeg_id"] not in keys:
continue
if biomarker in ZONED:
zoned[m["met_id"]] = (m["met_eeg_id"], biomarker)
elif m["met_z"] is not None:
values[m["met_eeg_id"]][f"z_{biomarker}"] = m["met_z"]
for z in _load("eeg_metrica_zona"):
if z["mez_met_id"] in zoned and z["mez_z"] is not None:
eeg_id, biomarker = zoned[z["mez_met_id"]]
values[eeg_id][f"z_{biomarker}_{z['mez_zona']}"] = z["mez_z"]
scored = scored.join(pd.DataFrame.from_dict(values, orient="index"), on="key")
scored = scored.sort_values(["pac_id", "fecha", "key"], na_position="last").reset_index(
drop=True
)
predictors = [c for c in scored.columns if c.startswith("z_")]
fit = scored[scored[predictors].notna().any(axis=1)].drop_duplicates("pac_id")
return (
fit.reset_index(drop=True).drop(columns=["pac_id", "fecha"]),
scored.drop(columns=["pac_id", "fecha"]),
)
# The planted effects of the synthetic cohort: (predictor, outcome) -> log odds per unit z.
PLANTED = {
("z_spikes_frontal_izq", "item_02"): 1.1,
("z_spikes_temporal_der", "item_04"): -0.9,
("z_spindles_central", "css"): -0.8,
("z_posterior_rhythm", "item_20"): 0.7,
}
def synthetic(items: dict, zones: list[str], n: int = 240, seed: int = 20261128) -> pd.DataFrame:
"""A seeded cohort with the effects of PLANTED: each child's module, age, the z of every
predictor (a tenth missing), her item scores (0 to 2, an occasional 7, 8 or 9 for "not
applicable") and her CSS (1 to 10), each drawn from a cumulative logit on her z."""
import numpy as np
rng = np.random.default_rng(seed)
predictors = (
[f"z_spikes_{z}" for z in zones]
+ [f"z_spindles_{z}" for z in zones[:5]]
+ ["z_posterior_rhythm", "z_gradient"]
)
rows = []
for k in range(n):
module = rng.choice(["TODDLER", "MODULO_1", "MODULO_2"], p=[0.4, 0.4, 0.2])
z = {
p: (None if rng.random() < 0.1 else float(np.round(rng.normal(0, 1.2), 4)))
for p in predictors
}
row = {
"key": f"syn-{k:04d}",
"age_months": float(np.round(rng.uniform(16, 36), 1)),
"ados_module": str(module),
**z,
}
def draw(outcome: str, cuts, row=row) -> int:
eta = sum(b * (row[p] or 0.0) for (p, o), b in PLANTED.items() if o == outcome)
u = rng.random() # P(level >= j) = expit(eta - cut_j): the level is the cuts passed
return int(sum(u < 1 / (1 + np.exp(c - eta)) for c in cuts))
for number, (_, _, codes) in items.items():
code = codes.get(str(module))
if code is None:
continue
row[code] = 7 if rng.random() < 0.03 else draw(f"item_{number:02d}", (-0.2, 1.4))
row["css"] = float(1 + draw("css", np.linspace(-2.5, 2.5, 9)))
rows.append(row)
return pd.DataFrame(rows)
def main() -> None:
old = Path(sys.argv[1] if len(sys.argv) > 1 else Path.home() / "ISSSTELEON-repo" / "models")
sys.path.insert(0, str(old / "libs" / "tea" / "src"))
from tea.associations.ados2 import _items
from tea.associations.ados2.api import Ados2Association
from tea.contracts.data import ZONES
as_records = lambda f: json.loads(f.to_json(orient="records")) # noqa: E731
out = {}
syn = synthetic(_items.ITEMS, list(ZONES))
for name, (fit, scored) in {"reference_tables": cohort(), "synthetic": (syn, syn)}.items():
module = Ados2Association(level="auto").fit(fit)
associations, scores = module.associations(), module.score(scored)
out[name] = {
"level": module.fitted["level"],
"n": module.fitted["n"],
"fit": as_records(fit),
"scored": as_records(scored),
"associations": as_records(associations),
"scores": as_records(scores),
}
estimated = int(associations["odds_ratio"].notna().sum())
print(
f"{name}: level {module.fitted['level']}, {module.fitted['n']} children, "
f"{estimated} of {len(associations)} associations estimated, {len(scores)} scores"
)
out["model"] = f"{module.name} {module.version} ({module.impl})"
out["planted"] = [
{"predictor": p, "outcome": o, "log_odds": b} for (p, o), b in PLANTED.items()
]
OUT.write_text(json.dumps(out, indent=1, ensure_ascii=False))
if __name__ == "__main__":
main()
-196
View File
@@ -1,196 +0,0 @@
// The reference app's Indicadores page for one domain, tab by tab: what it shows, in order.
// Run by tools/capture_pages.py (BASE, DOMAIN, OUT), from WebApp/ for its Playwright.
import { mkdirSync, writeFileSync } from "node:fs";
import { chromium } from "../WebApp/node_modules/playwright/index.mjs";
const { BASE, DOMAIN, OUT } = process.env;
const LOADING =
'mat-progress-bar, mat-spinner, mat-progress-spinner, [class*="skeleton"], [class*="loading"], [class*="cargando"], [aria-busy="true"]';
/** Everything visible on the page that a reader sees as structure, in document order:
* headings, card titles, KPI values' labels, tabs, table headers and plots (with their traces). */
function structure() {
const visible = (e) => e.checkVisibility?.() ?? e.offsetParent !== null;
const text = (e) => (e.innerText ?? "").replace(/\s+/g, " ").trim();
const style = (e) => {
const s = getComputedStyle(e);
return {
size: s.fontSize,
weight: s.fontWeight,
family: s.fontFamily.split(",")[0],
};
};
const out = [];
const selector = [
"h1",
"h2",
"h3",
"h4",
"h5",
"[role=tab]",
"mat-card-title",
"mat-card-subtitle",
"caption",
"th",
"legend",
".js-plotly-plot",
'[class*="kpi-title"]',
'[class*="kpi-label"]',
'[class*="titulo"]',
'[class*="title"]:not(h1,h2,h3,h4,h5,mat-card-title)',
].join(",");
for (const e of document.querySelectorAll(selector)) {
if (!visible(e)) continue;
if (e.classList.contains("js-plotly-plot")) {
const gd = e;
const layout = gd.layout ?? {};
const title = (t) => (typeof t === "string" ? t : t?.text) ?? null;
out.push({
kind: "plot",
title: title(layout.title),
x: title(layout.xaxis?.title),
y: title(layout.yaxis?.title),
barmode: layout.barmode ?? null,
traces: (gd.data ?? []).map((t) => {
const list = (v) =>
Array.isArray(v) ? v.slice(0, 40).map(String) : null;
const colors =
t.marker?.colors ??
(typeof t.marker?.color === "string"
? [t.marker.color]
: t.marker?.color);
return {
type: t.type ?? "scatter",
mode: t.mode ?? null,
orientation: t.orientation ?? null,
name: t.name ?? null,
hole: t.hole ?? null,
labels: list(t.labels),
categories: list(t.orientation === "h" ? t.y : t.x),
colors: list(colors),
};
}),
});
continue;
}
if (e.closest(".js-plotly-plot")) continue; // the plot's own svg text
const t = text(e);
if (!t || t.length > 200) continue;
out.push({
kind: e.tagName.toLowerCase(),
cls: e.className?.toString?.() ?? "",
text: t,
...style(e),
});
}
return out;
}
const browser = await chromium.launch();
// Tall: every figure of a tab renders at once (the old app scrolls inside its own frame).
const page = await browser.newPage({ viewport: { width: 1440, height: 6000 } });
mkdirSync(OUT, { recursive: true });
const seen = new Map(); // loading indicators: what they are and what they say
const responses = []; // the data each figure was drawn from
page.on("response", async (r) => {
const url = new URL(r.url());
if (!/^\/(cacu|cama|tea|governance)\//.test(url.pathname)) return;
if (!(r.headers()["content-type"] ?? "").includes("json")) return;
try {
const body = await r.json();
const bytes = JSON.stringify(body).length;
// patients' records are kept by size only (the figures are drawn from measures)
const patients = /EpisodeOfCare|Patient|seguimiento|pacientes/i.test(
url.pathname,
);
responses.push({
path: url.pathname + url.search,
status: r.status(),
...(patients || bytes > 1_000_000 ? { bytes } : { body }),
});
} catch {}
});
const watchLoading = setInterval(async () => {
try {
const found = await page.$$eval(LOADING, (els) =>
els
.filter((e) => e.checkVisibility?.())
.map((e) => ({
tag: e.tagName.toLowerCase(),
cls: e.className?.toString?.() ?? "",
label: e.getAttribute("aria-label") ?? "",
near: (e.parentElement?.innerText ?? "")
.replace(/\s+/g, " ")
.trim()
.slice(0, 160),
})),
);
for (const f of found) seen.set(JSON.stringify(f), f);
} catch {}
}, 150);
// The old app's sign-in is local to the browser (a fixed list of accounts).
await page.goto(`${BASE}/login`);
await page.getByRole("textbox", { name: "Usuario" }).fill("admin");
await page.getByRole("textbox", { name: "Contraseña" }).fill("admin2026");
await page.keyboard.press("Enter");
await page.waitForURL((u) => !u.pathname.includes("login"));
const tabs = {};
await page.goto(`${BASE}/indicadores/${DOMAIN}`);
await page.waitForTimeout(400);
await page.screenshot({ path: `${OUT}/loading.png` });
await page.waitForLoadState("networkidle", { timeout: 600_000 });
await page.waitForTimeout(3000);
// The page's sections (its figures have tabs of their own).
const names = await page.$$eval(".section-tabs [role=tab]", (els) =>
els.filter((e) => e.checkVisibility?.()).map((e) => e.innerText.trim()),
);
/** Settled: no loading indicator in sight and nothing to retry (the old app gives up on a
* slow figure and offers "Reintentar"); at most 15 minutes. */
async function settle() {
const deadline = Date.now() + 15 * 60_000;
while (Date.now() < deadline) {
await page.waitForTimeout(2000);
const loading = await page.$$eval(
LOADING,
(els) => els.filter((e) => e.checkVisibility?.()).length,
);
const retries = page.getByRole("button", { name: /^Reintentar/ });
if (await retries.count()) {
await retries
.first()
.click()
.catch(() => {});
continue;
}
if (!loading) {
await page.waitForTimeout(2000); // the plots draw after their data
return;
}
}
console.error("still loading after 15 minutes");
}
for (const [i, name] of names.entries()) {
await page
.locator(".section-tabs [role=tab]", { hasText: name })
.first()
.click();
await settle();
tabs[name] = await page.evaluate(structure);
await page.screenshot({ path: `${OUT}/tab-${i + 1}.png`, fullPage: true });
}
clearInterval(watchLoading);
writeFileSync(
`${OUT}/responses.json`,
JSON.stringify(responses, null, 1) + "\n",
);
writeFileSync(
`${OUT}/pages.json`,
JSON.stringify(
{ route: `/indicadores/${DOMAIN}`, tabs, loading: [...seen.values()] },
null,
1,
) + "\n",
);
await browser.close();
-77
View File
@@ -1,77 +0,0 @@
"""Capture what the reference app's pages show, for the WebApp to match: each tab of a domain's
Indicadores page as rendered by the old web image over its own API (loaded with the synthetic
hospital, as tools/capture_reference.py does), recorded as its headings, cards and plots in
order (`pages.json`), the loading indicators seen while it fills, and screenshots.
uv run python tools/capture_pages.py cacu
uv run python tools/capture_pages.py tea --hospital ~/isssteleon-data
Only the Docker CLI and a browser touch the old app; none of its code is imported or copied.
"""
import argparse
import json
import os
import socket
import subprocess
import time
import urllib.request
from pathlib import Path
from capture_reference import docker, image_id, running
HERE = Path(__file__).parent
WEB = { # the web image of each reference instance (CaCu's and CaMa's are one build)
"cacu": "isssteleon-cacu197/webapp:local",
"cama": "isssteleon/webapp:cama-dev-3743ea6",
"tea": "sitio-c/webapp:local",
}
def _port() -> int:
with socket.socket() as s:
s.bind(("127.0.0.1", 0))
return s.getsockname()[1]
def _up(url: str, seconds: int = 120) -> None:
deadline = time.monotonic() + seconds
while time.monotonic() < deadline:
try:
urllib.request.urlopen(url, timeout=5)
return
except OSError:
time.sleep(1)
raise TimeoutError(url)
def capture(domain: str, hospital: Path, out: Path) -> None:
web = f"capture-{domain}-web"
with running(domain, hospital, curves=False) as ref:
port = _port()
docker("rm", "-f", web, check=False)
link, publish = f"{ref.name}:webapi", f"127.0.0.1:{port}:80"
docker("run", "-d", "--name", web, "--network", "bridge", "--link", link,
"-p", publish, WEB[domain]) # fmt: skip
try:
_up(f"http://127.0.0.1:{port}/")
out.mkdir(parents=True, exist_ok=True)
env = {**os.environ, "BASE": f"http://127.0.0.1:{port}", "DOMAIN": domain,
"OUT": str(out.resolve())} # fmt: skip
subprocess.run(["node", str(HERE / "capture_pages.mjs")], cwd=HERE.parent / "WebApp",
env=env, check=True) # fmt: skip
manifest = {"domain": domain, "web": {"tag": WEB[domain], "id": image_id(WEB[domain])},
"api": {"tag": ref.image, "id": image_id(ref.image)},
"load": ref.load.strip().splitlines()} # fmt: skip
(out / "manifest.json").write_text(json.dumps(manifest, indent=1) + "\n")
finally:
docker("rm", "-f", web, check=False)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("domain", choices=WEB)
parser.add_argument("--hospital", type=Path, default=Path("tests/fixtures/hospital"))
parser.add_argument("--out", type=Path, default=Path("tests/fixtures/reference"))
args = parser.parse_args()
capture(args.domain, args.hospital, args.out / args.domain / "ui")