Initial commit: ai4se-harness-suite
Import harness suite (skills, installers, overnight-runner, docs) as a fresh history for InspireChina. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
51
example-project/e2e/debug.mjs
Normal file
51
example-project/e2e/debug.mjs
Normal file
@@ -0,0 +1,51 @@
|
||||
import { chromium } from 'playwright';
|
||||
|
||||
const BASE = 'http://localhost:5173';
|
||||
|
||||
async function run() {
|
||||
const browser = await chromium.launch({ headless: false, slowMo: 200 });
|
||||
const context = await browser.newContext({ viewport: { width: 1280, height: 800 } });
|
||||
const page = await context.newPage();
|
||||
|
||||
// Listen to console errors
|
||||
page.on('console', msg => { if (msg.type() === 'error') console.log('CONSOLE ERROR:', msg.text()); });
|
||||
page.on('response', resp => {
|
||||
if (resp.status() >= 400) console.log(`API ${resp.status()} ${resp.url()}`);
|
||||
});
|
||||
|
||||
// 1. Homepage
|
||||
await page.goto(BASE, { waitUntil: 'networkidle' });
|
||||
await page.screenshot({ path: 'e2e/screenshots/01-homepage.png', fullPage: true });
|
||||
console.log('✓ Homepage loaded');
|
||||
|
||||
// 2. Navigate to login
|
||||
await page.click('text=登录');
|
||||
await page.waitForURL('**/login');
|
||||
await page.screenshot({ path: 'e2e/screenshots/02-login.png', fullPage: true });
|
||||
console.log('✓ Login page loaded');
|
||||
|
||||
// 3. Login as admin
|
||||
await page.fill('input[type="email"], input[name="email"], input[placeholder*="邮箱"]', 'admin@test.com');
|
||||
await page.fill('input[type="password"], input[name="password"], input[placeholder*="密码"]', 'password');
|
||||
await page.click('button[type="submit"], button:has-text("登录")');
|
||||
await page.waitForTimeout(1500);
|
||||
await page.screenshot({ path: 'e2e/screenshots/03-after-login.png', fullPage: true });
|
||||
console.log('✓ Login submitted, current URL:', page.url());
|
||||
|
||||
// 4. Navigate to /admin/dashboard
|
||||
await page.goto(BASE + '/admin/dashboard', { waitUntil: 'networkidle' });
|
||||
await page.screenshot({ path: 'e2e/screenshots/04-admin-dashboard.png', fullPage: true });
|
||||
console.log('✓ Admin dashboard, current URL:', page.url());
|
||||
|
||||
// 5. Try different pages
|
||||
for (const path of ['/admin/users', '/admin/consultants', '/admin/appointments', '/admin/branches']) {
|
||||
await page.goto(BASE + path, { waitUntil: 'networkidle' });
|
||||
await page.screenshot({ path: `e2e/screenshots/05${path.replace(/\//g, '-')}.png`, fullPage: true });
|
||||
console.log(`✓ Page ${path}, URL: ${page.url()}`);
|
||||
}
|
||||
|
||||
await browser.close();
|
||||
console.log('\nDone! Check e2e/screenshots/ for results.');
|
||||
}
|
||||
|
||||
run().catch(err => { console.error(err); process.exit(1); });
|
||||
167
example-project/e2e/helpers/visual-test.ts
Normal file
167
example-project/e2e/helpers/visual-test.ts
Normal file
@@ -0,0 +1,167 @@
|
||||
import { type Locator, type Page } from '@playwright/test'
|
||||
|
||||
interface VlmConfig {
|
||||
baseUrl: string
|
||||
model: string
|
||||
apiKey: string
|
||||
provider: 'openai' | 'anthropic'
|
||||
}
|
||||
|
||||
interface AnalyzeOptions {
|
||||
prompt: string
|
||||
element?: Locator
|
||||
fullPage?: boolean
|
||||
}
|
||||
|
||||
function getConfig(): VlmConfig | null {
|
||||
const apiKey = process.env.VLM_API_KEY
|
||||
if (!apiKey) return null
|
||||
|
||||
const raw = (process.env.VLM_BASE_URL || 'https://api.openai.com/v1').replace(/\/+$/, '')
|
||||
const model = process.env.VLM_MODEL || 'gpt-4o-mini'
|
||||
|
||||
const provider: 'openai' | 'anthropic' =
|
||||
raw.includes('anthropic') || process.env.VLM_PROVIDER === 'anthropic'
|
||||
? 'anthropic'
|
||||
: 'openai'
|
||||
|
||||
// normalize baseUrl: strip trailing /v1 for anthropic, then provider appends /v1/messages
|
||||
const baseUrl = provider === 'anthropic' ? raw.replace(/\/v1$/, '') : raw
|
||||
|
||||
return { baseUrl, model, apiKey, provider }
|
||||
}
|
||||
|
||||
async function screenshot(pageOrLocator: Page | Locator, options: AnalyzeOptions): Promise<string> {
|
||||
let buf: Buffer
|
||||
if (options.element) {
|
||||
buf = await options.element.screenshot()
|
||||
} else if ('context' in pageOrLocator) {
|
||||
buf = await (pageOrLocator as Page).screenshot({ fullPage: options.fullPage })
|
||||
} else {
|
||||
buf = await (pageOrLocator as Locator).screenshot()
|
||||
}
|
||||
return buf.toString('base64')
|
||||
}
|
||||
|
||||
async function vlmFetch(url: string, init: RequestInit, retries = 3): Promise<Response> {
|
||||
for (let attempt = 1; attempt <= retries; attempt++) {
|
||||
const resp = await fetch(url, init)
|
||||
if (resp.ok) return resp
|
||||
const body = await resp.text()
|
||||
// retry on 429 (rate limit) and 5xx (server error)
|
||||
if ((resp.status === 429 || resp.status >= 500) && attempt < retries) {
|
||||
const delay = 1000 * Math.pow(2, attempt) + Math.random() * 1000
|
||||
console.log(` [VLM] API error ${resp.status}, retrying in ${Math.round(delay)}ms (attempt ${attempt}/${retries})`)
|
||||
await new Promise(r => setTimeout(r, delay))
|
||||
continue
|
||||
}
|
||||
throw new Error(`VLM API error ${resp.status}: ${body}`)
|
||||
}
|
||||
throw new Error('VLM API max retries exceeded')
|
||||
}
|
||||
|
||||
async function analyzeWithOpenAI(
|
||||
imageBase64: string, prompt: string, config: VlmConfig
|
||||
): Promise<string> {
|
||||
const resp = await vlmFetch(`${config.baseUrl}/chat/completions`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: `Bearer ${config.apiKey}`,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
model: config.model,
|
||||
messages: [
|
||||
{
|
||||
role: 'user',
|
||||
content: [
|
||||
{ type: 'text', text: prompt },
|
||||
{ type: 'image_url', image_url: { url: `data:image/png;base64,${imageBase64}`, detail: 'high' } },
|
||||
],
|
||||
},
|
||||
],
|
||||
max_tokens: 1024,
|
||||
}),
|
||||
})
|
||||
const data = await resp.json()
|
||||
return data.choices?.[0]?.message?.content || ''
|
||||
}
|
||||
|
||||
async function analyzeWithAnthropic(
|
||||
imageBase64: string, prompt: string, config: VlmConfig
|
||||
): Promise<string> {
|
||||
const resp = await vlmFetch(`${config.baseUrl}/v1/messages`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'x-api-key': config.apiKey,
|
||||
'anthropic-version': '2023-06-01',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
model: config.model,
|
||||
max_tokens: 1024,
|
||||
messages: [
|
||||
{
|
||||
role: 'user',
|
||||
content: [
|
||||
{
|
||||
type: 'image',
|
||||
source: { type: 'base64', media_type: 'image/png', data: imageBase64 },
|
||||
},
|
||||
{ type: 'text', text: prompt },
|
||||
],
|
||||
},
|
||||
],
|
||||
}),
|
||||
})
|
||||
const data = await resp.json()
|
||||
const textBlock = data.content?.find((c: any) => c.type === 'text')
|
||||
return textBlock?.text || ''
|
||||
}
|
||||
|
||||
export function visualTest() {
|
||||
const config = getConfig()
|
||||
|
||||
async function analyze(pageOrLocator: Page | Locator, options: AnalyzeOptions): Promise<string> {
|
||||
if (!config) {
|
||||
throw new Error(
|
||||
'VLM not configured. Set VLM_API_KEY in environment.\n' +
|
||||
' Examples:\n' +
|
||||
' OpenAI: VLM_API_KEY=sk-... (default model: gpt-4o-mini)\n' +
|
||||
' Ollama (local): VLM_BASE_URL=http://localhost:11434/v1 VLM_MODEL=llava VLM_API_KEY=ollama\n' +
|
||||
' Anthropic/Claude: VLM_BASE_URL=https://api.anthropic.com VLM_MODEL=claude-3-5-sonnet-latest VLM_API_KEY=sk-...\n' +
|
||||
' Zhipu/GLM-5V-Turbo: VLM_BASE_URL=https://open.bigmodel.cn/api/anthropic VLM_MODEL=glm-5v-turbo VLM_PROVIDER=anthropic VLM_API_KEY=your-key\n' +
|
||||
' ⚠️ DeepSeek API does NOT support vision/image input (tested via both OpenAI & Anthropic formats).'
|
||||
)
|
||||
}
|
||||
|
||||
const b64 = await screenshot(pageOrLocator, options)
|
||||
|
||||
if (config.provider === 'anthropic') {
|
||||
return analyzeWithAnthropic(b64, options.prompt, config)
|
||||
}
|
||||
return analyzeWithOpenAI(b64, options.prompt, config)
|
||||
}
|
||||
|
||||
async function expectPrompt(
|
||||
pageOrLocator: Page | Locator,
|
||||
options: AnalyzeOptions & { contains?: string[]; notContains?: string[] }
|
||||
): Promise<string> {
|
||||
const text = await analyze(pageOrLocator, options)
|
||||
const errors: string[] = []
|
||||
for (const substr of options.contains || []) {
|
||||
if (!text.includes(substr)) {
|
||||
errors.push(`Expected analysis to contain "${substr}", but got: "${text}"`)
|
||||
}
|
||||
}
|
||||
for (const substr of options.notContains || []) {
|
||||
if (text.includes(substr)) {
|
||||
errors.push(`Expected analysis NOT to contain "${substr}", but got: "${text}"`)
|
||||
}
|
||||
}
|
||||
if (errors.length > 0) throw new Error(errors.join('\n'))
|
||||
return text
|
||||
}
|
||||
|
||||
return { analyze, expectPrompt, isConfigured: config !== null }
|
||||
}
|
||||
78
example-project/e2e/package-lock.json
generated
Normal file
78
example-project/e2e/package-lock.json
generated
Normal file
@@ -0,0 +1,78 @@
|
||||
{
|
||||
"name": "e2e",
|
||||
"version": "1.0.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "e2e",
|
||||
"version": "1.0.0",
|
||||
"devDependencies": {
|
||||
"@playwright/test": "^1.61.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@playwright/test": {
|
||||
"version": "1.61.0",
|
||||
"resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.61.0.tgz",
|
||||
"integrity": "sha512-cKA5B6lpFEMyMGjxF54QihfYpB4FkEGH+qZhtArDEG+wezQAJY8Pq6C7T1SjWz+FFzt3TbyoXBQYk/0292TdJA==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"playwright": "1.61.0"
|
||||
},
|
||||
"bin": {
|
||||
"playwright": "cli.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/fsevents": {
|
||||
"version": "2.3.2",
|
||||
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz",
|
||||
"integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==",
|
||||
"dev": true,
|
||||
"hasInstallScript": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"darwin"
|
||||
],
|
||||
"engines": {
|
||||
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/playwright": {
|
||||
"version": "1.61.0",
|
||||
"resolved": "https://registry.npmjs.org/playwright/-/playwright-1.61.0.tgz",
|
||||
"integrity": "sha512-Z+7BeeqQPRRzklHsVFP4KTGIyMxKUmfeRA4WisM6G3/XW6nwGeX6fX9qYaDa+CiUqpOkb2f6X3nar05R3kSuJQ==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"playwright-core": "1.61.0"
|
||||
},
|
||||
"bin": {
|
||||
"playwright": "cli.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"fsevents": "2.3.2"
|
||||
}
|
||||
},
|
||||
"node_modules/playwright-core": {
|
||||
"version": "1.61.0",
|
||||
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.61.0.tgz",
|
||||
"integrity": "sha512-caX7TrY3Ml6egyDX0WUcTHDxodl/b51y5wJOdCEA36QviK/s2g081hvmGs8eaE3DWb6NYZQ6BjO/QkNRPenoPA==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"bin": {
|
||||
"playwright-core": "cli.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
19
example-project/e2e/package.json
Normal file
19
example-project/e2e/package.json
Normal file
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"name": "e2e",
|
||||
"version": "1.0.0",
|
||||
"description": "",
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
"test": "playwright test",
|
||||
"test:qa": "playwright test --project=qa",
|
||||
"test:dev": "playwright test --project=dev",
|
||||
"test:headed": "playwright test --headed",
|
||||
"test:debug": "playwright test --debug",
|
||||
"test:visual": "bash run-visual.sh",
|
||||
"test:visual:headed": "bash run-visual.sh --headed"
|
||||
},
|
||||
"type": "module",
|
||||
"devDependencies": {
|
||||
"@playwright/test": "^1.61.0"
|
||||
}
|
||||
}
|
||||
24
example-project/e2e/playwright.config.ts
Normal file
24
example-project/e2e/playwright.config.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
import { defineConfig } from '@playwright/test'
|
||||
|
||||
// E2E 用例按归属分两层(详见 tests/README.md):
|
||||
// tests/qa/ — QA 验收用例,合并闸门,用例基线在 docs/test-cases/e2e-cases/test-cases.md
|
||||
// tests/dev/ — 开发自测用例,仅供开发期快速反馈
|
||||
export default defineConfig({
|
||||
testDir: './tests',
|
||||
timeout: 30000,
|
||||
retries: 1,
|
||||
use: {
|
||||
baseURL: 'http://localhost:5173',
|
||||
viewport: { width: 1280, height: 800 },
|
||||
screenshot: 'only-on-failure',
|
||||
trace: 'on-first-retry',
|
||||
},
|
||||
projects: [
|
||||
{ name: 'qa', testDir: './tests/qa' },
|
||||
{ name: 'dev', testDir: './tests/dev' },
|
||||
],
|
||||
reporter: [
|
||||
['list'],
|
||||
['html', { outputFolder: 'playwright-report' }],
|
||||
],
|
||||
})
|
||||
32
example-project/e2e/run-visual.sh
Executable file
32
example-project/e2e/run-visual.sh
Executable file
@@ -0,0 +1,32 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
# ── Visual (VLM) E2E Tests ──
|
||||
# Requires a Vision Language Model API that supports image input.
|
||||
#
|
||||
# Usage:
|
||||
# OpenAI: VLM_API_KEY=sk-... ./run-visual.sh
|
||||
# Ollama (local/free): VLM_BASE_URL=http://localhost:11434/v1 VLM_MODEL=llava VLM_API_KEY=ollama ./run-visual.sh
|
||||
# Anthropic/Claude: VLM_BASE_URL=https://api.anthropic.com VLM_MODEL=claude-3-5-sonnet-latest VLM_API_KEY=sk-... ./run-visual.sh
|
||||
# Zhipu/GLM-5V-Turbo: VLM_BASE_URL=https://open.bigmodel.cn/api/anthropic VLM_MODEL=glm-5v-turbo VLM_PROVIDER=anthropic VLM_API_KEY=your-key ./run-visual.sh
|
||||
#
|
||||
# ⚠️ DeepSeek API does NOT support vision/image input on any model.
|
||||
|
||||
cd "$(dirname "$0")"
|
||||
|
||||
if [ -z "${VLM_API_KEY:-}" ]; then
|
||||
echo "❌ VLM_API_KEY not set."
|
||||
echo ""
|
||||
echo "Usage:"
|
||||
echo " OpenAI: VLM_API_KEY=sk-... ./run-visual.sh"
|
||||
echo " Ollama (local): VLM_BASE_URL=http://localhost:11434/v1 VLM_MODEL=llava VLM_API_KEY=ollama ./run-visual.sh"
|
||||
echo " Anthropic/Claude: VLM_BASE_URL=https://api.anthropic.com VLM_MODEL=claude-3-5-sonnet-latest VLM_API_KEY=sk-... ./run-visual.sh"
|
||||
echo " Zhipu/GLM-5V-Turbo: VLM_BASE_URL=https://open.bigmodel.cn/api/anthropic VLM_MODEL=glm-5v-turbo VLM_PROVIDER=anthropic VLM_API_KEY=your-key ./run-visual.sh"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "🔍 Running visual E2E tests..."
|
||||
echo " Model: ${VLM_MODEL:-gpt-4o-mini}"
|
||||
echo " Base URL: ${VLM_BASE_URL:-https://api.openai.com/v1}"
|
||||
|
||||
npx playwright test tests/dev/visual.spec.ts "$@"
|
||||
32
example-project/e2e/tests/README.md
Normal file
32
example-project/e2e/tests/README.md
Normal file
@@ -0,0 +1,32 @@
|
||||
# E2E 测试分层
|
||||
|
||||
本目录下的 E2E 用例按 **归属** 分成两层。两层的验收效力完全不同,不要混。
|
||||
|
||||
```
|
||||
tests/
|
||||
├── qa/ # QA 验收用例(自动化实现)—— 合并闸门
|
||||
└── dev/ # 开发自测用例(自动化实现)—— 仅供开发反馈
|
||||
```
|
||||
|
||||
| | `qa/` | `dev/` |
|
||||
|---|---|---|
|
||||
| 用例来源 | `docs/test-cases/e2e-cases/test-cases.md` 的 QA 验收用例 | 开发按 Plan 自定 |
|
||||
| 编号 | `TC-xxx` | 无编号,标题自解释 |
|
||||
| 谁判定 | QA | 开发本人 |
|
||||
| 合并闸门 | **是** —— 不通过不能合并 | 否 —— 挂了不阻塞别人,但必须自己修 |
|
||||
| 关注点 | 需求规格有没有被实现 | 我这次改的东西有没有被我改坏 |
|
||||
|
||||
## 约定
|
||||
|
||||
- `qa/` 下的每个 `test()` 都要能对应到 `docs/test-cases/e2e-cases/test-cases.md` 里的一条用例(编号一致)。
|
||||
- `dev/` 下的用例只服务于开发期的快速反馈,**不能** 作为验收依据。
|
||||
- 新增 QA 用例时,**先**在 `docs/test-cases/e2e-cases/test-cases.md` 里写文本用例,再写自动化。
|
||||
- 自动化实现可以由开发代写,但 **用例的判定权归 QA**。
|
||||
|
||||
## 运行
|
||||
|
||||
```bash
|
||||
npm test # 全部(qa + dev)
|
||||
npm run test:qa # 只跑 QA 验收用例
|
||||
npm run test:dev # 只跑开发自测用例
|
||||
```
|
||||
153
example-project/e2e/tests/dev/visual.spec.ts
Normal file
153
example-project/e2e/tests/dev/visual.spec.ts
Normal file
@@ -0,0 +1,153 @@
|
||||
import { test, expect } from '@playwright/test'
|
||||
import { visualTest } from '../../helpers/visual-test'
|
||||
|
||||
const ADMIN_EMAIL = 'admin@test.com'
|
||||
const ADMIN_PASSWORD = 'password'
|
||||
|
||||
const vlm = visualTest()
|
||||
|
||||
/* ─────────────── Visual Tests ─────────────── */
|
||||
|
||||
test.describe('Visual Tests', () => {
|
||||
|
||||
test('homepage hero section visual layout', async ({ page }) => {
|
||||
test.skip(!vlm.isConfigured, 'VLM not configured (set VLM_API_KEY)')
|
||||
|
||||
await page.goto('/')
|
||||
const analysis = await vlm.analyze(page, {
|
||||
prompt: `Describe the hero section of this consultation booking website homepage.
|
||||
What is the main heading text? What buttons/actions are available?
|
||||
List the exact text content you see.`,
|
||||
fullPage: true,
|
||||
})
|
||||
expect(analysis).toContain('专业咨询服务')
|
||||
console.log('[Visual] Homepage analysis:', analysis)
|
||||
})
|
||||
|
||||
test('login page form layout', async ({ page }) => {
|
||||
test.skip(!vlm.isConfigured, 'VLM not configured')
|
||||
|
||||
await page.goto('/login')
|
||||
const analysis = await vlm.analyze(page, {
|
||||
prompt: `Describe the login page form. What input fields are visible?
|
||||
Are there any labels? What does the submit button say?
|
||||
List all visible text elements.`,
|
||||
})
|
||||
expect(analysis).toContain('登录')
|
||||
console.log('[Visual] Login page analysis:', analysis)
|
||||
})
|
||||
|
||||
test('calendar date picker renders consecutive dates', async ({ page }) => {
|
||||
test.skip(!vlm.isConfigured, 'VLM not configured (set VLM_API_KEY)')
|
||||
|
||||
// Login and go to book page
|
||||
await page.goto('/login')
|
||||
await page.fill('input[type="email"]', ADMIN_EMAIL)
|
||||
await page.fill('input[type="password"]', ADMIN_PASSWORD)
|
||||
await page.click('button[type="submit"]')
|
||||
await page.waitForURL('**/admin/dashboard', { timeout: 10000 })
|
||||
|
||||
await page.goto('/user/book')
|
||||
await expect(page.locator('h1')).toHaveText('预约咨询')
|
||||
|
||||
// Select a consultant to reveal the date picker
|
||||
await page.locator('text=张医生').click()
|
||||
await expect(page.locator('text=2. 选择日期')).toBeVisible()
|
||||
|
||||
// Visual analysis of the date picker
|
||||
const analysis = await vlm.analyze(page.locator('.booking-steps'), {
|
||||
prompt: `Analyze the date picker section (step 2).
|
||||
1. How many date buttons are shown?
|
||||
2. List each date in YYYY-MM-DD format.
|
||||
3. Are the dates consecutive (no gaps)?
|
||||
4. Is today's date included as the first option?
|
||||
Return the list of dates and your observations.`,
|
||||
})
|
||||
console.log('[Visual] Date picker analysis:', analysis)
|
||||
|
||||
// Verify the date format is correct (YYYY-MM-DD)
|
||||
const dates = analysis.match(/\d{4}-\d{2}-\d{2}/g)
|
||||
expect(dates).not.toBeNull()
|
||||
expect(dates!.length).toBeGreaterThanOrEqual(5)
|
||||
})
|
||||
|
||||
test('admin dashboard stat cards layout', async ({ page }) => {
|
||||
test.skip(!vlm.isConfigured, 'VLM not configured')
|
||||
|
||||
await page.goto('/login')
|
||||
await page.fill('input[type="email"]', ADMIN_EMAIL)
|
||||
await page.fill('input[type="password"]', ADMIN_PASSWORD)
|
||||
await page.click('button[type="submit"]')
|
||||
await page.waitForURL('**/admin/dashboard', { timeout: 10000 })
|
||||
|
||||
const analysis = await vlm.analyze(page.locator('.stats-grid'), {
|
||||
prompt: `Analyze the dashboard statistics grid.
|
||||
1. How many stat cards are visible?
|
||||
2. For each card, what is the number/value and what is its label?
|
||||
3. Are all cards displayed in a grid layout?
|
||||
List each card's content.`,
|
||||
})
|
||||
expect(analysis).toContain('用户数')
|
||||
expect(analysis).toContain('咨询师')
|
||||
expect(analysis).toContain('总预约')
|
||||
expect(analysis).toContain('网点')
|
||||
console.log('[Visual] Dashboard stats analysis:', analysis)
|
||||
})
|
||||
|
||||
test('booking flow visual consistency (consultant → date → time → confirm)', async ({ page }) => {
|
||||
test.skip(!vlm.isConfigured, 'VLM not configured')
|
||||
|
||||
// Login and go to book page
|
||||
await page.goto('/login')
|
||||
await page.fill('input[type="email"]', ADMIN_EMAIL)
|
||||
await page.fill('input[type="password"]', ADMIN_PASSWORD)
|
||||
await page.click('button[type="submit"]')
|
||||
await page.waitForURL('**/admin/dashboard', { timeout: 10000 })
|
||||
|
||||
await page.goto('/user/book')
|
||||
await page.locator('text=张医生').click()
|
||||
await expect(page.locator('text=2. 选择日期')).toBeVisible()
|
||||
|
||||
// Pick a date to reveal time slots
|
||||
const dateBtn = page.locator('div.date-list button').first()
|
||||
await dateBtn.click()
|
||||
await page.waitForTimeout(1500)
|
||||
|
||||
// Full booking form visual analysis
|
||||
const analysis = await vlm.analyze(page.locator('.booking-steps'), {
|
||||
prompt: `Analyze this multi-step booking form.
|
||||
1. How many steps are currently visible?
|
||||
2. Which consultant is currently selected?
|
||||
3. What date was chosen?
|
||||
4. Are time slots visible? If yes, list the available times.
|
||||
5. Describe the overall layout and completeness of the form.
|
||||
Give a detailed step-by-step description.`,
|
||||
})
|
||||
console.log('[Visual] Booking form analysis:', analysis)
|
||||
})
|
||||
|
||||
test('admin sidebar navigation renders all links', async ({ page }) => {
|
||||
test.skip(!vlm.isConfigured, 'VLM not configured')
|
||||
|
||||
await page.goto('/login')
|
||||
await page.fill('input[type="email"]', ADMIN_EMAIL)
|
||||
await page.fill('input[type="password"]', ADMIN_PASSWORD)
|
||||
await page.click('button[type="submit"]')
|
||||
await page.waitForURL('**/admin/dashboard', { timeout: 10000 })
|
||||
|
||||
const analysis = await vlm.analyze(page.locator('.sidebar'), {
|
||||
prompt: `Analyze the admin sidebar navigation.
|
||||
1. List all navigation links visible.
|
||||
2. Is there a logout button?
|
||||
3. What is the title of the sidebar?
|
||||
List all link text.`,
|
||||
})
|
||||
expect(analysis).toContain('仪表盘')
|
||||
expect(analysis).toContain('用户管理')
|
||||
expect(analysis).toContain('咨询师管理')
|
||||
expect(analysis).toContain('预约管理')
|
||||
expect(analysis).toContain('网点管理')
|
||||
expect(analysis).toContain('退出')
|
||||
console.log('[Visual] Sidebar analysis:', analysis)
|
||||
})
|
||||
})
|
||||
341
example-project/e2e/tests/qa/app.spec.ts
Normal file
341
example-project/e2e/tests/qa/app.spec.ts
Normal file
@@ -0,0 +1,341 @@
|
||||
import { test, expect } from '@playwright/test'
|
||||
|
||||
const BASE = 'http://localhost:5173'
|
||||
const ADMIN_EMAIL = 'admin@test.com'
|
||||
const ADMIN_PASSWORD = 'password'
|
||||
|
||||
/* ─────────────── Public Pages ─────────────── */
|
||||
|
||||
test.describe('Public Pages', () => {
|
||||
|
||||
test('TC-001 首页加载', async ({ page }) => {
|
||||
await page.goto('/')
|
||||
await expect(page.locator('h1')).toHaveText('专业咨询服务')
|
||||
await expect(page.locator('text=免费注册')).toBeVisible()
|
||||
await expect(page.locator('text=立即预约')).toBeVisible()
|
||||
await expect(page.locator('text=© 2026 咨询预约平台')).toBeVisible()
|
||||
})
|
||||
|
||||
test('TC-002 登录页渲染', async ({ page }) => {
|
||||
await page.goto('/login')
|
||||
await expect(page.locator('h2')).toHaveText('登录')
|
||||
await expect(page.locator('input[type="email"]')).toBeVisible()
|
||||
await expect(page.locator('input[type="password"]')).toBeVisible()
|
||||
await expect(page.locator('button[type="submit"]')).toHaveText('登录')
|
||||
await expect(page.locator('text=还没有账号?')).toBeVisible()
|
||||
})
|
||||
|
||||
test('TC-003 注册页渲染', async ({ page }) => {
|
||||
await page.goto('/register')
|
||||
await expect(page.locator('h2')).toHaveText('注册')
|
||||
await expect(page.locator('input[type="email"]')).toBeVisible()
|
||||
await expect(page.locator('input[type="password"]')).toBeVisible()
|
||||
await expect(page.locator('button[type="submit"]')).toHaveText('注册')
|
||||
await expect(page.locator('text=已有账号?')).toBeVisible()
|
||||
})
|
||||
|
||||
test('TC-004 公开 API 可用', async ({ request }) => {
|
||||
let resp = await request.get(`${BASE}/api/v1/data-dictionaries`)
|
||||
expect(resp.status()).toBe(200)
|
||||
|
||||
resp = await request.get(`${BASE}/api/v1/business-rules`)
|
||||
expect(resp.status()).toBe(200)
|
||||
|
||||
resp = await request.get(`${BASE}/api/v1/consultants`)
|
||||
expect(resp.status()).toBe(200)
|
||||
const body = await resp.json()
|
||||
expect(body.length).toBeGreaterThanOrEqual(3)
|
||||
})
|
||||
|
||||
test('TC-005 导航跳转', async ({ page }) => {
|
||||
await page.goto('/')
|
||||
await page.click('text=登录')
|
||||
await expect(page).toHaveURL('/login')
|
||||
|
||||
await page.click('text=立即注册')
|
||||
await expect(page).toHaveURL('/register')
|
||||
})
|
||||
})
|
||||
|
||||
/* ─────────────── Auth & User Lifecycle (serial: share registered email) ─────────────── */
|
||||
|
||||
let registerEmail = ''
|
||||
|
||||
test.describe.serial('Auth & User Lifecycle', () => {
|
||||
|
||||
test('TC-006 管理员登录成功', async ({ page }) => {
|
||||
await page.goto('/login')
|
||||
await page.fill('input[type="email"]', ADMIN_EMAIL)
|
||||
await page.fill('input[type="password"]', ADMIN_PASSWORD)
|
||||
await page.click('button[type="submit"]')
|
||||
await page.waitForURL('**/admin/dashboard', { timeout: 10000 })
|
||||
await expect(page.locator('h1')).toHaveText('管理仪表盘')
|
||||
})
|
||||
|
||||
test('TC-007 错误密码提示', async ({ page }) => {
|
||||
await page.goto('/login')
|
||||
await page.fill('input[type="email"]', ADMIN_EMAIL)
|
||||
await page.fill('input[type="password"]', 'wrongpassword')
|
||||
await page.click('button[type="submit"]')
|
||||
await expect(page.locator('.error')).toBeVisible({ timeout: 8000 })
|
||||
})
|
||||
|
||||
test('TC-008 注册新用户', async ({ page }) => {
|
||||
registerEmail = `e2e_${Date.now()}@test.com`
|
||||
await page.goto('/register')
|
||||
|
||||
await page.locator('input[placeholder*="姓名"]').fill('E2E用户')
|
||||
await page.fill('input[type="email"]', registerEmail)
|
||||
await page.locator('input[placeholder*="选填"]').fill('13800000001')
|
||||
await page.fill('input[type="password"]', 'Test123456')
|
||||
|
||||
await page.click('button[type="submit"]')
|
||||
await page.waitForURL('**/user/dashboard', { timeout: 10000 })
|
||||
await expect(page.locator('text=E2E用户')).toBeVisible()
|
||||
})
|
||||
|
||||
test('TC-009 重复邮箱注册', async ({ page }) => {
|
||||
await page.goto('/register')
|
||||
await page.locator('input[placeholder*="姓名"]').fill('重复用户')
|
||||
await page.fill('input[type="email"]', registerEmail)
|
||||
await page.fill('input[type="password"]', 'Test123456')
|
||||
await page.click('button[type="submit"]')
|
||||
await expect(page.locator('.error')).toBeVisible({ timeout: 8000 })
|
||||
})
|
||||
|
||||
test('TC-010 新用户登录', async ({ page }) => {
|
||||
await page.goto('/login')
|
||||
await page.fill('input[type="email"]', registerEmail)
|
||||
await page.fill('input[type="password"]', 'Test123456')
|
||||
await page.click('button[type="submit"]')
|
||||
await page.waitForURL('**/user/dashboard', { timeout: 10000 })
|
||||
await expect(page.locator('h1').first()).toHaveText('用户中心')
|
||||
})
|
||||
|
||||
test('TC-011 用户仪表盘', async ({ page }) => {
|
||||
await page.goto('/login')
|
||||
await page.fill('input[type="email"]', registerEmail)
|
||||
await page.fill('input[type="password"]', 'Test123456')
|
||||
await page.click('button[type="submit"]')
|
||||
await page.waitForURL('**/user/dashboard', { timeout: 10000 })
|
||||
|
||||
await expect(page.locator('.stat-card').filter({ hasText: '总预约' })).toBeVisible()
|
||||
await expect(page.locator('text=待确认')).toBeVisible()
|
||||
await expect(page.locator('text=已完成')).toBeVisible()
|
||||
})
|
||||
|
||||
test('TC-012 浏览咨询师', async ({ page }) => {
|
||||
await page.goto('/login')
|
||||
await page.fill('input[type="email"]', registerEmail)
|
||||
await page.fill('input[type="password"]', 'Test123456')
|
||||
await page.click('button[type="submit"]')
|
||||
await page.waitForURL('**/user/dashboard', { timeout: 10000 })
|
||||
|
||||
await page.goto('/user/book')
|
||||
await expect(page.locator('h1')).toHaveText('预约咨询')
|
||||
await expect(page.locator('text=张医生')).toBeVisible()
|
||||
await expect(page.locator('text=李律师')).toBeVisible()
|
||||
await expect(page.locator('text=王教练')).toBeVisible()
|
||||
})
|
||||
|
||||
test('TC-013 预约 + 取消', async ({ page }) => {
|
||||
// Login
|
||||
await page.goto('/login')
|
||||
await page.fill('input[type="email"]', registerEmail)
|
||||
await page.fill('input[type="password"]', 'Test123456')
|
||||
await page.click('button[type="submit"]')
|
||||
await page.waitForURL('**/user/dashboard', { timeout: 10000 })
|
||||
|
||||
// Go to book page
|
||||
await page.goto('/user/book')
|
||||
await expect(page.locator('h1')).toHaveText('预约咨询')
|
||||
|
||||
// Step 1: Select consultant
|
||||
await page.locator('text=张医生').click()
|
||||
await expect(page.locator('text=2. 选择日期')).toBeVisible()
|
||||
|
||||
// Step 2: Pick a date
|
||||
const dateBtn = page.locator('div.date-list button').first()
|
||||
await expect(dateBtn).toBeVisible()
|
||||
await dateBtn.click()
|
||||
await page.waitForTimeout(1500)
|
||||
|
||||
// Step 3: Pick a time slot
|
||||
const slotBtn = page.locator('div.slot-list button').first()
|
||||
if (await slotBtn.isVisible({ timeout: 5000 })) {
|
||||
await slotBtn.click()
|
||||
await expect(page.locator('text=4. 备注')).toBeVisible()
|
||||
|
||||
// Step 4: Add note and submit
|
||||
await page.fill('textarea', 'E2E booking test')
|
||||
await page.click('text=确认预约')
|
||||
await page.waitForURL('**/user/appointments', { timeout: 10000 })
|
||||
|
||||
// Verify appointment created
|
||||
await expect(page.locator('h1')).toHaveText('我的预约')
|
||||
|
||||
// Cancel the appointment
|
||||
const cancelBtn = page.locator('button:has-text("取消")').first()
|
||||
if (await cancelBtn.isVisible({ timeout: 5000 })) {
|
||||
page.once('dialog', dialog => dialog.accept())
|
||||
await cancelBtn.click()
|
||||
await page.waitForTimeout(1500)
|
||||
await expect(page.locator('.status.cancelled').first()).toBeVisible({ timeout: 5000 })
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
test('TC-014 编辑个人信息', async ({ page }) => {
|
||||
await page.goto('/login')
|
||||
await page.fill('input[type="email"]', registerEmail)
|
||||
await page.fill('input[type="password"]', 'Test123456')
|
||||
await page.click('button[type="submit"]')
|
||||
await page.waitForURL('**/user/dashboard', { timeout: 10000 })
|
||||
|
||||
await page.goto('/user/profile')
|
||||
const nameInput = page.locator('input').nth(1)
|
||||
await nameInput.fill('E2E用户-已改名')
|
||||
const [dialog] = await Promise.all([
|
||||
page.waitForEvent('dialog', { timeout: 5000 }),
|
||||
page.click('text=保存'),
|
||||
])
|
||||
expect(dialog.message()).toContain('保存成功')
|
||||
await dialog.dismiss()
|
||||
})
|
||||
})
|
||||
|
||||
/* ─────────────── Admin Flows (independent tests) ─────────────── */
|
||||
|
||||
test.describe('Admin Flows', () => {
|
||||
|
||||
test('TC-015 仪表盘统计', async ({ page }) => {
|
||||
await page.goto('/login')
|
||||
await page.fill('input[type="email"]', ADMIN_EMAIL)
|
||||
await page.fill('input[type="password"]', ADMIN_PASSWORD)
|
||||
await page.click('button[type="submit"]')
|
||||
await page.waitForURL('**/admin/dashboard', { timeout: 10000 })
|
||||
|
||||
await expect(page.locator('h1')).toHaveText('管理仪表盘')
|
||||
await expect(page.locator('.stat-card').filter({ hasText: '用户数' })).toBeVisible()
|
||||
await expect(page.locator('.stat-card').filter({ hasText: '咨询师' })).toBeVisible()
|
||||
await expect(page.locator('.stat-card').filter({ hasText: '总预约' })).toBeVisible()
|
||||
await expect(page.locator('.stat-card').filter({ hasText: '待确认' })).toBeVisible()
|
||||
await expect(page.locator('.stat-card').filter({ hasText: '网点' })).toBeVisible()
|
||||
})
|
||||
|
||||
test('TC-016 用户管理', async ({ page }) => {
|
||||
await page.goto('/login')
|
||||
await page.fill('input[type="email"]', ADMIN_EMAIL)
|
||||
await page.fill('input[type="password"]', ADMIN_PASSWORD)
|
||||
await page.click('button[type="submit"]')
|
||||
await page.waitForURL('**/admin/dashboard', { timeout: 10000 })
|
||||
|
||||
await page.goto('/admin/users')
|
||||
await expect(page.locator('table')).toBeVisible({ timeout: 10000 })
|
||||
await expect(page.locator('text=admin@test.com')).toBeVisible()
|
||||
await expect(page.locator('text=管理员')).toBeVisible()
|
||||
|
||||
const toggleBtn = page.locator('button:has-text("禁用"), button:has-text("启用")').first()
|
||||
if (await toggleBtn.isVisible()) {
|
||||
await toggleBtn.click()
|
||||
await page.waitForTimeout(1000)
|
||||
}
|
||||
})
|
||||
|
||||
test('TC-017 咨询师管理', async ({ page }) => {
|
||||
await page.goto('/login')
|
||||
await page.fill('input[type="email"]', ADMIN_EMAIL)
|
||||
await page.fill('input[type="password"]', ADMIN_PASSWORD)
|
||||
await page.click('button[type="submit"]')
|
||||
await page.waitForURL('**/admin/dashboard', { timeout: 10000 })
|
||||
|
||||
await page.locator('a:has-text("咨询师管理")').click()
|
||||
await page.waitForURL('**/admin/consultants', { timeout: 10000 })
|
||||
await expect(page.locator('table')).toBeVisible({ timeout: 10000 })
|
||||
await expect(page.locator('text=张医生')).toBeVisible()
|
||||
await expect(page.locator('text=李律师')).toBeVisible()
|
||||
await expect(page.locator('text=王教练')).toBeVisible()
|
||||
})
|
||||
|
||||
test('TC-018 预约管理', async ({ page }) => {
|
||||
await page.goto('/login')
|
||||
await page.fill('input[type="email"]', ADMIN_EMAIL)
|
||||
await page.fill('input[type="password"]', ADMIN_PASSWORD)
|
||||
await page.click('button[type="submit"]')
|
||||
await page.waitForURL('**/admin/dashboard', { timeout: 10000 })
|
||||
|
||||
await page.locator('a:has-text("预约管理")').click()
|
||||
await page.waitForURL('**/admin/appointments', { timeout: 10000 })
|
||||
await expect(page.locator('h1')).toHaveText('预约管理')
|
||||
})
|
||||
|
||||
test('TC-019 网点 CRUD', async ({ page }) => {
|
||||
// Login
|
||||
await page.goto('/login')
|
||||
await page.fill('input[type="email"]', ADMIN_EMAIL)
|
||||
await page.fill('input[type="password"]', ADMIN_PASSWORD)
|
||||
await page.click('button[type="submit"]')
|
||||
await page.waitForURL('**/admin/dashboard', { timeout: 10000 })
|
||||
|
||||
// Go to branches
|
||||
await page.locator('a:has-text("网点管理")').click()
|
||||
await page.waitForURL('**/admin/branches', { timeout: 10000 })
|
||||
await expect(page.locator('h1')).toHaveText('网点管理')
|
||||
await expect(page.locator('text=朝阳咨询中心')).toBeVisible({ timeout: 10000 })
|
||||
await expect(page.locator('text=海淀咨询中心')).toBeVisible()
|
||||
await expect(page.locator('text=浦东咨询中心')).toBeVisible()
|
||||
|
||||
// ── CREATE ──
|
||||
await page.click('text=新增网点')
|
||||
await expect(page.locator('.modal')).toBeVisible()
|
||||
|
||||
// Modal: <div class="form-group"><label>名称</label><input v-model="form.name" class="input" /></div>
|
||||
await page.locator('.modal .form-group').nth(0).locator('input').fill('E2E测试网点')
|
||||
await page.locator('.modal .form-group').nth(1).locator('input').fill('东城区测试大街1号')
|
||||
await page.locator('.modal .form-group').nth(2).locator('input').fill('010-88889999')
|
||||
await page.locator('.modal button:has-text("保存")').click()
|
||||
await page.waitForTimeout(1500)
|
||||
await expect(page.locator('text=E2E测试网点')).toBeVisible({ timeout: 5000 })
|
||||
|
||||
// ── EDIT ──
|
||||
await page.locator('tr:has-text("E2E测试网点") button:has-text("编辑")').click()
|
||||
await expect(page.locator('.modal')).toBeVisible()
|
||||
await page.locator('.modal .form-group').nth(0).locator('input').fill('E2E测试网点-已改')
|
||||
await page.locator('.modal button:has-text("保存")').click()
|
||||
await page.waitForTimeout(1500)
|
||||
await expect(page.locator('text=E2E测试网点-已改')).toBeVisible({ timeout: 5000 })
|
||||
|
||||
// ── DELETE ──
|
||||
page.once('dialog', dialog => dialog.accept())
|
||||
await page.locator('tr:has-text("E2E测试网点-已改") button:has-text("删除")').click()
|
||||
await page.waitForTimeout(1500)
|
||||
await expect(page.locator('text=E2E测试网点-已改')).toHaveCount(0, { timeout: 5000 })
|
||||
})
|
||||
})
|
||||
|
||||
/* ─────────────── Edge Cases ─────────────── */
|
||||
|
||||
test.describe('Edge Cases', () => {
|
||||
|
||||
test('TC-020 未登录访问管理页', async ({ page }) => {
|
||||
await page.goto('/')
|
||||
await page.evaluate(() => localStorage.clear())
|
||||
await page.goto('/admin/dashboard')
|
||||
await expect(page).toHaveURL(/\/login/, { timeout: 5000 })
|
||||
})
|
||||
|
||||
test('TC-021 未登录访问用户页', async ({ page }) => {
|
||||
await page.goto('/')
|
||||
await page.evaluate(() => localStorage.clear())
|
||||
await page.goto('/user/dashboard')
|
||||
await expect(page).toHaveURL(/\/login/, { timeout: 5000 })
|
||||
})
|
||||
|
||||
test('TC-022 首页 CTA 可见', async ({ page }) => {
|
||||
await page.goto('/')
|
||||
await page.evaluate(() => localStorage.clear())
|
||||
await page.goto('/')
|
||||
const cta = page.locator('text=免费注册')
|
||||
await expect(cta).toBeVisible()
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user