Repository Public MIT
1// @vitest-environment node2/**3 * =============================================================================4 * SP BOUCHER | SOFTWARE & RESEARCH5 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING6 * =============================================================================7 *8 * Project : VQuant9 * File : server/next/health.test.ts10 * Module : server11 * Repository : https://git.spboucher.ai/vquant12 * Project Website : https://vquant.spboucher.ai13 * Created : 2026-11-2014 * Last Modified : 2026-11-2015 *16 * Author : Simon-Pierre Boucher17 * Position : Professor of Finance18 * Institution : Université du Québec en Outaouais (UQO)19 * Organization : SP Boucher20 * Website : https://spboucher.ai21 * Git : https://git.spboucher.ai22 *23 * Preferred Contact: contact@spboucher.ai24 * Development : dev@spboucher.ai25 * Support : support@spboucher.ai26 * Security/Admin : admin@spboucher.ai27 *28 * Copyright (c) 202629 * Simon-Pierre Boucher30 * All rights reserved where applicable. This file is governed by the31 * applicable project license, copyright notices and relevant law.32 * Existing third-party rights and notices remain unaffected.33 *34 * SPDX Identifier : MIT35 * License : MIT License36 * License File : LICENSE37 *38 * Do not embed credentials, private keys, access tokens,39 * certificates or confidential personal information.40 *41 * =============================================================================42 * END OF SP BOUCHER SOURCE HEADER43 * =============================================================================44 */4546import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";47import { resetDataLayer } from "./dataLayer";48import { PROBES, getDataHealth, resetHealth, summarizeCapabilities, type CapabilityResult } from "./health";4950const KEYS = { FMP_API_KEY: "fmp-test-key-0123456789", FINDATA_API_KEY: "findata-test-key-0123456789", EODHD_API_KEY: "eodhd-test-key-0123456789" };5152beforeEach(() => {53 Object.assign(process.env, KEYS);54 resetDataLayer();55 resetHealth();56});57afterEach(() => vi.unstubAllGlobals());5859const cap = (id: string, label: string, status: CapabilityResult["status"], detail: string | null = null): CapabilityResult => ({ id, label, ok: status === "ok", status, detail, latencyMs: 5, checkedAt: 1 });6061describe("summarizeCapabilities", () => {62 it("lists what works as coverage and what the plan refuses in the notes", () => {63 const s = summarizeCapabilities("eodhd", [cap("delayed_quotes", "delayed quotes", "ok"), cap("options", "option chains (US)", "ok"), cap("fundamentals", "fundamentals", "plan", "403"), cap("macro", "macro indicators", "plan"), cap("news", "news", "timeout")]);64 expect(s.coverage).toEqual(["delayed quotes", "option chains (US)"]);65 expect(s.notes).toMatch(/Refused by the current plan: fundamentals, macro indicators\./);66 expect(s.notes).toMatch(/Could not be checked just now: news \(timeout\)/);67 expect(s.notes).toMatch(/delayed about 15–20 minutes/);68 });69});7071describe("getDataHealth", () => {72 it("probes each provider, reports real coverage, caches, and leaks nothing", async () => {73 const fetchMock = vi.fn(async (input: URL | string, init?: RequestInit) => {74 const url = new URL(String(input));75 const p = url.pathname;76 const json = (body: unknown, status = 200) => new Response(typeof body === "string" ? body : JSON.stringify(body), { status });77 if (url.host.includes("financialmodelingprep")) {78 if (p.endsWith("/economic-calendar")) return json({ "Error Message": `Premium endpoint, see https://x.example/?apikey=${KEYS.FMP_API_KEY}` }, 402);79 if (p.endsWith("/quote")) return json([{ symbol: url.searchParams.get("symbol"), price: 10 }]);80 if (p.endsWith("/biggest-gainers")) return json([]);81 return json([{ date: "2026-11-19", any: 1 }]);82 }83 if (url.host.includes("eodhd")) {84 if (p.includes("/real-time/")) return json({ code: "AAPL.US", close: 342.99, timestamp: 1795203060 });85 if (p.includes("/fundamentals/") || p.includes("/calendar/") || p.includes("/economic-events") || p.includes("/macro-indicator")) return json("Forbidden", 403);86 if (p.includes("/options/")) return json({ data: [{ id: "X" }] });87 return json([{ date: "2026-11-19" }]);88 }89 // FinData90 if (p.endsWith("/market/bars")) return json({ data: [{ session_date: "2026-11-18" }, { session_date: "2026-11-19" }] });91 if (p.endsWith("/query")) {92 const sql = String(JSON.parse(String(init?.body)).sql);93 if (sql.includes("options_eod")) return json({ rows: [{ d: "2026-10-30" }] });94 if (sql.includes("_fx_")) return json({ error: { code: "query_error", message: "Catalog Error: Table does not exist" } }, 400);95 return json({ rows: [{ session_date: "2026-11-13" }] });96 }97 if (p.includes("/fundamentals/")) return json({ data: [{ metric: "Revenues" }] });98 return json({});99 });100 vi.stubGlobal("fetch", fetchMock);101102 const h = await getDataHealth();103 expect(h.providers.map((p) => p.id)).toEqual(["fmp", "findata", "eodhd"]);104 const [fmp, findata, eodhd] = h.providers;105106 expect(fmp).toMatchObject({ configured: true, ok: true, error: null });107 expect(typeof fmp.latencyMs).toBe("number");108 expect(fmp.coverage).toContain("financial statements");109 expect(fmp.coverage).not.toContain("economic calendar");110 expect(fmp.coverage).not.toContain("market movers"); // answered, but with nothing111 expect(fmp.notes).toMatch(/Refused by the current plan: economic calendar\./);112 expect(fmp.notes).toMatch(/Answered without data: market movers\./);113114 expect(findata.ok).toBe(true);115 expect(findata.notes).toMatch(/last session loaded: 2026-11-19/);116 expect(findata.notes).toMatch(/latest chain: 2026-10-30/);117 expect(findata.coverage).not.toContain("currency intraday bars (no daily series)");118119 expect(eodhd.coverage).toEqual(["delayed quotes", "end-of-day bars", "intraday bars", "option chains (US)", "news"]);120 expect(eodhd.notes).toMatch(/Refused by the current plan: fundamentals, earnings calendar, economic events, macro indicators\./);121 expect(eodhd.capabilities.find((c) => c.id === "fundamentals")).toMatchObject({ ok: false, status: "plan" });122123 // Probes do not count as traffic of the data layer.124 expect(h.providers.every((p) => p.calls === 0 && p.errors === 0)).toBe(true);125 const text = JSON.stringify(h);126 for (const k of Object.values(KEYS)) expect(text).not.toContain(k);127 expect(text).not.toMatch(/apikey=|api_token=|https?:\/\//);128129 const n = fetchMock.mock.calls.length;130 expect(n).toBe(PROBES.fmp.length + PROBES.findata.length + PROBES.eodhd.length);131 await getDataHealth();132 expect(fetchMock.mock.calls.length).toBe(n); // 60 s cache133 });134135 it("reports an unconfigured provider without probing it, and a dead one with a sanitized error", async () => {136 process.env.EODHD_API_KEY = "";137 const fetchMock = vi.fn(async (input: URL | string) => {138 const url = new URL(String(input));139 if (url.host.includes("findata")) throw Object.assign(new TypeError("fetch failed"), { cause: { code: "ECONNREFUSED" } });140 return new Response(JSON.stringify([{ symbol: "AAPL", price: 1, date: "2026-11-19" }]), { status: 200 });141 });142 vi.stubGlobal("fetch", fetchMock);143 const { providers } = await getDataHealth();144 const eodhd = providers.find((p) => p.id === "eodhd")!;145 expect(eodhd).toMatchObject({ configured: false, ok: false, latencyMs: null, coverage: [], capabilities: [] });146 expect(eodhd.notes).toMatch(/Not configured/);147 expect(fetchMock.mock.calls.some((c) => String(c[0]).includes("eodhd"))).toBe(false);148 const findata = providers.find((p) => p.id === "findata")!;149 expect(findata).toMatchObject({ configured: true, ok: false, coverage: [] });150 expect(findata.error).toMatch(/unreachable \(ECONNREFUSED\)/);151 });152});153