Files
stack/tests/pfs/test_no_cpt_text.py

183 lines
6.2 KiB
Python

"""No CPT descriptor text in the repository's tests and golden sets (the
user's rule: no AMA/CPT descriptor text in the repo; final review C1).
Two guards over every tracked test module, test fixture and golden set:
* a CPT code followed by a parenthesized descriptor of the kind CMS prints
in a rule ("99341 ( Home or residence visit for ...)"): runs everywhere,
CI included;
* any run of eight words shared with a ``pfs.cpt_code`` descriptor (the
licensed books' text): runs only where the replica holds that table.
A HCPCS Level II code's descriptor is CMS's own text (public domain), so a
parenthetical or colon clause after one (G0318, the placeholder GXXX3) is
not scanned for the eight-word runs.
"""
from __future__ import annotations
import re
import subprocess
import unicodedata
from functools import cache
from pathlib import Path
import pytest
from conf import connect
ROOT = Path(__file__).resolve().parents[2]
#: a five-digit code, then "(" and a capitalized word, a lower-case word and
#: at least 60 more characters on the line before a ")": a descriptor CMS
#: printed. "(codes ...)", "(a range ...)", "(see ...)" and a placeholder
#: such as "( [descriptor] )" are not descriptors.
DESCRIPTOR_PAREN = re.compile(
r"\b\d{5}\s*\(\s*(?!codes?\b|a range\b|see\b)[A-Z][a-z]+ [a-z]+ [^\n]{60,}?\)"
)
RUN = 8
#: files outside this plan that hold descriptor text on purpose, reported
#: in final-fix-report.md for the user's decision (R103 scope); the list is
#: never added to
KNOWN_EXEMPT = frozenset(
{
# descriptor-parser tests that predate Plan A (P49, 2026-09-09)
"tests/pfs/test_cpt_load.py",
"tests/pfs/test_descriptors.py",
"tests/pfs/test_elements.py",
"tests/pfs/test_extract.py",
"tests/pfs/fixtures/cpt_sample.xhtml",
# the market tier's own AMA-guard test input (6a45806), another
# builder's file; reported in final-fix-report.md, never added to
"tests/market/test_fts.py",
}
)
#: a HCPCS Level II code (or a proposed-rule placeholder) and the start of
#: its descriptor
_HCPCS_LEAD = re.compile(r"\b(?:[A-V]\d{4}|[A-Z]XXX\d)\s*([(:])")
def _scanned(rel: str) -> bool:
parts = Path(rel).parts
if rel.startswith("src/pfs/golden/"):
return True
if parts[:1] != ("tests",):
return False
return "fixtures" in parts or rel.endswith(".py")
@cache
def _files() -> tuple[str, ...]:
"""The tracked files the guards read (every file on disk under the same
paths when git is unavailable)."""
try:
out = subprocess.run(
["git", "ls-files", "-z", "--", "tests", "src/pfs/golden"],
cwd=ROOT,
capture_output=True,
check=True,
).stdout.decode()
rels = [r for r in out.split("\0") if r]
except (OSError, subprocess.CalledProcessError): # pragma: no cover
rels = [
str(p.relative_to(ROOT))
for base in ("tests", "src/pfs/golden")
for p in (ROOT / base).rglob("*")
if p.is_file()
]
return tuple(r for r in sorted(rels) if _scanned(r) and (ROOT / r).is_file())
def _text(rel: str) -> str:
try:
return (ROOT / rel).read_text(encoding="utf-8")
except UnicodeDecodeError: # pragma: no cover - binary fixture
return ""
def _words(text: str) -> list[str]:
return re.findall(r"[a-z0-9]+", unicodedata.normalize("NFKC", text).lower())
def _runs(words: list[str]) -> set[tuple[str, ...]]:
"""Eight-word runs with at least six words of letters (a list of codes
is not a run)."""
runs = (tuple(words[i : i + RUN]) for i in range(len(words) - RUN + 1))
return {run for run in runs if sum(w.isalpha() for w in run) >= 6}
def without_hcpcs_text(text: str) -> str:
"""*text* without the descriptor after each HCPCS Level II code: a
balanced parenthetical, or a colon clause to the end of its line or
quoted string."""
out, i = [], 0
for m in _HCPCS_LEAD.finditer(text):
if m.start() < i:
continue
j = m.end()
if m.group(1) == "(":
depth = 1
while j < len(text) and depth:
depth += {"(": 1, ")": -1}.get(text[j], 0)
j += 1
else:
stop = re.search(r'["\n]', text[j:])
j = j + stop.start() if stop else len(text)
out.append(text[i : m.end()])
i = j
out.append(text[i:])
return "".join(out)
def test_descriptor_parenthetical_pattern_catches_the_shape():
shape = "99999 ( Lorem ipsum " + "dolor sit amet " * 6 + "end)"
assert DESCRIPTOR_PAREN.search(shape)
for fine in (
"99341 ( [descriptor] ) and more",
"CPT codes 99341 (codes 99341 through 99350 are listed here in full) x",
"99343 ( Short text)",
"G0318 is not a five-digit code (Lorem ipsum dolor sit amet " * 3 + ")",
):
assert not DESCRIPTOR_PAREN.search(fine), fine
def test_hcpcs_level_two_text_is_set_aside():
text = 'code G0318 ( Lorem (ipsum) dolor) stays, "GXXX3: lorem ipsum" ok'
assert without_hcpcs_text(text) == 'code G0318 ( stays, "GXXX3:" ok'
def test_no_cpt_descriptor_parentheticals_in_tests_or_golden_sets():
hits = [
f"{rel}: {m.group(0)[:80]}"
for rel in _files()
for m in DESCRIPTOR_PAREN.finditer(_text(rel))
]
assert hits == []
_REPLICA = connect._replica_path("aco")
@pytest.mark.skipif(not _REPLICA.exists(), reason="live replica")
def test_no_eight_word_run_shared_with_a_cpt_descriptor():
con = connect.duckdb("aco", replica=True)
try:
rows = con.execute(
"SELECT DISTINCT descriptor FROM pfs.cpt_code WHERE descriptor IS NOT NULL"
).fetchall()
except Exception as exc: # noqa: BLE001 - only a missing table skips
pytest.skip(f"no pfs.cpt_code on the replica ({exc})")
finally:
con.close()
book: set[tuple[str, ...]] = set()
for (d,) in rows:
book |= _runs(_words(d))
hits = []
for rel in _files():
if rel in KNOWN_EXEMPT:
continue
shared = _runs(_words(without_hcpcs_text(_text(rel)))) & book
if shared:
hits.append(f"{rel}: {' '.join(sorted(shared)[0])}")
assert hits == []