> ## Documentation Index
> Fetch the complete documentation index at: https://calendar-effects.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# tests/test_contracts.py

> 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.

`tests/test_contracts.py` · chapter [Tests and team tooling](https://calendar-effects.mintlify.site/tour/10-tests-and-tooling.md), file 1 · 88 lines · [open in the repository](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/tests/test_contracts.py)

## What it does

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.

## What is inside

* **`DOC`** · [line 21](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/tests/test_contracts.py#L21)
* **`BLOCK`** · [line 22](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/tests/test_contracts.py#L22)
* **`ROW`** · [line 23](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/tests/test_contracts.py#L23)
* **`doc_contracts()`** · [line 26](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/tests/test_contracts.py#L26)

## What it checks

* docs and code define the same datasets (line 31)
* docs and code agree column by column (line 35)
* only known types are used (line 44)
* check columns accepts an exact match (line 50)
* check columns reports missing wrong and extra columns (line 54)
* require contract raises with every problem (line 62)
* pandas columns reads types as parquet will store them (line 67)
* parquet columns reads a spark style folder as stored (line 80)

## Connections

**Uses:** [`src/common/contracts.py`](https://calendar-effects.mintlify.site/reference/src/common/contracts)

## Source

```python title="tests/test_contracts.py" lines expandable theme={null}
"""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"]
```


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.