"""The written contracts (docs/data-contracts.md) and the code (src/common/contracts.py)
must always describe the same schemas. If one changes without the other, these tests fail."""
from __future__ import annotations
import re
from datetime import date
from pathlib import Path
import pandas as pd
import pytest
from common.contracts import (
ALLOWED_TYPES,
CONTRACTS,
check_columns,
pandas_columns,
parquet_columns,
require_contract,
)
DOC = Path(__file__).resolve().parents[1] / "docs" / "data-contracts.md"
BLOCK = re.compile(r"<!-- contract:(\w+) -->(.*?)<!-- /contract -->", re.S)
ROW = re.compile(r"^\|\s*`([^`]+)`\s*\|\s*([a-z]+)\s*\|", re.M)
def doc_contracts() -> dict[str, dict[str, str]]:
text = DOC.read_text(encoding="utf-8")
return {name: dict(ROW.findall(body)) for name, body in BLOCK.findall(text)}
def test_docs_and_code_define_the_same_datasets():
assert set(doc_contracts()) == set(CONTRACTS)
def test_docs_and_code_agree_column_by_column():
docs = doc_contracts()
for name, columns in CONTRACTS.items():
assert docs[name] == columns, (
f"{name}: docs/data-contracts.md says {docs[name]}, "
f"src/common/contracts.py says {columns}"
)
def test_only_known_types_are_used():
for name, columns in CONTRACTS.items():
unknown = set(columns.values()) - ALLOWED_TYPES
assert not unknown, f"{name} uses unknown types {unknown}"
def test_check_columns_accepts_an_exact_match():
assert check_columns("pageviews", dict(CONTRACTS["pageviews"])) == []
def test_check_columns_reports_missing_wrong_and_extra_columns():
actual = {"article": "string", "ticker": "string", "date": "string", "clicks": "long"}
problems = check_columns("pageviews", actual)
assert any("missing column 'views'" in p for p in problems)
assert any("'date' is string" in p for p in problems)
assert any("unexpected column 'clicks'" in p for p in problems)
def test_require_contract_raises_with_every_problem():
with pytest.raises(ValueError, match="missing column 'views'"):
require_contract("pageviews", {"article": "string", "ticker": "string", "date": "date"})
def test_pandas_columns_reads_types_as_parquet_will_store_them():
df = pd.DataFrame({
"article": ["Best_Buy"], "ticker": ["BBY"],
"date": [date(2024, 11, 29)], "views": pd.Series([1200], dtype="int32"),
})
assert pandas_columns(df) == CONTRACTS["pageviews"]
# A pandas datetime column is a timestamp, not a date, so it fails a date contract.
as_timestamp = df.assign(date=pd.to_datetime(df["date"]))
assert check_columns("pageviews", pandas_columns(as_timestamp)) == [
"pageviews: column 'date' is timestamp, contract says date"
]
def test_parquet_columns_reads_a_spark_style_folder_as_stored(tmp_path):
# An int column with a null is stored as int, though pandas would read it as double.
for batch in (0, 1):
(tmp_path / f"batch_id={batch}").mkdir()
pd.DataFrame({"article": ["Best_Buy"], "ticker": ["BBY"], "date": [date(2024, 11, 29)],
"views": pd.Series([None if batch else 1200], dtype="Int32")}
).to_parquet(tmp_path / f"batch_id={batch}" / "part-0.parquet", index=False)
(tmp_path / "_SUCCESS").write_text("")
assert parquet_columns(tmp_path) == CONTRACTS["pageviews"]