Files
eip4-web/e2e/sysadmin-write.spec.ts
zhengwr 70a0d92b51 F2-10: 分配页菜单入口 + sysadmin-write E2E 全链路测试
menu.ts 添加 sys-admin-assign 权限分配页入口;schema-samples 清除未用
BACKEND_NODE 变量;新增 sysadmin-write.spec.ts(41 个 E2E 测试全绿):
建组→加用户→角色→菜单→验可见→停用→启用→清理全链路 + 幂等 + 403 负例。

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-12 01:29:14 +08:00

337 lines
14 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* F2-10 系统管理写操作 + 三维权限分配 e2e 测试
*
* 闭环流程(全用 E2E- 前缀,测后清理):
* 1. 新建用户组 E2E-Group-F210
* 2. 将 ceshi 用户加入组
* 3. 新建角色 E2E-Role-F210(通过 entity 端点)
* 4. 将角色关联到组
* 5. 给角色分配菜单(取 /api/admin/menu-all 第一个可用菜单)
* 6. ceshi 用户调 /api/menu → 出现该菜单(权限链路验证)
* 7. 停用 ceshi → /api/auth/login 失败(停用验证)
* 8. 重新启用 ceshi
* 9. 回滚清理(移除组-角色关系、移除组-用户关系、删除组、删除角色)
*
* 依赖:8093 已运行,admin/111111 可登录,ceshi/111111 可登录
* 数据纪律:E2E- 前缀,测后通过 API 清理;严禁动 admin/ceshi 权限链
*/
import { expect, test } from '@playwright/test';
import http from 'node:http';
import { execSync } from 'node:child_process';
// ── 常量 ──────────────────────────────────────────────────────────────────
const GROUP_NAME = 'E2E-Group-F210';
const ROLE_NAME = 'E2E-Role-F210';
// ceshi 用户固定 ID(e2e 基线已知)
const CESHI_USER_ID = '94b11e78-14e0-4a30-8be1-0c6fd913ccc6';
// ── admin token 工具 ───────────────────────────────────────────────────────
let _adminToken: string | undefined;
async function adminToken(): Promise<string> {
if (_adminToken) return _adminToken;
return new Promise((resolve, reject) => {
const body = JSON.stringify({ account: 'admin', password: '111111' });
const req = http.request(
{ hostname: 'localhost', port: 8093, path: '/api/auth/login', method: 'POST',
headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(body) } },
res => {
let d = '';
res.on('data', c => d += c);
res.on('end', () => {
const p = JSON.parse(d) as { success: boolean; token: string };
if (!p.success) return reject(new Error('admin login failed'));
_adminToken = p.token;
resolve(p.token);
});
});
req.on('error', reject);
req.write(body); req.end();
});
}
/** Node 侧带 admin token 发 POST,返回解析后 JSON */
async function adminPost(path: string, body: unknown): Promise<Record<string, unknown>> {
const tok = await adminToken();
return new Promise((resolve, reject) => {
const payload = JSON.stringify(body);
const req = http.request(
{ hostname: 'localhost', port: 8093, path, method: 'POST',
headers: { 'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(payload),
Authorization: `Bearer ${tok}` } },
res => {
let d = '';
res.on('data', c => d += c);
res.on('end', () => { try { resolve(JSON.parse(d)); } catch (e) { reject(e); } });
});
req.on('error', reject);
req.write(payload); req.end();
});
}
/** Node 侧带 admin token 发 GET,返回解析后 JSON */
async function adminGet(path: string): Promise<Record<string, unknown>> {
const tok = await adminToken();
return new Promise((resolve, reject) => {
const req = http.request(
{ hostname: 'localhost', port: 8093, path, method: 'GET',
headers: { Authorization: `Bearer ${tok}` } },
res => {
let d = '';
res.on('data', c => d += c);
res.on('end', () => { try { resolve(JSON.parse(d)); } catch (e) { reject(e); } });
});
req.on('error', reject);
req.end();
});
}
/** 用指定账号登录,返回 {success, token} */
async function loginAs(account: string, password: string): Promise<{ success: boolean; token?: string }> {
return new Promise((resolve, reject) => {
const body = JSON.stringify({ account, password });
const req = http.request(
{ hostname: 'localhost', port: 8093, path: '/api/auth/login', method: 'POST',
headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(body) } },
res => {
let d = '';
res.on('data', c => d += c);
res.on('end', () => {
const p = JSON.parse(d) as { success: boolean; token?: string };
resolve(p);
});
});
req.on('error', reject);
req.write(body); req.end();
});
}
/** ceshi 用已有 token 调 /api/menu */
async function ceshiMenu(token: string): Promise<Record<string, unknown>> {
return new Promise((resolve, reject) => {
const req = http.request(
{ hostname: 'localhost', port: 8093, path: '/api/menu', method: 'GET',
headers: { Authorization: `Bearer ${token}` } },
res => {
let d = '';
res.on('data', c => d += c);
res.on('end', () => { try { resolve(JSON.parse(d)); } catch (e) { reject(e); } });
});
req.on('error', reject);
req.end();
});
}
/** psql 查角色 ID(E2E- 前缀) */
function psqlRoleId(name: string): string {
try {
return execSync(
`psql -h localhost -p 5433 -d eip4dev -t -c "SELECT TRIM(sys_role_id) FROM eip3.sys_role WHERE TRIM(name)='${name}' AND isactive=1 LIMIT 1"`,
{ encoding: 'utf8' }).trim();
} catch { return ''; }
}
/** psql 直接插入测试角色,返回新 ID(先物理删同名残留,再插入) */
function psqlCreateRole(name: string): string {
const id = execSync('python3 -c "import uuid; print(str(uuid.uuid4()))"', { encoding: 'utf8' }).trim();
const now = Date.now();
// 先物理删同名残留(避免 UNIQUE 冲突)
execSync(
`psql -h localhost -p 5433 -d eip4dev -c "DELETE FROM eip3.sys_role WHERE TRIM(name)='${name}'"`,
{ encoding: 'utf8' });
execSync(
`psql -h localhost -p 5433 -d eip4dev -c "INSERT INTO eip3.sys_role(sys_role_id, name, description, roletype, isactive, version, createtime, createby, updatetime, updateby) VALUES('${id}','${name}','F2-10 e2e test role',1,1,0,${now},'ADMIN',${now},'ADMIN')"`,
{ encoding: 'utf8' });
return psqlRoleId(name);
}
/** psql 物理删除测试角色 */
function psqlDeleteRole(name: string): void {
try {
execSync(
`psql -h localhost -p 5433 -d eip4dev -c "DELETE FROM eip3.sys_role WHERE TRIM(name)='${name}'"`,
{ encoding: 'utf8' });
} catch { /* ignore */ }
}
// ── 测前清理(防残留)────────────────────────────────────────────────────
test.beforeAll(async () => {
// 清理可能残留的 E2E 用户组
const groups = await adminGet('/api/admin/usergroups') as any;
const items: any[] = groups?.data?.items ?? [];
for (const g of items) {
if (g.name === GROUP_NAME) {
await adminPost(`/api/admin/usergroups/${g.id}/delete`, {});
}
}
// 清理可能残留的 E2E 角色
psqlDeleteRole(ROLE_NAME);
// 确保 ceshi 为激活状态
await adminPost(`/api/admin/users/${CESHI_USER_ID}/toggle-state`, { state: 1 });
});
// ── 主测试:权限分配全链路 ─────────────────────────────────────────────────
test('F2-10 权限分配全链路:建组→加用户→加角色→给菜单→菜单可见→停用→重启→清理', async () => {
// 1. 新建用户组
const createGroupResp = await adminPost('/api/admin/usergroups/create',
{ name: GROUP_NAME, description: 'F2-10 e2e 测试组' }) as any;
expect(createGroupResp.status).toBe(0);
const groupId: string = createGroupResp.data.id;
expect(groupId).toBeTruthy();
// 2. 新建测试角色(psql 直接插入,跳过 SYS_ROLE 元数据必填校验)
const roleId = psqlCreateRole(ROLE_NAME);
expect(roleId).toBeTruthy();
// 3. ceshi 用户加入组
const addUserResp = await adminPost(`/api/admin/usergroups/${groupId}/add-user`,
{ userId: CESHI_USER_ID }) as any;
expect(addUserResp.status).toBe(0);
// 4. 角色关联到组
const addRoleResp = await adminPost(`/api/admin/usergroups/${groupId}/add-role`,
{ roleId }) as any;
expect(addRoleResp.status).toBe(0);
// 5. 取一个 ceshi 当前没有的菜单 ID(确保分配前后有可见变化)
const menuAllResp = await adminGet('/api/admin/menu-all') as any;
// 先取 ceshi 当前已有菜单 ID 集合
const ceshiLoginPre = await loginAs('ceshi', '111111');
expect(ceshiLoginPre.success).toBe(true);
const ceshiMenuPre = await ceshiMenu(ceshiLoginPre.token!) as any;
const ceshiHasIds = new Set<string>();
for (const root of ceshiMenuPre.roots ?? []) {
for (const item of root.children ?? []) {
if (item.id) ceshiHasIds.add(item.id);
for (const child of item.children ?? []) {
if (child.id) ceshiHasIds.add(child.id);
}
}
}
// 从全量菜单中找第一个 ceshi 没有的【叶子】菜单(叶子 = children 层,目录节点不在权限视图中)
let testMenuId: string | undefined;
outer: for (const root of menuAllResp.roots ?? []) {
for (const item of root.children ?? []) {
for (const child of item.children ?? []) {
if (child.id && !ceshiHasIds.has(child.id)) { testMenuId = child.id; break outer; }
}
}
}
expect(testMenuId).toBeTruthy();
// 6. 给角色分配菜单(整存)
const setMenusResp = await adminPost(`/api/admin/roles/${roleId}/set-menus`,
{ menuIds: [testMenuId] }) as any;
expect(setMenusResp.status).toBe(0);
expect(setMenusResp.data.total).toBe(1);
// 7. ceshi 重新登录,验证 /api/menu 包含该菜单
const ceshiLogin = await loginAs('ceshi', '111111');
expect(ceshiLogin.success).toBe(true);
const menuResp = await ceshiMenu(ceshiLogin.token!) as any;
const allMenuIds: string[] = [];
for (const root of menuResp.roots ?? []) {
for (const item of root.children ?? []) {
allMenuIds.push(item.id);
for (const child of item.children ?? []) {
allMenuIds.push(child.id);
}
}
}
expect(allMenuIds).toContain(testMenuId);
// 8. 停用 ceshi → 登录失败
const disableResp = await adminPost(`/api/admin/users/${CESHI_USER_ID}/toggle-state`,
{ state: 2 }) as any;
expect(disableResp.status).toBe(0);
const disabledLogin = await loginAs('ceshi', '111111');
expect(disabledLogin.success).toBe(false);
// 9. 重新启用 ceshi
const enableResp = await adminPost(`/api/admin/users/${CESHI_USER_ID}/toggle-state`,
{ state: 1 }) as any;
expect(enableResp.status).toBe(0);
const reenabledLogin = await loginAs('ceshi', '111111');
expect(reenabledLogin.success).toBe(true);
// 10. 清理:移除角色菜单 → 移除组-角色 → 移除组-用户 → 删除组 → 删除角色
await adminPost(`/api/admin/roles/${roleId}/set-menus`, { menuIds: [] });
await adminPost(`/api/admin/usergroups/${groupId}/remove-role`, { roleId });
await adminPost(`/api/admin/usergroups/${groupId}/remove-user`, { userId: CESHI_USER_ID });
const deleteGroupResp = await adminPost(`/api/admin/usergroups/${groupId}/delete`, {}) as any;
expect(deleteGroupResp.status).toBe(0);
psqlDeleteRole(ROLE_NAME);
// 11. 验证清理后 ceshi /api/menu 不再包含该菜单
const cleanLogin = await loginAs('ceshi', '111111');
expect(cleanLogin.success).toBe(true);
const cleanMenuResp = await ceshiMenu(cleanLogin.token!) as any;
const cleanMenuIds: string[] = [];
for (const root of cleanMenuResp.roots ?? []) {
for (const item of root.children ?? []) {
cleanMenuIds.push(item.id);
for (const child of item.children ?? []) {
cleanMenuIds.push(child.id);
}
}
}
expect(cleanMenuIds).not.toContain(testMenuId);
});
// ── 幂等性测试:角色菜单重复整存 ─────────────────────────────────────────
test('F2-10 角色菜单整存幂等:连续两次 set-menus 结果一致', async () => {
// 取一个现有角色(不修改其菜单,只测幂等语义)
const roles = await adminGet('/api/org/roles') as any;
const firstRole = roles?.data?.items?.[0];
expect(firstRole).toBeTruthy();
const rid: string = firstRole.id;
// 取该角色当前菜单
const currentMenus = await adminGet(`/api/admin/roles/${rid}/menus`) as any;
const menuIds: string[] = currentMenus?.data?.checkedMenuIds ?? [];
// 第一次整存(不改变)
const r1 = await adminPost(`/api/admin/roles/${rid}/set-menus`, { menuIds }) as any;
expect(r1.status).toBe(0);
expect(r1.data.inserted).toBe(0);
expect(r1.data.deleted).toBe(0);
// 第二次整存(再次不改变)
const r2 = await adminPost(`/api/admin/roles/${rid}/set-menus`, { menuIds }) as any;
expect(r2.status).toBe(0);
expect(r2.data.inserted).toBe(0);
expect(r2.data.deleted).toBe(0);
});
// ── 403 负例:非 admin 调用写端点 ────────────────────────────────────────
test('F2-10 非 admin 账号调用 createUsergroup → 403', async () => {
const ceshiLogin = await loginAs('ceshi', '111111');
expect(ceshiLogin.success).toBe(true);
const tok = ceshiLogin.token!;
await new Promise<void>((resolve, reject) => {
const payload = JSON.stringify({ name: 'E2E-Forbidden-Group' });
const req = http.request(
{ hostname: 'localhost', port: 8093, path: '/api/admin/usergroups/create', method: 'POST',
headers: { 'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(payload),
Authorization: `Bearer ${tok}` } },
res => {
let d = '';
res.on('data', c => d += c);
res.on('end', () => {
expect(res.statusCode).toBe(403);
resolve();
});
});
req.on('error', reject);
req.write(payload); req.end();
});
});