mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-16 15:23:29 +00:00
Merge the review fixes for channel tests
This commit is contained in:
commit
669058d37c
18 files changed
+583
-87
No files matched your search
@@ -0,0 +1,76 @@
|
||||
/**
|
||||
* The admin notification test toast names each failing channel's cause
|
||||
* (review L5): the code the route sends is translated and the status is
|
||||
* shown, so the per-channel fields in the response have a reader.
|
||||
*/
|
||||
import { readFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { describeChannelTestFailures } from "../notification-test-failures";
|
||||
|
||||
const MESSAGES: Record<string, string> = {
|
||||
"settings.testConnection.errors.upstream_rejected":
|
||||
"The other end refused the message",
|
||||
"settings.testConnection.errors.credentials_rejected": "Credentials rejected",
|
||||
"admin.notificationTestFailed": "Failed to send test notification",
|
||||
};
|
||||
const t = (key: string) => MESSAGES[key] ?? key;
|
||||
|
||||
describe("describeChannelTestFailures", () => {
|
||||
it("lists only failing channels, with the translated cause and the status", () => {
|
||||
expect(
|
||||
describeChannelTestFailures(
|
||||
[
|
||||
{ channel: "APNS", success: true },
|
||||
{
|
||||
channel: "WEBHOOK",
|
||||
success: false,
|
||||
error: "The webhook answered HTTP 400.",
|
||||
errorCode: "upstream_rejected",
|
||||
upstreamStatus: 400,
|
||||
},
|
||||
{
|
||||
channel: "EMAIL",
|
||||
success: false,
|
||||
error: "The mail server rejected the credentials (SMTP 535).",
|
||||
errorCode: "credentials_rejected",
|
||||
smtpCode: 535,
|
||||
},
|
||||
],
|
||||
t,
|
||||
),
|
||||
).toEqual([
|
||||
"Webhook: The other end refused the message (HTTP 400)",
|
||||
"Email: Credentials rejected (SMTP 535)",
|
||||
]);
|
||||
});
|
||||
|
||||
it("falls back to the route's sentence when there is no known code", () => {
|
||||
expect(
|
||||
describeChannelTestFailures(
|
||||
[
|
||||
{
|
||||
channel: "NTFY",
|
||||
success: false,
|
||||
error: "SYSTEM_ALERT disabled in settings",
|
||||
},
|
||||
{ channel: "MYSTERY", success: false, errorCode: "unlisted" },
|
||||
],
|
||||
t,
|
||||
),
|
||||
).toEqual([
|
||||
"ntfy: SYSTEM_ALERT disabled in settings",
|
||||
"MYSTERY: Failed to send test notification",
|
||||
]);
|
||||
});
|
||||
|
||||
it("is what the admin toast renders", () => {
|
||||
const src = readFileSync(
|
||||
join(process.cwd(), "src/components/admin/reminders-section.tsx"),
|
||||
"utf8",
|
||||
);
|
||||
expect(src).toMatch(/describeChannelTestFailures\(data\?\.results/);
|
||||
expect(src).toMatch(/description:/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,46 @@
|
||||
import {
|
||||
CHANNEL_TYPE_LABELS,
|
||||
type ChannelType,
|
||||
} from "@/lib/notifications/types";
|
||||
|
||||
/** One channel's row in the admin notification test response. */
|
||||
export interface ChannelTestResult {
|
||||
channel: string;
|
||||
success: boolean;
|
||||
error?: string;
|
||||
errorCode?: string;
|
||||
upstreamStatus?: number;
|
||||
smtpCode?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* One line per failing channel for the admin test toast: the channel name,
|
||||
* the cause in the admin's language (the same `settings.testConnection.errors`
|
||||
* vocabulary the settings cards use), and the HTTP status or SMTP reply code.
|
||||
* A row without a known code falls back to the route's own sentence.
|
||||
*/
|
||||
export function describeChannelTestFailures(
|
||||
results: ReadonlyArray<ChannelTestResult>,
|
||||
t: (key: string) => string,
|
||||
): string[] {
|
||||
return results
|
||||
.filter((r) => !r.success)
|
||||
.map((r) => {
|
||||
const label = CHANNEL_TYPE_LABELS[r.channel as ChannelType] ?? r.channel;
|
||||
const key = r.errorCode
|
||||
? `settings.testConnection.errors.${r.errorCode}`
|
||||
: null;
|
||||
const translated = key ? t(key) : null;
|
||||
const cause =
|
||||
translated && translated !== key
|
||||
? translated
|
||||
: (r.error ?? t("admin.notificationTestFailed"));
|
||||
const code =
|
||||
typeof r.upstreamStatus === "number"
|
||||
? ` (HTTP ${r.upstreamStatus})`
|
||||
: typeof r.smtpCode === "number"
|
||||
? ` (SMTP ${r.smtpCode})`
|
||||
: "";
|
||||
return `${label}: ${cause}${code}`;
|
||||
});
|
||||
}
|
||||
@@ -22,6 +22,10 @@ import { useTranslations } from "@/lib/i18n/context";
|
||||
import { queryKeys } from "@/lib/query-keys";
|
||||
import { useAdminSettings, useUpdateSettings } from "./_shared";
|
||||
import { apiGet, apiPost } from "@/lib/api/api-fetch";
|
||||
import {
|
||||
describeChannelTestFailures,
|
||||
type ChannelTestResult,
|
||||
} from "./notification-test-failures";
|
||||
|
||||
interface NotificationHealth {
|
||||
windowHours: number;
|
||||
@@ -132,19 +136,23 @@ export function RemindersSection() {
|
||||
return apiPost<
|
||||
| {
|
||||
message?: string;
|
||||
results?: Array<{
|
||||
channel: string;
|
||||
success: boolean;
|
||||
error?: string;
|
||||
}>;
|
||||
results?: ChannelTestResult[];
|
||||
}
|
||||
| undefined
|
||||
>("/api/admin/notifications/test");
|
||||
},
|
||||
onSuccess: (data) => {
|
||||
const hasFailures = data?.results?.some((r) => !r.success);
|
||||
if (hasFailures) {
|
||||
toast.error(data?.message ?? t("admin.notificationTestFailed"));
|
||||
const failures = describeChannelTestFailures(data?.results ?? [], t);
|
||||
if (failures.length > 0) {
|
||||
toast.error(data?.message ?? t("admin.notificationTestFailed"), {
|
||||
description: (
|
||||
<ul className="space-y-0.5">
|
||||
{failures.map((line) => (
|
||||
<li key={line}>{line}</li>
|
||||
))}
|
||||
</ul>
|
||||
),
|
||||
});
|
||||
} else {
|
||||
toast.success(data?.message ?? t("admin.notificationTestSuccess"));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
/**
|
||||
* How the test-connection button reads a real failure response (#947).
|
||||
*
|
||||
* The component suite is SSR-only, so the button's probe is exercised as the
|
||||
* function the button calls: `apiFetchRaw` is stubbed with the envelope a
|
||||
* notification test route sends, and the result is rendered through the same
|
||||
* callout the button renders. Removing the meta extraction turns this red.
|
||||
*/
|
||||
import { readFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const apiFetchRawMock = vi.fn();
|
||||
vi.mock("@/lib/api/api-fetch", () => ({
|
||||
apiFetchRaw: (...args: unknown[]) => apiFetchRawMock(...args),
|
||||
}));
|
||||
|
||||
import {
|
||||
runConnectionTest,
|
||||
TestConnectionFailure,
|
||||
} from "../test-connection-button";
|
||||
|
||||
function envelope(status: number, body: unknown): Response {
|
||||
return new Response(JSON.stringify(body), {
|
||||
status,
|
||||
headers: { "Content-Type": "application/json" },
|
||||
});
|
||||
}
|
||||
|
||||
function renderFailure(
|
||||
result: Awaited<ReturnType<typeof runConnectionTest>>,
|
||||
): string {
|
||||
if (result.kind !== "error") throw new Error("expected a failure");
|
||||
return renderToStaticMarkup(
|
||||
<TestConnectionFailure
|
||||
message={`code:${result.errorCode}`}
|
||||
upstreamStatus={result.upstreamStatus}
|
||||
smtpCode={result.smtpCode}
|
||||
upstreamBody={result.upstreamBody}
|
||||
/>,
|
||||
);
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
apiFetchRawMock.mockReset();
|
||||
});
|
||||
|
||||
describe("runConnectionTest", () => {
|
||||
it("reads the code, the HTTP status and what the relay said from a 502", async () => {
|
||||
apiFetchRawMock.mockResolvedValue(
|
||||
envelope(502, {
|
||||
data: null,
|
||||
error: "The webhook answered HTTP 400.",
|
||||
meta: {
|
||||
errorCode: "upstream_rejected",
|
||||
upstreamStatus: 400,
|
||||
upstreamBody: "priority must be an integer",
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
const result = await runConnectionTest("/api/settings/webhook/test");
|
||||
|
||||
expect(apiFetchRawMock).toHaveBeenCalledWith("/api/settings/webhook/test", {
|
||||
method: "POST",
|
||||
});
|
||||
const html = renderFailure(result);
|
||||
expect(html).toContain("code:upstream_rejected (HTTP 400)");
|
||||
expect(html).toContain("priority must be an integer");
|
||||
});
|
||||
|
||||
it("reads the SMTP reply code from an email failure", async () => {
|
||||
apiFetchRawMock.mockResolvedValue(
|
||||
envelope(502, {
|
||||
data: null,
|
||||
error: "The mail server rejected the credentials (SMTP 535).",
|
||||
meta: { errorCode: "credentials_rejected", smtpCode: 535 },
|
||||
}),
|
||||
);
|
||||
|
||||
const html = renderFailure(
|
||||
await runConnectionTest("/api/settings/email/test"),
|
||||
);
|
||||
|
||||
expect(html).toContain("code:credentials_rejected (SMTP 535)");
|
||||
expect(html).not.toContain("test-connection-upstream-body");
|
||||
});
|
||||
|
||||
it("falls back to the generic code when a proxy replaced the body", async () => {
|
||||
apiFetchRawMock.mockResolvedValue(
|
||||
new Response("<html>Bad Gateway</html>", { status: 502 }),
|
||||
);
|
||||
|
||||
expect(await runConnectionTest("/api/settings/ntfy/test")).toEqual({
|
||||
kind: "error",
|
||||
errorCode: "generic",
|
||||
upstreamStatus: undefined,
|
||||
smtpCode: undefined,
|
||||
upstreamBody: undefined,
|
||||
});
|
||||
});
|
||||
|
||||
it("reports success with the latency", async () => {
|
||||
apiFetchRawMock.mockResolvedValue(
|
||||
envelope(200, { data: { ok: true, latencyMs: 42 }, error: null }),
|
||||
);
|
||||
|
||||
expect(await runConnectionTest("/api/nightscout/test")).toEqual({
|
||||
kind: "ok",
|
||||
latency: 42,
|
||||
});
|
||||
});
|
||||
|
||||
it("is what the button calls", () => {
|
||||
const src = readFileSync(
|
||||
join(process.cwd(), "src/components/settings/test-connection-button.tsx"),
|
||||
"utf8",
|
||||
);
|
||||
expect(src).toMatch(/setResult\(await runConnectionTest\(endpoint\)\)/);
|
||||
});
|
||||
});
|
||||
@@ -82,6 +82,48 @@ export function TestConnectionFailure({
|
||||
);
|
||||
}
|
||||
|
||||
export type ConnectionTestResult =
|
||||
| { kind: "ok"; latency: number }
|
||||
| {
|
||||
kind: "error";
|
||||
errorCode: string;
|
||||
upstreamStatus?: number;
|
||||
smtpCode?: number;
|
||||
upstreamBody?: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* The button's probe: POST the endpoint and read the envelope into what the
|
||||
* button shows. Exported so the reading of a real failure response can be
|
||||
* tested without a DOM.
|
||||
*/
|
||||
export async function runConnectionTest(
|
||||
endpoint: string,
|
||||
): Promise<ConnectionTestResult> {
|
||||
try {
|
||||
const res = await apiFetchRaw(endpoint, { method: "POST" });
|
||||
const json = (await res.json().catch(() => ({}))) as TestResponse;
|
||||
|
||||
if (res.ok && json.data?.ok !== false) {
|
||||
return { kind: "ok", latency: json.data?.latencyMs ?? 0 };
|
||||
}
|
||||
const meta = json.meta;
|
||||
return {
|
||||
kind: "error",
|
||||
errorCode: meta?.errorCode ?? "generic",
|
||||
upstreamStatus:
|
||||
typeof meta?.upstreamStatus === "number"
|
||||
? meta.upstreamStatus
|
||||
: undefined,
|
||||
smtpCode: typeof meta?.smtpCode === "number" ? meta.smtpCode : undefined,
|
||||
upstreamBody:
|
||||
typeof meta?.upstreamBody === "string" ? meta.upstreamBody : undefined,
|
||||
};
|
||||
} catch {
|
||||
return { kind: "error", errorCode: "connection_failed" };
|
||||
}
|
||||
}
|
||||
|
||||
export function TestConnectionButton({
|
||||
endpoint,
|
||||
disabled = false,
|
||||
@@ -89,49 +131,13 @@ export function TestConnectionButton({
|
||||
}: TestConnectionButtonProps) {
|
||||
const { t } = useTranslations();
|
||||
const [testing, setTesting] = useState(false);
|
||||
const [result, setResult] = useState<
|
||||
| { kind: "ok"; latency: number }
|
||||
| {
|
||||
kind: "error";
|
||||
errorCode: string;
|
||||
upstreamStatus?: number;
|
||||
smtpCode?: number;
|
||||
upstreamBody?: string;
|
||||
}
|
||||
| null
|
||||
>(null);
|
||||
const [result, setResult] = useState<ConnectionTestResult | null>(null);
|
||||
|
||||
async function handleClick() {
|
||||
setTesting(true);
|
||||
setResult(null);
|
||||
try {
|
||||
const res = await apiFetchRaw(endpoint, { method: "POST" });
|
||||
const json = (await res.json().catch(() => ({}))) as TestResponse;
|
||||
|
||||
if (res.ok && json.data?.ok !== false) {
|
||||
setResult({
|
||||
kind: "ok",
|
||||
latency: json.data?.latencyMs ?? 0,
|
||||
});
|
||||
} else {
|
||||
const meta = json.meta;
|
||||
setResult({
|
||||
kind: "error",
|
||||
errorCode: meta?.errorCode ?? "generic",
|
||||
upstreamStatus:
|
||||
typeof meta?.upstreamStatus === "number"
|
||||
? meta.upstreamStatus
|
||||
: undefined,
|
||||
smtpCode:
|
||||
typeof meta?.smtpCode === "number" ? meta.smtpCode : undefined,
|
||||
upstreamBody:
|
||||
typeof meta?.upstreamBody === "string"
|
||||
? meta.upstreamBody
|
||||
: undefined,
|
||||
});
|
||||
}
|
||||
} catch {
|
||||
setResult({ kind: "error", errorCode: "connection_failed" });
|
||||
setResult(await runConnectionTest(endpoint));
|
||||
} finally {
|
||||
setTesting(false);
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user