"""Previous-day bars are cached per symbol for one hour (REQ-10). Each `/api/chart/ohlc` miss fetched the prev-day window again, so a timeframe switch cost one Yahoo `1d/1mo` call every time. The prev-day window changes once per session, so a successful read is cached for an hour under `chart-prevday:SYM`. A failed read or an empty one is not cached, so the next miss retries. The Yahoo boundary is faked and counted; no network. """ import asyncio import pytest from core import ohlc from core.shared.cache import cache_clear DAILY = { "chart": { "result": [ { "timestamp": [1_700_000_000, 1_700_086_400], "indicators": { "quote": [ { "open": [10.0, 11.0], "high": [12.0, 13.0], "low": [9.0, 10.0], "close": [11.0, 12.0], "volume": [100, 200], } ] }, } ] } } @pytest.fixture def yahoo(monkeypatch): calls: list[tuple[str, dict]] = [] state = {"reply": DAILY} async def fake_yahoo(symbol, params): calls.append((symbol, dict(params))) return state["reply"] monkeypatch.setattr(ohlc, "fetch_yahoo_chart_json", fake_yahoo) cache_clear() yield calls, state cache_clear() def _daily_calls(calls, symbol): return [c for c in calls if c[0] == symbol and c[1].get("range") == "1mo"] def test_second_prev_day_read_of_a_symbol_is_served_from_cache(yahoo) -> None: calls, _ = yahoo first = asyncio.run(ohlc.fetch_daily_bars("AAPL")) second = asyncio.run(ohlc.fetch_daily_bars("AAPL")) assert len(_daily_calls(calls, "AAPL")) == 1 assert second == first assert len(first) == 2 def test_cache_is_per_symbol(yahoo) -> None: calls, _ = yahoo asyncio.run(ohlc.fetch_daily_bars("AAPL")) asyncio.run(ohlc.fetch_daily_bars("MSFT")) assert len(_daily_calls(calls, "AAPL")) == 1 assert len(_daily_calls(calls, "MSFT")) == 1 def test_an_empty_read_is_not_cached(yahoo) -> None: calls, state = yahoo state["reply"] = {"chart": {"result": []}} assert asyncio.run(ohlc.fetch_daily_bars("ZZZZ")) == [] assert asyncio.run(ohlc.fetch_daily_bars("ZZZZ")) == [] assert len(_daily_calls(calls, "ZZZZ")) == 2 def test_a_failed_read_is_not_cached(yahoo) -> None: calls, state = yahoo state["reply"] = None assert asyncio.run(ohlc.fetch_daily_bars("AAPL")) == [] state["reply"] = DAILY assert len(asyncio.run(ohlc.fetch_daily_bars("AAPL"))) == 2 assert len(_daily_calls(calls, "AAPL")) == 2