> ## 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_clean_files.py

> The committed clean files (clean/*.parquet) must match their contracts and what config/ and common.study say should be in them. A file that is out of date, such as a retailer added to config/retailers.csv without re-running the ETL, fails here with the script to re-run.

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

## What it does

The committed clean files (clean/\*.parquet) must match their contracts and what
config/ and common.study say should be in them. A file that is out of date, such as
a retailer added to config/retailers.csv without re-running the ETL, fails here with
the script to re-run.

## What is inside

* **`EDGE`** · [line 24](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/tests/test_clean_files.py#L24): Markets close for at most a few days in a row, so real data reaches this close to both ends of the study period; data from an older, shorter period does not.
* **`REDOWNLOAD`** · [line 25](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/tests/test_clean_files.py#L25)
* **`read(dataset)`** · [line 28](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/tests/test_clean_files.py#L28)

## What it checks

* clean file matches its contract (line 33)
* prices cover the in scope retailers and the market index (line 38)
* pageviews cover every in scope retailer on every day (line 48)
* retail sales cover every series in every month (line 66)
* master has one row per price row (line 75)
* master labels exactly the calendar events on trading days (line 83)

## Connections

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

## Source

```python title="tests/test_clean_files.py" lines expandable theme={null}
"""The committed clean files (clean/*.parquet) must match their contracts and what
config/ and common.study say should be in them. A file that is out of date, such as
a retailer added to config/retailers.csv without re-running the ETL, fails here with
the script to re-run."""
from __future__ import annotations

from datetime import timedelta

import pandas as pd
import pytest

from common.contracts import (
    check_columns,
    expand_events,
    load_retail_series,
    parquet_columns,
    price_tickers,
)
from common.settings import clean_path
from common.study import MARKET_TICKER, STUDY_END, STUDY_END_YEAR, STUDY_START, STUDY_START_YEAR

# Markets close for at most a few days in a row, so real data reaches this close to
# both ends of the study period; data from an older, shorter period does not.
EDGE = timedelta(days=7)
REDOWNLOAD = "common.study's period changed? Delete raw/prices/ and raw/wiki/ and re-run the ETL"


def read(dataset: str) -> pd.DataFrame:
    return pd.read_parquet(clean_path(dataset))


@pytest.mark.parametrize("dataset", ["prices", "pageviews", "retail_sales", "master"])
def test_clean_file_matches_its_contract(dataset):
    problems = check_columns(dataset, parquet_columns(clean_path(dataset)))
    assert not problems, f"clean/{dataset}.parquet: {problems}"


def test_prices_cover_the_in_scope_retailers_and_the_market_index():
    prices = read("prices")
    assert set(prices["ticker"]) == set(price_tickers()), (
        "config/retailers.csv changed: re-run etl/prices_download.py, etl/prices_clean.py, etl/join_master.py"
    )
    assert not prices.duplicated(["ticker", "date"]).any()
    assert STUDY_START <= prices["date"].min() and prices["date"].max() <= STUDY_END
    assert prices["date"].min() <= STUDY_START + EDGE and prices["date"].max() >= STUDY_END - EDGE, REDOWNLOAD


def test_pageviews_cover_every_in_scope_retailer_on_every_day():
    views = read("pageviews")
    retailers = set(price_tickers()) - {MARKET_TICKER}
    assert set(views["ticker"]) == retailers, (
        "config/retailers.csv or config/wiki_articles.csv changed: re-run etl/pageviews_download.py, "
        "etl/pageviews_clean.py, etl/join_master.py"
    )
    days = (STUDY_END - STUDY_START).days + 1
    per_ticker = views.groupby("ticker")["date"].agg(["nunique", "min", "max"])
    assert (per_ticker["nunique"] == days).all()
    assert (per_ticker["min"] == STUDY_START).all() and (per_ticker["max"] == STUDY_END).all()
    # pageviews_clean.py fills days with no data with 0, so a stale download shows up as
    # empty edges of the period rather than as missing rows.
    first = views[views["date"] < STUDY_START + EDGE]["views"].sum()
    last = views[views["date"] > STUDY_END - EDGE]["views"].sum()
    assert first > 0 and last > 0, REDOWNLOAD


def test_retail_sales_cover_every_series_in_every_month():
    sales = read("retail_sales")
    assert set(sales["category"]) == {s["category"] for s in load_retail_series()}, (
        "config/retail_series.csv changed: download the series and re-run etl/retail_clean.py"
    )
    months = (STUDY_END.year - STUDY_START.year) * 12 + STUDY_END.month - STUDY_START.month + 1
    assert (sales.groupby("category")["month"].nunique() == months).all()


def test_master_has_one_row_per_price_row():
    prices, master = read("prices"), read("master")
    keys = ["ticker", "date"]
    assert master[keys].sort_values(keys).reset_index(drop=True).equals(
        prices[keys].sort_values(keys).reset_index(drop=True)
    ), "re-run etl/join_master.py"


def test_master_labels_exactly_the_calendar_events_on_trading_days():
    master = read("master")
    trading_days = set(master["date"])
    expected = {(d.date(), e["event_type"])
                for e in expand_events(STUDY_START_YEAR, STUDY_END_YEAR)
                for d in pd.date_range(e["event_date"], e["event_end_date"])
                if d.date() in trading_days}
    labelled = master.dropna(subset=["event_type"])
    actual = set(zip(labelled["date"], labelled["event_type"]))
    assert actual == expected, (
        "config/event_types.csv or config/event_dates.csv changed: re-run etl/join_master.py "
        f"(missing {sorted(expected - actual)[:3]}, unexpected {sorted(actual - expected)[:3]})"
    )
```


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