Files
homarr/packages/integrations/src/unifi-os/test/unifi-sm-api.spec.ts
T

174 lines
5.5 KiB
TypeScript

// @vitest-environment node
import { Response, type RequestInit } from "undici";
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
vi.hoisted(() => {
process.env.SKIP_ENV_VALIDATION = "true";
process.env.SECRET_ENCRYPTION_KEY = "ff3f4f7ce30e870c9630de9e5d244ffa81101a24ed0dfe5f064beb53a7e684f1";
});
import { UnifiSmApi } from "../unifi-sm-api";
const GATEWAY_MAC = "aa:bb:cc:11:22:33";
const OTHER_MAC = "dd:ee:ff:44:55:66";
const jsonResponse = (body: unknown, status = 200) =>
new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } }) as never;
const sitesBody = {
data: [
{
siteId: "mine",
meta: { desc: "Mine", gatewayMac: GATEWAY_MAC },
statistics: { wans: { WAN: { externalIp: "203.0.113.10" } } },
},
{ siteId: "theirs", meta: { desc: "Theirs", gatewayMac: OTHER_MAC } },
],
};
const metricsBody = (metricTime: string) => ({
data: {
metrics: [
{
periods: [
{
metricTime: "2026-09-08T08:00:00Z",
data: { wan: { avgLatency: 99, maxLatency: 99, packetLoss: 5, uptime: 90, ispName: "Old" } },
},
{
metricTime,
data: { wan: { avgLatency: 11, maxLatency: 12, packetLoss: 0, uptime: 100, ispName: "Example ISP" } },
},
],
},
],
},
});
const createApi = () => {
const fetchAsync = vi.fn(async (url: string, _init?: RequestInit) =>
url.includes("isp-metrics") ? jsonResponse(metricsBody("2026-09-08T09:10:00Z")) : jsonResponse(sitesBody),
);
return { api: new UnifiSmApi("cloud-key", fetchAsync as never), fetchAsync };
};
beforeEach(() => {
UnifiSmApi.clearCache();
vi.useFakeTimers();
vi.setSystemTime(new Date("2026-09-08T09:37:00Z"));
});
afterEach(() => {
vi.useRealTimers();
});
describe("UnifiSmApi getIspMetricsAsync", () => {
test("returns the newest period of the site matching the gateway MAC", async () => {
const { api } = createApi();
const metrics = await api.getIspMetricsAsync(GATEWAY_MAC);
expect(metrics).toEqual({
name: "Example ISP",
externalIp: "203.0.113.10",
latencyMs: 11,
maxLatencyMs: 12,
packetLossPct: 0,
uptimePct: 100,
measuredAt: new Date("2026-09-08T09:10:00Z"),
});
});
test("returns the newest period by metricTime even when periods arrive out of order", async () => {
const fetchAsync = vi.fn(async (url: string, _init?: RequestInit) => {
if (!url.includes("isp-metrics")) return jsonResponse(sitesBody);
return jsonResponse({
data: {
metrics: [
{
periods: [
{
metricTime: "2026-09-08T09:10:00Z",
data: {
wan: { avgLatency: 11, maxLatency: 12, packetLoss: 0, uptime: 100, ispName: "Example ISP" },
},
},
{
metricTime: "2026-09-08T08:00:00Z",
data: { wan: { avgLatency: 99, maxLatency: 99, packetLoss: 5, uptime: 90, ispName: "Old" } },
},
],
},
],
},
});
});
const api = new UnifiSmApi("cloud-key", fetchAsync as never);
const metrics = await api.getIspMetricsAsync(GATEWAY_MAC);
expect(metrics?.latencyMs).toBe(11);
expect(metrics?.measuredAt).toEqual(new Date("2026-09-08T09:10:00Z"));
});
test("returns null when no cloud site matches, never another account site", async () => {
const { api } = createApi();
expect(await api.getIspMetricsAsync("11:22:33:44:55:66")).toBeNull();
});
test("returns null when the local gateway could not be identified", async () => {
const { api, fetchAsync } = createApi();
expect(await api.getIspMetricsAsync(null)).toBeNull();
expect(fetchAsync).not.toHaveBeenCalled();
});
test("queries a window wide enough for the cloud lag", async () => {
const { api, fetchAsync } = createApi();
await api.getIspMetricsAsync(GATEWAY_MAC);
const body = JSON.parse(
String(fetchAsync.mock.calls.find(([url]) => String(url).includes("isp-metrics"))?.[1]?.body),
);
const begin = new Date(body.sites[0].beginTimestamp).getTime();
const end = new Date(body.sites[0].endTimestamp).getTime();
// Une fenêtre de 15 min renvoie un tableau vide sur l'API réelle.
expect(end - begin).toBeGreaterThanOrEqual(3 * 60 * 60 * 1000);
});
test("serves a second call from cache instead of hitting the cloud again", async () => {
const { api, fetchAsync } = createApi();
await api.getIspMetricsAsync(GATEWAY_MAC);
const callsAfterFirst = fetchAsync.mock.calls.length;
await api.getIspMetricsAsync(GATEWAY_MAC);
expect(fetchAsync.mock.calls.length).toBe(callsAfterFirst);
});
test("refetches once the cache entry has expired", async () => {
const { api, fetchAsync } = createApi();
await api.getIspMetricsAsync(GATEWAY_MAC);
const callsAfterFirst = fetchAsync.mock.calls.length;
vi.setSystemTime(new Date("2026-09-08T09:43:00Z"));
await api.getIspMetricsAsync(GATEWAY_MAC);
expect(fetchAsync.mock.calls.length).toBeGreaterThan(callsAfterFirst);
});
test("returns null when the cloud rejects the key rather than propagating", async () => {
const fetchAsync = vi.fn(async (_url: string, _init?: RequestInit) =>
jsonResponse({ message: "unauthorized" }, 401),
);
const api = new UnifiSmApi("bad-key", fetchAsync as never);
expect(await api.getIspMetricsAsync(GATEWAY_MAC)).toBeNull();
});
});