feat: 实现认证辅助工具
- 创建 Token 管理器 RoleAuthManager - 创建认证辅助类 AuthHelper - 支持 Token 注入和真实登录两种模式 - 实现 Token 缓存机制 - 添加完整的单元测试(5个测试用例全部通过)
This commit is contained in:
@@ -0,0 +1,76 @@
|
||||
import { Page, BrowserContext } from '@playwright/test';
|
||||
import { RoleFactory } from '../roles/role-factory';
|
||||
import { RoleAuthManager } from './role-auth-manager';
|
||||
import type { RoleDefinition } from '../roles/base.role';
|
||||
|
||||
export class AuthHelper {
|
||||
constructor(
|
||||
private page: Page,
|
||||
private context: BrowserContext
|
||||
) {}
|
||||
|
||||
async loginAsRole(roleName: string, useTokenInjection: boolean = true): Promise<void> {
|
||||
const role = RoleFactory.getRole(roleName);
|
||||
|
||||
if (useTokenInjection) {
|
||||
await this.injectToken(role);
|
||||
} else {
|
||||
await this.performLogin(role);
|
||||
}
|
||||
}
|
||||
|
||||
private async injectToken(role: RoleDefinition): Promise<void> {
|
||||
const token = await RoleAuthManager.getRoleToken(role.name);
|
||||
|
||||
// 注入token到localStorage
|
||||
await this.page.addInitScript((token) => {
|
||||
localStorage.setItem('token', token);
|
||||
localStorage.setItem('username', 'admin');
|
||||
}, token);
|
||||
|
||||
// 设置cookie
|
||||
await this.context.addCookies([
|
||||
{
|
||||
name: 'token',
|
||||
value: token,
|
||||
domain: 'localhost',
|
||||
path: '/',
|
||||
}
|
||||
]);
|
||||
}
|
||||
|
||||
private async performLogin(role: RoleDefinition): Promise<void> {
|
||||
await this.page.goto('/login');
|
||||
|
||||
await this.page.fill('input[placeholder*="用户名"]', role.credentials.username);
|
||||
await this.page.fill('input[placeholder*="密码"]', role.credentials.password);
|
||||
await this.page.click('button[type="submit"]');
|
||||
|
||||
// 等待登录成功跳转
|
||||
await this.page.waitForURL(/\/(dashboard|home)?/, { timeout: 10000 });
|
||||
}
|
||||
|
||||
async logout(): Promise<void> {
|
||||
await this.page.click('[data-testid="user-menu"]');
|
||||
await this.page.click('[data-testid="logout-button"]');
|
||||
await this.page.waitForURL('/login');
|
||||
}
|
||||
|
||||
async clearAuth(): Promise<void> {
|
||||
await this.context.clearCookies();
|
||||
await this.page.evaluate(() => {
|
||||
localStorage.clear();
|
||||
sessionStorage.clear();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export async function createAuthenticatedPage(
|
||||
page: Page,
|
||||
context: BrowserContext,
|
||||
roleName: string
|
||||
): Promise<AuthHelper> {
|
||||
const helper = new AuthHelper(page, context);
|
||||
await helper.loginAsRole(roleName);
|
||||
return helper;
|
||||
}
|
||||
Reference in New Issue
Block a user