优化分批执行点击菜单

This commit is contained in:
dengqichen 2025-03-11 10:40:08 +08:00
parent aa4b2ff884
commit 3921448aa1
4 changed files with 67 additions and 122 deletions

View File

@ -39,17 +39,16 @@ function Get-TaskStatus {
Write-Host "Name: $taskName" Write-Host "Name: $taskName"
Write-Host "State: $($task.State)" Write-Host "State: $($task.State)"
# 获取更详细的任务信息
$taskInfo = Get-ScheduledTaskInfo -TaskName $taskName -ErrorAction SilentlyContinue
$trigger = $task.Triggers[0] $trigger = $task.Triggers[0]
if ($trigger) { if ($trigger) {
Write-Host "Schedule: Daily at $($trigger.StartBoundary.Split('T')[1].Substring(0,5))" Write-Host "Schedule: Daily at $($trigger.StartBoundary.Split('T')[1].Substring(0,5))"
try { if ($taskInfo -and $taskInfo.NextRunTime) {
if ($task.NextRunTime) { Write-Host "Next Run: $($taskInfo.NextRunTime.ToString('yyyy-MM-dd HH:mm'))"
Write-Host "Next Run: $($task.NextRunTime.ToString('yyyy-MM-dd HH:mm'))"
} else { } else {
Write-Host "Next Run: Not yet scheduled" Write-Host "Next Run: Task needs to be enabled"
}
} catch {
Write-Host "Next Run: Not available"
} }
} }

View File

@ -130,55 +130,30 @@ class TestLifecycle {
</div> </div>
</div> </div>
<h2>页面测试详情</h2> <h2>测试执行详情</h2>
<table> <table>
<thead> <thead>
<tr> <tr>
<th>页面名称</th> <th>页面名称</th>
<th>测试数</th> <th>测试结果</th>
<th>成功数</th> <th>执行时间</th>
<th>失败数</th> <th>成功数/总数</th>
<th>总耗时</th>
<th>错误信息</th> <th>错误信息</th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
${Object.entries(pageStats).map(([pageName, stats]) => ` ${performanceData.map(record => {
<tr> const stats = pageStats[record.pageName];
<td>${pageName}</td> return `
<td>${stats.totalTests}</td>
<td class="status-true">${stats.successCount}</td>
<td class="status-false">${stats.failureCount}</td>
<td>${(stats.totalDuration / 1000).toFixed(2)}</td>
<td>
${stats.errors.length > 0 ?
`<div class="error-list">${stats.errors.join('<br>')}</div>` :
''}
</td>
</tr>
`).join('')}
</tbody>
</table>
<h2>详细测试记录</h2>
<table>
<thead>
<tr>
<th>页面名称</th>
<th>状态</th>
<th>耗时</th>
<th>错误信息</th>
</tr>
</thead>
<tbody>
${performanceData.map(record => `
<tr> <tr>
<td>${record.pageName}</td> <td>${record.pageName}</td>
<td class="status-${record.success}">${record.success ? '通过' : '失败'}</td> <td class="status-${record.success}">${record.success ? '通过' : '失败'}</td>
<td>${(record.duration / 1000).toFixed(2)}</td> <td>${(record.duration / 1000).toFixed(2)}</td>
<td>${stats ? `${stats.successCount}/${stats.totalTests}` : '0/0'}</td>
<td class="status-false">${record.errorMessage || ''}</td> <td class="status-false">${record.errorMessage || ''}</td>
</tr> </tr>
`).join('')} `;
}).join('')}
</tbody> </tbody>
</table> </table>
</div> </div>

View File

@ -10,94 +10,53 @@ console.log(`[Node] Starting test execution process...`);
console.log(`[Node] Current environment: ${env}`); console.log(`[Node] Current environment: ${env}`);
async function runTestsAndSendReport() { async function runTestsAndSendReport() {
let testOutput = '';
let testSuccess = false;
const startTime = new Date(); const startTime = new Date();
console.log(`[Node] Test started at: ${startTime.toLocaleString()}`); console.log(`[Node] Test started at: ${startTime.toLocaleString()}`);
try { try {
// 根据环境设置加载对应的环境变量文件 // 加载环境变量
const envFile = `.env.${env}`; const envFile = `.env.${env}`;
console.log(`[Node] Loading environment file: ${envFile}`); console.log(`[Node] Loading environment file: ${envFile}`);
// 检查环境文件是否存在
if (!fs.existsSync(envFile)) { if (!fs.existsSync(envFile)) {
console.error(`[Node] Error: Environment file ${envFile} not found!`);
throw new Error(`Environment file ${envFile} not found`); throw new Error(`Environment file ${envFile} not found`);
} }
console.log(`[Node] Environment file found successfully`);
// 加载环境变量 // 加载环境变量
dotenv.config({ path: envFile }); const envConfig = dotenv.config({ path: envFile });
console.log(`[Node] Environment variables loaded successfully`); if (envConfig.error) {
throw new Error(`Failed to load environment variables: ${envConfig.error.message}`);
}
// 运行测试并捕获输出 // 验证必要的环境变量
console.log('[Node] =========================================='); if (!process.env.BASE_URL) {
throw new Error('BASE_URL environment variable is not set in ' + envFile);
}
console.log(`[Node] Environment loaded: BASE_URL = ${process.env.BASE_URL}`);
// 运行测试
console.log('[Node] Starting Playwright test execution...'); console.log('[Node] Starting Playwright test execution...');
console.log('[Node] =========================================='); execSync('npx playwright test', {
stdio: 'inherit',
testOutput = execSync('npx playwright test', {
encoding: 'utf8',
env: { env: {
...process.env, ...process.env,
NODE_ENV: env NODE_ENV: env
},
stdio: 'inherit' // 这将允许实时显示测试输出
});
testSuccess = true;
console.log('[Node] ==========================================');
console.log('[Node] Test execution completed successfully');
console.log('[Node] ==========================================');
} catch (error) {
console.log('[Node] ==========================================');
console.error('[Node] Test execution failed with error:');
console.error(error.message);
console.log('[Node] ==========================================');
testOutput = error.output ? error.output.join('\n') : error.message;
} }
});
const endTime = new Date(); console.log('[Node] Test execution completed');
const duration = (endTime - startTime) / 1000 / 60; // 转换为分钟
console.log(`[Node] Test duration: ${duration.toFixed(2)} minutes`);
// 读取性能报告 // 读取性能报告
console.log('[Node] Attempting to read performance report...'); console.log('[Node] Reading performance report...');
let performanceData = '';
try {
const reportPath = path.join(process.cwd(), 'test-results', 'performance-report.html'); const reportPath = path.join(process.cwd(), 'test-results', 'performance-report.html');
if (fs.existsSync(reportPath)) { const performanceReport = fs.readFileSync(reportPath, 'utf8');
performanceData = fs.readFileSync(reportPath, 'utf8');
console.log('[Node] Performance report read successfully');
} else {
console.log('[Node] No performance report found');
}
} catch (error) {
console.error('[Node] Failed to read performance report:', error.message);
}
// 构建邮件内容
console.log('[Node] Preparing email report...');
const emailHtml = `
<h1>Playwright 自动化测试报告 (${env}环境)</h1>
<div style="margin: 20px 0; padding: 10px; background-color: ${testSuccess ? '#e6ffe6' : '#ffe6e6'}; border-radius: 5px;">
<h2>测试结果: ${testSuccess ? '成功 ✅' : '失败 ❌'}</h2>
<p>执行环境: ${env}</p>
<p>执行时间: ${startTime.toLocaleString()}</p>
<p>持续时间: ${duration.toFixed(2)} 分钟</p>
</div>
${performanceData ? '<h2>性能报告</h2>' + performanceData : ''}
`;
// 发送邮件 // 发送邮件
try {
console.log('[Node] ==========================================');
console.log('[Node] Sending test report email...'); console.log('[Node] Sending test report email...');
const result = await emailService.sendMail({ const result = await emailService.sendMail({
to: 'dengqichen@iscmtech.com', to: 'dengqichen@iscmtech.com',
subject: `[${testSuccess ? '成功' : '失败'}] Playwright自动化测试报告 (${env}) - ${startTime.toLocaleDateString()}`, subject: `[成功] Playwright自动化测试报告 (${env}) - ${startTime.toLocaleDateString()}`,
html: emailHtml html: performanceReport
}); });
if (result.success) { if (result.success) {
@ -105,11 +64,30 @@ async function runTestsAndSendReport() {
} else { } else {
console.error('[Node] Failed to send test report email:', result.error); console.error('[Node] Failed to send test report email:', result.error);
} }
console.log('[Node] ==========================================');
} catch (error) { } catch (error) {
console.log('[Node] =========================================='); console.error('[Node] Error:', error.message);
console.error('[Node] Error sending email:', error.message);
console.log('[Node] =========================================='); // 如果测试失败,尝试读取已生成的报告
try {
const reportPath = path.join(process.cwd(), 'test-results', 'performance-report.html');
if (fs.existsSync(reportPath)) {
const performanceReport = fs.readFileSync(reportPath, 'utf8');
const result = await emailService.sendMail({
to: 'dengqichen@iscmtech.com',
subject: `[失败] Playwright自动化测试报告 (${env}) - ${startTime.toLocaleDateString()}`,
html: performanceReport
});
if (result.success) {
console.log('[Node] Error report email sent successfully');
}
} else {
console.error('[Node] No performance report found');
}
} catch (emailError) {
console.error('[Node] Failed to send error report:', emailError.message);
}
} }
} }
@ -119,13 +97,9 @@ console.log('[Node] Starting test automation process...');
console.log('[Node] =========================================='); console.log('[Node] ==========================================');
runTestsAndSendReport().then(() => { runTestsAndSendReport().then(() => {
console.log('[Node] Process will exit in 3 seconds...'); console.log('[Node] Process will exit in 3 seconds...');
setTimeout(() => { setTimeout(() => process.exit(0), 3000);
process.exit(0);
}, 3000);
}).catch(error => { }).catch(error => {
console.error('[Node] Fatal error:', error); console.error('[Node] Fatal error:', error);
console.log('[Node] Process will exit in 3 seconds...'); console.log('[Node] Process will exit in 3 seconds...');
setTimeout(() => { setTimeout(() => process.exit(1), 3000);
process.exit(1);
}, 3000);
}); });

View File

@ -1,4 +1 @@
[ []
1,
2
]