File size: 13,149 Bytes
356ffbd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
"""Release checks for sample-stability. Run: uv run --with pytest pytest -q

Raw files are read from ../_raw/ (a sibling of this repository; not distributed). Checks that need
them skip when they are absent: the quote check needs the Europe PMC full texts, the DOI checks
read the Crossref responses cached by scripts/build.py (set SS_LIVE_CROSSREF=1 to query Crossref
live instead), and the marker join needs the LifeFrom release 1 marker list.
"""
import csv
import json
import os
import re
import sys
import urllib.parse
import urllib.request
from collections import defaultdict
from pathlib import Path

import pytest

REL = Path(__file__).resolve().parents[1]
RAW = REL.parent / "_raw"
sys.path.insert(0, str(REL / "scripts"))
import build  # noqa: E402


def read(name):
    with open(REL / "data" / name, encoding="utf-8") as fh:
        return list(csv.DictReader(fh))


FINDINGS = read("stability_findings.csv")
SUMMARY = read("summary.csv")
SOURCES = read("sources.csv")
WEB = json.loads((REL / "web" / "sample-stability.json").read_text())
MARKERS = build.load_markers() if (RAW / "lifefrom-release-1" / "markers.csv").exists() else None


def need_markers():
    if MARKERS is None:
        pytest.skip("LifeFrom marker list not present in ../_raw/lifefrom-release-1/")

FINDING_COLS = ["finding_id", "analyte_key", "analyte_name", "analyte_reported", "marker_slug", "marker_name",
                "related_marker_slug", "marker_match", "measured_matrix", "specimen", "tube",
                "processing", "condition", "temp_category", "temp_reported", "stable_for", "stable_hours",
                "stable_cycles", "unstable_at", "unstable_at_hours", "unstable_at_cycles", "max_tested",
                "max_tested_hours", "max_tested_cycles", "result", "criterion", "criterion_type", "n", "population",
                "method_or_analyzer", "source_id", "doi", "source_label", "location", "full_text_read",
                "evidence_quote", "quote_status", "notes", "access_date"]


# ---- schema -------------------------------------------------------------------------------
def test_findings_columns():
    with open(REL / "data" / "stability_findings.csv", encoding="utf-8") as fh:
        assert next(csv.reader(fh)) == FINDING_COLS


def test_findings_enumerations():
    for r in FINDINGS:
        assert r["specimen"] in build.SPECIMENS, r["finding_id"]
        assert r["processing"] in build.PROCESSING, r["finding_id"]
        assert r["condition"] in build.CONDITIONS, r["finding_id"]
        assert r["temp_category"] in build.TEMPS, r["finding_id"]
        assert r["result"] in build.RESULTS, r["finding_id"]
        assert r["criterion_type"] in build.CRITERIA, r["finding_id"]
        assert r["full_text_read"] == "yes", r["finding_id"]
        assert r["criterion"], r["finding_id"]
        if r["temp_category"] == "other":
            assert r["temp_reported"], r["finding_id"]


def test_finding_ids_unique():
    ids = [r["finding_id"] for r in FINDINGS]
    assert len(ids) == len(set(ids))


def test_marker_slugs_join():
    need_markers()
    for r in FINDINGS:
        if r["marker_slug"]:
            assert r["marker_slug"] in MARKERS, r["finding_id"]
            assert r["marker_name"] == MARKERS[r["marker_slug"]]["canonical_name"]


def test_n_is_integer_when_present():
    for r in FINDINGS:
        assert r["n"] == "" or r["n"].isdigit(), r["finding_id"]


def test_web_schema():
    assert WEB["version"] == build.VERSION
    assert isinstance(WEB["analytes"], list) and WEB["analytes"]
    row_keys = {"specimen", "tube", "processing", "temp", "stable_for", "stable_hours", "criterion", "n", "doi",
                "source_label", "location"}
    total = 0
    slugs = set()
    for a in WEB["analytes"]:
        assert set(a) == {"slug", "marker_slug", "name", "rows"}
        assert a["slug"] not in slugs
        slugs.add(a["slug"])
        if MARKERS is not None:
            assert a["marker_slug"] is None or a["marker_slug"] in MARKERS
        for row in a["rows"]:
            assert row_keys <= set(row)
            assert row["location"]
            assert row["doi"].startswith("10.")
            assert row["stable_hours"] is None or isinstance(row["stable_hours"], (int, float))
            if row["condition"] != "freeze-thaw":
                assert isinstance(row["stable_hours"], (int, float))
            total += 1
    assert total == len(FINDINGS)


