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

> Tests for the dashboard (decisions 0008 and 0013): it reads only finished micro-batches, and every view runs without errors, on a laptop and hosted (where there is no local stream).

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

## What it does

Tests for the dashboard (decisions 0008 and 0013): it reads only finished micro-batches, and every
view runs without errors, on a laptop and hosted (where there is no local stream).

## What is inside

* **`APP`** · [line 9](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/tests/test_dashboard.py#L9)
* **`write_batch(folder, batch_id, rows, finished)`** · [line 12](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/tests/test_dashboard.py#L12)
* **`app(monkeypatch)`** · [line 35](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/tests/test_dashboard.py#L35)

## What it checks

* only finished batches are read in batch order (line 20)
* a missing output reads as empty (line 30)
* the live view explains what to do before any output (line 41)
* the live view waits for a published run when offline (line 51)
* the hosted app offers published runs only (line 60)
* every view runs from the committed snapshot (line 70)
* the replay plays the years picked and warns about training years (line 80)
* the retailer type filter applies to every count and a followed retailer gets charts (line 94)
* a changed snapshot is read again not served from the cache (line 109)
* a changed project module is reloaded with the rest (line 120)

## Connections

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

## Source

```python title="tests/test_dashboard.py" lines expandable theme={null}
"""Tests for the dashboard (decisions 0008 and 0013): it reads only finished micro-batches, and every
view runs without errors, on a laptop and hosted (where there is no local stream)."""
import pandas as pd
import pytest

from common.settings import REPO_ROOT, STREAM_SUBDIRS
from dashboard.app import REPLAY, read_stream

APP = str(REPO_ROOT / "src" / "dashboard" / "app.py")


def write_batch(folder, batch_id, rows, finished=True):
    path = folder / f"batch_id={batch_id}"
    path.mkdir(parents=True)
    pd.DataFrame(rows).to_parquet(path / "part-0.parquet", index=False)
    if finished:
        (path / "_SUCCESS").touch()


def test_only_finished_batches_are_read_in_batch_order(tmp_path):
    folder = tmp_path / STREAM_SUBDIRS["stream_signals"]
    write_batch(folder, 10, [{"ticker": "WMT", "date": "2024-11-29"}])
    write_batch(folder, 2, [{"ticker": "WMT", "date": "2024-11-27"}])
    write_batch(folder, 11, [{"ticker": "WMT", "date": "2024-12-02"}], finished=False)  # Spark still writing
    df = read_stream("stream_signals", tmp_path)
    assert list(df["date"].dt.strftime("%Y-%m-%d")) == ["2024-11-27", "2024-11-29"]
    assert df.attrs["batches"] == 2


def test_a_missing_output_reads_as_empty(tmp_path):
    assert read_stream("stream_predictions", tmp_path).empty


@pytest.fixture
def app(monkeypatch):
    from streamlit.testing.v1 import AppTest
    monkeypatch.setenv("CALENDAR_EFFECTS_OFFLINE", "1")          # no network in tests
    return AppTest.from_file(APP, default_timeout=60)


def test_the_live_view_explains_what_to_do_before_any_output(app, tmp_path):
    from dashboard.app import LOCAL
    at = app.run()
    at.radio[0].set_value("Live stream").run()
    next(r for r in at.radio if r.label == "Show").set_value(LOCAL).run()
    at.text_input[0].set_value(str(tmp_path)).run()   # an empty stream folder
    assert not at.exception
    assert any("No streaming output" in i.value and "demo_live.sh --private" in i.value for i in at.info)


def test_the_live_view_waits_for_a_published_run_when_offline(app):
    from dashboard.app import PUBLISHED
    at = app.run()
    at.radio[0].set_value("Live stream").run()
    next(r for r in at.radio if r.label == "Show").set_value(PUBLISHED).run()
    assert not at.exception
    assert any("No live run is being published" in i.value for i in at.info)


def test_the_hosted_app_offers_published_runs_only(app, monkeypatch):
    monkeypatch.setenv("CALENDAR_EFFECTS_HOSTED", "1")      # as on Streamlit Community Cloud: no job can run there
    at = app.run()
    at.radio[0].set_value("Live stream").run()
    assert not at.exception
    assert not [r for r in at.radio if r.label == "Show"] and not at.text_input
    assert any("No live run is being published" in i.value for i in at.info)


@pytest.mark.parametrize("view", [REPLAY, "Event history & forecast", "About"])
def test_every_view_runs_from_the_committed_snapshot(app, view):
    at = app.run()
    at.radio[0].set_value(view).run()
    assert not at.exception, at.exception
    if view == REPLAY:
        assert any(m.label == "Stream has reached" for m in at.metric)
    if view == "Event history & forecast":
        assert any("forecast" in m.label for m in at.metric)


def test_the_replay_plays_the_years_picked_and_warns_about_training_years(app):
    from common.study import ML_TEST_START_YEAR
    at = app.run()
    at.radio[0].set_value(REPLAY).run()
    years = next(s for s in at.select_slider if s.label == "Years to replay")
    assert years.value[0] == ML_TEST_START_YEAR and not at.warning   # by default: the model's test years
    early = years.options[0]
    years.set_value((early, early)).run()
    assert not at.exception, at.exception
    reached = next(m for m in at.metric if m.label == "Stream has reached")
    assert reached.value.endswith(str(early))                        # the replay restarted at that year
    assert any("not a fair test" in w.value for w in at.warning)


def test_the_retailer_type_filter_applies_to_every_count_and_a_followed_retailer_gets_charts(app):
    at = app.run()
    at.radio[0].set_value(REPLAY).run()
    from dashboard.app import snapshot
    at.session_state["replay_day"] = len(snapshot("replay")["days"]) - 1     # jump to the last day
    at.run()
    closed = lambda: int(next(m for m in at.metric if m.label == "Event windows closed").value)
    both = closed()
    next(m for m in at.multiselect if m.label == "Retailer type").set_value(["online"]).run()
    assert 0 < closed() < both
    next(s for s in at.selectbox if s.label == "Retailer to follow").set_value("AMZN").run()
    assert not at.exception, at.exception
    assert any("AMZN" in h.value for h in at.subheader)


def test_a_changed_snapshot_is_read_again_not_served_from_the_cache(tmp_path, monkeypatch):
    import os
    import dashboard.app as app
    monkeypatch.setattr(app, "SNAPSHOT_DIR", tmp_path)
    (tmp_path / "x.json").write_text('{"v": 1}')
    assert app.snapshot("x") == {"v": 1}
    (tmp_path / "x.json").write_text('{"v": 2}')              # a redeploy replaces the file
    os.utime(tmp_path / "x.json", (1, 1))
    assert app.snapshot("x") == {"v": 2}


def test_a_changed_project_module_is_reloaded_with_the_rest(tmp_path, monkeypatch):
    import importlib
    import sys
    import time

    from dashboard import reloader

    pkg = tmp_path / "ceproj"
    pkg.mkdir()
    (pkg / "__init__.py").write_text("")
    (pkg / "settings.py").write_text("VALUE = 1\n")
    monkeypatch.syspath_prepend(str(tmp_path))
    settings = importlib.import_module("ceproj.settings")
    reloader.refresh(("ceproj",))                       # first look: loads and remembers
    assert reloader.refresh(("ceproj",)) == []          # nothing changed
    time.sleep(0.01)
    (pkg / "settings.py").write_text("VALUE = 2\n")     # a redeploy changes the file
    import os
    os.utime(pkg / "settings.py", (time.time() + 5, time.time() + 5))
    assert "ceproj.settings" in reloader.refresh(("ceproj",))
    assert sys.modules["ceproj.settings"].VALUE == 2
```


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