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

> Tests for the dashboard's snapshot data, the live feed and the Hugging Face publishing (decisions 0010 and 0013).

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

## What it does

Tests for the dashboard's snapshot data, the live feed and the Hugging Face publishing
(decisions 0010 and 0013).

## What is inside

* **`FakeHub()`** · [line 187](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/tests/test_hosting.py#L187): Stands in for Hugging Face: keeps what each upload would have committed.
* **`FakeHub.create_repo(self)`** · [line 192](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/tests/test_hosting.py#L192)
* **`FakeHub.upload_folder(self, folder_path)`** · [line 195](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/tests/test_hosting.py#L195)
* **`finished_batch(out, batch_id, day)`** · [line 201](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/tests/test_hosting.py#L201)

## What it checks

* trend forecast is the least squares line with a prediction interval (line 18)
* trend forecast needs three years and skips missing ones (line 33)
* yearly paths average the retailers on each window day (line 39)
* event types that share every window are shown once (line 53)
* window day d is scored by the prediction made the day before (line 66)
* published tables never carry prices volumes or raw returns (line 78)
* card templates start with metadata and use known placeholders (line 85)
* every table in the dataset card is parquet (line 99)
* the space is a free static page that embeds the hosted dashboard (line 108)
* a live batch is published without price columns and only when finished (line 114)
* published tables are split by year like the model (line 130)
* a live run is live finished or stopped (line 137)
* only a signed in member with write access publishes (line 152)
* a new run never takes over a run that is streaming (line 174)
* a restarted job carries on its run and uploads what it had left (line 208)
* a job killed before finishing is marked stopped not complete (line 234)
* the runner name can be set for the cloud streamer (line 251)
* the cloud streamers copy holds what the demo needs and nothing else (line 257)

## Connections

**Uses:** [`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), [`src/hosting/live.py`](https://calendar-effects.mintlify.site/reference/src/hosting/live), [`src/hosting/publish_hf.py`](https://calendar-effects.mintlify.site/reference/src/hosting/publish_hf), [`src/hosting/snapshot.py`](https://calendar-effects.mintlify.site/reference/src/hosting/snapshot), [`src/hosting/__init__.py`](https://calendar-effects.mintlify.site/reference/src/hosting/init)

## Source

```python title="tests/test_hosting.py" lines expandable theme={null}
"""Tests for the dashboard's snapshot data, the live feed and the Hugging Face publishing
(decisions 0010 and 0013)."""
import string
from datetime import date

import numpy as np
import pandas as pd
import pytest
from scipy import stats

from common.settings import CARDS_DIR, DASHBOARD_URL, SITE_DIR, STREAM_SUBDIRS
from common.study import ML_TEST_START_YEAR, ML_TRAIN_END_YEAR, ML_VALIDATION_YEAR
from hosting.live import stage_batch
from hosting.publish_hf import NOT_PUBLISHED, by_split, public
from hosting.snapshot import DAYS, distinct_event_types, model_by_day, trend_forecast, yearly_paths


def test_trend_forecast_is_the_least_squares_line_with_a_prediction_interval():
    years = np.arange(2016, 2026)
    values = 0.01 * (years - 2016) + np.array([0.02, -0.01, 0.0, 0.015, -0.02, 0.01, 0.0, -0.005, 0.01, 0.0])
    f = trend_forecast(years, values, 2026, confidence=0.95)
    fit = stats.linregress(years, values)
    assert f["slope"] == pytest.approx(fit.slope)
    assert f["mid"] == pytest.approx(fit.intercept + fit.slope * 2026)
    # The prediction interval (one new year) is wider than the line's own confidence band.
    s = np.sqrt(((values - (fit.intercept + fit.slope * years)) ** 2).sum() / 8)
    sxx = ((years - years.mean()) ** 2).sum()
    half = stats.t.ppf(0.975, 8) * s * np.sqrt(1 + 1 / 10 + (2026 - years.mean()) ** 2 / sxx)
    assert f["hi"] - f["mid"] == pytest.approx(half)
    assert f["mid"] - f["lo"] == pytest.approx(half)


def test_trend_forecast_needs_three_years_and_skips_missing_ones():
    assert trend_forecast([2024, 2025], [0.1, 0.2], 2026) is None
    f = trend_forecast([2022, 2023, 2024, 2025], [0.0, np.nan, 0.2, 0.3], 2026)
    assert f["n"] == 3


def test_yearly_paths_average_the_retailers_on_each_window_day():
    rows = []
    for ticker, shift in (("AAA", 0.0), ("BBB", 0.02)):
        for d in DAYS:
            rows.append({"event_type": "x", "day0_date": date(2024, 11, 29), "ticker": ticker, "day": d,
                         "car": 0.001 * (d - DAYS[0]) + shift})
    paths = pd.DataFrame(rows)
    out = yearly_paths(paths)
    assert out["year"].tolist() == [2024] and out["n_tickers"].tolist() == [2]
    assert out[str(DAYS[-1])].iloc[0] == pytest.approx(0.001 * (DAYS[-1] - DAYS[0]) + 0.01)
    only_b = yearly_paths(paths, {"BBB"})
    assert only_b[str(DAYS[0])].iloc[0] == pytest.approx(0.02)


def test_event_types_that_share_every_window_are_shown_once(monkeypatch):
    import hosting.snapshot as snapshot
    monkeypatch.setattr(snapshot, "load_event_types", lambda in_scope_only=False: [
        {"event_type": "holiday"}, {"event_type": "sale"}, {"event_type": "other"}])
    cars = pd.DataFrame([
        # The holiday is a market holiday, so its day 0 is the next day: the sale's date.
        {"event_type": "holiday", "event_date": "2024-11-28", "day0_date": "2024-11-29"},
        {"event_type": "sale", "event_date": "2024-11-29", "day0_date": "2024-11-29"},
        {"event_type": "other", "event_date": "2024-10-31", "day0_date": "2024-10-31"},
    ])
    assert distinct_event_types(cars) == [("sale", ["holiday"]), ("other", [])]


def test_window_day_d_is_scored_by_the_prediction_made_the_day_before():
    days = list(pd.bdate_range("2024-11-18", periods=20))
    day0 = days[9]
    cars = pd.DataFrame([{"event_type": "sale", "ticker": "AAA", "day0_date": day0}])
    test = pd.DataFrame({"ticker": "AAA", "date": days, "flag": [int(i == 8) for i in range(20)],
                         "big_move_next": [int(i == 12) for i in range(20)]})
    out = model_by_day(cars, test, days).set_index("day")
    assert out.loc[0, "flag"] == 1          # flagged on day -1, about day 0
    assert out.loc[4, "y"] == 1             # the row of day +3 says day +4 was a big move
    assert len(out) == len(DAYS)


def test_published_tables_never_carry_prices_volumes_or_raw_returns():
    df = pd.DataFrame(columns=["ticker", "date", "ret", "mkt_ret", "vol_ratio", "timestamp_utc", "ar", "z_ar", "views"])
    assert not NOT_PUBLISHED & set(public(df).columns)
    assert {"ar", "z_ar", "views"} <= set(public(df).columns)


@pytest.mark.parametrize("card", ["dataset.md", "model.md", "space.md"])
def test_card_templates_start_with_metadata_and_use_known_placeholders(card):
    text = (CARDS_DIR / card).read_text()
    assert text.startswith("---\n")
    fields = {name for _, name, _, _ in string.Formatter().parse(text) if name}
    known = {"dataset_repo", "model_repo", "space_repo", "n_retailers", "n_online", "n_store", "first_year",
             "last_year", "forecast_year", "event_names", "estimation_days", "gap_days", "market",
             "attention_days", "abnormal_z", "spike_z", "alert_share", "alert_cutoff", "store_all_car",
             "store_all_p", "auc_roc", "precision_top", "base_rate", "lift_top", "test_years", "fit_years",
             "params", "features", "n_features", "spark_version", "metrics_table", "importance_table",
             "built", "code_version", "n_signals", "n_windows", "n_predictions", "n_test", "n_summary", "n_trend",
             "dashboard_url", "docs_url", "fit_years_train", "validation_year"}
    assert fields <= known, fields - known


def test_every_table_in_the_dataset_card_is_parquet():
    # The dataset viewer reads all of a repository's tables with one reader: a CSV among
    # Parquet files shows as an error there (it did for event_summary and event_trend).
    import yaml
    card = yaml.safe_load((CARDS_DIR / "dataset.md").read_text().split("---")[1])
    paths = [f["path"] for c in card["configs"] for f in c["data_files"]]
    assert paths and all(p.endswith(".parquet") for p in paths), paths


def test_the_space_is_a_free_static_page_that_embeds_the_hosted_dashboard():
    assert "sdk: static" in (CARDS_DIR / "space.md").read_text()
    page = (SITE_DIR / "index.html").read_text()
    assert f'src="{DASHBOARD_URL}/?embed=true' in page


def test_a_live_batch_is_published_without_price_columns_and_only_when_finished(tmp_path):
    out, staging = tmp_path / "stream", tmp_path / "staging"
    signals = out / STREAM_SUBDIRS["stream_signals"] / "batch_id=3"
    signals.mkdir(parents=True)
    pd.DataFrame({"ticker": ["WMT"], "date": ["2024-11-29"], "ret": [0.01], "mkt_ret": [0.002],
                  "vol_ratio": [1.4], "ar": [0.008]}).to_parquet(signals / "part-0.parquet")
    (signals / "_SUCCESS").touch()
    half = out / STREAM_SUBDIRS["stream_event_car"] / "batch_id=3"      # Spark still writing it
    half.mkdir(parents=True)
    assert stage_batch(out, 3, staging, "run1") == 1
    published = staging / "runs" / "run1" / STREAM_SUBDIRS["stream_signals"] / "batch_id=3"
    assert (published / "_SUCCESS").exists()
    assert set(pd.read_parquet(published / "part-0.parquet").columns) == {"ticker", "date", "ar"}
    assert not (staging / "runs" / "run1" / STREAM_SUBDIRS["stream_event_car"]).exists()


def test_published_tables_are_split_by_year_like_the_model():
    years = [ML_TRAIN_END_YEAR - 1, ML_TRAIN_END_YEAR, ML_VALIDATION_YEAR, ML_TEST_START_YEAR, ML_TEST_START_YEAR + 1]
    df = pd.DataFrame({"date": [f"{y}-06-01" for y in years]})
    parts = by_split(df)
    assert [len(parts[k]) for k in ("train", "validation", "test")] == [2, 1, 2]


def test_a_live_run_is_live_finished_or_stopped():
    from datetime import datetime, timedelta, timezone

    from hosting.live import QUIET_SECONDS, run_state

    def ago(seconds):
        return (datetime.now(timezone.utc) - timedelta(seconds=seconds)).isoformat(timespec="seconds")

    assert run_state(None) == "none"
    assert run_state({"run_id": "r", "updated_utc": ago(10), "finished": False}) == "live"
    assert run_state({"run_id": "r", "updated_utc": ago(QUIET_SECONDS + 60), "finished": False}) == "stopped"
    assert run_state({"run_id": "r", "updated_utc": ago(10), "finished": True}) == "finished"
    assert run_state({"run_id": "r", "updated_utc": ago(10)}) == "live"     # runs published before 'finished' existed


def test_only_a_signed_in_member_with_write_access_publishes(monkeypatch):
    import huggingface_hub

    from hosting.live import publish_check

    def login(me):
        monkeypatch.setattr(huggingface_hub.HfApi, "whoami", lambda self: me)

    def no_login(self):
        raise OSError("not logged in")

    monkeypatch.setattr(huggingface_hub.HfApi, "whoami", no_login)
    assert publish_check("team/live")[0] is False
    token = {"auth": {"accessToken": {"role": "write"}}}
    login({**token, "name": "mahad", "orgs": [{"name": "team", "roleInOrg": "admin"}]})
    assert publish_check("team/live") == (True, "mahad")
    login({**token, "name": "stranger", "orgs": []})
    assert publish_check("team/live")[0] is False
    login({"auth": {"accessToken": {"role": "read"}}, "name": "mahad", "orgs": [{"name": "team", "roleInOrg": "admin"}]})
    assert publish_check("team/live")[0] is False


def test_a_new_run_never_takes_over_a_run_that_is_streaming():
    from datetime import datetime, timezone

    from hosting.live import takes_over

    now = datetime.now(timezone.utc).isoformat(timespec="seconds")
    streaming = {"run_id": "demo", "updated_utc": now, "finished": False}
    assert takes_over(None, "test") is True                                 # nothing published yet
    assert takes_over(streaming, "test") is False                           # a demo is streaming
    assert takes_over(streaming, "demo") is True                            # the demo itself carries on
    assert takes_over({**streaming, "finished": True}, "test") is True      # the demo has ended


class FakeHub:
    """Stands in for Hugging Face: keeps what each upload would have committed."""
    def __init__(self):
        self.commits = []

    def create_repo(self, *a, **k):
        pass

    def upload_folder(self, folder_path, **k):
        from pathlib import Path
        files = {str(p.relative_to(folder_path)): p.read_bytes() for p in Path(folder_path).rglob("*") if p.is_file()}
        self.commits.append(files)


def finished_batch(out, batch_id, day):
    folder = out / STREAM_SUBDIRS["stream_signals"] / f"batch_id={batch_id}"
    folder.mkdir(parents=True)
    pd.DataFrame({"ticker": ["WMT"], "date": [pd.Timestamp(day)], "ar": [0.0]}).to_parquet(folder / "part-0.parquet")
    (folder / "_SUCCESS").touch()


def test_a_restarted_job_carries_on_its_run_and_uploads_what_it_had_left(tmp_path, monkeypatch):
    import json
    import huggingface_hub
    from hosting import live
    hub = FakeHub()
    monkeypatch.setattr(huggingface_hub, "HfApi", lambda: hub)
    monkeypatch.setattr(live.LivePublisher, "current", lambda self: None)     # no other run streaming
    out = tmp_path / "stream"
    finished_batch(out, 0, "2024-01-05")

    first = live.LivePublisher(out, resume=True, background=False)          # nothing saved: a new run
    first.add(0)
    first.push()
    finished_batch(out, 1, "2024-01-12")    # finished, but the job is stopped before uploading it
    assert first.published == 1 and json.loads((out / live.STATE).read_text())["last_batch"] == 0

    again = live.LivePublisher(out, resume=True, background=False)
    assert again.run_id == first.run_id and again.pending == [1]
    again.close(complete=True)
    current = json.loads(hub.commits[-1][live.CURRENT])
    assert current["batches"] == 2 and current["reached"] == "2024-01-12"
    assert current["finished"] and current["complete"]
    assert f"runs/{first.run_id}/{STREAM_SUBDIRS['stream_signals']}/batch_id=1/_SUCCESS" in hub.commits[-1]
    assert live.finish(out) == "live feed: nothing to finish"               # it already finished itself


def test_a_job_killed_before_finishing_is_marked_stopped_not_complete(tmp_path, monkeypatch):
    import json
    import huggingface_hub
    from hosting import live
    hub = FakeHub()
    monkeypatch.setattr(huggingface_hub, "HfApi", lambda: hub)
    monkeypatch.setattr(live.LivePublisher, "current", lambda self: None)
    out = tmp_path / "stream"
    finished_batch(out, 0, "2024-01-05")
    run = live.LivePublisher(out, background=False)
    run.add(0)
    run.push()                                # then the job is killed: no close()
    assert "marked finished" in live.finish(out)
    current = json.loads(hub.commits[-1][live.CURRENT])
    assert current["finished"] and not current["complete"]


def test_the_runner_name_can_be_set_for_the_cloud_streamer(monkeypatch):
    from hosting import live
    monkeypatch.setenv(live.RUNNER_ENV, "the cloud streamer")
    assert live.runner_name() == "the cloud streamer"


def test_the_cloud_streamers_copy_holds_what_the_demo_needs_and_nothing_else(tmp_path):
    import subprocess
    from common.settings import REPO_ROOT
    subprocess.run([str(REPO_ROOT / "scripts" / "sync_live_stream.sh"), "--into", str(tmp_path)], check=True)
    copied = {p.relative_to(tmp_path).parts[0] for p in tmp_path.iterdir()}
    assert copied == {"src", "config", "clean", "scripts", "requirements.txt", "pyproject.toml"}
    for needed in ("src/streaming/job.py", "src/producers/replay_to_files.py", "src/hosting/live.py",
                   "clean/master.parquet", "scripts/demo_live.sh", "config/retailers.csv"):
        assert (tmp_path / needed).exists(), needed
    assert [p.name for p in (tmp_path / "clean").iterdir()] == ["master.parquet"]
    assert [p.name for p in (tmp_path / "scripts").iterdir()] == ["demo_live.sh"]
```


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