# ---- every row has a location and a quote that is in the full text ------------------------
def test_every_row_has_location():
    for r in FINDINGS:
        assert r["location"].strip(), r["finding_id"]


def _check_quotes(rows):
    texts = {}
    for r in rows:
        if not r["evidence_quote"]:
            continue
        sid = r["source_id"]
        if sid not in texts:
            xml = RAW / "europepmc" / "fulltext" / f"{sid}.xml"
            if not xml.exists():
                pytest.skip("raw full text not present (raw files are not shipped)")
            texts[sid] = build.norm(build.fetch_fulltext.render(xml))
        assert build.norm(r["evidence_quote"]) in texts[sid], r["finding_id"]


def test_evidence_quotes_in_full_text():
    _check_quotes(FINDINGS)


QUOTE_OK = {"cc by", "cc0"}


def test_no_quote_ships_for_non_cc_by_sources():
    lic = {s["source_id"]: s["license"].strip().lower() for s in SOURCES}
    for r in FINDINGS:
        if lic[r["source_id"]] in QUOTE_OK:
            assert r["quote_status"] == "included" and r["evidence_quote"], r["finding_id"]
        else:
            assert r["quote_status"] == "withheld-licence" and r["evidence_quote"] == "", r["finding_id"]
    for p in (REL / "extraction").glob("PMC*.csv"):
        if lic.get(p.stem) in QUOTE_OK:
            continue
        with open(p, encoding="utf-8") as fh:
            for row in csv.DictReader(fh):
                assert row["evidence_quote"] == "", p.name
    with open(REL / "extraction" / "fasting_state.csv", encoding="utf-8") as fh:
        for row in csv.DictReader(fh):
            if lic.get(row["pmcid"]) not in QUOTE_OK:
                assert row["evidence_quote"] == "", row["pmcid"]


def test_cell_population_data_last_in_web():
    keys = [a["slug"] for a in WEB["analytes"]]
    cpd = [k for k in keys if re.match(r"^(ne|ly|mo)-", k)]
    assert cpd and keys[-len(cpd):] == cpd


# ---- durations -------------------------------------------------------------------------------
def test_durations_parse_to_hours():
    for r in FINDINGS:
        for col in ("stable_for", "max_tested", "unstable_at"):
            if not r[col]:
                continue
            kind, val = build.parse_duration(r[col])
            if r["condition"] == "freeze-thaw":
                assert kind == "cycles", r["finding_id"]
            else:
                assert kind == "hours", r["finding_id"]
                hcol = {"stable_for": "stable_hours", "max_tested": "max_tested_hours",
                        "unstable_at": "unstable_at_hours"}[col]
                assert abs(float(r[hcol]) - val) < 1e-6, r["finding_id"]


def test_duration_order():
    for r in FINDINGS:
        sfx = "cycles" if r["condition"] == "freeze-thaw" else "hours"
        s, m = float(r[f"stable_{sfx}"]), float(r[f"max_tested_{sfx}"])
        assert s <= m, r["finding_id"]
        if r[f"unstable_at_{sfx}"]:
            u = float(r[f"unstable_at_{sfx}"])
            assert s < u <= m, r["finding_id"]
            assert r["result"] in ("unstable-after", "unstable-at-first")
        elif r["result"] == "stated-limit":
            assert s <= m, r["finding_id"]
        else:
            assert r["result"] == "stable-to-max" and s == m, r["finding_id"]


@pytest.mark.parametrize("text,hours", [("8 h", 8), ("3 days", 72), ("2 weeks", 336), ("1 month", 730.5),
                                        ("1 year", 8766), ("30 min", 0.5), ("0 h", 0)])
def test_parse_duration_examples(text, hours):
    assert build.parse_duration(text) == ("hours", hours)


# ---- sources and DOIs ------------------------------------------------------------------------
def _crossref(doi):
    if os.environ.get("SS_LIVE_CROSSREF") == "1":
        req = urllib.request.Request("https://api.crossref.org/works/" + urllib.parse.quote(doi),
                                     headers={"User-Agent": build.UA})
        with urllib.request.urlopen(req, timeout=60) as r:
            return json.loads(r.read())
    fn = RAW / "crossref" / (urllib.parse.quote(doi.lower(), safe="") + ".json")
    if not fn.exists():
        pytest.skip("Crossref cache not present (raw files are not shipped); set SS_LIVE_CROSSREF=1")
    return json.loads(fn.read_text())


