| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249 |
- /** BFF HTTP 接口 + 对话 + 核验的端到端测试(假工具服务 + 剧本模型,不联网)。 */
- import { test, before, after } from 'node:test';
- import assert from 'node:assert/strict';
- import { createApp } from '../src/app.js';
- import { ReplayLlmClient } from '../src/harness/llm.js';
- import { FakeToolsClient, asToolsClient, collectSse, listen, tempDir, testSettings } from './fakes.js';
- let server;
- let base;
- let fake;
- before(async () => {
- fake = new FakeToolsClient();
- const llm = new ReplayLlmClient([
- // 第 1 轮:先读表,再给出正确答案
- { toolCalls: [{ name: 'data_read', arguments: { object_id: 'obj_stat', table: '1.0-3.0_MLCC', limit: 5 } }] },
- { text: '2025 年 1 月 MLCC 进口额为 400316.13 美元。' },
- ]);
- const { server: httpServer } = createApp({
- settings: testSettings(tempDir()),
- tools: asToolsClient(fake),
- llm,
- serveStatic: false,
- });
- server = await listen(httpServer);
- base = server.url;
- });
- after(async () => {
- await server.close();
- });
- async function api(path, init) {
- const response = await fetch(`${base}${path}`, init);
- const text = await response.text();
- let payload = null;
- try {
- payload = text ? JSON.parse(text) : null;
- }
- catch {
- payload = text;
- }
- if (!response.ok) {
- throw Object.assign(new Error(`HTTP ${response.status}: ${text.slice(0, 300)}`), { status: response.status, payload });
- }
- return payload;
- }
- test('GET /api/health 报告工具服务状态', async () => {
- const health = await api('/api/health');
- assert.equal(health.ok, true);
- assert.equal(health.harness, 'embedded-dsh-compatible');
- assert.equal(health.tools.ok, true);
- });
- test('GET /api/meta 暴露 preset 与工具清单', async () => {
- const meta = await api('/api/meta');
- assert.equal(meta.preset.name, 'customs-analyst');
- assert.equal(meta.tools.length, 4);
- const names = meta.tools.map((tool) => tool.name);
- assert.deepEqual(names.sort(), ['calculator', 'customs_process', 'data_read', 'list_objects']);
- assert.equal(meta.verification.enabled, true);
- });
- test('工作区 CRUD', async () => {
- const created = await api('/api/workspaces', {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ name: '接口测试区' }),
- });
- assert.equal(created.name, '接口测试区');
- const list = await api('/api/workspaces');
- assert.ok(list.items.some((item) => item.id === created.id));
- await api(`/api/workspaces/${created.id}`, { method: 'DELETE' });
- });
- test('multipart 上传(真实边界解析)', async () => {
- const form = new FormData();
- const csv = 'I_E_FLAG,HS_CODE,YEAR,WEEK,MONORSUM,COUNT,G_MODEL\nI,8532241000,2025,1,10.5,2,x\n';
- form.append('file', new Blob([csv], { type: 'text/csv' }), '测试 上传.csv');
- const object = await api('/api/workspaces/ws_test/files', { method: 'POST', body: form });
- assert.equal(object.kind, 'raw');
- assert.match(object.name, /测试 上传\.csv/);
- });
- test('原始字节上传(X-Filename)', async () => {
- const object = await api('/api/workspaces/ws_test/files', {
- method: 'POST',
- headers: { 'Content-Type': 'application/octet-stream', 'X-Filename': encodeURIComponent('raw-upload.csv') },
- body: 'a,b\n1,2\n',
- });
- assert.equal(object.name, 'raw-upload.csv');
- });
- test('对象预览与下载', async () => {
- const preview = await api('/api/objects/obj_stat/preview?table=1.0-3.0_MLCC&limit=1');
- assert.equal(preview.rows.length, 1);
- const response = await fetch(`${base}/api/objects/obj_stat/download?name=${encodeURIComponent('统计结果.xlsx')}`);
- assert.equal(response.status, 200);
- assert.match(response.headers.get('content-disposition') ?? '', /filename/);
- });
- test('处理任务接口', async () => {
- const run = await api('/api/process', {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ workspace_id: 'ws_test', input_object_id: 'obj_raw' }),
- });
- assert.equal(run.status, 'succeeded');
- const fetched = await api(`/api/process/${run.id}`);
- assert.equal(fetched.id, run.id);
- const list = await api('/api/process');
- assert.ok(list.items.length >= 1);
- });
- test('会话创建 + 历史 + 删除', async () => {
- const session = await api('/api/sessions', {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ workspace_id: 'ws_test' }),
- });
- assert.equal(session.workspace_id, 'ws_test');
- const messages = await api(`/api/sessions/${session.id}/messages`);
- assert.deepEqual(messages.items, []);
- const renamed = await api(`/api/sessions/${session.id}`, {
- method: 'PUT',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ title: '改名后的会话' }),
- });
- assert.equal(renamed.title, '改名后的会话');
- await api(`/api/sessions/${session.id}`, { method: 'DELETE' });
- });
- test('对话:工具调用 → 数字核验通过 → 交付', async () => {
- const session = await api('/api/sessions', {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ workspace_id: 'ws_test' }),
- });
- const response = await fetch(`${base}/api/sessions/${session.id}/chat`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ message: '2025 年 1 月 MLCC 进口额是多少?' }),
- });
- assert.equal(response.status, 200);
- assert.match(response.headers.get('content-type') ?? '', /text\/event-stream/);
- const events = await collectSse(response);
- const names = events.map((event) => event.event);
- assert.ok(names.includes('token'), '缺少 token 事件');
- assert.ok(names.includes('tool_call'), '缺少 tool_call 事件');
- assert.ok(names.includes('tool_result'), '缺少 tool_result 事件');
- assert.ok(names.includes('verification'), '缺少 verification 事件');
- const verification = events.find((event) => event.event === 'verification').data;
- assert.equal(verification.verdict, 'accept');
- assert.ok(verification.chips.length >= 1);
- assert.equal(verification.chips[0].call_id.startsWith('call_'), true);
- const final = events.find((event) => event.event === 'final').data;
- assert.equal(final.delivered, true);
- assert.match(final.text, /400316\.13/);
- const stored = await api(`/api/sessions/${session.id}/messages`);
- assert.equal(stored.items.length, 2); // user + assistant
- assert.equal(stored.items[1].role, 'assistant');
- assert.ok(stored.items[1].tool_calls.length >= 1);
- assert.equal(stored.items[1].verification.verdict, 'accept');
- const ledger = await api(`/api/sessions/${session.id}/ledger`);
- assert.ok(ledger.calls.length >= 1);
- });
- test('空消息与不存在的会话被拒绝', async () => {
- const session = await api('/api/sessions', {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ workspace_id: 'ws_test' }),
- });
- await assert.rejects(() => api(`/api/sessions/${session.id}/chat`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ message: ' ' }) }), /400/);
- await assert.rejects(() => api('/api/sessions/sess_not_exist/messages'), /404/);
- });
- test('静态资源未配置时返回 404', async () => {
- const response = await fetch(`${base}/`);
- assert.equal(response.status, 404);
- });
- test('未知接口返回结构化 404', async () => {
- const response = await fetch(`${base}/api/nope`);
- assert.equal(response.status, 404);
- const payload = await response.json();
- assert.equal(payload.error, 'NOT_FOUND');
- });
- test('按行取数(溯源抽屉)与嵌套对象路径', async () => {
- const row = await api('/api/objects/obj_stat/row?table=1.0-3.0_MLCC&row=1');
- assert.equal(row.row_index, 1);
- assert.equal(row.values['基础类目'], '多层瓷介电容器(MLCC)');
- assert.match(row.row_hash, /^sha256:/);
- // 契约里的嵌套写法应等价
- const nested = await api('/api/workspaces/ws_test/objects/obj_stat');
- assert.equal(nested.id, 'obj_stat');
- await assert.rejects(() => api('/api/workspaces/ws_other/objects/obj_stat'), /404/);
- const missing = await fetch(`${base}/api/objects/obj_stat/row?table=1.0-3.0_MLCC&row=9999`);
- assert.equal(missing.status, 404);
- });
- test('预览支持 offset 与行号(用于高亮跳转)', async () => {
- const preview = await api('/api/objects/obj_stat/preview?table=1.0-3.0_MLCC&limit=2&offset=1');
- assert.equal(preview.offset, 1);
- assert.deepEqual(preview.row_indexes, [1]);
- assert.equal(preview.total, 2);
- });
- test('处理进度 SSE 推送 progress 与 done', async () => {
- const run = await api('/api/process', {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ workspace_id: 'ws_test', input_object_id: 'obj_raw' }),
- });
- const response = await fetch(`${base}/api/process/${run.id}/stream`);
- assert.equal(response.status, 200);
- assert.match(response.headers.get('content-type') ?? '', /text\/event-stream/);
- const events = await collectSse(response);
- const names = events.map((event) => event.event);
- assert.ok(names.includes('progress'), '缺少 progress 事件');
- assert.ok(names.includes('done'), '缺少 done 事件');
- const done = events.find((event) => event.event === 'done').data;
- assert.equal(done.status, 'succeeded');
- assert.equal(done.object_id, 'obj_stat');
- const missing = await fetch(`${base}/api/process/run_not_exist/stream`);
- assert.equal(missing.status, 404);
- });
- test('会话台账单次调用详情(calculator chip 用)', async () => {
- // 这个用例需要一次"干净"的对话(剧本客户端是有状态的),所以自己起一个服务实例
- const llm = new ReplayLlmClient([
- { toolCalls: [{ name: 'data_read', arguments: { object_id: 'obj_stat', table: '1.0-3.0_MLCC' } }] },
- { text: '2025 年 1 月 MLCC 进口额为 400316.13 美元。' },
- ]);
- const fresh = createApp({ settings: testSettings(tempDir()), tools: asToolsClient(fake), llm, serveStatic: false });
- const running = await listen(fresh.server);
- try {
- const create = await fetch(`${running.url}/api/sessions`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ workspace_id: 'ws_test' }),
- });
- const session = (await create.json());
- const chat = await fetch(`${running.url}/api/sessions/${session.id}/chat`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ message: '2025 年 1 月 MLCC 进口额是多少?' }),
- });
- const events = await collectSse(chat);
- const final = events.find((event) => event.event === 'final').data;
- assert.equal(final.verification, 'accept');
- const ledger = (await (await fetch(`${running.url}/api/sessions/${session.id}/ledger`)).json());
- assert.ok(ledger.calls.length >= 1, '应该有台账记录');
- const call = ledger.calls[0];
- const detail = (await (await fetch(`${running.url}/api/sessions/${session.id}/ledger/${call.call_id}`)).json());
- assert.equal(detail.call.call_id, call.call_id);
- assert.equal(detail.call.tool, 'data_read');
- assert.ok(Array.isArray(detail.values) && detail.values.length > 0);
- assert.equal(detail.call.args.object_id, 'obj_stat');
- const wrongSession = await fetch(`${running.url}/api/sessions/sess_other/ledger/${call.call_id}`);
- assert.equal(wrongSession.status, 404);
- }
- finally {
- await running.close();
- }
- });
- //# sourceMappingURL=api.test.js.map
|