// @ts-nocheck import http from 'k6/http'; import { check, sleep } from 'k6'; import { Rate, Trend } from 'k6/metrics'; const errorRate = new Rate('errors'); const responseTime = new Trend('response_time'); export const options = { stages: [ { duration: '1m', target: 50 }, // 1分钟内逐步增加到50用户 { duration: '3m', target: 50 }, // 保持50用户3分钟 { duration: '1m', target: 0 }, // 1分钟内减少到0 ], thresholds: { http_req_duration: ['p(95)<200', 'p(99)<500'], // API 响应要求更严格 http_req_failed: ['rate<0.01'], errors: ['rate<0.01'], }, }; const BASE_URL = __ENV.BASE_URL || 'http://localhost:3000'; export default function () { const endpoints = [ { url: '/api/contact', method: 'GET', tags: { name: 'contact-api' } }, { url: '/api/cms/revalidate', method: 'GET', tags: { name: 'cms-revalidate' } }, ]; // GET 请求测试 for (const ep of endpoints) { const res = http.get(`${BASE_URL}${ep.url}`, { tags: ep.tags }); // API 即使返回 401/405 也算可用(有认证保护) const success = check(res, { 'status is not 500': (r) => r.status !== 500, 'response time < 200ms': (r) => r.timings.duration < 200, }); errorRate.add(!success); responseTime.add(res.timings.duration); } // POST 请求测试(联系表单提交) const contactPayload = JSON.stringify({ name: '性能测试用户', email: 'perf-test@example.com', message: '这是一条性能测试消息,请忽略。', _hp: '', // 蜜罐字段 }); const postRes = http.post(`${BASE_URL}/api/contact`, contactPayload, { headers: { 'Content-Type': 'application/json' }, tags: { name: 'contact-submit' }, }); const postSuccess = check(postRes, { 'contact submit status is not 500': (r) => r.status !== 500, 'contact submit response time < 500ms': (r) => r.timings.duration < 500, }); errorRate.add(!postSuccess); responseTime.add(postRes.timings.duration); sleep(1); } export function handleSummary(data) { return { 'performance/api-test-summary.json': JSON.stringify(data, null, 2), }; }