def test_every_doi_resolves_via_crossref_and_matches_title():
    for s in SOURCES:
        rec = _crossref(s["doi"])
        msg = rec.get("message")
        assert msg, s["doi"]
        assert msg["DOI"].lower() == s["doi"].lower()
        assert build.title_match(msg, s["title"]) >= 0.85, s["doi"]


def test_every_finding_source_listed():
    ids = {s["source_id"] for s in SOURCES}
    dois = {s["doi"] for s in SOURCES}
    for r in FINDINGS:
        assert r["source_id"] in ids and r["doi"] in dois


def test_sources_fields():
    for s in SOURCES:
        assert s["doi"].startswith("10.")
        assert s["open_access"] in ("yes", "no", "unclear")
        assert s["full_text_read"] == "yes"
        assert s["doi_resolves_crossref"] == "yes"
        assert s["access_date"] == "2026-11-25"


# ---- summary is the conservative minimum ----------------------------------------------------
def test_summary_is_minimum():
    by = defaultdict(list)
    for r in FINDINGS:
        temp = r["temp_category"] if r["temp_category"] != "other" else f"other ({r['temp_reported']})"
        by[(r["analyte_key"], r["specimen"], r["processing"], r["condition"], temp)].append(r)
    assert len(by) == len(SUMMARY)
    for s in SUMMARY:
        fs = by[(s["analyte_key"], s["specimen"], s["processing"], s["condition"], s["temp"])]
        assert s["study_quality_assessed"] == "no" and "No study-quality assessment" in s["caveat"]
        col = "stable_cycles" if s["condition"] == "freeze-thaw" else "stable_hours"
        assert float(s["shortest_stable"]) == min(float(f[col]) for f in fs)
        assert int(s["n_studies"]) == len({f["source_id"] for f in fs})
        assert 1 <= int(s["n_studies_consistent"]) <= int(s["n_studies"]) or s["agreement"] == "conflicting"
        assert int(s["n_findings"]) == len(fs)


# ---- authors and marker scope -----------------------------------------------------------------
def test_source_label_first_author_against_crossref_and_article():
    """Label's first author = article XML first author, and agrees with Crossref's first author.
    Where Crossref's deposited order differs from the article, the label author must still be in
    Crossref's author list and be Europe PMC's first author; sources.csv records the discrepancy."""
    for s in SOURCES:
        rec = _crossref(s["doi"])["message"]
        label_first = s["source_label"].split(" et al.")[0].rsplit(" ", 2)[0] if " et al." in s["source_label"] \
            else s["source_label"].split(",")[0].rsplit(" ", 1)[0]
        assert label_first == s["first_author"], s["source_id"]
        xml = RAW / "europepmc" / "fulltext" / f"{s['source_id']}.xml"
        if xml.exists():
            assert build.xml_authors(s["source_id"])[0] == s["first_author"], s["source_id"]
        cr_first = build.norm(build.crossref_first_author(rec))
        mine = build.norm(s["first_author"])
        if set(mine.split()) <= set(cr_first.split()) or set(cr_first.split()) <= set(mine.split()):
            assert s["first_author_check"].startswith("matches Crossref"), s["source_id"]
        else:
            families = {build.norm(a.get("family", "")) for a in rec.get("author", [])}
            assert mine in families, s["source_id"]
            assert "Crossref deposit order differs" in s["first_author_check"], s["source_id"]


def test_marker_slug_respects_specimen_and_fasting():
    for r in FINDINGS:
        slug = r["marker_slug"]
        if slug in build.MARKER_SCOPE:
            _, _, ok, needs_fasting = build.MARKER_SCOPE[slug]
            assert r["measured_matrix"] in ok, r["finding_id"]
            assert r["marker_match"] == "exact"
        if r["related_marker_slug"] and not slug:
            assert r["marker_match"] != "exact", r["finding_id"]
        if slug == "potassium-serum":
            assert r["measured_matrix"] == "serum"
    # no plasma or whole-blood potassium row carries the serum marker
    assert not [r for r in FINDINGS if r["marker_slug"] == "potassium-serum"
                and r["specimen"] not in ("serum", "whole-blood-clotted", "capillary-serum")]
    # emergency-department samples are not 'fasting'
    assert not [r for r in FINDINGS if r["marker_slug"] == "glucose-fasting" and "emergency" in r["population"].lower()]


def test_summary_separates_processing_states():
    keys = {(s["analyte_key"], s["specimen"], s["processing"], s["condition"], s["temp"]) for s in SUMMARY}
    assert len(keys) == len(SUMMARY)