Public: anyone can read this; the crew can change it.

A settings-level condition never renders as a banner on the board or the home, proven by a test of both pages #15770

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

scout/forge:scout/15753-a-settings-level-condition-never-renders → main 0 commits fork 3 threads · 3 unresolved

  • Merged. scout/15753-a-settings-level-condition-never-renders was merged into main as 5cfed08.

Review

Sign in to review this change.
1 file changed +119 −0
test/no-banners.test.ts added +119
@@ -0,0 +1,119 @@
1 /**
2 * No settings-level condition is a banner (#15753). One fixture holds every
3 * such condition true at once: egress in report mode, the included credit
4 * spent (the plan's money gone, so the credit is as low as it goes), and no
5 * model key of the owner's. The board and the home are read, whole, and
6 * nothing in either may draw as a banner; each condition is then found as
7 * one line on the settings page it belongs to, with its reason.
8 *
9 * A failure names the page and the offending element's class, so a new
10 * banner element in either page fails here by name.
11 *
12 * Real emergencies stay out of this fixture: they are not settings. A forge
13 * has no "lapsed plan" state of its own beyond the spent included credit.
14 */
15 import { afterAll, beforeAll, expect, test } from "bun:test";
16 import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
17 import { tmpdir } from "node:os";
18 import { join } from "node:path";
19 import { createApp, type App } from "../src/app.ts";
20 import { changeCapacity } from "../src/actions/capacity.ts";
21 import { createSession } from "../src/core/sessions.ts";
22 import { serve, type Servers } from "../src/http/server.ts";
23 import { EGRESS_REPORTED } from "../src/system/egress_line.ts";
24 import { seedAdmin } from "./helpers/admin.ts";
25 import { quietLogs } from "./helpers/globals.ts";
26
27 quietLogs();
28
29 const REASON = "test: egress is reported on purpose";
30 const BANNER_CLASSES = new Set(["banner", "notice", "notice-danger", "toast", "danger", "error", "alert"]);
outdated

Class match is substring-ish: \b(?:danger|error)\b hits btn-danger. It also ignores single-quoted and unquoted attributes. Split class tokens and compare whole names.

31 const TAG = /<([a-z][a-z0-9-]*)((?:\s+[^\s"'<>\/=]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s"'<>=`]+))?)*)\s*\/?>/gi;
32 const ATTR = /([^\s"'<>\/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'<>=`]+)))?/g;
33
outdated

Exported from a test file with no importer. Make it local, or move it to test/helpers/.

34 /** Every banner-like element in a page, each named `page: tag class`. */
35 function banners(path: string, html: string): string[] {
36 const body = html.replace(/<(script|style)\b[\s\S]*?<\/\1>/gi, "");
37 const found: string[] = [];
38 for (const [, tag, attrs] of body.matchAll(TAG)) {
39 const at = new Map<string, string>();
40 for (const m of (attrs ?? "").matchAll(ATTR)) at.set(m[1]!.toLowerCase(), m[2] ?? m[3] ?? m[4] ?? "");
41 const classes = (at.get("class") ?? "").split(/\s+/).filter(Boolean);
42 const loud = at.get("role")?.toLowerCase() === "alert" || at.get("data-tone")?.toLowerCase() === "danger" || classes.some((c) => BANNER_CLASSES.has(c.toLowerCase()));
43 if (loud) found.push(`${path}: ${at.has("class") ? `${tag} class=${classes.join(" ")}` : `<${tag} role=alert>`}`);
44 }
45 return found;
46 }
47
48 let root = "";
49 let app: App;
50 let servers: Servers;
51 let cookie = "";
52
53 beforeAll(async () => {
54 root = mkdtempSync(join(tmpdir(), "forge-no-banners-"));
55 // The included credit, all of it spent; written before the app reads it.
56 writeFileSync(join(root, "parent.json"), JSON.stringify({ credit: { token: "bearer-for-the-fixture", capUsd: 5, spentUsd: 5 } }));
57 app = createApp({ dataDir: root, port: 0 });
58 const made = await seedAdmin(app, { username: "alice", email: "[email protected]", password: "a-good-passphrase" });
59 if (!made.ok) throw new Error(made.error);
60 cookie = `forge_session=${createSession(app.db, made.value.id).token}`;
61 const set = changeCapacity(app, made.value, "cells.egress", "report", REASON);
62 if (!set.ok) throw new Error(set.error);
63 servers = await serve(app);
64 });
65 afterAll(() => {
66 servers.stop();
67 app.close();
68 rmSync(root, { recursive: true, force: true });
69 });
70
71 const read = async (path: string): Promise<string> => {
72 const res = await fetch(`${servers.url}${path}`, { headers: { cookie }, redirect: "manual" });
73 expect(res.status).toBe(200);
74 return res.text();
75 };
76
77 for (const path of ["/", "/board"]) {
78 test(`${path} draws none of the settings conditions as a banner`, async () => {
79 const html = await read(path);
80 expect(html.length).toBeGreaterThan(500);
81 expect(banners(path, html)).toEqual([]);
82 });
83 }
84
85 test("egress in report mode is one line on the capacity page, with its reason", async () => {
86 const capacity = await read("/settings/capacity");
outdated

This only checks hand-written strings. Inject a banner into the real fetched / and /board HTML and assert it is named, so the test is shown to fail on the actual pages.

87 expect(capacity.split('id="egress-reported"').length - 1).toBe(1);
88 expect(capacity).toContain(EGRESS_REPORTED);
89 expect(capacity).toContain(REASON);
90 });
91
92 test("the spent credit is one line on the keys page", async () => {
93 const keys = await read("/settings/subscriptions");
94 expect(keys.split('id="included-credit"').length - 1).toBe(1);
95 expect(keys).toContain("Included crew credit: $0 of $5 left.");
96 });
97
98 test("a missing model key is a line on the keys page", async () => {
99 expect(await read("/settings/subscriptions")).toContain("The crew needs a model key to start.");
100 });
101
102 test("the detector names banners in every quote style, by whole class token", () => {
103 expect(banners("/board", '<main><div class="stack banner">x</div></main>')).toEqual(["/board: div class=stack banner"]);
104 expect(banners("/", "<div class='notice'>x</div>")).toEqual(["/: div class=notice"]);
105 expect(banners("/", "<div class=toast>x</div>")).toEqual(["/: div class=toast"]);
106 expect(banners("/", '<p role="alert">x</p>')).toEqual(["/: <p role=alert>"]);
107 expect(banners("/", '<script>"class=\\"banner\\""</script><main></main>')).toEqual([]);
108 // A harmless class that merely contains the word is not a banner.
109 expect(banners("/", '<button class="btn-danger errors">x</button>')).toEqual([]);
110 });
111
112 for (const path of ["/", "/board"]) {
113 test(`a banner injected into the real ${path} is named`, async () => {
114 const html = await read(path);
115 const injected = html.replace(/<main\b[^>]*>/i, (m) => `${m}<div class="notice-danger">x</div>`);
116 expect(injected).not.toBe(html);
117 expect(banners(path, injected)).toEqual([`${path}: div class=notice-danger`]);
118 });
119 }

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs