"""Contract suite for every frontend-consumed endpoint (plan TEST-T2). Two layers: - ``TestFrontendContract`` pins the registration surface: every /api path the frontend calls must exist in the OpenAPI schema with the method the client uses (and a declared response model where the backend declares one). This is the 404-guard from test_chart_route_registration.py generalized to the whole frontend surface. - ``TestLiveContracts``/``TestValidationErrors`` drive real requests through the FastAPI app: success shape, validation errors, and provider-timeout/error fallback. All I/O is monkeypatched (SQLite lives on a tmp_path via core.shared.db.DB_PATH, providers are stubs), so the suite is hermetic and xdist-safe. """ import json import threading import time from datetime import date, timedelta from pathlib import Path import pandas as pd import pytest from fastapi.testclient import TestClient import core.shared.db as db from app.main import app from core.domain.schemas import DiscoverPatternRequest def _collect_api_routes() -> dict[tuple[str, str], set[str]]: """path -> methods for every /api route, recursing included routers.""" from fastapi.routing import APIRoute, _IncludedRouter seen: dict[str, set[str]] = {} def collect(routes: list) -> None: for route in routes: if isinstance(route, APIRoute): seen.setdefault(route.path, set()).update(route.methods) elif isinstance(route, _IncludedRouter): collect(route.include_context.included_router.routes) elif hasattr(route, "routes"): collect(route.routes) collect(list(app.routes)) for router in app.routes: if isinstance(router, _IncludedRouter): collect(router.include_context.included_router.routes) return seen API_ROUTES = _collect_api_routes() def _collect_ws_routes() -> set[str]: """Every registered WebSocket path (APIWebSocketRoute carries the full prefixed path; monitor's /{source} wildcard covers the feed sources).""" from fastapi.routing import _IncludedRouter seen: set[str] = set() def collect(routes: list) -> None: for route in routes: name = type(route).__name__ if "WebSocketRoute" in name and getattr(route, "path", None): seen.add(route.path) elif isinstance(route, _IncludedRouter): collect(route.include_context.included_router.routes) elif hasattr(route, "routes"): collect(route.routes) collect(list(app.routes)) for router in app.routes: if isinstance(router, _IncludedRouter): collect(router.include_context.included_router.routes) return seen WS_ROUTES = _collect_ws_routes() def _frontend_paths() -> dict[str, set[str]]: """Extract every /api/... URL the frontend references. Regexes over the TS sources keep the suite maintenance-free: a new fetch in static/js adds itself to the contract. URLs are normalized to registered shapes before comparison: - query strings (``?a=${x}``) are dropped — parameter contracts live on the endpoint, not the client URL; - dynamic path segments (template literals like ``/api/dashboard/widgets/${id}``) are matched against the registered ``{param}`` routes, so a renamed backend path fails here instead of 404ing in the browser. """ import re js_root = Path("static/js") if not js_root.is_dir(): return {} pat_str = re.compile(r"['\"](/api/[A-Za-z0-9/_.\-]+)['\"]") pat_tpl = re.compile(r"`(/api/[^`\s]*)") raw: set[str] = set() for source in js_root.rglob("*.ts"): text = source.read_text() raw.update(match.group(1) for match in pat_str.finditer(text)) raw.update(match.group(1) for match in pat_tpl.finditer(text)) resolved: set[str] = set() for url in raw: path = url.split("?", 1)[0].rstrip("/") if not path or path == "/api" or not path.startswith("/api/"): continue if path in API_ROUTES: resolved.add(path) continue matched = _match_dynamic_path(path) if matched: resolved.add(matched) return {path: {"GET"} for path in resolved} def _match_dynamic_path(path: str) -> str | None: """Match a client path built from a template literal (its ``${...}`` segments already stripped) against a registered ``{param}`` route.""" import re for candidate in API_ROUTES: escaped = re.escape(candidate) regex = re.sub(r"\\\{[^}]+\\\}", "[^/]+", escaped) if re.fullmatch(regex, path): return candidate return None # The frontend also issues non-GET requests. This table pairs each mutating # URL the client sends with the method it uses, so a backend that drops (or # re-methods) an endpoint fails here instead of in the browser. MUTATIONS: tuple[tuple[str, str], ...] = ( ("/api/watchlist", "POST"), ("/api/backtest/alert-configs", "POST"), ("/api/backtest/alert-configs/preview", "POST"), ("/api/backtest/alert-configs/validate", "POST"), ("/api/backtest/alert-configs/{config_id}", "PUT"), ("/api/backtest/alert-configs/{config_id}", "DELETE"), ("/api/backtest/start", "POST"), ("/api/backtest/stop", "POST"), ("/api/bankruptcy/dismiss", "POST"), ("/api/bankruptcy/dismiss", "DELETE"), ("/api/chart/alerts", "GET"), ("/api/chart/alerts/sync", "POST"), ("/api/chart/alerts/{alert_id}", "PUT"), ("/api/chart/alerts/{alert_id}", "DELETE"), ("/api/chat", "POST"), ("/api/dashboard/tabs", "GET"), ("/api/dashboard/tabs", "POST"), ("/api/dashboard/tabs/{tab_id}", "PUT"), ("/api/dashboard/tabs/{tab_id}", "DELETE"), ("/api/dashboard/widgets", "GET"), ("/api/dashboard/widgets", "POST"), ("/api/dashboard/widgets/{widget_id}", "PUT"), ("/api/dashboard/widgets/{widget_id}", "DELETE"), ("/api/filters", "GET"), ("/api/filters", "POST"), ("/api/filters/{name}", "DELETE"), ("/api/hf/download-data", "POST"), ("/api/hf/push-config", "POST"), ("/api/hf/restore-config", "POST"), ("/api/hf/restore-config", "GET"), ("/api/hf/sync", "POST"), ("/api/llm/model", "POST"), ("/api/playbook", "GET"), ("/api/reports/dates", "GET"), ("/api/reports/candidates", "GET"), ("/api/playbook", "POST"), ("/api/playbook/{setup_id}", "PUT"), ("/api/playbook/{setup_id}", "DELETE"), ("/api/playbook/{setup_id}/screenshots", "POST"), ("/api/playbook/{setup_id}/screenshots/{screenshot_id}", "DELETE"), ("/api/playbook/{setup_id}/screenshots/{screenshot_id}/cover", "POST"), ("/api/screener", "POST"), ("/api/symbol-flags", "GET"), ("/api/symbol-flags", "POST"), ("/api/symbol-flags/{id}", "PUT"), ("/api/symbol-flags/{id}", "DELETE"), ("/api/symbol-flags/order", "PUT"), ("/api/trades/annotations", "GET"), ("/api/trades/annotations/{trade_key:path}", "POST"), ("/api/trades/auth", "POST"), ("/api/trades/auth/callback", "POST"), ) # every frontend-consumed path with the methods the client needs on it CONSUMED: dict[str, set[str]] = {} def _add(path: str, *methods: str) -> None: CONSUMED.setdefault(path, set()).update(methods) for _path, _method in MUTATIONS: _add(_path, _method) for _path in ( "/api/at-risk/screens", "/api/backtest/status", "/api/backtest/alert-elements/catalog", "/api/dashboard/external-feed-sources", "/api/dilution/{symbol}", "/api/discover/fallback", "/api/dsl/schema", "/api/hf/data-status", "/api/hf/status", "/api/hf/sync/progress", "/api/level2/status", "/api/llm/models", "/api/llm/status", "/api/market-pulse/enrich", "/api/news/batch", "/api/reverse-splits", "/api/scan", "/api/scan/calendar", "/api/scan/calendar/export", "/api/signals/history", "/api/signals/metrics", "/api/signals/status", "/api/stock-catalysts/{symbol}", "/api/stock-catalysts/{symbol}/fast", "/api/stock-catalysts/{symbol}/news", "/api/symbol-flags/fields", "/api/symbol-flags/sources", "/api/trades/status", "/api/trades/transactions", "/api/trades/auth-url", ): _add(_path, "GET") # WebSockets the frontend opens. WS_PATHS: tuple[str, ...] = ( "/api/backtest/stream", "/api/dashboard/widgets/{widget_id}/stream", "/api/level2/stream", "/api/signals/stream", ) # monitor serves every external feed source through one WS wildcard # (modules/monitor/routes.py: @router.websocket("/{source}")); the frontend's # feed widgets connect to /api/monitor/{source} for each EXTERNAL_FEED_SOURCES id. WS_MONITOR_SOURCES: tuple[str, ...] = ("momo", "titan", "titan_news", "titan_filings", "titan_halts") class TestFrontendContract: def test_frontend_urls_resolve_to_registered_routes(self) -> None: """Every /api URL pattern in static/js must resolve to a registered route.""" frontend = _frontend_paths() assert frontend, "no frontend /api URLs found — extraction broke" @pytest.mark.parametrize("path", sorted(_frontend_paths())) def test_frontend_path_is_registered(self, path: str) -> None: assert path in API_ROUTES, f"frontend URL pattern {path} matches no registered route" def test_extraction_covers_the_known_surface(self) -> None: """Guard the extractor itself: if these stop matching, the frontend moved off core/api.ts-style URL literals and the suite is blind.""" frontend = _frontend_paths() for probe in ( "/api/watchlist", "/api/dashboard/widgets", "/api/chart/ohlc", "/api/trades/annotations", "/api/discover/fallback", ): assert probe in frontend, f"extractor missed {probe}" @pytest.mark.parametrize(("path", "methods"), sorted(CONSUMED.items())) def test_consumed_endpoint_registered_with_method(self, path: str, methods: set[str]) -> None: registered = API_ROUTES.get(path) assert registered is not None, f"{path} missing from the app" missing_methods = methods - registered assert not missing_methods, f"{path} lacks methods {sorted(missing_methods)}" @pytest.mark.parametrize("path", WS_PATHS) def test_websocket_path_is_registered(self, path: str) -> None: assert path in WS_ROUTES, f"{path} missing; registered WS paths: {sorted(WS_ROUTES)}" @pytest.mark.parametrize("source", WS_MONITOR_SOURCES) def test_monitor_feed_websocket_source_is_registered(self, source: str) -> None: assert "/api/monitor/{source}" in WS_ROUTES # and the id the widget sends is a valid feed source server-side from modules.dashboard.routes import EXTERNAL_FEED_SOURCES assert source in EXTERNAL_FEED_SOURCES class _ContractBase: """Every live-contract test needs the same three things: a throwaway DB, a TestClient over the real app, and no outbound network. All three come from tests/conftest.py so a fix to one suite cannot leave the others reaching for the real config store. """ @pytest.fixture() def client(self, app_client: TestClient) -> TestClient: return app_client @pytest.fixture() def raw_client(self, raw_app_client: TestClient) -> TestClient: """Surfaces server-side exceptions as real 500s, for routes with no wrap_provider_errors safety net.""" return raw_app_client def _session_on_disk(session: str) -> bool: """Whether the daily database holds a bar for *session*. Read through the study module rather than a second DuckDB handle: this is the same question `available_dates` answers, asked independently. """ from modules.reports.study import has_session return has_session(session) class TestLiveContracts(_ContractBase): # ── watchlist ── # Mutations are POST with a JSON body; a GET must never change data. @staticmethod def _wl(client: TestClient, action: str, symbol: str = "", data: str | None = None): return client.post("/api/watchlist", json={"action": action, "symbol": symbol, "data": data}) def test_watchlist_round_trip(self, client: TestClient) -> None: resp = self._wl(client, "add", "aapl") assert resp.status_code == 200 body = client.get("/api/watchlist").json() assert [i["symbol"] for i in body["watchlist"]] == ["AAPL"] resp = self._wl(client, "remove", "AAPL") assert resp.status_code == 200 assert client.get("/api/watchlist").json()["watchlist"] == [] def test_watchlist_get_refuses_mutations(self, client: TestClient) -> None: resp = client.get("/api/watchlist", params={"action": "add", "symbol": "NVDA"}) assert resp.status_code == 405 assert client.get("/api/watchlist").json()["watchlist"] == [] def test_watchlist_save_rejects_non_array(self, client: TestClient) -> None: resp = self._wl(client, "save", data=json.dumps({"symbol": "AAPL"})) assert resp.status_code == 400 assert resp.json()["detail"].startswith("Watchlist data must be a JSON array") def test_watchlist_save_rejects_bad_json(self, client: TestClient) -> None: resp = self._wl(client, "save", data="{not json") assert resp.status_code == 400 assert resp.json()["detail"].startswith("Invalid JSON") def test_watchlist_save_round_trip(self, client: TestClient) -> None: payload = [{"symbol": "MSFT", "addedAt": "2026-09-25T10:00:00"}] resp = self._wl(client, "save", data=json.dumps(payload)) assert resp.status_code == 200 body = client.get("/api/watchlist").json() assert body["watchlist"][0]["symbol"] == "MSFT" assert body["watchlist"][0]["addedAt"] == "2026-09-25T10:00:00" def test_watchlist_clear(self, client: TestClient) -> None: self._wl(client, "add", "TSLA") assert self._wl(client, "clear").status_code == 200 assert client.get("/api/watchlist").json()["watchlist"] == [] # ── filters ── def test_filters_crud(self, client: TestClient) -> None: from modules.settings.routes import DEFAULT_FILTERS by_name = sorted(DEFAULT_FILTERS, key=lambda f: str(f["name"])) assert client.get("/api/filters").json()["filters"] == by_name created = client.post("/api/filters", json={"name": "my filter", "expression": "price > vwap"}) assert created.status_code == 200 assert created.json()["filters"] == sorted( [*by_name, {"name": "my filter", "expression": "price > vwap"}], key=lambda f: str(f["name"]), ) # upsert on the same name client.post("/api/filters", json={"name": "my filter", "expression": "gap_pct > 5"}) assert client.get("/api/filters").json()["filters"][-1]["expression"] == "gap_pct > 5" deleted = client.delete("/api/filters/my filter") assert deleted.status_code == 200 assert client.get("/api/filters").json()["filters"] == by_name # ── dashboard tabs ── def test_dashboard_tabs_lifecycle(self, client: TestClient) -> None: tabs = client.get("/api/dashboard/tabs").json()["tabs"] assert len(tabs) == 1 and tabs[0]["id"] == 1 created = client.post("/api/dashboard/tabs", json={"name": "Crypto", "position": 1}) assert created.status_code == 200 assert created.json()["name"] == "Crypto" tab_id = created.json()["id"] renamed = client.put(f"/api/dashboard/tabs/{tab_id}", json={"name": "Crypto2"}) assert renamed.json()["name"] == "Crypto2" assert client.put(f"/api/dashboard/tabs/{tab_id}", json={"name": " "}).status_code == 400 assert client.put("/api/dashboard/tabs/999", json={"name": "x"}).status_code == 404 assert client.delete("/api/dashboard/tabs/1").status_code == 400 # default tab assert client.delete(f"/api/dashboard/tabs/{tab_id}").json() == {"success": True} # ── dashboard widgets ── def test_dashboard_widget_lifecycle(self, client: TestClient) -> None: assert client.get("/api/dashboard/widgets").json() == {"widgets": []} created = client.post( "/api/dashboard/widgets", json={"type": "watchlist", "config_ref": {}, "position": 2, "col_span": 2, "tab_id": 1}, ) assert created.status_code == 200 widget = created.json() assert widget["type"] == "watchlist" and widget["position"] == 2 and widget["col_span"] == 2 updated = client.put( f"/api/dashboard/widgets/{widget['id']}", json={"type": "watchlist", "config_ref": {}, "position": 5, "muted": True}, ) assert updated.json()["position"] == 5 and updated.json()["muted"] is True assert client.put("/api/dashboard/widgets/999", json={"type": "watchlist", "config_ref": {}}).status_code == 404 assert client.delete(f"/api/dashboard/widgets/{widget['id']}").json() == {"success": True} def test_dashboard_widget_validation_errors(self, client: TestClient) -> None: # unknown widget type is a 422 (Literal type) assert client.post("/api/dashboard/widgets", json={"type": "nope", "config_ref": {}}).status_code == 422 # a symbol widget may omit its symbol and follow the dashboard selection resp = client.post("/api/dashboard/widgets", json={"type": "chart", "config_ref": {}}) assert resp.status_code == 200 # a symbol that is present must be text resp = client.post("/api/dashboard/widgets", json={"type": "chart", "config_ref": {"symbol": 42}}) assert resp.status_code == 400 and "symbol" in resp.json()["detail"] # unknown at_risk tab resp = client.post("/api/dashboard/widgets", json={"type": "at_risk", "config_ref": {"tab": "moon"}}) assert resp.status_code == 400 and "tab" in resp.json()["detail"] # out-of-range layout resp = client.post("/api/dashboard/widgets", json={"type": "watchlist", "config_ref": {}, "col_span": 9}) assert resp.status_code == 400 and "col_span" in resp.json()["detail"] resp = client.post("/api/dashboard/widgets", json={"type": "watchlist", "config_ref": {}, "row_height": 10}) assert resp.status_code == 400 and "row_height" in resp.json()["detail"] # unknown external feed source resp = client.post("/api/dashboard/widgets", json={"type": "external_feed", "config_ref": {"source": "rss"}}) assert resp.status_code == 400 and "source" in resp.json()["detail"] def test_dashboard_custom_widget_validation(self, client: TestClient) -> None: ok = {"url": "/api/bankruptcy", "columns": ["symbol", "filed_at"]} assert client.post("/api/dashboard/widgets", json={"type": "custom", "config_ref": ok}).status_code == 200 # The URL must stay on this server's own /api surface: a stored widget # is a persistent, auto-refreshing request the user may forget about. for bad_url in ("https://evil.example/api/x", "//evil.example/api/x", "/static/x", "api/x", "/api/..\\x"): resp = client.post( "/api/dashboard/widgets", json={"type": "custom", "config_ref": {**ok, "url": bad_url}}, ) assert resp.status_code == 400, bad_url assert "url" in resp.json()["detail"] for bad_columns in ([], "symbol", [""], [1], ["ok"] * 9): resp = client.post( "/api/dashboard/widgets", json={"type": "custom", "config_ref": {**ok, "columns": bad_columns}}, ) assert resp.status_code == 400, bad_columns assert "columns" in resp.json()["detail"] for bad_limit in (0, 201, "10", True): resp = client.post( "/api/dashboard/widgets", json={"type": "custom", "config_ref": {**ok, "limit": bad_limit}}, ) assert resp.status_code == 400, bad_limit assert "limit" in resp.json()["detail"] # Optional keys: absent rows_path and a present one both round-trip. created = client.post( "/api/dashboard/widgets", json={"type": "custom", "config_ref": {**ok, "rows_path": "data.results", "limit": 10}}, ).json() assert created["config_ref"]["rows_path"] == "data.results" assert created["config_ref"]["limit"] == 10 def test_dashboard_widgets_tab_filter(self, client: TestClient) -> None: client.post("/api/dashboard/widgets", json={"type": "watchlist", "config_ref": {}, "tab_id": 1}) tab = client.post("/api/dashboard/tabs", json={"name": "Two"}).json() client.post("/api/dashboard/widgets", json={"type": "watchlist", "config_ref": {}, "tab_id": tab["id"]}) all_widgets = client.get("/api/dashboard/widgets").json()["widgets"] assert len(all_widgets) == 2 filtered = client.get("/api/dashboard/widgets", params={"tab_id": tab["id"]}).json()["widgets"] assert [w["tab_id"] for w in filtered] == [tab["id"]] def test_external_feed_sources_catalog(self, client: TestClient) -> None: body = client.get("/api/dashboard/external-feed-sources").json() ids = {s["id"] for s in body["sources"]} assert {"momo", "titan", "titan_news", "titan_filings", "titan_halts"} <= ids for source in body["sources"]: assert source["label"] and source["ws_path"].startswith("/api/monitor/") # ── bankruptcy dismiss ── def test_bankruptcy_dismiss_round_trip(self, client: TestClient) -> None: resp = client.post("/api/bankruptcy/dismiss", json=["AAPL", "TSLA"]) assert resp.status_code == 200 assert resp.json() == {"success": True, "dismissed": 2} dismissed = client.get("/api/bankruptcy/dismissed").json() assert sorted(d["symbol"] for d in dismissed["dismissed"]) == ["AAPL", "TSLA"] assert client.request("DELETE", "/api/bankruptcy/dismiss", json=["AAPL"]).json()["undismissed"] == 1 after = client.get("/api/bankruptcy/dismissed").json()["dismissed"] assert [d["symbol"] for d in after] == ["TSLA"] def test_bankruptcy_dismiss_rejects_missing_body(self, client: TestClient) -> None: assert client.post("/api/bankruptcy/dismiss").status_code == 422 # ── signals history ── def test_signals_history_filters(self, client: TestClient) -> None: db.add_signal( { "symbol": "AAPL", "signal": "crossing_vwap", "timestamp": 1.0, "price": 100.0, "stop": 95.0, "target": 110.0, "confidence": 0.9, "retracement_pct": 0.1, "reason": "test", "created_at": "2026-09-25", }, config_id=7, ) db.add_signal( { "symbol": "MSFT", "signal": "crossing_vwap", "timestamp": 2.0, "price": 50.0, "stop": 48.0, "target": 55.0, "confidence": 0.8, "retracement_pct": 0.2, "reason": "test", "created_at": "2026-09-25", }, config_id=8, ) all_signals = client.get("/api/signals/history").json()["signals"] assert len(all_signals) == 2 by_symbol = client.get("/api/signals/history", params={"symbol": "aapl"}).json()["signals"] assert [s["symbol"] for s in by_symbol] == ["AAPL"] by_config = client.get("/api/signals/history", params={"config_id": 8}).json()["signals"] assert [s["config_id"] for s in by_config] == [8] by_outcome = client.get("/api/signals/history", params={"outcome": "win"}).json()["signals"] assert by_outcome == [] # validation bounds assert client.get("/api/signals/history", params={"limit": 0}).status_code == 422 assert client.get("/api/signals/history", params={"limit": 501}).status_code == 422 # ── signals metrics ── def test_signals_metrics_rolls_up_by_signal_type(self, client: TestClient) -> None: seeded = 0 def seed(signal: str, outcome: str, config_id: int) -> None: nonlocal seeded seeded += 1 signal_id = db.add_signal( { "symbol": "AAPL", "signal": signal, # add_signal is INSERT OR IGNORE over a uniqueness key, so # each seed needs its own timestamp to be stored at all. "timestamp": float(seeded), "price": 100.0, "stop": 95.0, "target": 110.0, "confidence": 0.5, "retracement_pct": 0.1, "reason": "test", "created_at": "2026-09-25", }, config_id=config_id, ) assert signal_id is not None, "the seed row was rejected as a duplicate" if outcome != "pending": db.set_signal_outcome(signal_id, outcome=outcome) # No rows yet: "nothing resolved" must not read as a 0% hit rate. empty = client.get("/api/signals/metrics").json() assert empty["total"] == 0 assert empty["win_rate"] is None seed("crossing_vwap", "win", 3) seed("crossing_vwap", "loss", 3) seed("breakout", "win", 3) seed("breakout", "pending", 4) pooled = client.get("/api/signals/metrics").json() assert pooled["total"] == 4 assert pooled["wins"] == 2 assert pooled["losses"] == 1 # An unresolved signal is pending, never counted as a loss. assert pooled["pending"] == 1 assert pooled["win_rate"] == 2 / 3 by_signal = {row["signal"]: row for row in pooled["by_signal"]} assert by_signal["crossing_vwap"]["wins"] == 1 assert by_signal["crossing_vwap"]["pending"] == 0 assert by_signal["breakout"]["wins"] == 1 assert by_signal["breakout"]["pending"] == 1 assert by_signal["breakout"]["losses"] == 0 scoped = client.get("/api/signals/metrics", params={"config_id": 3}).json() assert scoped["total"] == 3 assert [row["signal"] for row in scoped["by_signal"]] == ["crossing_vwap", "breakout"] # ── symbol-flags delete path (contract others don't cover) ── def test_symbol_flag_delete_404(self, client: TestClient) -> None: assert client.delete("/api/symbol-flags/424242").status_code == 404 # ── reports section ── def test_reports_dates_are_sessions_the_database_actually_has(self, client: TestClient) -> None: """The picker must not offer a day the study cannot answer for. The market calendar runs to 2029, so deriving the list from it would offer 260 dates with no data behind them. """ body = client.get("/api/reports/dates").json() assert body["dates"], "the daily database should yield sessions" assert body["dates"] == sorted(body["dates"], reverse=True) assert body["latest"] == body["dates"][0] assert body["latest"] <= date.today().isoformat() assert _session_on_disk(body["latest"]), f"{body['latest']} has no daily bars" def test_reports_dates_ships_the_plan_the_page_paints_into_its_boxes(self, client: TestClient) -> None: """The defaults the page shows have to be the defaults it gets. The page fills its plan boxes from here, so a second copy of the numbers in the frontend would be a default that quietly stops being true. The two that are empty stay empty, and the assertion is that they build the plan the endpoint claims -- not that they merely parse. """ from modules.reports.plan import build_plan body = client.get("/api/reports/dates").json() shown = body["plan_defaults"] assert set(shown) == { "entry", "trigger", "tp1", "tp1_size", "tp2", "stop", "breakeven", } # Empty is the default for these two and there is no text to put there. assert shown["trigger"] == "" assert shown["tp2"] == "" plan = build_plan( entry=shown["entry"], tp1=shown["tp1"], tp1_size=shown["tp1_size"], stop=shown["stop"], breakeven=shown["breakeven"], ) assert plan.entry_expr == shown["entry"] assert plan.targets[0].offset == 20.0 assert plan.targets[0].size == 1.0 assert plan.stop_pct == 1.0 assert plan.breakeven is False def test_reports_dates_defaults_are_what_an_empty_request_measures(self, client: TestClient) -> None: """The boxes have to describe the study a request with nothing in it runs. Otherwise the page states a plan and silently measures another one, which is the failure the whole section is about: numbers that answer a question nobody asked. """ from modules.reports import service shown = client.get("/api/reports/dates").json()["plan_defaults"] session = client.get("/api/reports/dates").json()["latest"] assert _session_on_disk(session), f"{session} has no daily bars" # An empty plan and the shown plan are the same plan, so the level, # the targets and the stop the page prints are the ones measured. assert service.build_plan() == service.build_plan( entry=shown["entry"], tp1=shown["tp1"], tp1_size=shown["tp1_size"], stop=shown["stop"], breakeven=shown["breakeven"], ) def test_reports_candidates_rejects_a_non_iso_date(self, client: TestClient) -> None: resp = client.get("/api/reports/candidates", params={"date": "28-10-2025", "filter": "close > 1"}) assert resp.status_code == 422 assert "YYYY-MM-DD" in resp.json()["detail"] def test_reports_candidates_requires_a_filter(self, client: TestClient) -> None: """No filter, no universe: the study measures what an expression selects.""" resp = client.get("/api/reports/candidates", params={"date": "2026-01-05"}) assert resp.status_code == 422 assert "filter is required" in resp.json()["detail"] def test_reports_candidates_says_a_filter_matched_nothing(self, client: TestClient) -> None: """A parseable filter that selects no name is its own answer. Distinct from a date with no bars: the day exists, the expression just excludes everything on it, and the two want different fixes. """ session = client.get("/api/reports/dates").json()["latest"] assert _session_on_disk(session), f"{session} has no daily bars" resp = client.get( "/api/reports/candidates", params={"date": session, "filter": "close > 100000"}, ) assert resp.status_code == 422 assert f"No names matched the filter on {session}" in resp.json()["detail"] def test_reports_candidates_rejects_an_unparseable_filter(self, client: TestClient) -> None: """The compiler's own wording reaches the caller, not a stack trace.""" session = client.get("/api/reports/dates").json()["latest"] resp = client.get( "/api/reports/candidates", params={"date": session, "filter": "close >< nonsense"}, ) assert resp.status_code == 422 assert resp.json()["detail"] def test_reports_candidates_rejects_a_date_with_no_bars(self, client: TestClient) -> None: """A well-formed date the database has never heard of is a 422, not a 500.""" resp = client.get("/api/reports/candidates", params={"date": "1999-01-04", "filter": "close > 1"}) assert resp.status_code == 422 assert "No daily bars" in resp.json()["detail"] @pytest.mark.parametrize( "plan", [ {"tp1": "1.2"}, {"tp1": "0"}, {"tp2": "40%"}, {"tp1": "5%", "tp2": "3%"}, {"tp1_size": "150%"}, {"tp1_size": "half"}, {"stop": "abc"}, # `close >< nope` parses to a comparison with no right operand, so a # parse-only check accepts it and every name fills unfiltered. {"trigger": "close >< nope"}, {"trigger": "nope_column > 1"}, ], ) def test_reports_candidates_refuses_a_plan_it_cannot_measure(self, client: TestClient, plan: dict) -> None: """A plan the parser cannot read is a 422 carrying its own wording. The study is a measurement of one particular trade, so a level that reads as something other than what was written is worse than a refusal: it returns numbers, and the numbers answer a question nobody asked. """ session = client.get("/api/reports/dates").json()["latest"] resp = client.get( "/api/reports/candidates", params={"date": session, "filter": "close > 1", **plan}, ) assert resp.status_code == 422 assert resp.json()["detail"] def test_dilution_page_redirects_to_its_own_document(self, client: TestClient) -> None: """The Dilution Profile is a page of its own, so /dilution forwards to it. `symbol` is the whole identity of the link, so a bookmark or shared URL that names one has to land on that symbol's profile. """ resp = client.get( "/dilution", params={"symbol": "AAPL"}, follow_redirects=False, ) assert resp.status_code == 307 assert resp.headers["location"] == "/research?view=dilution&symbol=AAPL" def test_dilution_page_redirect_drops_a_stale_tab(self, client: TestClient) -> None: """A bare /dilution has no query, and a stale `tab` from the old At Risk tab is dropped. The tab named a screen of At Risk, which this page no longer is, so it must not follow the reader onto the profile. """ resp = client.get("/dilution", follow_redirects=False) assert resp.status_code == 307 assert resp.headers["location"] == "/research?view=dilution" resp = client.get( "/dilution", params={"symbol": "AAPL", "tab": "holders"}, follow_redirects=False, ) assert resp.status_code == 307 assert resp.headers["location"] == "/research?view=dilution&symbol=AAPL" def test_dilution_registrations_answers_a_valid_symbol( self, client: TestClient, monkeypatch: pytest.MonkeyPatch ) -> None: """`/api/dilution//registrations` answers 200 for a well-formed ticker. The SEC payload is stubbed: this asserts the route's contract, not what EDGAR says about AAPL today. Unstubbed it was a live SEC round trip that cost 79s of the suite's wall clock and whose result depended on the filings of the day. """ monkeypatch.setattr( "modules.dilution.routes.fetch_sec_submissions", lambda *args, **kwargs: {"filings": {"recent": {"form": [], "filingDate": []}}}, ) resp = client.get("/api/dilution/AAPL/registrations") assert resp.status_code == 200 body = resp.json() assert body["ticker"] == "AAPL" assert body["registrations"] == [] assert body["error"] is None def test_at_risk_page_redirect_carries_the_tab_query(self, client: TestClient) -> None: """The query is the tab's identity, so /at-risk forwards it. The client resolves `?tab=` (and the dilution profile's `symbol`) from the query it is served with; dropping it here would undo the /dilution legacy redirect's work and land every bookmark on a page with no screen open. """ resp = client.get( "/at-risk", params={"tab": "dilution", "symbol": "AAPL"}, follow_redirects=False, ) assert resp.status_code == 307 assert resp.headers["location"] == "/static/at-risk.html?tab=dilution&symbol=AAPL" resp = client.get("/at-risk", follow_redirects=False) assert resp.status_code == 307 assert resp.headers["location"] == "/static/at-risk.html" def test_reports_page_redirects_to_the_backtest_tab(self, client: TestClient) -> None: """/reports is now the Reports tab of /backtest, not a page of its own. The query is the study's identity -- which session, measured by which filter -- so a link or bookmark that names one has to land on that same study, not on the run tab with the study thrown away. """ resp = client.get( "/reports", params={"date": "2026-09-25", "filter": "gap_pct > 5"}, follow_redirects=False, ) assert resp.status_code in (302, 307) location = resp.headers["location"] assert location.startswith("/backtest?") assert "tab=reports" in location assert "date=2026-09-25" in location assert "gap_pct" in location def test_reports_page_redirect_carries_no_stale_parameters(self, client: TestClient) -> None: """A bare /reports still names the tab, and the API routes are untouched.""" resp = client.get("/reports", follow_redirects=False) assert resp.status_code in (302, 307) assert resp.headers["location"] == "/backtest?tab=reports" assert client.get("/api/reports/dates").status_code == 200 # ── playbook CRUD ── def test_playbook_crud_round_trip(self, client: TestClient) -> None: assert client.get("/api/playbook").json() == {"setups": []} created = client.post("/api/playbook", json={"name": "Gap and go", "category": "momentum"}) assert created.status_code == 200 setup = created.json() assert setup["name"] == "Gap and go" assert setup["screenshots"] == [] updated = client.put(f"/api/playbook/{setup['id']}", json={"name": "Gap 'n go", "notes": "premarket"}) assert updated.json()["name"] == "Gap 'n go" assert client.put("/api/playbook/999", json={"name": "x"}).status_code == 404 assert client.delete(f"/api/playbook/{setup['id']}").json() == {"success": True} assert client.delete("/api/playbook/999").status_code == 404 assert client.get("/api/playbook").json() == {"setups": []} # ── trades (provider-agnostic surface) ── def test_trades_status_shape(self, client: TestClient) -> None: resp = client.get("/api/trades/status") assert resp.status_code == 200 body = resp.json() assert {"status", "has_api_credentials", "has_token_file", "callback_url"} <= set(body) def test_trades_transactions_unauthenticated_is_empty( self, client: TestClient, monkeypatch: pytest.MonkeyPatch ) -> None: # The provider is stubbed unauthenticated: on a machine with a real # ~/.schwab_token.json the status route would authenticate the shared # client, and this test would read that machine's cached trades. class _UnauthenticatedProvider: def get_status(self) -> dict[str, object]: return {"status": "no_token"} def load_cached_transactions(self) -> list[dict[str, object]] | None: return None monkeypatch.setattr("modules.trades.routes.get_trade_provider", _UnauthenticatedProvider) resp = client.get("/api/trades/transactions") assert resp.status_code == 200 body = resp.json() assert body["count"] == 0 and body["transactions"] == [] def test_trades_cached_transactions_are_not_served_for_another_account( self, client: TestClient, monkeypatch: pytest.MonkeyPatch ) -> None: # trades_cache is one row for the whole app: a request naming a # different account (or a wider window) must not be answered with the # cached account's fills under the currently resolved account number. class _CachedOtherAccountProvider: def __init__(self) -> None: self.fetched: list[tuple[int, str | None]] = [] def is_authenticated(self) -> bool: return True def get_status(self) -> dict[str, object]: return { "status": "authenticated", "account_number": "RESOLVED", "cache": {"account": "OTHER", "days": 30, "transaction_count": 1}, } def load_cached_transactions(self) -> list[dict[str, object]]: return [{"transaction_id": "cached-one", "symbol": "OTHER"}] def load_transactions(self, days: int = 30, account: str | None = None) -> list[dict[str, object]]: self.fetched.append((days, account)) return [{"transaction_id": "fresh", "symbol": "MINE"}] provider = _CachedOtherAccountProvider() monkeypatch.setattr("modules.trades.routes.get_trade_provider", lambda: provider) same = client.get("/api/trades/transactions", params={"account": "OTHER"}).json() assert same["cached"] is True assert same["account_number"] == "OTHER" other = client.get("/api/trades/transactions", params={"account": "MINE"}).json() assert other["cached"] is False assert other["transactions"] == [{"transaction_id": "fresh", "symbol": "MINE"}] assert provider.fetched == [(30, "MINE")] wider = client.get("/api/trades/transactions", params={"days": 90}).json() assert wider["cached"] is False assert provider.fetched[-1] == (90, None) def test_trades_annotations_round_trip(self, client: TestClient) -> None: assert client.get("/api/trades/annotations").json() == {"annotations": []} saved = client.post( "/api/trades/annotations/2026-09-25 AAPL 1", json={"tags": ["gap"], "playbook_setup_id": None, "notes": "clean break"}, ) assert saved.status_code == 200 assert saved.json()["trade_key"] == "2026-09-25 AAPL 1" listed = client.get("/api/trades/annotations").json()["annotations"] assert len(listed) == 1 and listed[0]["notes"] == "clean break" def test_trades_auth_callback_requires_redirect_url(self, client: TestClient) -> None: resp = client.post("/api/trades/auth/callback", json={"redirect_url": ""}) assert resp.status_code == 400 assert "redirect_url" in resp.json()["detail"] # ── at-risk generic screen ── def test_at_risk_unknown_screen_404(self, client: TestClient) -> None: resp = client.get("/api/at-risk/screen/does-not-exist") assert resp.status_code == 404 # ── hf settings surface ── def test_hf_sync_progress_shape(self, client: TestClient) -> None: body = client.get("/api/hf/sync/progress").json() assert {"active", "stage", "detail", "batches_done", "batches_total"} <= set(body) def test_hf_status_shape(self, client: TestClient) -> None: body = client.get("/api/hf/status").json() assert {"repo", "token_set", "last_sync"} <= set(body) def test_hf_push_success_contract(self, client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setattr("modules.settings.routes.hf_manager.push_config", lambda: True) assert client.post("/api/hf/push-config").json() == {"success": True} def test_hf_restore_starts_in_background_and_reports_outcome( self, client: TestClient, monkeypatch: pytest.MonkeyPatch ) -> None: """Restore must answer immediately and report the real outcome later. It used to be awaited inside the request (a full app_state.db download plus an import that holds the DB lock), which blocked the caller for the whole transfer. """ gate = threading.Event() def fake_restore() -> bool: gate.wait(timeout=30) return True monkeypatch.setattr("modules.settings.routes.hf_manager.restore_config", fake_restore) started = client.post("/api/hf/restore-config").json() assert started["status"] == "started" assert client.get("/api/hf/restore-config").json()["status"] == "running" # A second POST while one is in flight must not start a duplicate # import against the same connection. assert client.post("/api/hf/restore-config").json()["status"] == "running" gate.set() deadline = time.monotonic() + 30 status = "running" while time.monotonic() < deadline: status = client.get("/api/hf/restore-config").json()["status"] if status != "running": break time.sleep(0.02) assert status == "ok" def test_hf_restore_failure_is_reported_not_raised( self, client: TestClient, monkeypatch: pytest.MonkeyPatch ) -> None: def boom() -> bool: raise RuntimeError("hf down") monkeypatch.setattr("modules.settings.routes.hf_manager.restore_config", boom) assert client.post("/api/hf/restore-config").json()["status"] == "started" deadline = time.monotonic() + 30 body: dict[str, str] = {} while time.monotonic() < deadline: body = client.get("/api/hf/restore-config").json() if body["status"] == "error": break time.sleep(0.02) assert body["status"] == "error" assert "hf down" in body["detail"] def test_db_lock_stats_shape(self, client: TestClient) -> None: body = client.get("/api/db/lock-stats").json() assert {"acquisitions", "hold_seconds", "max_hold_seconds", "wait_seconds", "max_wait_seconds"} <= set( body["totals"] ) assert isinstance(body["by_operation"], dict) # ── screener cache clear ── def test_screener_clear_finviz_cache(self, client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setattr( "modules.screener.routes.clear_finviz_cache", lambda: {"symbols": 3}, ) body = client.post("/api/screener/clear-finviz-cache").json() assert body["status"] == "success" and body["cleared"] == {"symbols": 3} # ── backtest surface ── def test_backtest_status_shape(self, client: TestClient) -> None: body = client.get("/api/backtest/status").json() assert body["state"] in ("idle", "running", "paused") for key in ("processed", "total", "error", "warning"): assert key in body def test_backtest_alert_configs_round_trip(self, client: TestClient) -> None: assert client.get("/api/backtest/alert-configs").json() == {"alert_configs": []} created = client.post( "/api/backtest/alert-configs", json={"name": "vwap break", "detector_expression": "close > 5"}, ) assert created.status_code == 200 config = created.json() assert config["detector_types"] == ["dsl_expression"] updated = client.put( f"/api/backtest/alert-configs/{config['id']}", json={"name": "vwap break 2", "detector_expression": "close < 5"}, ) assert updated.json()["name"] == "vwap break 2" assert ( client.put( "/api/backtest/alert-configs/999", json={"name": "nope", "detector_expression": "close > 1"} ).status_code == 404 ) assert client.delete(f"/api/backtest/alert-configs/{config['id']}").json() == {"success": True} def test_backtest_alert_config_validation(self, client: TestClient) -> None: resp = client.post("/api/backtest/alert-configs", json={"name": " "}) assert resp.status_code == 400 and "Name" in resp.json()["detail"] resp = client.post("/api/backtest/alert-configs", json={"name": "no logic"}) assert resp.status_code == 400 and "condition" in resp.json()["detail"].lower() resp = client.post( "/api/backtest/alert-configs", json={"name": "bad expr", "detector_expression": "close >"}, ) assert resp.status_code == 400 resp = client.post( "/api/backtest/alert-configs", json={"name": "bad detector", "detector_types": ["moon_phase"]}, ) assert resp.status_code == 400 and "Unsupported" in resp.json()["detail"] def test_backtest_alert_elements_catalog(self, client: TestClient) -> None: body = client.get("/api/backtest/alert-elements/catalog").json() assert isinstance(body["elements"], list) and body["elements"] for element in body["elements"]: assert "key" in element def test_backtest_start_rejects_unknown_config(self, client: TestClient) -> None: resp = client.post( "/api/backtest/start", json={"date": "2026-09-25", "from_time": "09:30", "to_time": "16:00", "alert_config_id": 424242}, ) assert resp.status_code == 400 assert "not found" in resp.json()["detail"] # ── level2 subscribe response shape (refcounted, no WS needed) ── def test_level2_subscribe_rejects_missing_symbol(self, client: TestClient) -> None: assert client.post("/api/level2/subscribe").status_code == 422 # ── discover groups ── def test_discover_patterns_returns_the_group_shape(self, client: TestClient) -> None: resp = client.post("/api/discover/patterns", json={"session": "momentum", "rows": [], "min_support": 4}) assert resp.status_code == 200 body = resp.json() assert body["status"] == "success" assert body["universe_size"] == 0 assert body["described_count"] == 0 assert body["groups"] == [] def test_discover_patterns_rejects_bad_support(self, client: TestClient) -> None: assert client.post("/api/discover/patterns", json={"rows": [], "min_support": 99}).status_code == 422 assert client.post("/api/discover/patterns", json={"rows": [], "min_support": 1}).status_code == 422 def test_discover_patterns_ignores_intraday(self, client: TestClient) -> None: """`include_intraday` is gone from the request, and cannot be smuggled back in.""" assert "include_intraday" not in DiscoverPatternRequest.model_fields resp = client.post("/api/discover/patterns", json={"rows": [], "include_intraday": True}) assert resp.status_code == 200 assert resp.json()["groups"] == [] # ── llm ── def test_llm_model_rejects_unknown_model(self, client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None: class _FakeAgent: model = "m1" async def get_available_models(self): return ["m1"] monkeypatch.setattr("app.main.get_llm_agent", lambda: _FakeAgent()) resp = client.post("/api/llm/model", json={"model": "nope"}) assert resp.status_code == 400 assert "not available" in resp.json()["detail"] class TestValidationErrors(_ContractBase): """Validation errors on read endpoints the frontend builds URLs for.""" def test_scan_rejects_bad_filter(self, client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setattr( "modules.scan.routes.scan_service.scan", lambda *args, **kwargs: (_ for _ in ()).throw(AssertionError("must not run")), ) resp = client.get("/api/scan", params={"filter": "close >", "symbols": ""}) # A malformed expression is the caller's input: 400, not a server fault (decided 2026-10-17). assert resp.status_code == 400 assert "Unexpected end" in resp.json()["detail"] @pytest.mark.parametrize("limit", [-1, 0, 1001]) def test_scan_rejects_out_of_range_limit(self, client: TestClient, limit: int) -> None: resp = client.get("/api/scan", params={"limit": limit}) assert resp.status_code == 422 @pytest.mark.parametrize("limit", [250, 1000]) def test_scan_accepts_in_range_limit(self, client: TestClient, monkeypatch: pytest.MonkeyPatch, limit: int) -> None: monkeypatch.setattr( "modules.scan.routes.scan_service.scan", lambda *args, **kwargs: ([], False), ) resp = client.get("/api/scan", params={"limit": limit, "symbols": "AAPL"}) assert resp.status_code == 200 class TestScanLimitInstruction(_ContractBase): """`limit N` written in the filter expression, resolved at the boundary.""" @staticmethod def _capture(monkeypatch: pytest.MonkeyPatch) -> list[tuple]: """Stub the scan service and capture the arguments it was called with.""" calls: list[tuple] = [] def _fake(*args, **kwargs): calls.append(args) return [] def _fake_with_flag(*args, **kwargs): value = _fake(*args, **kwargs) return (value, False) if isinstance(value, list) else (value["results"], False) monkeypatch.setattr("modules.scan.routes.scan_service.scan", _fake_with_flag) return calls def test_the_instruction_becomes_the_request_limit( self, client: TestClient, monkeypatch: pytest.MonkeyPatch ) -> None: calls = self._capture(monkeypatch) resp = client.get("/api/scan", params={"filter": "close > 5 limit 30"}) assert resp.status_code == 200 # positional: filter, symbols, timeframe, start, end, limit assert calls[0][0] == "close > 5" assert calls[0][-1] == 30 def test_an_explicit_param_beats_the_instruction(self, client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None: calls = self._capture(monkeypatch) assert client.get("/api/scan", params={"filter": "close > 5 limit 30", "limit": 77}).status_code == 200 assert calls[0][-1] == 77 def test_no_limit_anywhere_falls_back_to_the_default( self, client: TestClient, monkeypatch: pytest.MonkeyPatch ) -> None: calls = self._capture(monkeypatch) assert client.get("/api/scan", params={"filter": "close > 5"}).status_code == 200 assert calls[0][-1] == 250 def test_the_instruction_never_reaches_the_expression_body( self, client: TestClient, monkeypatch: pytest.MonkeyPatch ) -> None: # The SQL compiler and the calendar's month-pinned plan read this text # as a boolean body; a `limit` clause there would be a parse error. calls = self._capture(monkeypatch) client.get("/api/scan", params={"filter": "close > 5 and volume > 1M sort close desc limit 5"}) assert calls[0][0] == "close > 5 and volume > 1M sort close desc" def test_a_result_count_at_the_cap_is_reported_as_truncated( self, client: TestClient, monkeypatch: pytest.MonkeyPatch ) -> None: monkeypatch.setattr( "modules.scan.routes.scan_service.scan", lambda *args, **kwargs: ([{"symbol": "AAA"}] * 2, False), ) body = client.get("/api/scan", params={"filter": "close > 5 limit 2"}).json() assert (body["count"], body["truncated"]) == (2, True) def test_a_short_result_set_is_not_reported_as_truncated( self, client: TestClient, monkeypatch: pytest.MonkeyPatch ) -> None: monkeypatch.setattr( "modules.scan.routes.scan_service.scan", lambda *args, **kwargs: ([{"symbol": "AAA"}], False), ) # A distinct body from the other cases on purpose: the cache key is # (stripped filter, limit), so a filter reused across these tests # would return the previous case's cached response. body = client.get("/api/scan", params={"filter": "close > 9 limit 250"}).json() assert (body["count"], body["truncated"]) == (1, False) def test_a_malformed_instruction_is_rejected_not_ignored( self, client: TestClient, monkeypatch: pytest.MonkeyPatch ) -> None: calls = self._capture(monkeypatch) # `limit abc` is left in the text by the splitter, so the expression # parser is what rejects it -- a typo must not silently scan everything. resp = client.get("/api/scan", params={"filter": "close > 5 limit abc"}) assert resp.status_code == 400 assert calls == [] def test_scan_rejects_overlong_filter(self, client: TestClient) -> None: resp = client.get("/api/scan", params={"filter": "a" * 3001}) assert resp.status_code == 400 assert "too long" in resp.json()["detail"] def test_scan_explain_shape(self, client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setattr( "modules.scan.routes.scan_service.explain_scan", lambda *args, **kwargs: {"sql": "SELECT 1", "diagnostics": [], "matched_by_clause": {}}, ) resp = client.get("/api/scan", params={"explain": "1", "filter": "price > vwap"}) assert resp.status_code == 200 body = resp.json() assert body["sql"] == "SELECT 1" and body["diagnostics"] == [] def test_chart_ohlc_rejects_bad_timeframe(self, client: TestClient) -> None: resp = client.get("/api/chart/ohlc", params={"symbol": "AAPL", "timeframe": "2w"}) assert resp.status_code == 400 assert "timeframe" in resp.json()["detail"] resp = client.get("/api/chart/ohlc", params={"symbol": "", "timeframe": "1d"}) assert resp.status_code == 400 def test_chart_ohlc_provider_failure_is_502(self, client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None: from core.shared.cache import cache_clear cache_clear() async def _no_bars(symbol: str, timeframe: str): return None, None monkeypatch.setattr("modules.chart.routes.fetch_main_bars", _no_bars) monkeypatch.setattr("modules.chart.routes.compute_prev_day", lambda daily: {}) resp = client.get("/api/chart/ohlc", params={"symbol": "AAPL", "timeframe": "1d"}) assert resp.status_code == 502 cache_clear() def test_chart_ohlc_success_and_cache(self, client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None: from core.shared.cache import cache_clear cache_clear() calls: list[str] = [] async def _bars(symbol: str, timeframe: str): calls.append(f"{symbol}:{timeframe}") return [ {"time": "2026-09-24T14:30:00Z", "open": 1.0, "high": 2.0, "low": 0.5, "close": 1.5, "volume": 100} ], "yahoo" monkeypatch.setattr("modules.chart.routes.fetch_main_bars", _bars) monkeypatch.setattr("modules.chart.routes.compute_prev_day", lambda daily: {"close": 1.2}) resp = client.get("/api/chart/ohlc", params={"symbol": "aapl", "timeframe": "1d"}) assert resp.status_code == 200 body = resp.json() assert body["symbol"] == "AAPL" and body["source"] == "yahoo" assert body["bars"][0]["close"] == 1.5 and body["prev_day"] == {"close": 1.2} # second hit served from the (symbol, timeframe) cache, not the provider client.get("/api/chart/ohlc", params={"symbol": "AAPL", "timeframe": "1d"}) assert calls == ["AAPL:1d"] cache_clear() def test_stock_catalysts_rejects_bad_date(self, client: TestClient) -> None: resp = client.get("/api/stock-catalysts/AAPL", params={"signal_date": "25-09-2026"}) assert resp.status_code == 400 assert "YYYY-MM-DD" in resp.json()["detail"] resp = client.get("/api/stock-catalysts/AAPL/news", params={"as_of_date": "yesterday"}) assert resp.status_code == 400 assert "YYYY-MM-DD" in resp.json()["detail"] def test_stock_catalysts_news_success(self, client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setattr( "modules.analysis.routes.fetch_press_release", lambda symbol, as_of, limit: [{"title": "PR", "url": "https://example.com", "published_at": "2026-09-25"}], ) resp = client.get("/api/stock-catalysts/AAPL/news") assert resp.status_code == 200 assert resp.json()["press_releases"][0]["title"] == "PR" def test_market_pulse_empty_symbols_400(self, client: TestClient) -> None: resp = client.get("/api/market-pulse/enrich", params={"symbols": " , ,"}) assert resp.status_code == 400 assert "No symbols" in resp.json()["detail"] def test_market_pulse_too_many_symbols_400(self, client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setattr( "modules.market_pulse.routes.get_market_pulse_enrichment", lambda symbols: (_ for _ in ()).throw(ValueError("Too many symbols (31); max 30 per request")), ) symbols = ",".join(f"S{i}" for i in range(31)) resp = client.get("/api/market-pulse/enrich", params={"symbols": symbols}) assert resp.status_code == 400 assert "max 30" in resp.json()["detail"] def test_market_pulse_30_symbols_accepted(self, client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None: seen: list[list[str]] = [] def fake(symbols: list[str]) -> dict[str, dict[str, float]]: seen.append(list(symbols)) return {s: {"float_shares": 1.0} for s in symbols} monkeypatch.setattr("modules.market_pulse.routes.get_market_pulse_enrichment", fake) symbols = ",".join(f"S{i}" for i in range(30)) resp = client.get("/api/market-pulse/enrich", params={"symbols": symbols}) assert resp.status_code == 200 assert len(resp.json()) == 30 assert len(seen) == 1 and len(seen[0]) == 30 def test_market_pulse_31_symbols_400_from_real_service(self, client: TestClient) -> None: symbols = ",".join(f"S{i}" for i in range(31)) resp = client.get("/api/market-pulse/enrich", params={"symbols": symbols}) assert resp.status_code == 400 assert "max 30" in resp.json()["detail"] def test_market_pulse_success(self, client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setattr( "modules.market_pulse.routes.get_market_pulse_enrichment", lambda symbols: {"AAPL": {"float_shares": 1.0}}, ) resp = client.get("/api/market-pulse/enrich", params={"symbols": "aapl"}) assert resp.status_code == 200 assert resp.json() == {"AAPL": {"float_shares": 1.0}} def test_news_batch_empty_symbols_is_empty_map(self, client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setattr( "modules.analysis.routes.finviz.fetch_news_bulk", lambda symbols: (_ for _ in ()).throw(AssertionError("must not run")), ) resp = client.get("/api/news/batch", params={"symbols": ""}) assert resp.status_code == 200 assert resp.json() == {} def test_news_batch_dedupes_and_caches(self, client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None: from core.shared import cache cache.cache_clear() calls: list[list[str]] = [] def _bulk(symbols: list[str]) -> dict[str, object]: calls.append(list(symbols)) return {"AAPL": {"headline": "hi", "url": "u", "created_at": "t", "source": "finviz"}} monkeypatch.setattr("modules.analysis.routes.finviz.fetch_news_bulk", _bulk) resp = client.get("/api/news/batch", params={"symbols": "aapl,AAPL,msft"}) assert resp.status_code == 200 body = resp.json() assert body["AAPL"]["headline"] == "hi" and "MSFT" not in body # the same normalized batch is served from cache without a re-fetch client.get("/api/news/batch", params={"symbols": "AAPL,msft"}) assert len(calls) == 1 cache.cache_clear() def test_news_batch_provider_failure_is_500(self, raw_client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None: from core.shared import cache cache.cache_clear() def _boom(symbols: list[str]) -> dict[str, object]: raise RuntimeError("finviz down") monkeypatch.setattr("modules.analysis.routes.finviz.fetch_news_bulk", _boom) resp = raw_client.get("/api/news/batch", params={"symbols": "AAPL"}) assert resp.status_code == 500 cache.cache_clear() def test_discover_fallback_success_shape(self, client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setattr( "modules.discover.routes._service.get_webull_fallback", lambda session, direction="gainers": [{"name": "AAPL", "close": 1.0, "volume": 10, "change": 2.0}], ) resp = client.get("/api/discover/fallback", params={"session": "market"}) assert resp.status_code == 200 body = resp.json() assert body["status"] == "success" and body["source"] == "webull" assert body["total_count"] == 1 and body["results"][0]["name"] == "AAPL" def test_discover_fallback_provider_failure_is_500( self, client: TestClient, monkeypatch: pytest.MonkeyPatch ) -> None: def _boom(session: str, direction: str = "gainers") -> list[dict[str, object]]: raise RuntimeError("webull down") monkeypatch.setattr("modules.discover.routes._service.get_webull_fallback", _boom) resp = client.get("/api/discover/fallback", params={"session": "market"}) assert resp.status_code == 500 # The provider's own text must not reach the client (HTTP-9): the handler # logs it and answers with the generic detail. assert resp.json()["detail"] == "Internal server error" assert "webull down" not in resp.text def test_reverse_splits_provider_failure_is_500(self, client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None: def _boom(symbol: str, days: int) -> list[dict[str, object]]: raise RuntimeError("defeatbeta down") monkeypatch.setattr("modules.lists.service._get_reverse_splits", _boom) resp = client.get("/api/reverse-splits", params={"symbol": "AAPL"}) assert resp.status_code == 500 assert resp.json()["detail"] == "Internal server error" assert "defeatbeta down" not in resp.text def test_reverse_splits_batch_ignores_per_symbol_failures( self, client: TestClient, monkeypatch: pytest.MonkeyPatch ) -> None: def _splits(symbol: str, days: int) -> list[dict[str, object]]: if symbol == "BAD": raise RuntimeError("no data") return [{"symbol": symbol, "ex_date": "2026-09-01", "ratio": "1:10", "old_rate": 10, "new_rate": 1}] monkeypatch.setattr("modules.lists.service._get_reverse_splits", _splits) # Detail runs only for symbols the calendar discovers (SRC-2): discover GOOD and BAD, # with an isolated discovery cache so no other test's rows leak in. monkeypatch.setattr("modules.lists.service._discovery_cache", {}) monkeypatch.setattr( "modules.lists.service._calendar_discover", lambda: [ {"symbol": "GOOD", "split_date": date.today().isoformat(), "ratio": "1:10"}, {"symbol": "BAD", "split_date": date.today().isoformat(), "ratio": "1:10"}, ], ) resp = client.get("/api/reverse-splits", params={"symbols": "GOOD,BAD"}) assert resp.status_code == 200 body = resp.json() assert body["count"] == 1 and body["reverse_splits"][0]["symbol"] == "GOOD" def test_reverse_splits_keeps_fractional_rates_and_skips_degenerate_ones( self, client: TestClient, monkeypatch: pytest.MonkeyPatch ) -> None: # int() truncation turned 1:2.5 into 1:2 and 0.2:1 into 0:1; a zero # rate is not a split at all and must be dropped, not rendered. recent = pd.Timestamp(date.today() - timedelta(days=1)).date() frame = pd.DataFrame( [ {"symbol": "AAPL", "ex_date": recent, "ratio": 1 / 2.5, "old_rate": 2.5, "new_rate": 1.0}, {"symbol": "AAPL", "ex_date": recent, "ratio": 0.2, "old_rate": 1.0, "new_rate": 0.2}, {"symbol": "AAPL", "ex_date": recent, "ratio": 0.0, "old_rate": 1.0, "new_rate": 0.0}, ] ) monkeypatch.setattr("modules.lists.service.splits_provider.get_splits", lambda symbol: frame) resp = client.get("/api/reverse-splits", params={"symbol": "AAPL"}) assert resp.status_code == 200 rows = resp.json()["reverse_splits"] assert [r["ratio"] for r in rows] == ["1:2.5", "0.2:1"] assert [r["new_rate"] for r in rows] == [1.0, 0.2] def test_screener_invalid_filter_is_400(self, client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None: class _FakeService: def run(self, **kwargs: object): raise ValueError("unknown column") monkeypatch.setattr("modules.screener.routes.ScreenerService", _FakeService) resp = client.post( "/api/screener", json={"columns": ["name"], "filters": [], "limit": 10}, ) assert resp.status_code == 400 assert "unknown column" in resp.json()["detail"] def test_screener_provider_failure_is_500(self, client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None: class _FakeService: def run(self, **kwargs: object): raise RuntimeError("tradingview down") monkeypatch.setattr("modules.screener.routes.ScreenerService", _FakeService) resp = client.post("/api/screener", json={"columns": ["name"], "filters": [], "limit": 10}) assert resp.status_code == 500 assert resp.json()["detail"] == "Internal server error" assert "tradingview down" not in resp.text def test_dashboard_news_feed_limit_bounds(self, client: TestClient) -> None: assert client.get("/api/dashboard/news-feed", params={"limit": 0}).status_code == 422 assert client.get("/api/dashboard/news-feed", params={"limit": 101}).status_code == 422 def test_dashboard_news_feed_upstream_failure_serves_empty( self, client: TestClient, monkeypatch: pytest.MonkeyPatch ) -> None: import modules.dashboard.routes as dash dash._news_feed_cache = None monkeypatch.setattr("modules.dashboard.routes._NEWS_FEED_TTL", 0.0) class _BoomClient: def __init__(self, *args: object, **kwargs: object) -> None: pass async def __aenter__(self) -> "_BoomClient": return self async def __aexit__(self, *args: object) -> None: return None async def get(self, url: str) -> object: raise RuntimeError("rss down") def raise_for_status(self) -> None: return None monkeypatch.setattr(dash.httpx, "AsyncClient", _BoomClient) resp = client.get("/api/dashboard/news-feed") assert resp.status_code == 200 assert resp.json() == {"items": []} def test_dashboard_filings_provider_failure_is_500( self, raw_client: TestClient, monkeypatch: pytest.MonkeyPatch ) -> None: def _boom(symbol: str) -> None: raise RuntimeError("edgar down") monkeypatch.setattr("modules.dashboard.routes.fetch_sec_submissions", _boom) resp = raw_client.get("/api/dashboard/filings/AAPL") assert resp.status_code == 500 # unexpected exception propagates as 500 def test_dashboard_filings_no_submissions_is_empty( self, client: TestClient, monkeypatch: pytest.MonkeyPatch ) -> None: monkeypatch.setattr("modules.dashboard.routes.fetch_sec_submissions", lambda symbol: None) resp = client.get("/api/dashboard/filings/AAPL") assert resp.status_code == 200 assert resp.json() == {"filings": []} def test_scan_calendar_export_no_data_404(self, client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None: from core.shared.cache import cache_clear cache_clear() monkeypatch.setattr( "modules.scan.routes.scan_service.get_scan_calendar_data", lambda *args, **kwargs: {}, ) resp = client.get("/api/scan/calendar/export") assert resp.status_code == 404 cache_clear() def test_scan_calendar_shape(self, client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None: from core.shared.cache import cache_clear cache_clear() monkeypatch.setattr( "modules.scan.routes.scan_service.get_scan_calendar_data", lambda *args, **kwargs: {"2026-09-25": []}, ) resp = client.get("/api/scan/calendar", params={"year": 2026, "month": 9}) assert resp.status_code == 200 body = resp.json() assert body["year"] == 2026 and body["month"] == 9 assert body["data"] == {"2026-09-25": []} cache_clear() def test_scan_etag_round_trip(self, client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None: from core.shared.cache import cache_clear cache_clear() row = { "symbol": "AAPL", "date": "2026-09-25", "daily_bars": [{"time": "2026-09-25", "open": 1.0, "high": 1.0, "low": 1.0, "close": 1.0, "volume": 1}], } monkeypatch.setattr( "modules.scan.routes.scan_service.scan", lambda *args, **kwargs: ([row], False), ) first = client.get("/api/scan", params={"symbols": "AAPL", "timeframe": "1D"}) assert first.status_code == 200 etag = first.headers.get("ETag") assert etag assert first.json()["count"] == 1 second = client.get("/api/scan", params={"symbols": "AAPL", "timeframe": "1D"}, headers={"if-none-match": etag}) assert second.status_code == 304 cache_clear() def test_scan_symbol_list_with_filter_warns(self, client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None: from core.shared.cache import cache_clear cache_clear() monkeypatch.setattr( "modules.scan.routes.scan_service.scan", lambda *args, **kwargs: ([], False), ) resp = client.get("/api/scan", params={"symbols": "AAPL", "filter": "price > vwap", "timeframe": "1D"}) assert resp.status_code == 200 assert any("not applied" in w for w in resp.json()["warnings"]) cache_clear() def test_chat_rejects_missing_body(self, client: TestClient) -> None: assert client.post("/api/chat").status_code == 422 class TestProviderTimeoutFallback(_ContractBase): """Provider-timeout fallback: transient upstream failures must never be served as cached empty results (plan TEST-T4 crosses here for routes).""" def test_ohlc_upstream_failure_is_not_cached(self, client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None: """A 502 from /ohlc must not poison the cache: the next call with a working provider succeeds.""" from core.shared.cache import cache_clear cache_clear() fail = True async def _flaky(symbol: str, timeframe: str): if fail: return None, None return [{"time": 1, "open": 1.0, "high": 1.0, "low": 1.0, "close": 1.0, "volume": 1}], "yahoo" monkeypatch.setattr("modules.chart.routes.fetch_main_bars", _flaky) monkeypatch.setattr("modules.chart.routes.compute_prev_day", lambda daily: {}) assert client.get("/api/chart/ohlc", params={"symbol": "AAPL", "timeframe": "1d"}).status_code == 502 fail = False resp = client.get("/api/chart/ohlc", params={"symbol": "AAPL", "timeframe": "1d"}) assert resp.status_code == 200 assert resp.json()["bars"] cache_clear()