chore: sync local latest state and repository cleanup

This commit is contained in:
Your Name
2026-03-23 13:02:36 +08:00
parent f1ff3d629f
commit 2ef0f17961
493 changed files with 46912 additions and 7977 deletions

View File

@@ -1,275 +1,141 @@
import { test, expect } from '../fixtures/test-data';
import { test, expect } from '@playwright/test';
import * as fs from 'fs';
import * as path from 'path';
import { fileURLToPath } from 'url';
/**
* 🦟 蚊子项目 - 用户端到端旅程测试(修复版
*
* 测试场景真实API交互
* 1. 页面访问和加载流程
* 2. 响应式布局测试
* 3. 错误处理测试
* 用户核心旅程测试(严格模式 - 固定版本
*
* 双模式执行
* - 无真实凭证显式跳过test.skip
* - 有真实凭证:严格断言 2xx/3xx
*/
test.describe('🎯 用户核心旅程测试', () => {
test.beforeEach(async ({ page, testData }) => {
// 设置测试环境
console.log(`\n 测试活动ID: ${testData.activityId}`);
console.log(` API Key: ${testData.apiKey.substring(0, 20)}...`);
});
const API_BASE_URL = process.env.API_BASE_URL || 'http://localhost:8080';
const FRONTEND_URL = process.env.PLAYWRIGHT_BASE_URL || 'http://localhost:5173';
test('🏠 首页加载和活动列表展示', async ({ page, testData, apiClient }) => {
await test.step('访问首页', async () => {
await page.goto('/');
// 验证页面加载 - 接受"Mosquito"或"蚊子"
await expect(page).toHaveTitle(/Mosquito|蚊子/);
await expect(page.locator('body')).toBeVisible();
// 截图记录
await page.screenshot({ path: `e2e-results/home-page-${Date.now()}.png` });
console.log(' ✅ 首页加载成功');
});
const DEFAULT_TEST_API_KEY = 'test-api-key-000000000000';
const DEFAULT_TEST_USER_TOKEN = 'test-e2e-token';
await test.step('验证活动列表API端点可访问', async () => {
try {
const response = await apiClient.getActivities();
if (response.code === 200) {
console.log(` ✅ 活动列表API返回 ${response.data?.length || 0} 个活动`);
} else {
console.log(` ⚠️ 活动列表API返回: ${response.code}(需要认证)`);
}
} catch (error) {
console.log(' ⚠️ API调用失败可能需要有效认证');
}
});
});
interface TestData {
activityId: number;
apiKey: string;
userToken: string;
userId: number;
shortCode: string;
baseUrl: string;
apiBaseUrl: string;
}
test('📊 活动详情和统计数据展示', async ({ page, testData, apiClient }) => {
await test.step('尝试获取活动详情API', async () => {
try {
const response = await apiClient.getActivity(testData.activityId);
if (response.code === 200) {
console.log(` ✅ 活动详情: ${response.data.name}`);
} else {
console.log(` ⚠️ 活动详情API返回: ${response.code}`);
}
} catch (error) {
console.log(' ⚠️ 活动详情API调用失败');
}
});
function loadTestData(): TestData {
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const testDataPath = path.join(__dirname, '..', '.e2e-test-data.json');
await test.step('前端页面展示活动信息', async () => {
// 访问活动页面
await page.goto(`/?activityId=${testData.activityId}`);
// 等待页面加载
await page.waitForLoadState('networkidle');
// 截图记录
await page.screenshot({
path: `e2e-results/activity-detail-${Date.now()}.png`
});
console.log(' ✅ 活动详情页面截图完成');
});
});
const defaultData: TestData = {
activityId: 1,
apiKey: DEFAULT_TEST_API_KEY,
userToken: process.env.E2E_USER_TOKEN || DEFAULT_TEST_USER_TOKEN,
userId: 10001,
shortCode: 'test123',
baseUrl: process.env.PLAYWRIGHT_BASE_URL || 'http://localhost:5173',
apiBaseUrl: process.env.API_BASE_URL || 'http://localhost:8080',
};
test('🏆 排行榜查看流程', async ({ page, testData, apiClient }) => {
await test.step('尝试获取排行榜数据API', async () => {
try {
const response = await apiClient.getLeaderboard(testData.activityId, 0, 10);
if (response.code === 200) {
console.log(' ✅ 排行榜数据获取成功');
} else {
console.log(` ⚠️ 排行榜API返回: ${response.code}`);
}
} catch (error) {
console.log(' ⚠️ 排行榜API调用失败');
}
});
try {
if (fs.existsSync(testDataPath)) {
const data = JSON.parse(fs.readFileSync(testDataPath, 'utf-8'));
return { ...defaultData, ...data };
}
} catch (error) {
console.warn('无法加载测试数据,使用默认值');
}
await test.step('前端展示排行榜页面', async () => {
// 访问排行榜页面
await page.goto(`/rank`);
await page.waitForLoadState('networkidle');
// 截图记录
await page.screenshot({
path: `e2e-results/leaderboard-${Date.now()}.png`
});
console.log(' ✅ 排行榜页面截图完成');
});
});
return defaultData;
}
test('🔗 短链生成和访问流程', async ({ page, testData, apiClient }) => {
await test.step('尝试生成短链API', async () => {
try {
const originalUrl = `https://example.com/test?activityId=${testData.activityId}&timestamp=${Date.now()}`;
const response = await apiClient.createShortLink(originalUrl, testData.activityId);
if (response.code === 201) {
const shortCode = response.data.code || response.data.shortUrl?.split('/').pop();
console.log(` ✅ 生成短链: ${shortCode}`);
} else {
console.log(` ⚠️ 短链API返回: ${response.code}`);
}
} catch (error) {
console.log(' ⚠️ 短链API调用失败');
}
});
function hasRealApiCredentials(data: TestData): boolean {
return Boolean(
data.apiKey &&
data.userToken &&
data.apiKey !== DEFAULT_TEST_API_KEY &&
data.userToken !== DEFAULT_TEST_USER_TOKEN
);
}
await test.step('访问分享页面', async () => {
// 访问分享页面
await page.goto(`/share`);
await page.waitForLoadState('networkidle');
// 截图记录
await page.screenshot({
path: `e2e-results/share-page-${Date.now()}.png`
});
console.log(' ✅ 分享页面截图完成');
});
});
// 加载测试数据
const testData = loadTestData();
const useRealCredentials = hasRealApiCredentials(testData);
const E2E_STRICT = process.env.E2E_STRICT === 'true';
test('📈 分享统计数据查看', async ({ page, testData, apiClient }) => {
await test.step('尝试获取分享统计API', async () => {
try {
const response = await apiClient.getShareMetrics(testData.activityId);
if (response.code === 200) {
console.log(` ✅ 分享统计: ${response.data?.totalClicks || 0} 次点击`);
} else {
console.log(` ⚠️ 分享统计API返回: ${response.code}`);
}
} catch (error) {
console.log(' ⚠️ 分享统计API调用失败');
}
});
await test.step('前端查看分享统计', async () => {
// 访问分享页面查看统计
await page.goto('/share');
await page.waitForLoadState('networkidle');
// 截图记录
await page.screenshot({
path: `e2e-results/share-metrics-${Date.now()}.png`
});
console.log(' ✅ 分享统计页面截图完成');
});
});
test('🎫 API Key验证流程', async ({ page, testData, apiClient }) => {
await test.step('验证API Key格式', async () => {
expect(testData.apiKey).toBeDefined();
expect(testData.apiKey.length).toBeGreaterThan(0);
console.log(` ✅ API Key格式有效`);
});
await test.step('尝试验证API Key', async () => {
try {
const isValid = await apiClient.validateApiKey(testData.apiKey);
console.log(` API Key验证结果: ${isValid ? '有效' : '无效'}`);
} catch (error) {
console.log(' ⚠️ API Key验证失败需要后端认证');
}
});
});
});
test.describe('📱 响应式布局测试', () => {
test('移动端布局检查', async ({ page }) => {
await page.setViewportSize({ width: 375, height: 667 });
test.describe('🎯 用户核心旅程测试(严格模式)', () => {
// 首页不需要凭证,始终执行
test('🏠 首页应可访问(无需凭证)', async ({ page }) => {
await page.goto('/');
await page.waitForLoadState('networkidle');
await page.screenshot({
path: `e2e-results/mobile-layout-${Date.now()}.png`,
fullPage: true
await expect(page.locator('#app')).toBeAttached();
});
if (!useRealCredentials) {
// 严格模式下无真实凭证时必须失败,非严格模式才跳过
if (E2E_STRICT) {
test('📊 活动列表API需要真实凭证', async () => {
throw new Error('严格模式需要真实凭证E2E_USER_TOKEN但未提供有效凭证测试失败');
});
} else {
test.skip('📊 活动列表API需要真实凭证', async ({ request }) => {
// 此测试需要真实凭证,无凭证时跳过
});
}
} else {
// 有真实凭证时严格断言
test('📊 活动列表API - 严格断言', async ({ request }) => {
const response = await request.get(`${API_BASE_URL}/api/v1/activities`, {
headers: {
'X-API-Key': testData.apiKey,
'Authorization': `Bearer ${testData.userToken}`,
},
});
const status = response.status();
// 严格断言:只接受 2xx/3xx
expect(
status,
`活动列表API应返回2xx/3xx实际${status}`
).toBeGreaterThanOrEqual(200);
expect(
status,
`活动列表API应返回2xx/3xx实际${status}`
).toBeLessThan(400);
});
console.log(' ✅ 移动端布局检查完成');
});
test('平板端布局检查', async ({ page }) => {
await page.setViewportSize({ width: 768, height: 1024 });
await page.goto('/');
await page.waitForLoadState('networkidle');
await page.screenshot({
path: `e2e-results/tablet-layout-${Date.now()}.png`,
fullPage: true
test('后端健康检查应正常 - 严格断言', async ({ request }) => {
const response = await request.get(`${API_BASE_URL}/actuator/health`);
expect(
response.status(),
`健康检查应返回200实际${response.status()}`
).toBe(200);
const body = await response.json();
expect(
body.status,
`健康检查状态应为UP实际${body.status}`
).toBe('UP');
});
console.log(' ✅ 平板端布局检查完成');
});
test('桌面端布局检查', async ({ page }) => {
await page.setViewportSize({ width: 1280, height: 720 });
await page.goto('/');
await page.waitForLoadState('networkidle');
await page.screenshot({
path: `e2e-results/desktop-layout-${Date.now()}.png`,
fullPage: true
test('前端服务应可访问 - 严格断言', async ({ page }) => {
const response = await page.goto(FRONTEND_URL);
expect(
response,
'页面响应不应为null'
).not.toBeNull();
expect(
response?.status(),
`前端应返回2xx/3xx实际${response?.status()}`
).toBeGreaterThanOrEqual(200);
expect(
response?.status(),
`前端应返回2xx/3xx实际${response?.status()}`
).toBeLessThan(400);
});
console.log(' ✅ 桌面端布局检查完成');
});
});
test.describe('⚡ 性能测试', () => {
test('API响应时间测试', async ({ request }) => {
const startTime = Date.now();
await request.get('http://localhost:8080/actuator/health');
const responseTime = Date.now() - startTime;
console.log(` API响应时间: ${responseTime}ms`);
expect(responseTime).toBeLessThan(5000); // 5秒内响应
});
test('页面加载时间测试', async ({ page }) => {
const startTime = Date.now();
await page.goto('/');
await page.waitForLoadState('networkidle');
const loadTime = Date.now() - startTime;
console.log(` 页面加载时间: ${loadTime}ms`);
expect(loadTime).toBeLessThan(10000); // 10秒内加载
});
});
test.describe('🔒 错误处理测试', () => {
test('处理无效的活动ID', async ({ page }) => {
await page.goto('/?activityId=999999');
await page.waitForLoadState('networkidle');
// 验证页面仍然可以加载(显示错误信息)
await expect(page.locator('body')).toBeVisible();
console.log(' ✅ 无效活动ID处理测试完成');
});
test('处理网络错误', async ({ request }) => {
// 测试一个不存在的端点
const response = await request.get('http://localhost:8080/api/v1/nonexistent');
// 应该返回404
expect([401, 404]).toContain(response.status());
console.log(' ✅ 网络错误处理测试完成');
});
});
}
});