Some checks failed
CI / lint (push) Successful in 1m25s
CI / notebooks-smoke (push) Successful in 2m11s
Deploy / changes (push) Successful in 22s
Infra CI / notebooks (push) Successful in 1m0s
CI / test (push) Failing after 5m34s
Infra CI / zotero (push) Successful in 31s
Infra CI / docs (push) Successful in 54s
Infra CI / api (push) Successful in 2m5s
Infra CI / bcda (push) Successful in 2m21s
Infra CI / llm (push) Successful in 1m30s
Infra CI / mc (push) Successful in 35s
Deploy / notebooks (push) Has been skipped
Deploy / zotero (push) Has been skipped
Deploy / docs (push) Has been skipped
Deploy / api (push) Successful in 2m14s
Deploy / bcda (push) Successful in 2m35s
Deploy / mc (push) Has been skipped
Deploy / llm (push) Successful in 1m47s
Deploy / report (push) Successful in 16s
Harden / build-scan-report (push) Successful in 37m31s
Comment Pull / comment-pull (push) Failing after 1m2s
Notebooks Integration / notebooks-integration (push) Failing after 11m47s
LLM Golden / llm-golden (push) Successful in 9m47s
Renovate / renovate (push) Successful in 1m56s
Zotero Sync / zotero-sync (push) Successful in 2m56s
BCDA Vendor / bcda-vendor (push) Failing after 41s
Package Supply Chain / pkg-supply-chain (push) Successful in 1m23s
731 lines
28 KiB
Python
731 lines
28 KiB
Python
import json
|
|
import os
|
|
import zipfile
|
|
from datetime import date
|
|
from pathlib import Path
|
|
|
|
import duckdb
|
|
import httpx
|
|
import pytest
|
|
|
|
from drugs import asp
|
|
from drugs import http as dh
|
|
from drugs import tables as T
|
|
|
|
FIXTURE = Path(__file__).parent / "fixtures" / "asp_page_head.html"
|
|
|
|
|
|
class _NoWait:
|
|
def wait(self):
|
|
pass
|
|
|
|
|
|
@pytest.fixture
|
|
def root(monkeypatch, tmp_path):
|
|
monkeypatch.setattr(dh, "data_root", lambda: tmp_path)
|
|
monkeypatch.setattr(dh, "pacer", lambda provider: _NoWait())
|
|
dh._MANIFESTS.clear()
|
|
return tmp_path
|
|
|
|
|
|
# ── the page ─────────────────────────────────────────────────────────
|
|
def test_parse_asp_page_kinds_and_quarters():
|
|
links = asp.parse_asp_page(FIXTURE.read_text())
|
|
got = {(lk.quarter, lk.kind): lk.url for lk in links}
|
|
assert got[("2026-Q4", "pricing")] == (
|
|
"https://www.cms.gov/files/zip/"
|
|
"october-2026-medicare-part-b-payment-limit-files-final.zip"
|
|
)
|
|
assert got[("2026-Q4", "crosswalk")] == (
|
|
"https://www.cms.gov/files/zip/october-2026-ndc-hcpcs-crosswalk-final.zip"
|
|
)
|
|
vaccine = [lk for lk in links if lk.kind == "vaccine"]
|
|
assert len(vaccine) == 2 and {lk.quarter for lk in vaccine} == {""}
|
|
assert ("2018-Q2", "noc") in got and ("2018-Q1", "pricing") in got
|
|
assert got[("2005-Q1", "pricing")] == (
|
|
"https://www.cms.gov/Medicare/Medicare-Fee-for-Service-Part-B-Drugs/"
|
|
"McrPartBDrugAvgSalesPrice/downloads/jan05aspbyhcpcsv6_033106.zip"
|
|
)
|
|
assert ("2005-Q1", "crosswalk") in got
|
|
assert len(links) == 8
|
|
assert links[0].text == "October 2026 Medicare Part B Payment Limit Files"
|
|
|
|
|
|
def test_parse_asp_page_edge_cases():
|
|
html = """
|
|
<a href="/files/zip/january-2023-asp-pricing-file.zip">2023 ASP Pricing File (ZIP)</a>
|
|
<a href="/files/zip/april-2023-noc-pricing-file.zip">2023 NOC Pricing File</a>
|
|
<a href="/x/2018-July-ASP-Pricing-File.zip">ASP Pricing File</a>
|
|
<a href="/files/zip/jan06.zip">January 2006 ASP Pricing File/ASP NOC Pricing File/ASP NDC-HCPCS Crosswalk</a>
|
|
<a href="/files/zip/jul06.zip">July 2006 ASP NDC-HCPCS Crosswalk - Updated</a>
|
|
<a href="/files/zip/oct09.zip">October 2009 ASP NOC Pricing File</a>
|
|
<a href="/files/zip/mystery.zip">Something else entirely</a>
|
|
<a href="/files/zip/no-month.zip">ASP Pricing File</a>
|
|
<a href="/files/pdf/guide.pdf">Guide to the files (PDF)</a>
|
|
<a>no href at all</a>
|
|
<a href="/files/zip/oct05.zip">Oct. 2005 ASP Pricing File and ASP NOC Pricing File</a>
|
|
"""
|
|
links = asp.parse_asp_page(html)
|
|
got = [(lk.quarter, lk.kind) for lk in links]
|
|
assert got == [
|
|
("2023-Q1", "pricing"),
|
|
("2023-Q2", "noc"),
|
|
("2018-Q3", "pricing"),
|
|
("2006-Q1", "pricing"),
|
|
("2006-Q3", "crosswalk"),
|
|
("2009-Q4", "noc"),
|
|
("", "other"),
|
|
("", "other"),
|
|
("2005-Q4", "pricing"),
|
|
]
|
|
assert links[1].text == "2023 NOC Pricing File"
|
|
|
|
|
|
def test_direct_url_unwraps_license():
|
|
p = "/Medicare/Medicare-Fee-for-Service-Part-B-Drugs/x/downloads/a.zip"
|
|
want = "https://www.cms.gov" + p
|
|
assert asp.direct_url(f"https://www.cms.gov/apps/ama/license.asp?file={p}") == want
|
|
assert asp.direct_url(f"/apps/ama/license.asp?file={p}") == want
|
|
assert asp.direct_url(f"https://www.cms.gov/license/ama?file={p}") == want
|
|
assert asp.direct_url("/files/zip/a.zip") == "https://www.cms.gov/files/zip/a.zip"
|
|
assert asp.direct_url("https://x.test/a.zip") == "https://x.test/a.zip"
|
|
|
|
|
|
def test_hoard_path_and_newest_per_quarter(root):
|
|
def lk(kind):
|
|
return asp.AspLink("2026-Q2", kind, "u", "t")
|
|
|
|
assert asp.hoard_path(lk("pricing")) == root / "cms/asp/asp_2026-Q2.zip"
|
|
assert asp.hoard_path(lk("noc")) == root / "cms/asp/noc/noc_2026-Q2.zip"
|
|
assert asp.hoard_path(lk("crosswalk")) == root / "cms/asp/xwalk/xwalk_2026-Q2.zip"
|
|
with pytest.raises(ValueError):
|
|
asp.hoard_path(lk("vaccine"))
|
|
|
|
|
|
def test_one_zip_per_quarter_newest_wins(tmp_path):
|
|
a = tmp_path / "asp_2026-Q2.zip"
|
|
b = tmp_path / "asp_2026-Q2.ab12cd34.zip"
|
|
c = tmp_path / "asp_2026-Q1.zip"
|
|
junk = tmp_path / "asp_notes.zip"
|
|
for p in (a, b, c, junk):
|
|
p.write_bytes(b"x")
|
|
os.utime(a, (1_000, 1_000))
|
|
os.utime(b, (2_000, 2_000))
|
|
got = asp.newest_per_quarter([a, b, c, junk])
|
|
assert got == {"2026-Q1": c, "2026-Q2": b}
|
|
# the older copy still wins when it is the newer file
|
|
os.utime(a, (3_000, 3_000))
|
|
assert asp.newest_per_quarter([a, b])["2026-Q2"] == a
|
|
assert asp.newest_per_quarter([]) == {}
|
|
|
|
|
|
def test_expected_quarters():
|
|
q = asp.expected_quarters(date(2026, 11, 13))
|
|
assert q[0] == "2005-Q1" and q[-1] == "2026-Q4" and len(q) == 88
|
|
assert asp.expected_quarters(date(2005, 1, 1)) == ["2005-Q1"]
|
|
assert asp.expected_quarters(date(2005, 3, 31)) == ["2005-Q1"]
|
|
assert asp.expected_quarters(date(2006, 2, 1)) == [
|
|
"2005-Q1",
|
|
"2005-Q2",
|
|
"2005-Q3",
|
|
"2005-Q4",
|
|
"2006-Q1",
|
|
]
|
|
|
|
|
|
# ── the member logic ─────────────────────────────────────────────────
|
|
def test_col_map_covers_dev_script_and_new_columns():
|
|
dev = {
|
|
"hcpcs code": "hcpcs_code",
|
|
"hcpcs_code": "hcpcs_code",
|
|
"short description": "short_description",
|
|
"short_description": "short_description",
|
|
"hcpcs code dosage": "dosage_or_unit",
|
|
"hcpcs_code_dosage": "dosage_or_unit",
|
|
"dosage": "dosage_or_unit",
|
|
"dosage or unit": "dosage_or_unit",
|
|
"payment limit": "payment_limit",
|
|
"payment_limit": "payment_limit",
|
|
}
|
|
for k, v in dev.items():
|
|
assert asp.COL_MAP[k] == v
|
|
assert asp.COL_MAP["co-insurance percentage"] == "coinsurance_pct"
|
|
assert asp.COL_MAP["notes"] == "notes"
|
|
assert asp.COL_MAP["long description"] == "short_description"
|
|
assert asp.COL_MAP["manufacturer"] == "manufacturer"
|
|
assert asp.COL_MAP["drug generic name (trade name)"] == "drug_name"
|
|
|
|
|
|
def test_find_header_row():
|
|
assert asp.find_header_row(["a", "Note: HCPCS code x,y", "HCPCS Code,Foo"]) == 2
|
|
assert asp.find_header_row(['"HCPCS Code","Foo"']) == 0
|
|
assert asp.find_header_row(["", "Drug Generic Name (Trade Name),Dosage"]) == 1
|
|
assert asp.find_header_row(["Drug Name (Generic),Dosage"]) == 0
|
|
assert asp.find_header_row(["nothing here"]) == -1
|
|
assert asp.find_header_row([]) == -1
|
|
|
|
|
|
NAMES_2015Q3 = [
|
|
"Jul 15 ASP Pricing File - updated 090115.xls",
|
|
"section 508 version of Jul 15 ASP Pricing File - updated 090115.csv",
|
|
]
|
|
NAMES_2026Q2 = [
|
|
"April 2026 Drugs Not Payable Under Part B 030926.xls",
|
|
"April 2026 Medicare Part B Payment Limit File 032426.xls",
|
|
"section 508 version of April 2026 Drugs Not Payable Under Part B 030926.csv",
|
|
"section 508 version of April 2026 Medicare Part B Payment Limit File 032426.csv",
|
|
]
|
|
|
|
|
|
def test_pick_pricing_file_matches_dev_script():
|
|
assert asp.pick_pricing_file(["Jan05ASPbyHCPCSv6_033106.xls"]) == (
|
|
"Jan05ASPbyHCPCSv6_033106.xls"
|
|
)
|
|
assert asp.pick_pricing_file(NAMES_2015Q3) == NAMES_2015Q3[1]
|
|
assert asp.pick_pricing_file(
|
|
[
|
|
"January 2026 Medicare Part B Payment Limit File updated 022526.xls",
|
|
"section 508 version of January 2026 Medicare Part B Payment Limit "
|
|
"File updated 022526.csv",
|
|
]
|
|
).endswith("022526.csv")
|
|
assert asp.pick_pricing_file(NAMES_2026Q2) == NAMES_2026Q2[3]
|
|
assert asp.pick_pricing_file(["a.xls", "b.pdf"]) == "a.xls"
|
|
assert asp.pick_pricing_file(["ASP.xlsx", "other.xls"]) == "ASP.xlsx"
|
|
assert (
|
|
asp.pick_pricing_file(["other.csv", "payment limit.csv"]) == "payment limit.csv"
|
|
)
|
|
assert asp.pick_pricing_file(["x.csv"]) == "x.csv"
|
|
assert (
|
|
asp.pick_pricing_file(["Oct 2025 NOC Pricing File.csv", "readme.txt"]) is None
|
|
)
|
|
assert asp.pick_pricing_file(["Crosswalk.csv", "ndc.xls"]) is None
|
|
|
|
|
|
def test_pick_member_prefers_csv_over_its_xls_twin():
|
|
# P7: one member per kind per zip
|
|
assert asp.pick_member(NAMES_2026Q2, "not-payable") == NAMES_2026Q2[2]
|
|
assert asp.pick_member(NAMES_2026Q2, "noc") is None
|
|
names = [
|
|
"1 - Apr06_ASPbyHCPCS_122107.xls",
|
|
"1 - Apr06_ASPbyHCPCS_122107.csv",
|
|
"1 - Apr06_ASPNOC_20Sep06.xls",
|
|
"1 - Apr06_ASPNOC_20Sep06.csv",
|
|
"April06ASPNDC-HCPCSCrosswalk_20Mar06.xls",
|
|
]
|
|
assert asp.pick_member(names, "noc") == "1 - Apr06_ASPNOC_20Sep06.csv"
|
|
assert asp.pick_member(names[2:3] + names[4:], "noc") == names[2]
|
|
assert asp.pick_member(["Drugs_Not_Payable.xlsx"], "not-payable") == (
|
|
"Drugs_Not_Payable.xlsx"
|
|
)
|
|
assert asp.pick_member(["x.csv"], "noc") is None
|
|
with pytest.raises(ValueError):
|
|
asp.pick_member(names, "crosswalk")
|
|
|
|
|
|
# ── reading tables ───────────────────────────────────────────────────
|
|
PRICING_HEAD = (
|
|
"Payment Allowance Limits for Medicare Part B Drugs,,,,,,,,,,,\r\n"
|
|
",,,,,,,,,,,\r\n"
|
|
"Note 1: HCPCS code lines mention HCPCS code here,,,,,,,,,,,\r\n"
|
|
"HCPCS Code,Short Description,HCPCS Code Dosage,Payment Limit,"
|
|
"Co-insurance Percentage,Vaccine AWP%,Vaccine Limit,Blood AWP%,Blood limit,"
|
|
"Clotting Factor,Notes\r\n"
|
|
)
|
|
PRICING_ROWS = (
|
|
"90371,x,1 ML,140.209,20.000,,,,,,\r\n"
|
|
'J9035,Bevacizumab injection,10 MG,"$66.123",20.000,,,,,,\r\n'
|
|
)
|
|
NP_CSV = (
|
|
"Drugs Not Payable Under Part B,,,\r\n"
|
|
",,,\r\n"
|
|
"HCPCS Code,Long Description,Manufacturer,,,,\r\n"
|
|
'J7330," Autologous cultured chondrocytes, implant ",Vericel Corporation,,,,\r\n'
|
|
"90999,x,Acme,,,,\r\n"
|
|
",,,,,,\r\n"
|
|
)
|
|
NOC_CSV = (
|
|
"Payment Allowance Limits for NOC Drugs,,,\r\n"
|
|
",,,\r\n"
|
|
"Drug Generic Name (Trade Name),Dosage,Payment Limit,Notes\r\n"
|
|
"Examplumab,10 MG,12.5,\r\n"
|
|
"Vasopressin (Long Grove),1 UNIT,$2.462,\r\n"
|
|
",,,\r\n"
|
|
)
|
|
|
|
|
|
def make_zip(path: Path, members: dict[str, str | bytes]) -> Path:
|
|
with zipfile.ZipFile(path, "w") as zf:
|
|
for name, body in members.items():
|
|
zf.writestr(
|
|
name, body if isinstance(body, bytes) else body.encode("latin-1")
|
|
)
|
|
return path
|
|
|
|
|
|
def test_cpt_short_description_never_stored(tmp_path):
|
|
z = make_zip(
|
|
tmp_path / "asp_2026-Q2.zip",
|
|
{
|
|
"section 508 version of April 2026 Payment Limit File.csv": PRICING_HEAD
|
|
+ PRICING_ROWS
|
|
},
|
|
)
|
|
rows, noc = asp.parse_quarter_zip(
|
|
z, "2026-Q2", source_url="https://cms.test/a.zip", item_key="K1"
|
|
)
|
|
assert noc == []
|
|
by = {r.hcpcs: r for r in rows}
|
|
assert by["90371"].level == "I" and by["90371"].short_desc == ""
|
|
assert by["90371"].dosage == "1 ML" and by["90371"].payment_limit == 140.209
|
|
assert by["90371"].coinsurance_pct == 20.0
|
|
j = by["J9035"]
|
|
assert j.level == "II" and j.short_desc == "Bevacizumab injection"
|
|
assert j.payment_limit == 66.123 and j.list_kind == "payment"
|
|
assert j.quarter == "2026-Q2" and j.item_key == "K1"
|
|
assert j.source_url == "https://cms.test/a.zip"
|
|
assert j.source_file == "section 508 version of April 2026 Payment Limit File.csv"
|
|
assert "Bevacizumab" not in " ".join(r.short_desc for r in rows if r.level == "I")
|
|
|
|
|
|
def test_numbers_codes_and_blank_rows(tmp_path):
|
|
body = (
|
|
PRICING_HEAD
|
|
+ ' j9035 ,Bevacizumab,10 MG,"$1,066.50",,,,,,,see note\r\n'
|
|
+ "J0000,Unparseable,1 MG,n/a,abc,,,,,,\r\n"
|
|
+ "J0001,Short row\r\n"
|
|
+ ",,,,,,,,,,\r\n"
|
|
+ " ,blank code,,,,,,,,,\r\n"
|
|
+ "J0002,Too many,1 MG,1.0,20,,,,,,,extra,fields\r\n"
|
|
+ "D0120,dental,1,2.0,,,,,,,\r\n"
|
|
)
|
|
z = make_zip(tmp_path / "asp_2020-Q1.zip", {"ASP Pricing File.csv": body})
|
|
rows, _ = asp.parse_quarter_zip(z, "2020-Q1", source_url="")
|
|
by = {r.hcpcs: r for r in rows}
|
|
# a line with more fields than columns is malformed and skipped
|
|
assert set(by) == {"J9035", "J0000", "J0001", "D0120"}
|
|
assert by["J9035"].payment_limit == 1066.5 and by["J9035"].notes == "see note"
|
|
assert by["J0000"].payment_limit is None and by["J0000"].coinsurance_pct is None
|
|
assert by["J0001"].dosage == "" and by["J0001"].short_desc == "Short row"
|
|
assert by["D0120"].level == "CDT" and by["D0120"].short_desc == ""
|
|
assert by["J9035"].item_key == "" and by["J9035"].source_url == ""
|
|
|
|
|
|
def test_not_payable_rows_kept(tmp_path):
|
|
z = make_zip(
|
|
tmp_path / "asp_2026-Q2.zip",
|
|
{
|
|
"April 2026 Drugs Not Payable Under Part B 030926.xls": b"not read",
|
|
"section 508 version of April 2026 Drugs Not Payable Under Part B 030926.csv": NP_CSV,
|
|
"section 508 version of April 2026 Payment Limit File.csv": PRICING_HEAD
|
|
+ PRICING_ROWS,
|
|
},
|
|
)
|
|
rows, _ = asp.parse_quarter_zip(z, "2026-Q2", source_url="u")
|
|
np_rows = [r for r in rows if r.list_kind == "not-payable"]
|
|
assert len(np_rows) == 2 and len(rows) == 4
|
|
j = next(r for r in np_rows if r.hcpcs == "J7330")
|
|
assert j.payment_limit is None and j.coinsurance_pct is None
|
|
assert j.manufacturer == "Vericel Corporation"
|
|
assert j.short_desc == " Autologous cultured chondrocytes, implant "
|
|
assert j.source_file.endswith("Under Part B 030926.csv")
|
|
lvl1 = next(r for r in np_rows if r.hcpcs == "90999")
|
|
assert lvl1.level == "I" and lvl1.short_desc == "" and lvl1.manufacturer == "Acme"
|
|
assert all(r.manufacturer == "" for r in rows if r.list_kind == "payment")
|
|
|
|
|
|
def test_noc_member_parsed(tmp_path):
|
|
z = make_zip(
|
|
tmp_path / "noc_2025-Q4.zip",
|
|
{
|
|
"Oct 2025 NOC Pricing File 090425.xls": b"not read",
|
|
"section 508 version of Oct 2025 NOC Pricing File 090425.csv": NOC_CSV,
|
|
},
|
|
)
|
|
rows, noc = asp.parse_quarter_zip(
|
|
z, "2025-Q4", source_url="https://cms.test/n.zip", item_key="K2"
|
|
)
|
|
assert rows == []
|
|
assert [(n.drug_name, n.dosage, n.payment_limit) for n in noc] == [
|
|
("Examplumab", "10 MG", 12.5),
|
|
("Vasopressin (Long Grove)", "1 UNIT", 2.462),
|
|
]
|
|
assert noc[0].quarter == "2025-Q4" and noc[0].item_key == "K2"
|
|
assert noc[0].source_url == "https://cms.test/n.zip"
|
|
assert noc[0].source_file.endswith("090425.csv")
|
|
|
|
|
|
def test_bundled_zip_gives_both_and_one_member_per_kind(tmp_path):
|
|
# 2006-style zip: pricing, NOC and crosswalk, each as .xls and .csv twins
|
|
z = make_zip(
|
|
tmp_path / "asp_2006-Q2.zip",
|
|
{
|
|
"1 - Apr06_ASPbyHCPCS.xls": b"x",
|
|
"1 - Apr06_ASPbyHCPCS.csv": PRICING_HEAD + PRICING_ROWS,
|
|
"1 - Apr06_ASPNOC.xls": b"x",
|
|
"1 - Apr06_ASPNOC.csv": NOC_CSV,
|
|
"April06ASPNDC-HCPCSCrosswalk.csv": "HCPCS Code,NDC\r\nJ9035,1\r\n",
|
|
},
|
|
)
|
|
rows, noc = asp.parse_quarter_zip(z, "2006-Q2", source_url="")
|
|
assert [r.hcpcs for r in rows] == ["90371", "J9035"]
|
|
assert len(noc) == 2
|
|
|
|
|
|
def test_header_missing_gives_no_rows(tmp_path):
|
|
z = make_zip(
|
|
tmp_path / "asp_2020-Q1.zip", {"ASP Pricing File.csv": "a,b\r\n1,2\r\n"}
|
|
)
|
|
assert asp.parse_quarter_zip(z, "2020-Q1", source_url="") == ([], [])
|
|
z2 = make_zip(tmp_path / "asp_2020-Q2.zip", {"readme.txt": "hi"})
|
|
assert asp.parse_quarter_zip(z2, "2020-Q2", source_url="") == ([], [])
|
|
|
|
|
|
class _Sheet:
|
|
def __init__(self, grid):
|
|
self.grid = grid
|
|
self.nrows = len(grid)
|
|
self.ncols = max(len(r) for r in grid)
|
|
|
|
def cell_value(self, r, c):
|
|
row = self.grid[r]
|
|
return row[c] if c < len(row) else ""
|
|
|
|
|
|
class _Book:
|
|
def __init__(self, grid, sheets=None):
|
|
self.sheets = [("Sheet1", _Sheet(grid))] + [
|
|
(name, _Sheet(g)) for name, g in (sheets or [])
|
|
]
|
|
|
|
def sheet_names(self):
|
|
return [n for n, _ in self.sheets]
|
|
|
|
def sheet_by_index(self, i):
|
|
return self.sheets[i][1]
|
|
|
|
|
|
XLS_GRID = [
|
|
["Payment Allowance Limits"],
|
|
[""],
|
|
["HCPCS Code", "Short Description", "HCPCS Code Dosage", "Payment Limit"],
|
|
[90371.0, "x", "1 ML", 140.209],
|
|
["J9035 ", "Bevacizumab injection", "10 MG", 66.123],
|
|
["", "", "", ""],
|
|
["J0001", "Whole", "1 MG", 5.0],
|
|
]
|
|
|
|
|
|
def test_xls_member_through_fake_workbook(tmp_path):
|
|
z = make_zip(
|
|
tmp_path / "asp_2005-Q1.zip", {"Jan05ASPbyHCPCSv6_033106.xls": b"BIFF"}
|
|
)
|
|
seen = {}
|
|
|
|
def open_wb(**kw):
|
|
seen.update(kw)
|
|
return _Book(XLS_GRID)
|
|
|
|
rows, noc = asp.parse_quarter_zip(
|
|
z, "2005-Q1", source_url="u", open_workbook=open_wb
|
|
)
|
|
assert seen == {"file_contents": b"BIFF"}
|
|
assert noc == []
|
|
assert [
|
|
(r.hcpcs, r.level, r.short_desc, r.dosage, r.payment_limit) for r in rows
|
|
] == [
|
|
("90371", "I", "", "1 ML", 140.209),
|
|
("J9035", "II", "Bevacizumab injection", "10 MG", 66.123),
|
|
("J0001", "II", "Whole", "1 MG", 5.0),
|
|
]
|
|
csv_z = make_zip(
|
|
tmp_path / "asp_2005-Q2.zip",
|
|
{"ASP.csv": PRICING_HEAD + PRICING_ROWS},
|
|
)
|
|
csv_rows, _ = asp.parse_quarter_zip(csv_z, "2005-Q2", source_url="u")
|
|
assert [(r.hcpcs, r.dosage, r.payment_limit) for r in csv_rows] == [
|
|
(r.hcpcs, r.dosage, r.payment_limit) for r in rows[:2]
|
|
]
|
|
|
|
|
|
def test_xls_without_header_and_default_workbook(tmp_path, monkeypatch):
|
|
z = make_zip(tmp_path / "asp_2005-Q1.zip", {"ASP.xls": b"BIFF"})
|
|
assert asp.parse_quarter_zip(
|
|
z, "2005-Q1", source_url="", open_workbook=lambda **kw: _Book([["a"], ["b"]])
|
|
) == ([], [])
|
|
import sys
|
|
import types
|
|
|
|
fake = types.SimpleNamespace(open_workbook=lambda **kw: _Book(XLS_GRID))
|
|
monkeypatch.setitem(sys.modules, "xlrd", fake)
|
|
rows, _ = asp.parse_quarter_zip(z, "2005-Q1", source_url="")
|
|
assert len(rows) == 3
|
|
|
|
|
|
def test_noc_xls_member(tmp_path):
|
|
grid = [
|
|
["Drug Generic Name (Trade Name)", "Dosage", "Payment Limit"],
|
|
["Abatacept", "250 MG", 477.0],
|
|
["", "", ""],
|
|
]
|
|
z = make_zip(tmp_path / "noc_2008-Q1.zip", {"Jan08 NOC.xls": b"BIFF"})
|
|
_, noc = asp.parse_quarter_zip(
|
|
z, "2008-Q1", source_url="", open_workbook=lambda **kw: _Book(grid)
|
|
)
|
|
assert [(n.drug_name, n.dosage, n.payment_limit) for n in noc] == [
|
|
("Abatacept", "250 MG", 477.0)
|
|
]
|
|
|
|
|
|
# ── manifest and gaps ────────────────────────────────────────────────
|
|
def test_manifest_urls_and_known_urls(root):
|
|
assert asp.manifest_urls() == set()
|
|
d = root / "cms" / "asp"
|
|
d.mkdir(parents=True)
|
|
f = d / "asp_2026-Q1.zip"
|
|
f.write_bytes(b"z")
|
|
dh.manifest(f, "https://cms.test/q1.zip")
|
|
assert asp.manifest_urls() == {"https://cms.test/q1.zip"}
|
|
(root / "cms" / "asp_source_urls.csv").write_text(
|
|
"quarter,url\n2026-Q2,https://cms.test/q2.zip\n"
|
|
)
|
|
assert asp.canonical_urls() == {"2026-Q2": "https://cms.test/q2.zip"}
|
|
|
|
|
|
def test_plan_fetch_actions(root):
|
|
d = root / "cms" / "asp"
|
|
d.mkdir(parents=True)
|
|
(d / "asp_2026-Q1.zip").write_bytes(b"q1")
|
|
(d / "asp_2026-Q2.zip").write_bytes(b"q2")
|
|
(d / "asp_2025-Q4.zip").write_bytes(b"q4")
|
|
dh.manifest(d / "asp_2025-Q4.zip", "https://cms.test/2025q4.zip")
|
|
(root / "cms" / "asp_source_urls.csv").write_text(
|
|
"quarter,url\n2026-Q2,https://cms.test/q2-a.zip\n2026-Q1,https://cms.test/q1.zip\n"
|
|
)
|
|
|
|
def lk(q, kind, url):
|
|
return asp.AspLink(q, kind, url, "t")
|
|
|
|
links = [
|
|
lk("2025-Q4", "pricing", "https://cms.test/2025q4.zip"), # in manifest
|
|
lk("2026-Q1", "pricing", "https://cms.test/q1.zip"), # canonical, adopt
|
|
lk("2026-Q2", "pricing", "https://cms.test/q2-b.zip"), # updated posting
|
|
lk("2026-Q3", "pricing", "https://cms.test/q3.zip"), # new
|
|
lk("2026-Q3", "noc", "https://cms.test/n3.zip"),
|
|
lk("", "vaccine", "https://cms.test/v.zip"),
|
|
]
|
|
plan = asp.plan_fetch(links, refresh=False)
|
|
assert [(p.link.quarter, p.link.kind, p.action) for p in plan] == [
|
|
("2025-Q4", "pricing", "have"),
|
|
("2026-Q1", "pricing", "adopt"),
|
|
("2026-Q2", "pricing", "fetch-beside"),
|
|
("2026-Q3", "pricing", "fetch"),
|
|
("2026-Q3", "noc", "fetch"),
|
|
]
|
|
assert plan[3].dest == d / "asp_2026-Q3.zip"
|
|
forced = asp.plan_fetch(links, refresh=True)
|
|
assert {p.action for p in forced[:3]} == {"fetch-beside"}
|
|
assert forced[3].action == "fetch"
|
|
|
|
|
|
def test_gap_pairs_and_note():
|
|
have = {"pricing": {"2026-Q1", "2026-Q3"}, "noc": set(), "crosswalk": set()}
|
|
listed = {("2026-Q3", "noc"), ("2026-Q3", "crosswalk")}
|
|
exp = ["2026-Q1", "2026-Q2", "2026-Q3"]
|
|
pairs = asp.gap_pairs(exp, have, listed)
|
|
assert pairs == ["2026-Q2 pricing", "2026-Q3 crosswalk", "2026-Q3 noc"]
|
|
assert asp.gap_note(pairs).startswith("no hoarded file for: 2026-Q2 pricing")
|
|
assert asp.gap_note([]) == ""
|
|
many = [f"{2000 + i}-Q1 pricing" for i in range(40)]
|
|
note = asp.gap_note(many)
|
|
assert note.endswith("(+28 more)") and "2011-Q1 pricing" in note
|
|
|
|
|
|
def test_missing_quarter_is_gap_not_zero(tmp_path):
|
|
z1 = make_zip(
|
|
tmp_path / "asp_2026-Q1.zip", {"ASP.csv": PRICING_HEAD + PRICING_ROWS}
|
|
)
|
|
z3 = make_zip(
|
|
tmp_path / "asp_2026-Q3.zip", {"ASP.csv": PRICING_HEAD + PRICING_ROWS}
|
|
)
|
|
got = asp.newest_per_quarter([z1, z3])
|
|
have = {"pricing": set(got), "noc": set(), "crosswalk": set()}
|
|
pairs = asp.gap_pairs(["2026-Q1", "2026-Q2", "2026-Q3"], have, set())
|
|
assert "2026-Q2 pricing" in asp.gap_note(pairs)
|
|
con = duckdb.connect(":memory:")
|
|
for q, z in (("2026-Q1", z1), ("2026-Q3", z3)):
|
|
rows, _ = asp.parse_quarter_zip(z, q, source_url="")
|
|
asp.write_asp(con, q, rows)
|
|
assert asp.read_asp(con, quarter="2026-Q2") == []
|
|
assert len(asp.read_asp(con, quarter="2026-Q1")) == 2
|
|
|
|
|
|
# ── a transport-level updated posting lands beside ──────────────────
|
|
def test_updated_posting_lands_beside(root):
|
|
d = root / "cms" / "asp"
|
|
d.mkdir(parents=True)
|
|
old = d / "asp_2026-Q2.zip"
|
|
old.write_bytes(b"old posting")
|
|
dh.manifest(old, "https://cms.test/A.zip")
|
|
link = asp.AspLink("2026-Q2", "pricing", "https://cms.test/B.zip", "t")
|
|
(plan,) = asp.plan_fetch([link], refresh=False)
|
|
assert plan.action == "fetch-beside"
|
|
seen = []
|
|
|
|
def handler(req):
|
|
seen.append(str(req.url))
|
|
return httpx.Response(200, content=b"new posting")
|
|
|
|
cl = httpx.Client(transport=httpx.MockTransport(handler))
|
|
out = asp.apply_plan(cl, plan)
|
|
assert seen == ["https://cms.test/B.zip"]
|
|
assert out != old and out.read_bytes() == b"new posting"
|
|
assert old.read_bytes() == b"old posting"
|
|
urls = [
|
|
json.loads(x)["url"]
|
|
for x in (root / "drugs/MANIFEST.jsonl").read_text().splitlines()
|
|
]
|
|
assert urls == ["https://cms.test/A.zip", "https://cms.test/B.zip"]
|
|
# it is now the newest copy of the quarter
|
|
assert asp.newest_per_quarter(d.glob("asp_*.zip")) == {"2026-Q2": out}
|
|
# a second plan sees B in the manifest
|
|
(again,) = asp.plan_fetch([link], refresh=False)
|
|
assert again.action == "have"
|
|
|
|
|
|
def test_apply_plan_adopt_and_have(root):
|
|
d = root / "cms" / "asp"
|
|
d.mkdir(parents=True)
|
|
f = d / "asp_2026-Q1.zip"
|
|
f.write_bytes(b"q1")
|
|
(root / "cms" / "asp_source_urls.csv").write_text(
|
|
"quarter,url\n2026-Q1,https://cms.test/q1.zip\n"
|
|
)
|
|
link = asp.AspLink("2026-Q1", "pricing", "https://cms.test/q1.zip", "t")
|
|
(plan,) = asp.plan_fetch([link], refresh=False)
|
|
assert plan.action == "adopt"
|
|
boom = httpx.Client(transport=httpx.MockTransport(lambda r: pytest.fail("fetched")))
|
|
assert asp.apply_plan(boom, plan) == f
|
|
rec = json.loads((root / "drugs/MANIFEST.jsonl").read_text())
|
|
assert (
|
|
rec["url"] == "https://cms.test/q1.zip" and "asp_source_urls.csv" in rec["note"]
|
|
)
|
|
(plan2,) = asp.plan_fetch([link], refresh=False)
|
|
assert plan2.action == "have" and asp.apply_plan(boom, plan2) == f
|
|
|
|
|
|
def test_page_hoard(root):
|
|
seen = []
|
|
|
|
def handler(req):
|
|
seen.append(req.headers["user-agent"])
|
|
return httpx.Response(200, content=b"<html>one</html>")
|
|
|
|
cl = httpx.Client(
|
|
headers={"User-Agent": "ua"}, transport=httpx.MockTransport(handler)
|
|
)
|
|
p = asp.fetch_page(cl)
|
|
assert (
|
|
p == root / "drugs/cms/asp-pricing-files.html"
|
|
and p.read_bytes() == b"<html>one</html>"
|
|
)
|
|
assert asp.hoarded_page() == p
|
|
cl2 = httpx.Client(
|
|
transport=httpx.MockTransport(
|
|
lambda r: httpx.Response(200, content=b"<html>two</html>")
|
|
)
|
|
)
|
|
p2 = asp.fetch_page(cl2)
|
|
assert p2 != p and p.read_bytes() == b"<html>one</html>"
|
|
assert asp.hoarded_page() == p2
|
|
assert (
|
|
asp.ASP_PAGE
|
|
== "https://www.cms.gov/medicare/payment/part-b-drugs/asp-pricing-files"
|
|
)
|
|
|
|
|
|
def test_hoarded_page_absent(root):
|
|
assert asp.hoarded_page() is None
|
|
|
|
|
|
# ── tables ───────────────────────────────────────────────────────────
|
|
def test_write_noc_replaces_quarter():
|
|
con = duckdb.connect(":memory:")
|
|
a = T.NocRow("2025-Q4", "A", "1 MG", 1.0, "f", "u", "k")
|
|
b = T.NocRow("2025-Q3", "B", "1 MG", None, "f", "u", "k")
|
|
asp.write_noc(con, "2025-Q4", [a])
|
|
asp.write_noc(con, "2025-Q3", [b])
|
|
asp.write_noc(con, "2025-Q4", [T.NocRow("2025-Q4", "C", "", 2.0, "f", "u", "")])
|
|
assert [r.drug_name for r in asp.read_noc(con)] == ["B", "C"]
|
|
assert [r.drug_name for r in asp.read_noc(con, "2025-Q3")] == ["B"]
|
|
|
|
|
|
def test_2005_style_noc_sheet_inside_the_pricing_workbook(tmp_path):
|
|
noc_grid = [
|
|
["Note"],
|
|
["Drug Name (Generic)", "Dosage", "Payment Limit", "Notes"],
|
|
["Allopurinol Sodium", "500 MG", "455.714", "Revised"],
|
|
["Amikacin Sulfate", "50 MG", "$0.492", ""],
|
|
]
|
|
z = make_zip(tmp_path / "asp_2005-Q1.zip", {"Jan05ASPbyHCPCSv6.xls": b"BIFF"})
|
|
rows, noc = asp.parse_quarter_zip(
|
|
z,
|
|
"2005-Q1",
|
|
source_url="u",
|
|
open_workbook=lambda **kw: _Book(XLS_GRID, [("Jan05_NOC_rev", noc_grid)]),
|
|
)
|
|
assert len(rows) == 3
|
|
assert [(n.drug_name, n.payment_limit) for n in noc] == [
|
|
("Allopurinol Sodium", 455.714),
|
|
("Amikacin Sulfate", 0.492),
|
|
]
|
|
assert noc[0].source_file == "Jan05ASPbyHCPCSv6.xls#NOC"
|
|
# no NOC sheet: no NOC rows
|
|
_, none = asp.parse_quarter_zip(
|
|
z, "2005-Q1", source_url="u", open_workbook=lambda **kw: _Book(XLS_GRID)
|
|
)
|
|
assert none == []
|
|
|
|
|
|
def test_manufacturer_is_stripped(tmp_path):
|
|
body = "HCPCS Code,Long Description,Manufacturer\r\nJ0209,Some drug,\tHope Pharmaceuticals \r\n"
|
|
z = make_zip(tmp_path / "asp_2026-Q4.zip", {"Drugs Not Payable.csv": body})
|
|
(row,), _ = asp.parse_quarter_zip(z, "2026-Q4", source_url="")
|
|
assert row.manufacturer == "Hope Pharmaceuticals" and row.list_kind == "not-payable"
|
|
|
|
|
|
def test_reconcile_copies_chains_reposts(root):
|
|
import os
|
|
|
|
d = root / "cms" / "asp"
|
|
d.mkdir(parents=True)
|
|
a, b = d / "asp_2026-Q2.zip", d / "asp_2026-Q2.fffcdab8.zip"
|
|
a.write_bytes(b"orig")
|
|
b.write_bytes(b"repost")
|
|
os.utime(a, (1_000, 1_000))
|
|
os.utime(b, (2_000, 2_000))
|
|
(d / "asp_2026-Q1.zip").write_bytes(b"alone")
|
|
(d / "noc").mkdir()
|
|
n1, n2 = d / "noc" / "noc_2025-Q4.zip", d / "noc" / "noc_2025-Q4.aaaaaaaa.zip"
|
|
n1.write_bytes(b"1")
|
|
n2.write_bytes(b"2")
|
|
os.utime(n1, (1_000, 1_000))
|
|
os.utime(n2, (2_000, 2_000))
|
|
(root / "cms" / "asp_source_urls.csv").write_text(
|
|
"quarter,url\n2026-Q2,https://cms.test/A.zip\n"
|
|
)
|
|
dh.manifest(b, "https://cms.test/B.zip")
|
|
assert asp.reconcile_copies() == 4
|
|
assert asp.reconcile_copies() == 4
|
|
recs = [
|
|
json.loads(x) for x in (root / "drugs/MANIFEST.jsonl").read_text().splitlines()
|
|
]
|
|
old = next(r for r in recs if r["path"] == "cms/asp/asp_2026-Q2.zip")
|
|
assert old["url"] == "https://cms.test/A.zip"
|
|
assert old["superseded_by"] == "cms/asp/asp_2026-Q2.fffcdab8.zip"
|
|
assert any(r.get("supersedes") == "cms/asp/asp_2026-Q2.zip" for r in recs)
|
|
noc_old = next(r for r in recs if r["path"] == "cms/asp/noc/noc_2025-Q4.zip")
|
|
assert noc_old["url"] == "" and noc_old["superseded_by"].endswith("aaaaaaaa.zip")
|
|
assert asp.manifest_urls() >= {"https://cms.test/A.zip", "https://cms.test/B.zip"}
|
|
assert asp.reconcile_copies({}) == 4
|