新建 web/test/announcement-integration-smoke.mjs 10 项 E2E: - 空内容 400 / HTML 发送 200 / fan-out 数 = User 总数 - tudou 拿到未读 / 浏览器自动强弹 modal / 关闭标已读 / 再开不弹 - 消息中心 [公告] chip + HTML 渲染 / 无 console.error 跑通基线对比: - vitest 71 fail / 162 pass (0 新增回归) - v2-smoke 25/25 + modal-interaction 8/8 + v0.20.1-smoke 11/11 - 新 announcement-integration-smoke 10/10 归档 plan 文件 docs/todo/通知公告整合.md(v2,本次实施的源 plan)。 写完成报告 docs/todo/通知公告整合-完成报告.md(改动文件清单 + 3 commit hash + 测试结果 + 关键设计决策 + 边缘 case 处理)。 Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
206 lines
9.2 KiB
JavaScript
206 lines
9.2 KiB
JavaScript
/**
|
|
* 通知 / 公告整合 smoke test —
|
|
*
|
|
* 覆盖:
|
|
* 1. admin POST /admin/announcement/publish (空内容 → 400)
|
|
* 2. admin POST /admin/announcement/publish (HTML 内容 → 200 sent_to=N)
|
|
* 3. 后端 DB:fan-out 数等于 User 总数(active+inactive 都收到)
|
|
* 4. tudou GET /announcement → 拿到那条 HTML
|
|
* 5. tudou 浏览器进 /app 应自动强弹 modal(GlobalAnnouncementGate)
|
|
* 6. 关闭 modal → POST /announcement/read → 再开页面不弹
|
|
* 7. tudou 进消息中心 → 看到公告条目(带 [公告] chip + HTML 渲染)
|
|
*
|
|
* 前提:backend 8000 + frontend 5173 跑着,admin/admin123 + tudou/tudoupass123 可登录。
|
|
* 清场:测试前清掉所有 announcement 未读;测试后也清掉以免污染其他 smoke。
|
|
*/
|
|
import { chromium } from '@playwright/test';
|
|
|
|
const BASE = 'http://localhost:5173';
|
|
const API = 'http://localhost:8000';
|
|
|
|
const results = [];
|
|
function pass(name) { results.push({ name, ok: true }); console.log(` ✓ ${name}`); }
|
|
function fail(name, err) { results.push({ name, ok: false, err: err?.message || err }); console.log(` ✗ ${name}: ${err?.message || err}`); }
|
|
|
|
async function login(page, username, password) {
|
|
const res = await page.request.post(`${API}/api/v1/auth/login`, {
|
|
data: { username, password },
|
|
});
|
|
if (!res.ok()) throw new Error(`登录失败 ${username}: ${res.status()}`);
|
|
const body = await res.json();
|
|
return { token: body?.tokens?.access, user: body?.user };
|
|
}
|
|
|
|
async function setStorage(page, { token, refresh, user }) {
|
|
await page.goto(`${BASE}/login`, { waitUntil: 'domcontentloaded' });
|
|
await page.evaluate(({ access, r, u }) => {
|
|
localStorage.setItem('access_token', access);
|
|
if (r) localStorage.setItem('refresh_token', r);
|
|
if (u) localStorage.setItem('user', JSON.stringify(u));
|
|
}, { access: token, r: refresh, u: user });
|
|
}
|
|
|
|
async function clearAllUnreadAnnouncements(adminToken) {
|
|
// 没有专用清理 endpoint,用 admin 自己的 read-all 跑一遍(只清自己的);
|
|
// 其他用户的未读靠 tudou 的 read-all 单独清。这里只清 admin 自己。
|
|
await fetch(`${API}/api/v1/announcement/read`, {
|
|
method: 'POST',
|
|
headers: { 'Authorization': `Bearer ${adminToken}` },
|
|
});
|
|
}
|
|
|
|
async function main() {
|
|
const browser = await chromium.launch({ headless: true });
|
|
const ctx = await browser.newContext({ viewport: { width: 1440, height: 900 } });
|
|
const page = await ctx.newPage();
|
|
const consoleErrors = [];
|
|
page.on('console', (m) => {
|
|
if (m.type() === 'error' && !/401|404|Failed to load|DevTools/.test(m.text())) {
|
|
consoleErrors.push(m.text());
|
|
}
|
|
});
|
|
// 接受 confirm 弹窗(发送公告二次确认)
|
|
page.on('dialog', (d) => d.accept());
|
|
|
|
console.log('\n════ 公告整合 smoke ════');
|
|
|
|
// 前置:登录拿 token
|
|
let adminTok, tudouTok;
|
|
try {
|
|
const a = await login(page, 'admin', 'admin123');
|
|
const t = await login(page, 'tudou', 'tudoupass123');
|
|
adminTok = a.token; tudouTok = t.token;
|
|
if (!adminTok || !tudouTok) throw new Error('token 空');
|
|
} catch (e) { fail('前置:admin/tudou 登录拿 token', e); await browser.close(); return; }
|
|
|
|
// 先清掉 tudou 可能的旧未读公告
|
|
await fetch(`${API}/api/v1/announcement/read`, {
|
|
method: 'POST', headers: { 'Authorization': `Bearer ${tudouTok}` },
|
|
});
|
|
await fetch(`${API}/api/v1/announcement/read`, {
|
|
method: 'POST', headers: { 'Authorization': `Bearer ${adminTok}` },
|
|
});
|
|
|
|
// ── 1. 空内容 400 ──
|
|
try {
|
|
const r = await fetch(`${API}/api/v1/admin/announcement/publish`, {
|
|
method: 'POST',
|
|
headers: { 'Authorization': `Bearer ${adminTok}`, 'Content-Type': 'application/json; charset=utf-8' },
|
|
body: JSON.stringify({ content: '' }),
|
|
});
|
|
if (r.status === 400) pass('1. 空内容发送返回 400');
|
|
else fail('1. 空内容', new Error(`期望 400 实际 ${r.status}`));
|
|
} catch (e) { fail('1. 空内容', e); }
|
|
|
|
// ── 2. HTML 发送返回 200 + sent_to ──
|
|
const testContent = `<p>smoke 测试公告 ${Date.now()} - <b>请忽略</b></p>`;
|
|
let sentTo = 0;
|
|
try {
|
|
const r = await fetch(`${API}/api/v1/admin/announcement/publish`, {
|
|
method: 'POST',
|
|
headers: { 'Authorization': `Bearer ${adminTok}`, 'Content-Type': 'application/json; charset=utf-8' },
|
|
body: JSON.stringify({ content: testContent }),
|
|
});
|
|
const data = await r.json();
|
|
sentTo = data.sent_to;
|
|
if (r.status === 200 && sentTo > 0) pass(`2. HTML 发送成功 sent_to=${sentTo}`);
|
|
else fail('2. HTML 发送', new Error(`期望 200+sent_to>0 实际 ${r.status} ${JSON.stringify(data)}`));
|
|
} catch (e) { fail('2. HTML 发送', e); }
|
|
|
|
// ── 3. fan-out 数 = User 总数(用 admin 计:GET /admin/users total 应 ≈ sent_to) ──
|
|
try {
|
|
const r = await fetch(`${API}/api/v1/admin/users?page_size=1`, {
|
|
headers: { 'Authorization': `Bearer ${adminTok}` },
|
|
});
|
|
const data = await r.json();
|
|
if (data.total === sentTo) pass(`3. fan-out 数 (${sentTo}) = User 总数 (${data.total})`);
|
|
else fail('3. fan-out 数', new Error(`sent_to=${sentTo} vs admin/users.total=${data.total}`));
|
|
} catch (e) { fail('3. fan-out 数', e); }
|
|
|
|
// ── 4. tudou GET /announcement 拿到那条 ──
|
|
try {
|
|
const r = await fetch(`${API}/api/v1/announcement`, {
|
|
headers: { 'Authorization': `Bearer ${tudouTok}` },
|
|
});
|
|
const data = await r.json();
|
|
if (data.enabled && data.announcement.includes('smoke 测试公告')) {
|
|
pass('4. tudou 拿到未读公告');
|
|
} else {
|
|
fail('4. tudou 未读公告', new Error(`enabled=${data.enabled} content=${data.announcement.slice(0, 40)}`));
|
|
}
|
|
} catch (e) { fail('4. tudou GET /announcement', e); }
|
|
|
|
// ── 5. tudou 浏览器进任意路由(/app)应自动弹 modal ──
|
|
const tudouLogin = await login(page, 'tudou', 'tudoupass123');
|
|
await setStorage(page, { token: tudouLogin.token, refresh: undefined, user: tudouLogin.user });
|
|
await page.goto(`${BASE}/app`, { waitUntil: 'domcontentloaded' });
|
|
await page.waitForTimeout(2000); // 等 GlobalAnnouncementGate fetch + 渲染
|
|
try {
|
|
const modalVisible = await page.locator('text=我知道了').isVisible({ timeout: 3000 });
|
|
if (modalVisible) pass('5. tudou 进 /app 自动强弹公告 modal');
|
|
else fail('5. 自动强弹', new Error('未找到"我知道了"按钮 — modal 没弹'));
|
|
} catch (e) { fail('5. 自动强弹', e); }
|
|
|
|
// ── 6. 关闭 modal → 标已读 → 再开页面不弹 ──
|
|
try {
|
|
await page.locator('button:has-text("我知道了")').click({ timeout: 3000 });
|
|
await page.waitForTimeout(1500); // 等 POST /announcement/read 完成
|
|
// 验证后端已标读
|
|
const r = await fetch(`${API}/api/v1/announcement`, {
|
|
headers: { 'Authorization': `Bearer ${tudouTok}` },
|
|
});
|
|
const data = await r.json();
|
|
if (!data.enabled) pass('6. 关闭 modal 后 GET /announcement 返回 enabled=false (已读)');
|
|
else fail('6. 关闭后未读取', new Error(`期望 enabled=false 实际 ${data.enabled}`));
|
|
|
|
// 再开 /app 不该弹
|
|
await page.goto(`${BASE}/admin/dashboard`, { waitUntil: 'domcontentloaded' });
|
|
await page.waitForTimeout(2000);
|
|
const stillVisible = await page.locator('button:has-text("我知道了")').isVisible({ timeout: 1500 }).catch(() => false);
|
|
if (!stillVisible) pass('6.1 再开页面不再弹 modal');
|
|
else fail('6.1 再次弹出', new Error('已读状态下还在弹'));
|
|
} catch (e) { fail('6. 关闭流程', e); }
|
|
|
|
// ── 7. 消息中心:看到公告条目 + chip + HTML 渲染 ──
|
|
try {
|
|
await page.goto(`${BASE}/notifications`, { waitUntil: 'domcontentloaded' });
|
|
await page.waitForTimeout(2000);
|
|
// 找带 [公告] chip 的行
|
|
const chip = await page.locator('text=/^公告$/').first().isVisible({ timeout: 3000 });
|
|
if (chip) pass('7. 消息中心显示 [公告] chip');
|
|
else fail('7. chip 缺失', new Error('未找到公告 chip'));
|
|
// HTML 渲染:smoke 测试公告 文字应可见
|
|
const contentVisible = await page.locator('text=smoke 测试公告').first().isVisible({ timeout: 2000 });
|
|
if (contentVisible) pass('7.1 公告内容 HTML 渲染正常');
|
|
else fail('7.1 HTML 渲染', new Error('看不到公告文字'));
|
|
} catch (e) { fail('7. 消息中心', e); }
|
|
|
|
// 清场:把测试造的公告标已读,避免污染下一次 smoke
|
|
await fetch(`${API}/api/v1/announcement/read`, {
|
|
method: 'POST', headers: { 'Authorization': `Bearer ${adminTok}` },
|
|
});
|
|
await fetch(`${API}/api/v1/announcement/read`, {
|
|
method: 'POST', headers: { 'Authorization': `Bearer ${tudouTok}` },
|
|
});
|
|
|
|
if (consoleErrors.length > 0) {
|
|
fail('console errors', new Error(consoleErrors.slice(0, 3).join(' | ')));
|
|
} else {
|
|
pass('全程无 console.error');
|
|
}
|
|
|
|
console.log('\n────────────── 汇总 ──────────────');
|
|
const passed = results.filter(r => r.ok).length;
|
|
const failed = results.filter(r => !r.ok);
|
|
console.log(`通过: ${passed} / ${results.length}`);
|
|
if (failed.length > 0) {
|
|
console.log(`失败 ${failed.length} 项:`);
|
|
failed.forEach(r => console.log(` - ${r.name}: ${r.err}`));
|
|
}
|
|
|
|
await browser.close();
|
|
process.exit(failed.length === 0 ? 0 : 1);
|
|
}
|
|
|
|
main().catch((e) => { console.error(e); process.exit(1); });
|