Debian Codegraph @

test/playwright/tests/scan.spec.mjs

raw
1 import {expect, test} from "@playwright/test";
2 import {login} from "../helpers/auth.mjs";
3
4 test.describe.serial("Scan flow across WebUI tabs", () => {
5 let page = null;
6 let scannedSubjects = [];
7 const scannedBefore = {scanTab: 0, throughput: 0};
8
9 async function gotoTab(name) {
10 await page.locator(`#${name}_nav`).click();
11 }
12
13 function extractNumber(text) {
14 return parseInt(text.replace(/\D/g, ""), 10);
15 }
16
17 async function readScanTab(skipNavigation = false) {
18 // Status tab → scanned widget
19 if (!skipNavigation) {
20 await gotoTab("status");
21 await page.waitForResponse((resp) => resp.url().includes("/stat") && resp.status() === 200);
22 }
23 const scannedWidget = page.locator("#statWidgets .widget[title*='scanned']");
24 await expect(scannedWidget).toBeVisible();
25 const scannedTitle = await scannedWidget.getAttribute("title");
26 return extractNumber(scannedTitle);
27 }
28
29 async function readThroughput() {
30 // Throughput tab → id="rrd-total-value"
31 await gotoTab("throughput");
32 await page.waitForResponse((resp) => resp.url().includes("/graph") && resp.status() === 200);
33 const throughputValue = page.locator("#rrd-total-value");
34 await expect(throughputValue).toBeVisible();
35 return extractNumber(await throughputValue.textContent());
36 }
37
38 async function expectAlertSuccess(expectedText) {
39 // Wait for a new alert to appear by counting existing alerts first
40 const initialAlertCount = await page.locator(".alert-success, .alert-modal.alert-success").count();
41
42 // Wait for a new alert to appear
43 await expect(async () => {
44 const currentCount = await page.locator(".alert-success, .alert-modal.alert-success").count();
45 return currentCount > initialAlertCount;
46 }).toPass({timeout: 5000});
47
48 // Get the most recently appeared alert (last one)
49 const alert = page.locator(".alert-success, .alert-modal.alert-success").last();
50 await expect(alert).toBeVisible();
51 const text = await alert.textContent();
52 expect(text).toContain(expectedText);
53 await expect(alert).not.toBeVisible({timeout: 10000});
54 }
55
56 /**
57 * Test symbol ordering functionality
58 * @param {string} table - Table name ("scan" or "history")
59 * @param {boolean} needsExpand - Whether row needs to be expanded
60 */
61 async function testSymbolOrdering(table, needsExpand) {
62 const tableLocator = page.locator(`#historyTable_${table} tbody`);
63 const firstRow = tableLocator.locator("tr").first();
64 await expect(firstRow).toBeVisible();
65
66 if (needsExpand) {
67 await firstRow.click();
68 await page.waitForTimeout(200); // Wait for expand animation
69 }
70
71 // Get the detail row that immediately follows the row we clicked/selected
72 const detailRow = firstRow.locator("+ tr.footable-detail-row");
73 await expect(detailRow).toBeVisible();
74
75 // Find the symbols row within the detail table (identified by the th containing sort buttons)
76 const symbolsRow = detailRow.locator("tr:has(th:has(.sym-order-toggle))");
77 const symbolsCell = symbolsRow.locator("td");
78
79 // Get initial symbols order
80 let previousSymbols = await symbolsCell.innerHTML();
81
82 // Use the dropdown selector to change symbols order
83 const selector = page.locator(`#selSymOrder_${table}`);
84 await expect(selector).toBeVisible();
85
86 // Test each sort order in sequence (initial order is "magnitude")
87 for (const order of ["name", "score"]) {
88 await selector.selectOption(order);
89 await expect.poll(async () => await symbolsCell.innerHTML(), {timeout: 3000}).not.toBe(previousSymbols);
90 previousSymbols = await symbolsCell.innerHTML();
91 }
92
93 // Verify no JavaScript errors occurred (especially the regression bug)
94 const errors = [];
95 page.on("pageerror", (err) => errors.push(err.message));
96 await page.waitForTimeout(500);
97 expect(errors).toHaveLength(0);
98 }
99
100 test.beforeAll(async ({browser}, testInfo) => {
101 const context = await browser.newContext();
102 page = await context.newPage();
103 const {enablePassword} = testInfo.project.use.rspamdPasswords;
104 await login(page, enablePassword);
105 });
106
107 test.afterAll(async () => {
108 await page.close();
109 });
110
111 test.describe("Phase 1: before scanning", () => {
112 test("Read current Scanned counters", async () => {
113 scannedBefore.scanTab = await readScanTab(true);
114 scannedBefore.throughput = await readThroughput();
115 });
116 });
117
118 test.describe("Phase 2: scanning", () => {
119 test("Scan two test messages", async ({}, testInfo) => {
120 const {testId} = testInfo;
121 await gotoTab("scan");
122 const scanMessageBtn = page.locator('#scan button[data-upload="checkv2"]');
123 await expect(scanMessageBtn).toBeDisabled();
124
125 scannedSubjects = [];
126
127 for (let i = 1; i <= 2; i++) {
128 const timestamp = Date.now();
129 const msgId = `E2E-${i}-${timestamp}@example.com`;
130 const subject = `E2E Test ${i} ${testId}-${timestamp}`;
131 scannedSubjects.push(subject);
132
133 await page.locator("#scanMsgSource").fill(
134 `Message-Id: ${msgId}\nFrom: [email protected]\nSubject: ${subject}\n\nTest body`
135 );
136 await scanMessageBtn.click();
137
138 await expectAlertSuccess("Data successfully scanned");
139 await expect(
140 page.locator(`#historyTable_scan tbody tr:first-child td.footable-first-visible:has-text("${msgId}")`)
141 ).toBeVisible();
142 }
143 });
144
145 test("Symbol ordering works on Scan tab", async () => {
146 await testSymbolOrdering("scan", false);
147 });
148 });
149
150 test.describe("Phase 3: after scanning", () => {
151 test("History shows scanned messages", async () => {
152 await gotoTab("history");
153
154 // Check both scanned messages are present in reverse order
155 for (let i = 0; i < scannedSubjects.length; i++) {
156 const subject = scannedSubjects[scannedSubjects.length - 1 - i]; // reverse order
157 await expect(
158 page.locator("#historyTable_history tbody tr").nth(i)
159 .locator(`td:has-text("${subject}")`)
160 ).toBeVisible();
161 }
162 });
163
164 test("Symbol ordering works on History tab", async () => {
165 await testSymbolOrdering("history", true);
166 });
167
168 test("History can be reset", async () => {
169 // Reset history
170 const resetBtn = page.locator("#resetHistory");
171 await expect(resetBtn).toBeVisible();
172 page.once("dialog", (dialog) => dialog.accept());
173 await resetBtn.click();
174
175 const updateHistoryBtn = page.locator("#updateHistory");
176 await expect(updateHistoryBtn).toBeDisabled();
177 await expect(updateHistoryBtn).not.toBeDisabled();
178
179 const rows = await page.locator("#historyTable_history tbody tr").count();
180 // Known bug: Rspamd leaves one row after history reset
181 expect([0, 1]).toContain(rows);
182 });
183 });
184
185 test.describe("Phase 4: counters after scanning", () => {
186 test("Status tab `Scanned` counter increased by 2", async () => {
187 const scanTab = await readScanTab();
188 expect(scanTab).toBe(scannedBefore.scanTab + 2);
189 });
190
191 test("Throughput `Total messages` counter increased", async ({}, testInfo) => {
192 testInfo.setTimeout(140000);
193 // With empty RRD the first PDP is lost, so only +1 is visible
194 // Depending on row boundaries, throughput may show +2 or even +3
195 const targetValues = [
196 scannedBefore.throughput + 1,
197 scannedBefore.throughput + 2,
198 scannedBefore.throughput + 3,
199 ];
200
201 let lastValue = null;
202 try {
203 await expect.poll(async () => {
204 lastValue = await readThroughput();
205 return targetValues.includes(lastValue);
206 }, {
207 interval: 5000,
208 // step = 1s, pdp_per_row = 60 → next row every 60s
209 timeout: 125000,
210 }).toBeTruthy();
211 } catch (e) {
212 const msg = `Throughput counter should be one of [${targetValues.join(", ")}], got ${lastValue}`;
213 throw new Error(msg, {cause: e});
214 }
215 });
216 });
217
218 test.describe("Regression: classifier list after RO → disconnect → enable", () => {
219 test("Classifier dropdown is populated after reconnect", async ({browser}, testInfo) => {
220 const {readOnlyPassword, enablePassword} = testInfo.project.use.rspamdPasswords;
221
222 // Use isolated context to avoid pre-populated state from other tests
223 const context = await browser.newContext();
224 const page2 = await context.newPage();
225
226 async function gotoTabLocal(name) {
227 await page2.locator(`#${name}_nav`).click();
228 }
229
230 // Login as read-only
231 await login(page2, readOnlyPassword);
232 await page2.waitForSelector("#navBar:not(.d-none)");
233
234 // Go to Scan in RO
235 await gotoTabLocal("scan");
236 await expect(page2.locator("#scan")).toBeVisible();
237
238 // Disconnect and login as enable (writable)
239 await page2.locator("#disconnect").click();
240 // Avoid shared login() helper which calls page.goto('/') to stay on the same tab.
241 await page2.locator("#connectPassword").fill(enablePassword);
242 // Expect classifiers request after successful enable login
243 const p = page2.waitForResponse(
244 (r) => r.url().includes("/bayes/classifiers") && r.status() === 200,
245 {timeout: 5000}
246 );
247 await page2.locator("#connectButton").click();
248 await page2.waitForSelector("#navBar:not(.d-none)");
249 await p;
250
251 // Expect classifiers to be populated
252 const classifier = page2.locator("#classifier");
253 await expect(classifier).toBeVisible();
254 const optionCount = await classifier.locator("option").count();
255 expect(optionCount).toBeGreaterThan(1);
256
257 // Verify that a subsequent getClassifiers call under the same config is skipped
258 let reqCount = 0;
259 function reqListener(r) {
260 if (r.url().includes("/bayes/classifiers")) {
261 reqCount += 1;
262 }
263 }
264 page2.on("request", reqListener);
265
266 await page2.evaluate(() => new Promise((resolve) => {
267 // AMD require is available in the UI
268 // eslint-disable-next-line no-undef
269 require(["app/upload"], (u) => {
270 u.getClassifiers();
271 resolve();
272 });
273 }));
274
275 await page2.waitForTimeout(250);
276 page2.off("request", reqListener);
277 expect(reqCount).toBe(0);
278
279 // Options must remain populated (not reset to just default)
280 const finalCount = await classifier.locator("option").count();
281 expect(finalCount).toBeGreaterThan(1);
282
283 await page2.close();
284 await context.close();
285 });
286 });
287 });