Commit 5617f1b0 by chenwq

```

feat(e2e): 添加E2E自动化测试项目配置

- 新增项目配置文件,包括环境变量示例(.env.example)和忽略规则(.gitignore)
- 配置不同测试环境(local/dev/test)的基础URL和账号管理
- 实现测试账号认证机制和登录页面自动化登录功能
- 创建基础测试用例和SAAS-V5.8.6版本相关采购发货页面测试
- 设置Playwright测试框架配置,支持多浏览器测试(Edge/Firefox/WebKit)

docs(e2e): 完善项目文档和使用说明

- 编写详细的README.md文档,包含常用命令、用例范围、浏览器选择说明
- 文档化环境地址配置、测试账号设置和报告查看方法
- 提供本地环境IP自动识别和手动指定的使用指导

refactor(e2e): 重构测试执行脚本和面板界面

- 替换原有测试命令为新的run-e2e.mjs脚本,支持环境参数传递
- 开发E2E测试面板界面,提供可视化的项目、环境、用例范围选择
- 实现测试结果实时输出和报告展示功能
- 移除原有的example测试用例,采用新的测试组织结构
```
1 parent 7679da67
E2E_USERNAME=
E2E_PASSWORD=
......@@ -6,3 +6,5 @@ node_modules/
/blob-report/
/playwright/.cache/
/playwright/.auth/
.env.local
# E2E 自动化测试项目
这个项目用于运行 SAAS+ 的 Playwright 自动化测试,默认只测试 Edge 浏览器。
## 常用命令
| 命令 | 作用 | 什么时候用 |
| --- | --- | --- |
| `npm test` | 使用默认环境运行 Edge 测试 | 不指定环境时使用,目前默认是测试环境 |
| `npm run test:local` | 运行本地开发环境 Edge 测试 | 本地前端服务已经启动后使用 |
| `npm run test:dev` | 运行开发环境 Edge 测试 | 要测开发环境地址时使用 |
| `npm run test:test` | 运行测试环境 Edge 测试 | 要测测试环境地址时使用,日常验证优先用这个 |
| `npm run panel` | 启动可视化测试面板 | 想在浏览器里点按钮运行测试、查看报告时使用 |
## 用例范围
用例按目录区分:
| 范围 | 目录 | 说明 |
| --- | --- | --- |
| 基础功能 | `projects/dj-carlife-web/tests/basic` | 登录页、系统底层能力等通用用例 |
| SAAS-V5.8.6 | `projects/dj-carlife-web/tests/saas-v5.8.6` | 5.8.6 版本新增需求用例 |
| 全部用例 | `tests` | 基础功能 + 各版本用例 |
命令行可以这样选择范围:
```bash
npm run test:test -- --suite=basic
npm run test:test -- --suite=saas-v5.8.6
npm run test:test
```
面板里也可以通过“用例范围”选择当前运行基础功能、SAAS-V5.8.6,或全部用例。
## 浏览器选择
默认只跑 Edge。
如果要跑全部浏览器,可以在面板里选择“全部浏览器”。全部浏览器包含:
- Edge
- Firefox
- WebKit
命令行也可以手动指定:
```bash
npm run test:test -- --project=edge
npm run test:test -- --project=firefox
npm run test:test -- --project=webkit
```
如果要一次跑全部浏览器,使用:
```bash
npm run test:test -- --project=edge --project=firefox --project=webkit
```
## 环境地址
| 环境 | 地址 |
| --- | --- |
| 本地环境 local | `http://本机IP:8080/dj-carlife-web/#/` |
| 开发环境 dev | `http://192.168.3.191:8543/#/` |
| 测试环境 test | `http://frontend.test.glsx.com.cn/dj-carlife-web/#/` |
本地环境的 IP 会在每次运行时自动读取当前电脑的局域网 IP,不需要手动写死 `192.168.2.31`。
如果自动识别到的 IP 不对,可以临时指定:
```bash
E2E_LOCAL_HOST=192.168.x.x npm run test:local
```
在 Windows PowerShell 中可以这样写:
```powershell
$env:E2E_LOCAL_HOST="192.168.x.x"; npm run test:local
```
## 测试账号
测试账号和密码不要写进代码里,放在 `.env.local`:
```bash
E2E_USERNAME=账号
E2E_PASSWORD=密码
```
## 查看报告
运行测试后会生成 Playwright 报告。推荐直接启动面板:
```bash
npm run panel
```
面板会从 `5200` 端口开始启动,如果端口被占用,会自动尝试下一个端口。
......@@ -3,7 +3,11 @@
"version": "1.0.0",
"main": "index.js",
"scripts": {
"serve": "playwright test"
"panel": "node tools/e2e-panel/server.mjs",
"test": "node scripts/run-e2e.mjs",
"test:local": "node scripts/run-e2e.mjs local",
"test:dev": "node scripts/run-e2e.mjs dev",
"test:test": "node scripts/run-e2e.mjs test"
},
"keywords": [],
"author": "",
......
import { defineConfig, devices } from '@playwright/test';
import { getE2EEnv } from './projects/dj-carlife-web/config/e2e-env';
/**
* Read environment variables from file.
* https://github.com/motdotla/dotenv
*/
// import dotenv from 'dotenv';
// import path from 'path';
// dotenv.config({ path: path.resolve(__dirname, '.env') });
const e2eEnv = getE2EEnv();
const appProject = process.env.E2E_APP_PROJECT || 'dj-carlife-web';
const testDirs = {
'dj-carlife-web': './projects/dj-carlife-web/tests',
};
/**
* See https://playwright.dev/docs/test-configuration.
*/
export default defineConfig({
testDir: './tests',
/* Run tests in files in parallel */
fullyParallel: true,
/* Fail the build on CI if you accidentally left test.only in the source code. */
testDir: testDirs[appProject as keyof typeof testDirs] || testDirs['dj-carlife-web'],
timeout: 90000,
fullyParallel: false,
forbidOnly: !!process.env.CI,
/* Retry on CI only */
retries: process.env.CI ? 2 : 0,
/* Opt out of parallel tests on CI. */
workers: process.env.CI ? 1 : undefined,
/* Reporter to use. See https://playwright.dev/docs/test-reporters */
workers: 1,
reporter: [['html']],
/* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */
use: {
/* Base URL to use in actions like `await page.goto('')`. */
baseURL: 'http://localhost:3000',
/* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */
baseURL: e2eEnv.baseURL,
trace: 'on-first-retry',
},
/* Configure projects for major browsers */
projects: [
{
name: 'chromium',
use: { ...devices['Desktop Chrome'] },
name: 'edge',
use: { ...devices['Desktop Chrome'], channel: 'msedge' },
},
{
name: 'firefox',
use: { ...devices['Desktop Firefox'] },
},
{
name: 'webkit',
use: { ...devices['Desktop Safari'] },
},
/* Test against mobile viewports. */
// {
// name: 'Mobile Chrome',
// use: { ...devices['Pixel 5'] },
// },
// {
// name: 'Mobile Safari',
// use: { ...devices['iPhone 12'] },
// },
/* Test against branded browsers. */
// {
// name: 'Microsoft Edge',
// use: { ...devices['Desktop Edge'], channel: 'msedge' },
// },
// {
// name: 'Google Chrome',
// use: { ...devices['Desktop Chrome'], channel: 'chrome' },
// },
],
/* Run your local dev server before starting the tests */
// webServer: {
// command: 'npm run start',
// url: 'http://localhost:3000',
// reuseExistingServer: !process.env.CI,
// },
});
import { networkInterfaces } from 'node:os';
export const CURRENT_ENV = 'test';
export const E2E_ACCOUNT = {
username: process.env.E2E_USERNAME,
password: process.env.E2E_PASSWORD,
};
function getLocalIp() {
for (const addresses of Object.values(networkInterfaces())) {
for (const address of addresses || []) {
if (address.family === 'IPv4' && !address.internal) {
return address.address;
}
}
}
return '127.0.0.1';
}
const localHost = process.env.E2E_LOCAL_HOST || getLocalIp();
export const E2E_ENVS = {
local: {
baseURL: `http://${localHost}:8080/dj-carlife-web/#/`,
},
dev: {
baseURL: 'http://192.168.3.191:8543/#/',
},
test: {
baseURL: 'http://frontend.test.glsx.com.cn/dj-carlife-web/#/',
},
} as const;
export type E2EEnvName = keyof typeof E2E_ENVS;
export function getE2EEnv(name = process.env.E2E_ENV || CURRENT_ENV) {
if (name in E2E_ENVS) {
return E2E_ENVS[name as E2EEnvName];
}
throw new Error(
`未知测试环境:${name}。可用环境:${Object.keys(E2E_ENVS).join('、')}。`
);
}
export function getE2EUrl(path: string, name = process.env.E2E_ENV || CURRENT_ENV) {
const e2eEnv = getE2EEnv(name);
return `${e2eEnv.baseURL}${path.replace(/^\/+/, '')}`;
}
export function getE2EAccount() {
if (!E2E_ACCOUNT.username || !E2E_ACCOUNT.password) {
throw new Error('缺少测试账号或密码。请在 .env.local 中配置 E2E_USERNAME 和 E2E_PASSWORD 后再运行测试。');
}
return {
username: E2E_ACCOUNT.username,
password: E2E_ACCOUNT.password,
};
}
import { test as base, expect } from '@playwright/test';
import { getE2EAccount, getE2EUrl } from '../config/e2e-env';
import { login } from '../pages/login.page';
export const test = base.extend({
page: async ({ page }, use) => {
const account = getE2EAccount();
await page.goto(getE2EUrl('login'), { waitUntil: 'commit' });
await login(page, account);
await use(page);
},
});
export { expect };
import { expect, type Page } from '@playwright/test';
export async function waitForLoginPage(page: Page) {
const accountInput = page.getByPlaceholder(/账户|账号/);
const passwordInput = page.getByPlaceholder(/密码/);
const loginButton = page.getByRole('button', { name: /登录/ });
for (let attempt = 0; attempt < 2; attempt += 1) {
try {
await expect(accountInput).toBeVisible({ timeout: 60000 });
await expect(passwordInput).toBeVisible();
await expect(loginButton).toBeVisible();
return;
} catch (error) {
if (attempt === 1) {
throw error;
}
await page.reload({ waitUntil: 'commit' });
}
}
}
export async function login(page: Page, account: { username: string; password: string }) {
await waitForLoginPage(page);
await page.getByPlaceholder(/账户|账号/).fill(account.username);
await page.getByPlaceholder(/密码/).fill(account.password);
await page.getByRole('button', { name: /登录/ }).click();
await expect(page).not.toHaveURL(/\/login/, { timeout: 30000 });
}
import { expect, test } from '@playwright/test';
import { getE2EUrl } from '../../config/e2e-env';
import { waitForLoginPage } from '../../pages/login.page';
test('基础功能:登录页可以正常打开', async ({ page }) => {
await page.goto(getE2EUrl('login'), { waitUntil: 'commit' });
await expect(page).toHaveURL(/\/login/);
await waitForLoginPage(page);
});
import { expect, test } from '../../fixtures/auth';
import { getE2EUrl } from '../../config/e2e-env';
function normalizeLabelText(text: string) {
return text.replace(/\s+/g, '').replace(/[::]+$/, '');
}
test('SAAS-V5.8.6:采购发货页面新增产品ID搜索项和列表字段', async ({ page }) => {
await page.goto(getE2EUrl('purchaseAndDelivery'), { waitUntil: 'commit' });
await expect(page.getByText(/正在加载资源/)).toBeHidden({ timeout: 60000 });
await expect(page).toHaveURL(/purchaseAndDelivery/);
await expect(page.getByRole('button', { name: '查询' })).toBeVisible({ timeout: 60000 });
const searchFields = [
'产品名称',
'产品编码',
'所属分类',
'系列',
'订单编号',
'下单时间',
'下单商户',
'发货状态',
'分配状态',
'采购模式',
'发货主体',
'审核时间',
'发货方',
'发货时间',
'签收状态',
'供应商名称',
'供应商编码',
'产品ID',
];
const searchItems = [];
for (const field of searchFields) {
const label = page.getByText(new RegExp(`^\\s*${field}[::]\\s*$`)).first();
await expect(label, `搜索项中没有找到“${field}”`).toBeVisible({ timeout: 60000 });
const box = await label.boundingBox();
expect(box, `搜索项“${field}”没有可见位置`).not.toBeNull();
searchItems.push({ field, x: box!.x, y: box!.y });
}
const searchLabels = searchItems
.sort((left, right) => (Math.abs(left.y - right.y) < 8 ? left.x - right.x : left.y - right.y))
.map(({ field }) => field);
const signStatusIndex = searchLabels.indexOf('签收状态');
const productIdSearchIndex = searchLabels.indexOf('产品ID');
expect(
productIdSearchIndex,
`“产品ID”搜索项必须紧跟在“签收状态”后面,实际搜索项顺序:${searchLabels.join('、')}`
).toBe(signStatusIndex + 1);
const table = page.locator('.el-table, table').filter({ hasText: '产品名称' }).first();
await expect(table).toContainText('产品名称', { timeout: 60000 });
await expect(table).toContainText('产品ID');
const tableHeaders = await table.locator('.el-table__header-wrapper th .cell, thead th').evaluateAll((elements) =>
elements
.map((element) => element.textContent || '')
.map((text) => text.replace(/\s+/g, '').replace(/[::]+$/, ''))
.filter(Boolean)
);
const productNameIndex = tableHeaders.findIndex((text) => normalizeLabelText(text) === '产品名称');
const productIdTableIndex = tableHeaders.findIndex((text) => normalizeLabelText(text) === '产品ID');
expect(productNameIndex, `列表中没有找到“产品名称”,实际表头:${tableHeaders.join('、')}`).toBeGreaterThanOrEqual(0);
expect(productIdTableIndex, `列表中没有找到“产品ID”,实际表头:${tableHeaders.join('、')}`).toBeGreaterThanOrEqual(0);
expect(
productIdTableIndex,
`“产品ID”列表字段必须紧跟在“产品名称”后面,实际表头顺序:${tableHeaders.join('、')}`
).toBe(productNameIndex + 1);
});
import { existsSync, readFileSync } from 'node:fs';
import { spawnSync } from 'node:child_process';
const envName = process.argv[2];
const rawArgs = process.argv.slice(3);
const appProjects = new Map([
['dj-carlife-web', {
root: 'projects/dj-carlife-web',
suites: new Map([
['basic', 'projects/dj-carlife-web/tests/basic'],
['saas-v5.8.6', 'projects/dj-carlife-web/tests/saas-v5.8.6'],
]),
}],
]);
let suiteName = 'all';
let appProjectName = 'dj-carlife-web';
const extraArgs = [];
for (let index = 0; index < rawArgs.length; index += 1) {
const arg = rawArgs[index];
if (arg === '--app-project') {
appProjectName = rawArgs[index + 1] || '';
index += 1;
continue;
}
if (arg.startsWith('--app-project=')) {
appProjectName = arg.split('=').slice(1).join('=');
continue;
}
if (arg === '--suite') {
suiteName = rawArgs[index + 1] || '';
index += 1;
continue;
}
if (arg.startsWith('--suite=')) {
suiteName = arg.split('=').slice(1).join('=');
continue;
}
extraArgs.push(arg);
}
if (!appProjects.has(appProjectName)) {
console.error('未知测试项目:' + appProjectName + '。可用项目:' + [...appProjects.keys()].join('、') + '。');
process.exit(1);
}
const appProject = appProjects.get(appProjectName);
const suitePath = appProject.suites.get(suiteName);
if (suiteName !== 'all' && !suitePath) {
console.error('未知用例范围:' + suiteName + '。请确认该项目已配置此用例范围。');
process.exit(1);
}
const hasProjectArg = extraArgs.some((arg) => arg === '--project' || arg.startsWith('--project='));
const playwrightArgs = [
'playwright',
'test',
...(hasProjectArg ? [] : ['--project=edge']),
...(suitePath ? [suitePath] : [appProject.root]),
...extraArgs,
];
if (existsSync('.env.local')) {
const lines = readFileSync('.env.local', 'utf8').split(/\r?\n/);
for (const line of lines) {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith('#') || !trimmed.includes('=')) continue;
const [key, ...valueParts] = trimmed.split('=');
process.env[key.trim()] = valueParts.join('=').trim();
}
}
const result = spawnSync('npx', playwrightArgs, {
stdio: 'inherit',
shell: true,
env: {
...process.env,
...(envName ? { E2E_ENV: envName } : {}),
E2E_APP_PROJECT: appProjectName,
},
});
if (result.error) {
console.error(result.error.message);
}
process.exit(result.status ?? 1);
import { test, expect } from '@playwright/test';
test('has title', async ({ page }) => {
await page.goto('https://playwright.dev/');
// Expect a title "to contain" a substring.
await expect(page).toHaveTitle(/Playwright/);
});
test('get started link', async ({ page }) => {
await page.goto('https://playwright.dev/');
// Click the get started link.
await page.getByRole('link', { name: 'Get started' }).click();
// Expects page to have a heading with the name of Installation.
await expect(page.getByRole('heading', { name: 'Installation' })).toBeVisible();
});
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>E2E 测试面板</title>
<style>
:root {
color-scheme: light;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
background: #f6f8fb;
color: #1f2937;
}
body {
margin: 0;
padding: 28px;
}
main {
max-width: 1180px;
margin: 0 auto;
}
h1 {
margin: 0 0 8px;
font-size: 28px;
}
.sub {
margin: 0 0 22px;
color: #64748b;
}
section {
margin-bottom: 20px;
}
.toolbar {
display: flex;
flex-wrap: wrap;
gap: 12px;
align-items: end;
padding: 18px;
border: 1px solid #dbe3ef;
border-radius: 8px;
background: #fff;
}
label {
display: grid;
gap: 6px;
font-size: 13px;
color: #475569;
}
select, button {
height: 38px;
border-radius: 6px;
border: 1px solid #cbd5e1;
background: #fff;
color: #0f172a;
font-size: 14px;
}
select {
min-width: 150px;
padding: 0 10px;
}
button {
padding: 0 16px;
border-color: #2563eb;
background: #2563eb;
color: #fff;
cursor: pointer;
}
button.secondary {
border-color: #cbd5e1;
background: #fff;
color: #1d4ed8;
}
button:disabled {
cursor: not-allowed;
opacity: .6;
}
.quick {
display: flex;
flex-wrap: wrap;
gap: 10px;
}
.quick button {
background: #fff;
color: #1d4ed8;
}
.status {
margin: 12px 0;
min-height: 24px;
font-weight: 600;
}
.workspace {
display: grid;
grid-template-columns: 1fr;
gap: 16px;
align-items: start;
}
.console {
overflow: hidden;
border: 1px solid #1e293b;
border-radius: 8px;
background: #0f172a;
box-shadow: 0 12px 30px rgba(15, 23, 42, .12);
}
.console-header {
display: flex;
justify-content: space-between;
gap: 12px;
align-items: center;
padding: 12px 14px;
color: #e2e8f0;
border-bottom: 1px solid #243449;
font-size: 14px;
font-weight: 700;
cursor: pointer;
user-select: none;
}
.console-toggle {
color: #cbd5e1;
font-size: 12px;
font-weight: 600;
}
.console.is-collapsed pre {
display: none;
}
.console-state {
color: #93c5fd;
font-size: 12px;
font-weight: 600;
}
.console pre {
box-sizing: border-box;
width: 100%;
height: 260px;
margin: 0;
padding: 16px;
overflow: auto;
color: #e5e7eb;
font-family: Consolas, "Courier New", monospace;
font-size: 13px;
line-height: 1.55;
white-space: pre-wrap;
word-break: break-word;
}
.report {
overflow: hidden;
border: 1px solid #dbe3ef;
border-radius: 8px;
background: #fff;
}
.report-header {
display: flex;
justify-content: space-between;
gap: 12px;
align-items: center;
padding: 12px 14px;
border-bottom: 1px solid #e2e8f0;
}
.report-header strong {
font-size: 15px;
}
iframe {
width: 100%;
height: 680px;
border: 0;
background: #fff;
}
.empty-report {
display: grid;
min-height: 680px;
place-items: center;
color: #64748b;
}
.is-hidden {
display: none !important;
}
@media (max-width: 900px) {
body {
padding: 18px;
}
.console pre {
height: 220px;
min-height: 220px;
}
iframe,
.empty-report {
height: 520px;
min-height: 520px;
}
}
</style>
</head>
<body>
<main>
<h1>E2E 测试面板</h1>
<p class="sub">选择项目、环境、测试范围和浏览器,点击按钮运行测试。</p>
<section class="toolbar">
<label>
项目
<select id="appProject"></select>
</label>
<label>
环境
<select id="env"></select>
</label>
<label>
用例范围
<select id="suite"></select>
</label>
<label>
浏览器
<select id="browser"></select>
</label>
<button id="run">运行测试</button>
<button id="showReport" class="secondary">查看最新报告</button>
</section>
<div id="status" class="status">等待运行</div>
<div id="workspace" class="workspace">
<section id="consolePanel" class="console is-hidden is-collapsed" aria-live="polite">
<div id="consoleHeader" class="console-header" role="button" tabindex="0">
<strong>运行输出</strong>
<span><span id="consoleState" class="console-state">已收起</span> <span id="consoleToggle" class="console-toggle">展开</span></span>
</div>
<pre id="output">等待测试开始...</pre>
</section>
<section class="report">
<div class="report-header">
<strong>最新报告</strong>
<button id="refreshReport" class="secondary">刷新报告</button>
</div>
<div id="emptyReport" class="empty-report">还没有显示报告。</div>
<iframe id="reportFrame" class="is-hidden" title="Playwright 测试报告"></iframe>
</section>
</div>
</main>
<script src="/panel-config.js"></script>
<script>
const appProject = document.querySelector('#appProject');
const env = document.querySelector('#env');
const suite = document.querySelector('#suite');
const browser = document.querySelector('#browser');
const run = document.querySelector('#run');
const showReport = document.querySelector('#showReport');
const refreshReport = document.querySelector('#refreshReport');
const status = document.querySelector('#status');
const workspace = document.querySelector('#workspace');
const consolePanel = document.querySelector('#consolePanel');
const consoleHeader = document.querySelector('#consoleHeader');
const consoleState = document.querySelector('#consoleState');
const consoleToggle = document.querySelector('#consoleToggle');
const output = document.querySelector('#output');
const emptyReport = document.querySelector('#emptyReport');
const reportFrame = document.querySelector('#reportFrame');
const selectOptions = window.E2E_PANEL_SELECT_OPTIONS;
function renderSelectOptions() {
Object.entries(selectOptions).forEach(([selectId, options]) => {
const select = document.querySelector(`#${selectId}`);
select.replaceChildren(...options.map(({ value, label }) => {
const option = document.createElement('option');
option.value = value;
option.textContent = label;
return option;
}));
});
}
renderSelectOptions();
const buttons = Array.from(document.querySelectorAll('button'));
let progressTimer = null;
let runStartedAt = 0;
let lastOutputAt = 0;
function setButtonsDisabled(disabled) {
buttons.forEach((button) => button.disabled = disabled);
}
function setConsoleCollapsed(collapsed) {
consolePanel.classList.toggle('is-collapsed', collapsed);
consoleToggle.textContent = collapsed ? '展开' : '收起';
}
function showConsole() {
workspace.classList.add('is-running');
consolePanel.classList.remove('is-hidden');
setConsoleCollapsed(false);
consoleState.textContent = '运行中';
output.textContent = '';
}
function startProgressHeartbeat() {
stopProgressHeartbeat();
runStartedAt = Date.now();
lastOutputAt = runStartedAt;
progressTimer = window.setInterval(() => {
const now = Date.now();
const seconds = Math.floor((now - runStartedAt) / 1000);
const idleSeconds = Math.floor((now - lastOutputAt) / 1000);
consoleState.textContent = `运行中 ${seconds}s`;
if (idleSeconds >= 10) {
appendOutput(`\n[面板] 测试仍在运行,已用时 ${seconds}s,正在等待页面或接口返回...\n`, { system: true });
lastOutputAt = now;
}
}, 5000);
}
function stopProgressHeartbeat() {
if (progressTimer) {
window.clearInterval(progressTimer);
progressTimer = null;
}
}
function finishConsole() {
workspace.classList.remove('is-running');
consolePanel.classList.remove('is-hidden');
setConsoleCollapsed(false);
consoleState.textContent = '已完成';
}
function appendOutput(text, options = {}) {
if (!options.system) {
lastOutputAt = Date.now();
}
output.textContent += text;
output.scrollTop = output.scrollHeight;
}
function clearReportFrame(message = '本轮测试运行中,报告完成后会自动显示。') {
reportFrame.classList.add('is-hidden');
reportFrame.removeAttribute('src');
emptyReport.classList.remove('is-hidden');
emptyReport.textContent = message;
}
function showReportFrame() {
emptyReport.classList.add('is-hidden');
reportFrame.classList.remove('is-hidden');
reportFrame.src = `/report/?t=${Date.now()}`;
}
async function refreshReportStatus() {
const response = await fetch('/report-status');
const result = await response.json();
showReport.disabled = !result.exists;
refreshReport.disabled = !result.exists;
return result.exists;
}
async function handleStream(response) {
if (!response.ok) {
const errorResult = await response.json().catch(() => ({}));
throw new Error(errorResult.output || '测试启动失败');
}
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
let finalResult = null;
while (true) {
const { value, done } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split('\n');
buffer = lines.pop() || '';
for (const line of lines) {
if (!line.trim()) continue;
const message = JSON.parse(line);
if (message.type === 'output') {
appendOutput(message.output);
}
if (message.type === 'done') {
finalResult = message;
}
}
}
return finalResult || { ok: false, reportExists: false };
}
async function runTest(nextAppProject, nextEnv, nextBrowser, nextSuite) {
setButtonsDisabled(true);
clearReportFrame();
showConsole();
startProgressHeartbeat();
status.textContent = '测试运行中...';
try {
const response = await fetch('/run-stream', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ project: nextAppProject, env: nextEnv, browser: nextBrowser, suite: nextSuite }),
});
const result = await handleStream(response);
status.textContent = result.ok ? '测试通过,已显示最新报告' : '测试失败,已显示最新报告';
await refreshReportStatus();
if (result.reportExists) {
showReportFrame();
}
} catch (error) {
clearReportFrame('本轮测试启动失败,没有生成新报告。');
status.textContent = `运行失败:${error.message}`;
} finally {
stopProgressHeartbeat();
setButtonsDisabled(false);
finishConsole();
await refreshReportStatus();
}
}
consoleHeader.addEventListener('click', () => setConsoleCollapsed(!consolePanel.classList.contains('is-collapsed')));
consoleHeader.addEventListener('keydown', (event) => {
if (event.key === 'Enter' || event.key === ' ') {
event.preventDefault();
setConsoleCollapsed(!consolePanel.classList.contains('is-collapsed'));
}
});
run.addEventListener('click', () => runTest(appProject.value, env.value, browser.value, suite.value));
showReport.addEventListener('click', showReportFrame);
refreshReport.addEventListener('click', showReportFrame);
document.querySelectorAll('[data-env]').forEach((button) => {
button.addEventListener('click', () => runTest(button.dataset.project, button.dataset.env, button.dataset.browser, button.dataset.suite));
});
refreshReportStatus();
</script>
</body>
</html>
window.E2E_PANEL_SELECT_OPTIONS = {
appProject: [
{ value: 'dj-carlife-web', label: 'D+智享车生活PC' },
],
env: [
{ value: 'test', label: '测试环境' },
{ value: 'dev', label: '开发环境' },
{ value: 'local', label: '本地环境' },
],
suite: [
{ value: 'basic', label: '基础功能' },
{ value: 'saas-v5.8.6', label: 'SAAS-V5.8.6' },
{ value: 'all', label: '全部用例' },
],
browser: [
{ value: 'edge', label: 'Edge' },
{ value: 'all', label: '全部浏览器' },
{ value: 'firefox', label: 'Firefox' },
{ value: 'webkit', label: 'WebKit' },
],
};
import { createServer } from 'node:http';
import { networkInterfaces } from 'node:os';
import { existsSync } from 'node:fs';
import { readFile } from 'node:fs/promises';
import { spawn } from 'node:child_process';
import { dirname, extname, join, normalize, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
const __dirname = dirname(fileURLToPath(import.meta.url));
const startPort = Number(process.env.E2E_PANEL_PORT || 5200);
const reportDir = resolve(process.cwd(), 'playwright-report');
const appProjects = new Map([
['dj-carlife-web', { label: 'D+智享车生活PC', suites: new Set(['all', 'basic', 'saas-v5.8.6']) }],
]);
const envs = new Set(['local', 'dev', 'test']);
const browsers = new Set(['edge', 'all', 'firefox', 'webkit']);
let running = false;
const reportChineseScript = String.raw`
<script>
(() => {
const textMap = new Map([
['Search tests', '搜索用例'],
['All', '全部'],
['Passed', '通过'],
['Failed', '失败'],
['Flaky', '不稳定'],
['Skipped', '跳过'],
['Total time:', '总耗时:'],
['Filtered:', '筛选结果:'],
['Errors', '错误'],
['Test Steps', '测试步骤'],
['Filter steps', '搜索步骤'],
['Screenshots', '截图'],
['Traces', '调试轨迹'],
['Videos', '视频'],
['Attachments', '附件'],
['Copy prompt', '复制提示'],
['Copied', '已复制'],
]);
function translateText(value) {
if (!value) return value;
let next = value;
for (const [english, chinese] of textMap) {
next = next.replaceAll(english, chinese);
}
return next;
}
function translateNode(node) {
if (node.nodeType === Node.TEXT_NODE) {
const next = translateText(node.nodeValue);
if (next !== node.nodeValue) node.nodeValue = next;
return;
}
if (node.nodeType !== Node.ELEMENT_NODE) return;
for (const attr of ['placeholder', 'aria-label', 'title']) {
if (node.hasAttribute(attr)) {
const value = node.getAttribute(attr);
const next = translateText(value);
if (next !== value) node.setAttribute(attr, next);
}
}
for (const child of node.childNodes) translateNode(child);
}
function translateReport() {
document.title = 'Playwright 测试报告';
translateNode(document.body);
}
translateReport();
new MutationObserver(translateReport).observe(document.body, {
childList: true,
subtree: true,
characterData: true,
attributes: true,
attributeFilter: ['placeholder', 'aria-label', 'title'],
});
})();
</script>`;
const contentTypes = {
'.html': 'text/html; charset=utf-8',
'.js': 'text/javascript; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.json': 'application/json; charset=utf-8',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.svg': 'image/svg+xml',
'.webp': 'image/webp',
'.zip': 'application/zip',
'.md': 'text/markdown; charset=utf-8',
};
function readBody(req) {
return new Promise((resolve, reject) => {
let body = '';
req.on('data', (chunk) => {
body += chunk;
if (body.length > 10000) {
reject(new Error('请求内容太大'));
req.destroy();
}
});
req.on('end', () => resolve(body));
req.on('error', reject);
});
}
function sendJson(res, status, value) {
res.writeHead(status, { 'content-type': 'application/json; charset=utf-8' });
res.end(JSON.stringify(value));
}
function reportExists() {
return existsSync(join(reportDir, 'index.html'));
}
async function serveReport(req, res) {
if (!reportExists()) {
res.writeHead(404, { 'content-type': 'text/html; charset=utf-8' });
res.end('<!doctype html><meta charset="utf-8"><body>还没有生成测试报告,请先运行一次测试。</body>');
return;
}
const url = new URL(req.url || '/', 'http://localhost');
const relativePath = decodeURIComponent(url.pathname.replace(/^\/report\/?/, '')) || 'index.html';
const filePath = resolve(reportDir, normalize(relativePath));
if (!filePath.startsWith(reportDir)) {
res.writeHead(403, { 'content-type': 'text/plain; charset=utf-8' });
res.end('不能访问报告目录外的文件。');
return;
}
let file = await readFile(filePath);
if (filePath.endsWith('index.html')) {
file = Buffer.from(file.toString('utf8').replace('</body>', reportChineseScript + '</body>'), 'utf8');
}
res.writeHead(200, { 'content-type': contentTypes[extname(filePath)] || 'application/octet-stream' });
res.end(file);
}
function buildPlaywrightArgs(env, appProject, browser, suite) {
const args = ['scripts/run-e2e.mjs', env, '--app-project=' + appProject];
if (browser === 'all') {
args.push('--project=edge', '--project=firefox', '--project=webkit');
} else {
args.push(`--project=${browser}`);
}
if (suite !== 'all') {
args.push(`--suite=${suite}`);
}
return args;
}
function runPlaywright({ env, appProject, browser, suite }) {
return new Promise((resolve) => {
const args = buildPlaywrightArgs(env, appProject, browser, suite);
const child = spawn('node', args, {
cwd: process.cwd(),
shell: true,
env: process.env,
});
let output = '';
child.stdout.on('data', (chunk) => {
output += chunk.toString();
});
child.stderr.on('data', (chunk) => {
output += chunk.toString();
});
child.on('close', (code) => {
resolve({ code, output });
});
child.on('error', (error) => {
resolve({ code: 1, output: error.message });
});
});
}
function streamPlaywright({ env, appProject, browser, suite, req, res }) {
return new Promise((resolve) => {
const args = buildPlaywrightArgs(env, appProject, browser, suite);
const send = (value) => {
if (!res.destroyed) {
res.write(`${JSON.stringify(value)}\n`);
}
};
const child = spawn('node', args, {
cwd: process.cwd(),
shell: true,
env: process.env,
});
let finished = false;
const stopChild = () => {
if (!finished && !child.killed) {
child.kill();
}
};
const cleanup = () => {
req.off('aborted', stopChild);
res.off('close', stopChild);
};
req.on('aborted', stopChild);
res.on('close', stopChild);
child.stdout.on('data', (chunk) => {
send({ type: 'output', output: chunk.toString() });
});
child.stderr.on('data', (chunk) => {
send({ type: 'output', output: chunk.toString() });
});
child.on('close', (code) => {
finished = true;
cleanup();
const result = {
type: 'done',
ok: code === 0,
code,
reportExists: reportExists(),
reportUrl: '/report/',
};
send(result);
resolve(result);
});
child.on('error', (error) => {
finished = true;
cleanup();
const result = {
type: 'done',
ok: false,
code: 1,
reportExists: reportExists(),
reportUrl: '/report/',
};
send({ type: 'output', output: error.message });
send(result);
resolve(result);
});
});
}
function validateRunParams(env, project, browser, suite) {
const projectConfig = appProjects.get(project);
if (!envs.has(env) || !projectConfig || !browsers.has(browser) || !projectConfig.suites.has(suite)) {
return '参数不正确。请检查项目、环境、浏览器和用例范围。';
}
return '';
}
function createPanelServer() {
return createServer(async (req, res) => {
try {
if (req.method === 'GET' && req.url === '/panel-config.js') {
const file = await readFile(join(__dirname, 'panel-config.js'));
res.writeHead(200, { 'content-type': contentTypes['.js'] });
res.end(file);
return;
}
if (req.method === 'GET' && req.url === '/') {
const html = await readFile(join(__dirname, 'index.html'), 'utf8');
res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' });
res.end(html);
return;
}
if (req.method === 'GET' && req.url === '/report-status') {
sendJson(res, 200, { exists: reportExists(), url: '/report/' });
return;
}
if (req.method === 'GET' && req.url?.startsWith('/report/')) {
await serveReport(req, res);
return;
}
if (req.method === 'POST' && req.url === '/run') {
if (running) {
sendJson(res, 409, { ok: false, reportExists: reportExists(), output: '已有测试正在运行,请等待它结束。' });
return;
}
const body = JSON.parse((await readBody(req)) || '{}');
const env = body.env;
const project = body.project || 'dj-carlife-web';
const browser = body.browser || 'edge';
const suite = body.suite || 'all';
const error = validateRunParams(env, project, browser, suite);
if (error) {
sendJson(res, 400, { ok: false, reportExists: reportExists(), output: error });
return;
}
running = true;
const result = await runPlaywright({ env, appProject: project, browser, suite });
running = false;
sendJson(res, 200, { ok: result.code === 0, reportExists: reportExists(), reportUrl: '/report/', ...result });
return;
}
if (req.method === 'POST' && req.url === '/run-stream') {
if (running) {
sendJson(res, 409, { ok: false, reportExists: reportExists(), output: '已有测试正在运行,请等待它结束。' });
return;
}
const body = JSON.parse((await readBody(req)) || '{}');
const env = body.env;
const project = body.project || 'dj-carlife-web';
const browser = body.browser || 'edge';
const suite = body.suite || 'all';
const error = validateRunParams(env, project, browser, suite);
if (error) {
sendJson(res, 400, { ok: false, reportExists: reportExists(), output: error });
return;
}
running = true;
res.writeHead(200, {
'content-type': 'application/x-ndjson; charset=utf-8',
'cache-control': 'no-cache',
connection: 'keep-alive',
});
try {
await streamPlaywright({ env, appProject: project, browser, suite, req, res });
} finally {
running = false;
res.end();
}
return;
}
sendJson(res, 404, { ok: false, output: '没有找到这个页面。' });
} catch (error) {
running = false;
sendJson(res, 500, { ok: false, reportExists: reportExists(), output: error.message });
}
});
}
function getLocalIp() {
for (const addresses of Object.values(networkInterfaces())) {
for (const address of addresses || []) {
if (address.family === 'IPv4' && !address.internal) {
return address.address;
}
}
}
return '127.0.0.1';
}
function listen(port) {
const host = getLocalIp();
const server = createPanelServer();
server.once('error', (error) => {
if (error.code === 'EADDRINUSE') {
console.log(`端口 ${port} 已被占用,正在尝试端口 ${port + 1}...`);
listen(port + 1);
return;
}
throw error;
});
server.listen(port, host, () => {
console.log(`E2E 测试面板已启动:http://${host}:${port}`);
});
}
listen(startPort);
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!