|
| 1 | +import { afterEach, beforeEach, describe, expect, test } from "bun:test"; |
| 2 | +import { RealPromClient } from "./real.ts"; |
| 3 | + |
| 4 | +const ORIGINAL_FETCH = globalThis.fetch; |
| 5 | + |
| 6 | +interface CapturedRequest { |
| 7 | + url: string; |
| 8 | + headers: Record<string, string>; |
| 9 | +} |
| 10 | + |
| 11 | +function installMockFetch(responder: (req: CapturedRequest) => unknown): CapturedRequest[] { |
| 12 | + const requests: CapturedRequest[] = []; |
| 13 | + globalThis.fetch = (async (input: unknown, init?: RequestInit): Promise<Response> => { |
| 14 | + const url = typeof input === "string" ? input : String(input); |
| 15 | + const headers: Record<string, string> = {}; |
| 16 | + const raw = init?.headers ?? {}; |
| 17 | + if (raw instanceof Headers) { |
| 18 | + raw.forEach((v, k) => { |
| 19 | + headers[k.toLowerCase()] = v; |
| 20 | + }); |
| 21 | + } else if (Array.isArray(raw)) { |
| 22 | + for (const [k, v] of raw as Array<[string, string]>) headers[k.toLowerCase()] = v; |
| 23 | + } else { |
| 24 | + for (const [k, v] of Object.entries(raw as Record<string, string>)) { |
| 25 | + headers[k.toLowerCase()] = v; |
| 26 | + } |
| 27 | + } |
| 28 | + const captured: CapturedRequest = { url, headers }; |
| 29 | + requests.push(captured); |
| 30 | + const data = responder(captured); |
| 31 | + return new Response(JSON.stringify({ status: "success", data }), { |
| 32 | + headers: { "content-type": "application/json" }, |
| 33 | + }); |
| 34 | + }) as typeof fetch; |
| 35 | + return requests; |
| 36 | +} |
| 37 | + |
| 38 | +beforeEach(() => { |
| 39 | + // ensure clean state |
| 40 | +}); |
| 41 | + |
| 42 | +afterEach(() => { |
| 43 | + globalThis.fetch = ORIGINAL_FETCH; |
| 44 | +}); |
| 45 | + |
| 46 | +describe("RealPromClient.headers", () => { |
| 47 | + test("uses tokenProvider per request and overrides static bearerToken", async () => { |
| 48 | + let count = 0; |
| 49 | + const tokenProvider = async () => `t-${++count}`; |
| 50 | + const requests = installMockFetch(() => []); |
| 51 | + const client = new RealPromClient({ |
| 52 | + baseUrl: "https://prom.example.com", |
| 53 | + bearerToken: "static-loses", |
| 54 | + tokenProvider, |
| 55 | + }); |
| 56 | + await client.listMetrics({}); |
| 57 | + await client.listMetrics({}); |
| 58 | + expect(requests).toHaveLength(2); |
| 59 | + expect(requests[0]!.headers.authorization).toBe("Bearer t-1"); |
| 60 | + expect(requests[1]!.headers.authorization).toBe("Bearer t-2"); |
| 61 | + }); |
| 62 | + |
| 63 | + test("falls back to static bearerToken when no provider", async () => { |
| 64 | + const requests = installMockFetch(() => []); |
| 65 | + const client = new RealPromClient({ |
| 66 | + baseUrl: "https://prom.example.com", |
| 67 | + bearerToken: "abc", |
| 68 | + }); |
| 69 | + await client.listMetrics({}); |
| 70 | + expect(requests[0]!.headers.authorization).toBe("Bearer abc"); |
| 71 | + }); |
| 72 | + |
| 73 | + test("falls back to basic auth when no token sources", async () => { |
| 74 | + const requests = installMockFetch(() => []); |
| 75 | + const client = new RealPromClient({ |
| 76 | + baseUrl: "https://prom.example.com", |
| 77 | + basicAuth: { user: "u", password: "p" }, |
| 78 | + }); |
| 79 | + await client.listMetrics({}); |
| 80 | + const expected = `Basic ${Buffer.from("u:p").toString("base64")}`; |
| 81 | + expect(requests[0]!.headers.authorization).toBe(expected); |
| 82 | + }); |
| 83 | + |
| 84 | + test("omits Authorization when no auth configured", async () => { |
| 85 | + const requests = installMockFetch(() => []); |
| 86 | + const client = new RealPromClient({ baseUrl: "https://prom.example.com" }); |
| 87 | + await client.listMetrics({}); |
| 88 | + expect(requests[0]!.headers.authorization).toBeUndefined(); |
| 89 | + }); |
| 90 | +}); |
| 91 | + |
| 92 | +describe("RealPromClient parsers", () => { |
| 93 | + test("metricMetadata normalises Record<metric, items[]> shape", async () => { |
| 94 | + installMockFetch(() => ({ |
| 95 | + http_requests_total: [{ type: "counter", help: "Total requests.", unit: "" }], |
| 96 | + kube_pod_status_phase: [{ type: "gauge", help: "Phase.", unit: "" }], |
| 97 | + })); |
| 98 | + const client = new RealPromClient({ baseUrl: "https://prom.example.com" }); |
| 99 | + const md = await client.metricMetadata({}); |
| 100 | + expect(md).toHaveLength(2); |
| 101 | + expect(md.find((m) => m.metric === "http_requests_total")?.type).toBe("counter"); |
| 102 | + }); |
| 103 | + |
| 104 | + test("targets returns down lastError and filters by job", async () => { |
| 105 | + installMockFetch(() => ({ |
| 106 | + activeTargets: [ |
| 107 | + { |
| 108 | + labels: { job: "payments", instance: "i1" }, |
| 109 | + health: "down", |
| 110 | + lastError: "connection refused", |
| 111 | + scrapeUrl: "http://i1/metrics", |
| 112 | + }, |
| 113 | + { |
| 114 | + labels: { job: "billing", instance: "i2" }, |
| 115 | + health: "up", |
| 116 | + scrapeUrl: "http://i2/metrics", |
| 117 | + }, |
| 118 | + ], |
| 119 | + })); |
| 120 | + const client = new RealPromClient({ baseUrl: "https://prom.example.com" }); |
| 121 | + const all = await client.targets({}); |
| 122 | + expect(all).toHaveLength(2); |
| 123 | + const payments = await client.targets({ job: "payments" }); |
| 124 | + expect(payments).toHaveLength(1); |
| 125 | + expect(payments[0]!.lastError).toBe("connection refused"); |
| 126 | + }); |
| 127 | + |
| 128 | + test("listMetrics filters by case-insensitive substring", async () => { |
| 129 | + installMockFetch(() => ["http_requests_total", "kube_pod_status_phase"]); |
| 130 | + const client = new RealPromClient({ baseUrl: "https://prom.example.com" }); |
| 131 | + const m = await client.listMetrics({ contains: "HTTP" }); |
| 132 | + expect(m).toEqual(["http_requests_total"]); |
| 133 | + }); |
| 134 | +}); |
0 commit comments