codegen-authenticated.ts
2.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/**
* 启动已认证的 Playwright Codegen
*
* 使用方式:
* 1. 先确保 auth.json 已存在(运行 npx playwright test login.setup.ts)
* 2. 然后运行:npx ts-node scripts/codegen-authenticated.ts
*
* 或者直接使用命令:
* npx playwright codegen --storage-state=auth.json $BASE_URL
*/
import { spawn } from 'child_process';
import path from 'path';
import fs from 'fs';
import dotenv from 'dotenv';
// 加载环境变量
dotenv.config({ path: path.resolve(__dirname, '../.env') });
const authFile = path.join(process.cwd(), 'auth.json');
const baseUrl = process.env.BASE_URL || 'http://localhost:8080';
console.log('='.repeat(50));
console.log('启动已认证的 Playwright Codegen');
console.log('='.repeat(50));
console.log(`认证文件: ${authFile}`);
console.log(`目标地址: ${baseUrl}`);
console.log('');
// 检查 auth.json 是否存在
if (!fs.existsSync(authFile)) {
console.error('错误: auth.json 文件不存在!');
console.error('请先运行以下命令生成认证文件:');
console.error(' npx playwright test login.setup.ts');
console.log('');
console.error('如果环境变量未设置,还需要设置:');
console.error(' BASE_URL - 目标网站地址');
console.error(' TEST_USER_NAME - 登录后显示的用户名(用于验证登录成功)');
process.exit(1);
}
console.log('✓ auth.json 文件存在');
console.log('');
// 启动 codegen
console.log('正在启动 Codegen...');
console.log('');
const isWindows = process.platform === 'win32';
// Playwright codegen 使用 --load-storage 来加载已保存的认证状态
const loadStorageArg = isWindows ? `--load-storage ${authFile}` : `--load-storage=${authFile}`;
const codegen = spawn(
'npx',
['playwright', 'codegen', loadStorageArg, baseUrl],
{
stdio: 'inherit',
shell: true,
cwd: process.cwd()
}
);
codegen.on('close', (code) => {
if (code !== 0) {
console.error(`Codegen 退出,代码: ${code}`);
}
process.exit(code ?? 0);
});
codegen.on('error', (err) => {
console.error('启动 Codegen 失败:', err);
process.exit(1);
});
// 处理 Ctrl+C
process.on('SIGINT', () => {
console.log('\n正在关闭 Codegen...');
codegen.kill('SIGINT');
});