smoke.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. #!/usr/bin/env node
  2. 'use strict';
  3. // 零依赖冒烟测试:拉起真实服务(随机端口),全量核对端点行为后关停。
  4. // 安全边界:只做只读请求 + 无副作用 POST(校验失败类、空操作);
  5. // 绝不触碰 DELETE /api/reports/data、/api/crawl/start、/api/open-folder、
  6. // /api/image/test、/api/chat/test,也不在数据湖有主体时调用 /api/reports/ask。
  7. // 用法:node scripts/smoke.js
  8. const { spawn } = require('child_process');
  9. const net = require('net');
  10. const http = require('http');
  11. const path = require('path');
  12. const ROOT = path.resolve(__dirname, '..');
  13. function pickPort() {
  14. return new Promise((resolve, reject) => {
  15. const srv = net.createServer();
  16. srv.unref();
  17. srv.on('error', reject);
  18. srv.listen(0, '127.0.0.1', () => {
  19. const port = srv.address().port;
  20. srv.close(() => resolve(port));
  21. });
  22. });
  23. }
  24. function request(port, method, urlPath, body) {
  25. return new Promise((resolve, reject) => {
  26. const req = http.request({
  27. host: '127.0.0.1', port, method, path: urlPath, timeout: 15000,
  28. headers: body !== undefined ? { 'Content-Type': 'application/json' } : {},
  29. }, (res) => {
  30. const chunks = [];
  31. res.on('data', (c) => chunks.push(c));
  32. res.on('end', () => resolve({
  33. status: res.statusCode,
  34. headers: res.headers,
  35. text: Buffer.concat(chunks).toString('utf8'),
  36. json: () => JSON.parse(Buffer.concat(chunks).toString('utf8')),
  37. }));
  38. });
  39. req.on('error', reject);
  40. req.on('timeout', () => req.destroy(new Error('timeout')));
  41. if (body !== undefined) req.write(JSON.stringify(body));
  42. req.end();
  43. });
  44. }
  45. const results = [];
  46. async function check(name, fn) {
  47. try {
  48. await fn();
  49. results.push({ name, ok: true });
  50. } catch (e) {
  51. results.push({ name, ok: false, error: e.message });
  52. }
  53. }
  54. function expect(cond, msg) {
  55. if (!cond) throw new Error(msg);
  56. }
  57. async function waitForHealth(port, timeoutMs = 20000) {
  58. const start = Date.now();
  59. for (;;) {
  60. try {
  61. const res = await request(port, 'GET', '/healthz');
  62. if (res.status === 200) return;
  63. } catch { /* not up yet */ }
  64. if (Date.now() - start > timeoutMs) throw new Error('服务未在超时内启动');
  65. await new Promise((r) => setTimeout(r, 300));
  66. }
  67. }
  68. function enc(s) { return encodeURIComponent(s); }
  69. async function main() {
  70. const port = await pickPort();
  71. const child = spawn(process.execPath, [path.join(ROOT, 'server.js')], {
  72. env: { ...process.env, PORT: String(port), HOST: '127.0.0.1' },
  73. stdio: ['ignore', 'pipe', 'pipe'],
  74. });
  75. let bootLog = '';
  76. child.stdout.on('data', (c) => { bootLog += c; });
  77. child.stderr.on('data', (c) => { bootLog += c; });
  78. try {
  79. await waitForHealth(port);
  80. let workspaceRoot = '';
  81. {
  82. const res = await request(port, 'GET', '/api/default-root');
  83. workspaceRoot = res.json().root;
  84. }
  85. const encRoot = enc(workspaceRoot);
  86. const b64Root = Buffer.from(workspaceRoot, 'utf8').toString('base64url');
  87. // ---- 基础与健康 ----
  88. await check('GET /healthz', async () => {
  89. const r = await request(port, 'GET', '/healthz');
  90. expect(r.status === 200 && r.json().ok === true, `status=${r.status}`);
  91. });
  92. await check('GET /readyz', async () => {
  93. const r = await request(port, 'GET', '/readyz');
  94. const j = r.json();
  95. expect(r.status === 200 && typeof j.ok === 'boolean' && typeof j.workspaceReady === 'boolean', `status=${r.status}`);
  96. });
  97. await check('GET /api/default-root', async () => {
  98. const r = await request(port, 'GET', '/api/default-root');
  99. expect(r.status === 200 && !!r.json().root, `status=${r.status}`);
  100. });
  101. // ---- 设置域 ----
  102. await check('GET /api/models', async () => {
  103. const r = await request(port, 'GET', '/api/models');
  104. const j = r.json();
  105. expect(r.status === 200 && Array.isArray(j.models) && j.models.length >= 5 && !!j.default, `status=${r.status}`);
  106. });
  107. await check('GET /api/settings(脱敏)', async () => {
  108. const r = await request(port, 'GET', '/api/settings');
  109. const j = r.json();
  110. expect(r.status === 200 && typeof j.rootDir === 'string' && typeof j.port === 'number', `status=${r.status}`);
  111. expect(!j.apiKey || j.apiKey.includes('••••'), 'apiKey 未脱敏');
  112. });
  113. await check('POST /api/settings 非法 pageSize → 400', async () => {
  114. const r = await request(port, 'POST', '/api/settings', { pageSize: 9999 });
  115. expect(r.status === 400, `status=${r.status}`);
  116. });
  117. await check('POST /api/settings 非法 delayMs → 400', async () => {
  118. const r = await request(port, 'POST', '/api/settings', { delayMs: -5 });
  119. expect(r.status === 400, `status=${r.status}`);
  120. });
  121. await check('POST /api/settings 非法 autoSyncTime → 400', async () => {
  122. const r = await request(port, 'POST', '/api/settings', { autoSyncTime: '99:99' });
  123. expect(r.status === 400, `status=${r.status}`);
  124. });
  125. await check('GET /api/settings 含 autoSync 字段', async () => {
  126. const r = await request(port, 'GET', '/api/settings');
  127. const j = r.json();
  128. expect(typeof j.autoSyncEnabled === 'boolean' && /^\d{1,2}:\d{2}$/.test(j.autoSyncTime || ''), 'autoSync 字段缺失');
  129. });
  130. // ---- 采集域 ----
  131. await check('GET /api/session', async () => {
  132. const r = await request(port, 'GET', '/api/session');
  133. expect(r.status === 200 && typeof r.json().cookieConfigured === 'boolean', `status=${r.status}`);
  134. });
  135. await check('GET /api/shops(base64url root)', async () => {
  136. const r = await request(port, 'GET', `/api/shops?root=${b64Root}`);
  137. expect(r.status === 200 && Array.isArray(r.json().shops), `status=${r.status}`);
  138. });
  139. await check('GET /api/shops 非法 root → 403', async () => {
  140. const bad = Buffer.from('/tmp/elsewhere', 'utf8').toString('base64url');
  141. const r = await request(port, 'GET', `/api/shops?root=${bad}`);
  142. expect(r.status === 403, `status=${r.status}`);
  143. });
  144. await check('GET /api/scan', async () => {
  145. const r = await request(port, 'GET', `/api/scan?root=${encRoot}`);
  146. const j = r.json();
  147. expect(r.status === 200 && Array.isArray(j.shops), `status=${r.status}`);
  148. });
  149. await check('GET /api/crawl/status', async () => {
  150. const r = await request(port, 'GET', '/api/crawl/status');
  151. expect(r.status === 200 && typeof r.json().status === 'string', `status=${r.status}`);
  152. });
  153. await check('POST /api/crawl/stop(空操作)', async () => {
  154. const r = await request(port, 'POST', '/api/crawl/stop');
  155. expect(r.status === 200 && r.json().ok === true, `status=${r.status}`);
  156. });
  157. // ---- 生成/任务/历史域 ----
  158. await check('GET /api/tasks', async () => {
  159. const r = await request(port, 'GET', '/api/tasks');
  160. const j = r.json();
  161. expect(r.status === 200 && j.summary && Array.isArray(j.tasks), `status=${r.status}`);
  162. });
  163. await check('GET /api/job/未知ID → 404', async () => {
  164. const r = await request(port, 'GET', '/api/job/00000000-0000-0000-0000-000000000000');
  165. expect(r.status === 404, `status=${r.status}`);
  166. });
  167. await check('GET /api/creations', async () => {
  168. const r = await request(port, 'GET', `/api/creations?root=${encRoot}&limit=5`);
  169. const j = r.json();
  170. expect(r.status === 200 && typeof j.total === 'number' && Array.isArray(j.items), `status=${r.status}`);
  171. });
  172. await check('GET /files 越界 → 403', async () => {
  173. const r = await request(port, 'GET', `/files?path=${enc('/etc/passwd')}`);
  174. expect(r.status === 403, `status=${r.status}`);
  175. });
  176. await check('GET /files 缺参 → 400', async () => {
  177. const r = await request(port, 'GET', '/files');
  178. expect(r.status === 400, `status=${r.status}`);
  179. });
  180. // ---- 日志 ----
  181. await check('GET /api/logs', async () => {
  182. const r = await request(port, 'GET', '/api/logs');
  183. expect(r.status === 200 && Array.isArray(r.json().logs), `status=${r.status}`);
  184. });
  185. await check('POST /api/logs/clear', async () => {
  186. const r = await request(port, 'POST', '/api/logs/clear');
  187. expect(r.status === 200 && r.json().ok === true, `status=${r.status}`);
  188. });
  189. // ---- 数据报表域 ----
  190. await check('GET /api/reports/status(不限方法 GET)', async () => {
  191. const r = await request(port, 'GET', '/api/reports/status');
  192. expect(r.status === 200 && r.json().napos, `status=${r.status}`);
  193. });
  194. await check('POST /api/reports/status(不限方法 POST)', async () => {
  195. const r = await request(port, 'POST', '/api/reports/status');
  196. expect(r.status === 200, `status=${r.status}`);
  197. });
  198. await check('GET /api/reports/columns', async () => {
  199. const r = await request(port, 'GET', '/api/reports/columns');
  200. expect(r.status === 200 && Array.isArray(r.json().columns) && r.json().columns.length >= 10, `status=${r.status}`);
  201. });
  202. await check('GET /api/reports/entities', async () => {
  203. const r = await request(port, 'GET', '/api/reports/entities');
  204. expect(r.status === 200 && Array.isArray(r.json().entities), `status=${r.status}`);
  205. });
  206. await check('GET /api/reports/sync/status', async () => {
  207. const r = await request(port, 'GET', '/api/reports/sync/status');
  208. expect(r.status === 200 && typeof r.json().running === 'boolean', `status=${r.status}`);
  209. });
  210. await check('GET /api/reports/syncs', async () => {
  211. const r = await request(port, 'GET', '/api/reports/syncs');
  212. expect(r.status === 200 && Array.isArray(r.json().runs), `status=${r.status}`);
  213. });
  214. await check('GET /api/reports/daily', async () => {
  215. const r = await request(port, 'GET', '/api/reports/daily');
  216. expect(r.status === 200, `status=${r.status}`);
  217. });
  218. await check('GET /api/reports/aggregate', async () => {
  219. const r = await request(port, 'GET', '/api/reports/aggregate');
  220. expect(r.status === 200, `status=${r.status}`);
  221. });
  222. await check('GET /api/reports/export → CSV', async () => {
  223. const r = await request(port, 'GET', '/api/reports/export');
  224. expect(r.status === 200 && /text\/csv/.test(r.headers['content-type'] || ''), `status=${r.status}`);
  225. });
  226. await check('GET /api/reports/report-html → HTML', async () => {
  227. const r = await request(port, 'GET', '/api/reports/report-html');
  228. expect(r.status === 200 && /text\/html/.test(r.headers['content-type'] || ''), `status=${r.status}`);
  229. });
  230. await check('POST /api/reports/ask(有主体时跳过)', async () => {
  231. const ent = await request(port, 'GET', '/api/reports/entities');
  232. if (ent.json().entities.length > 0) return; // 有主体会真调对话模型,跳过
  233. const r = await request(port, 'POST', '/api/reports/ask', { q: 'test' });
  234. expect(r.status === 400 && r.json().code === 'ASK_NO_ENTITY', `status=${r.status}`);
  235. });
  236. // ---- 静态与路由行为 ----
  237. for (const p of ['/', '/index.html', '/app.js', '/crawl.js', '/gen.js', '/history.js', '/tasks.js', '/reports.js', '/style.css', '/vendor/echarts.min.js']) {
  238. await check(`静态 ${p}`, async () => {
  239. const r = await request(port, 'GET', p);
  240. expect(r.status === 200, `status=${r.status}`);
  241. });
  242. }
  243. await check('GET /no-such-path → 404', async () => {
  244. const r = await request(port, 'GET', '/no-such-path');
  245. expect(r.status === 404, `status=${r.status}`);
  246. });
  247. await check('DELETE /api/settings → 405', async () => {
  248. const r = await request(port, 'DELETE', '/api/settings');
  249. expect(r.status === 405, `status=${r.status}`);
  250. });
  251. // ---- 优雅停机(SIGTERM 后应自行退出) ----
  252. await check('SIGTERM 优雅停机', async () => {
  253. process.kill(child.pid, 'SIGTERM');
  254. const exited = await new Promise((resolve) => {
  255. const t = setTimeout(() => resolve(false), 8000);
  256. child.on('exit', () => { clearTimeout(t); resolve(true); });
  257. });
  258. expect(exited, 'SIGTERM 后 8 秒内未退出');
  259. });
  260. } catch (e) {
  261. results.push({ name: '(测试执行中断)', ok: false, error: e.message });
  262. } finally {
  263. try { child.kill('SIGKILL'); } catch { /* already dead */ }
  264. }
  265. const failed = results.filter((r) => !r.ok);
  266. console.log('\n========== 冒烟测试结果 ==========');
  267. for (const r of results) {
  268. console.log(`${r.ok ? '✓' : '✗'} ${r.name}${r.ok ? '' : ' ← ' + r.error}`);
  269. }
  270. console.log(`\n通过 ${results.length - failed.length}/${results.length}`);
  271. if (failed.length) {
  272. console.log('\n服务启动日志(末尾 500 字):');
  273. console.log(bootLog.slice(-500));
  274. process.exit(1);
  275. }
  276. }
  277. main().catch((e) => {
  278. console.error('冒烟脚本自身异常:', e);
  279. process.exit(1);
  280. });