dsh-uitest 2.1.2 → 2.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,723 +0,0 @@
1
- import assert from 'node:assert/strict';
2
- import fs from 'node:fs';
3
- import http from 'node:http';
4
- import os from 'node:os';
5
- import path from 'node:path';
6
- import test from 'node:test';
7
-
8
- import { createStudioPanel, registerStudioRoutes } from '../host.mjs';
9
- import { createBatch, patchBatch, saveCaseRun } from '../store.mjs';
10
- import { loadConfig } from '../../lib/config.mjs';
11
-
12
- function makeProject() {
13
- const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'studio-host-'));
14
- fs.writeFileSync(path.join(dir, 'uitest.config.json'), JSON.stringify({
15
- baseUrl: 'http://example.test',
16
- auth: { username: 'tester', storageState: '.auth/state.json' },
17
- cases: { markdown: 'cases' },
18
- output: { dir: 'reports' },
19
- }, null, 2));
20
- fs.mkdirSync(path.join(dir, 'cases'), { recursive: true });
21
- fs.writeFileSync(path.join(dir, 'cases', 'cases.md'), '## TC-LOGIN-001 登录\n\n| 项 | 内容 |\n|---|---|\n| **前置条件** | 系统可访问 |\n| **操作步骤** | 打开登录页 |\n| **预期结果** | 进入首页 |\n');
22
- return dir;
23
- }
24
-
25
- function makeConnection(ctxDir) {
26
- const routes = new Map();
27
- const ctx = {
28
- get(name) {
29
- if (name === 'workspaceRegistry') return { list: () => [{ path: ctxDir, title: 'test' }] };
30
- return undefined;
31
- },
32
- logger: { warn() {} },
33
- connection: {
34
- fetch: {
35
- register(spec) {
36
- routes.set(spec.path, spec);
37
- return () => {};
38
- },
39
- },
40
- },
41
- };
42
- return { ctx, routes };
43
- }
44
-
45
- function request(routes, pathName, { method = 'GET', body } = {}) {
46
- const pathname = pathName.split('?')[0];
47
- const route = routes.get('/api/uitest/studio' + pathname);
48
- assert.ok(route, 'route exists: ' + pathname);
49
- const init = { method, headers: {} };
50
- if (body !== undefined) {
51
- init.headers['content-type'] = 'application/json';
52
- init.body = JSON.stringify(body);
53
- }
54
- return route.fetch(new Request('http://dsh.internal/api/uitest/studio' + pathName, init));
55
- }
56
-
57
- function makeCentralServer() {
58
- const calls = [];
59
- const server = http.createServer((req, res) => {
60
- let body = '';
61
- req.on('data', (chunk) => { body += chunk; });
62
- req.on('end', () => {
63
- const parsed = body ? JSON.parse(body) : {};
64
- const url = new URL(req.url, 'http://localhost');
65
- calls.push({ method: req.method, url: req.url, body: parsed });
66
- res.setHeader('content-type', 'application/json');
67
- if (url.pathname === '/browse') {
68
- const kind = url.searchParams.get('kind') || 'episodes';
69
- return res.end(JSON.stringify({
70
- ok: true,
71
- kind,
72
- items: [{ uuid: kind + '-1', name: kind + ' 一', fact: '事实', summary: '摘要', labels: ['Entity'], content: '内容' }],
73
- has_more: false,
74
- }));
75
- }
76
- if (req.method === 'DELETE' && url.pathname.startsWith('/episodes/')) {
77
- return res.end(JSON.stringify({ ok: true, uuid: url.pathname.split('/').pop(), deleted: true }));
78
- }
79
- if (url.pathname.startsWith('/episodes/')) {
80
- return res.end(JSON.stringify({ ok: true, item: { uuid: url.pathname.split('/').pop(), name: '近况一', content: '完整内容' } }));
81
- }
82
- if (url.pathname === '/extractions') {
83
- return res.end(JSON.stringify({ ok: true, items: [{ uuid: 'ex-1', category: 'page', points: [{ detail: '表头固定' }] }] }));
84
- }
85
- if (url.pathname === '/semantic-index') {
86
- return res.end(JSON.stringify({ ok: true, scanned: 2, indexed: 2, remaining: 3, errors: [] }));
87
- }
88
- if (url.pathname === '/extract') {
89
- return res.end(JSON.stringify({ ok: true, engine: 'heuristic', scanned: 2, stored: [], remaining: 5 }));
90
- }
91
- if (url.pathname === '/categories/backfill') {
92
- return res.end(JSON.stringify({ ok: true, scanned: 3, updated: 2 }));
93
- }
94
- if (url.pathname === '/search') {
95
- return res.end(JSON.stringify({ ok: true, results: [{ uuid: 'f-1', fact: '履约单需要先审批', name: '履约流程' }] }));
96
- }
97
- if (url.pathname === '/ingest') {
98
- return res.end(JSON.stringify({ ok: true, results: (parsed.episodes || []).map((episode) => ({ name: episode.name, ok: true, uuid: 'u-' + episode.name })) }));
99
- }
100
- res.statusCode = 404;
101
- res.end(JSON.stringify({ ok: false, error: 'not found' }));
102
- });
103
- });
104
- return new Promise((resolve) => server.listen(0, '127.0.0.1', () => resolve({ server, calls, url: 'http://127.0.0.1:' + server.address().port })));
105
- }
106
-
107
- function withCentral(dir, central) {
108
- const file = path.join(dir, 'uitest.config.json');
109
- const raw = JSON.parse(fs.readFileSync(file, 'utf8'));
110
- raw.knowledge = { central };
111
- fs.writeFileSync(file, JSON.stringify(raw, null, 2));
112
- return file;
113
- }
114
-
115
- test('studio host: bootstrap / case / plan / flows', async () => {
116
- const dir = makeProject();
117
- const { ctx, routes } = makeConnection(dir);
118
- const panel = createStudioPanel(ctx);
119
- const dispose = registerStudioRoutes({ ctx, panel });
120
- const boot = await (await request(routes, '/bootstrap?project=' + encodeURIComponent(dir))).json();
121
- assert.equal(boot.ok, true);
122
- assert.equal(boot.capabilities.importUpload, true);
123
- assert.equal(boot.counts.total, 1);
124
- assert.equal(boot.cases[0].tcId, 'TC-LOGIN-001');
125
- const one = await (await request(routes, '/case?project=' + encodeURIComponent(dir) + '&id=TC-LOGIN-001')).json();
126
- assert.equal(one.ok, true);
127
- assert.equal(one.case.tcId, 'TC-LOGIN-001');
128
- const plan = await (await request(routes, '/plan', { method: 'POST', body: { project: dir, caseIds: ['TC-LOGIN-001'] } })).json();
129
- assert.equal(plan.ok, true);
130
- assert.equal(plan.plan.summary.agent, 1);
131
- const flows = await (await request(routes, '/flows?project=' + encodeURIComponent(dir))).json();
132
- assert.equal(flows.ok, true);
133
- const batches = await (await request(routes, '/batch?project=' + encodeURIComponent(dir))).json();
134
- assert.equal(batches.ok, true);
135
- assert.deepEqual(batches.batches, []);
136
- await dispose();
137
- });
138
-
139
- test('studio host: 保存并读取执行反馈', async () => {
140
- const dir = makeProject();
141
- const { ctx, routes } = makeConnection(dir);
142
- const panel = createStudioPanel(ctx);
143
- registerStudioRoutes({ ctx, panel });
144
- const saved = await (await request(routes, '/feedback', {
145
- method: 'POST',
146
- body: { project: dir, caseId: 'TC-LOGIN-001', batchId: 'b-1', runStatus: 'failed', note: '先等表头出现再查询' },
147
- })).json();
148
- assert.equal(saved.ok, true);
149
- assert.match(saved.feedback.id, /^fb-/);
150
- const list = await (await request(routes, '/feedback?project=' + encodeURIComponent(dir) + '&caseId=TC-LOGIN-001')).json();
151
- assert.equal(list.ok, true);
152
- assert.equal(list.feedbacks.length, 1);
153
- assert.equal(list.feedbacks[0].note, '先等表头出现再查询');
154
- const missing = await (await request(routes, '/feedback', { method: 'POST', body: { project: dir, caseId: 'TC-LOGIN-001', note: ' ' } })).json();
155
- assert.equal(missing.ok, false);
156
- assert.equal(missing.error.code, 'FEEDBACK_REQUIRED');
157
- });
158
-
159
- test('studio host: 保存中心知识库配置并可测试连接', async () => {
160
- const dir = makeProject('');
161
- const { ctx, routes } = makeConnection(dir);
162
- const panel = createStudioPanel(ctx);
163
- registerStudioRoutes({ ctx, panel });
164
- const saved = await (await request(routes, '/settings', {
165
- method: 'POST',
166
- body: {
167
- project: dir,
168
- knowledgeCentral: {
169
- enabled: true,
170
- url: 'http://127.0.0.1:9',
171
- groupId: 'test-central',
172
- timeoutMs: 3000,
173
- batchSize: 1,
174
- },
175
- },
176
- })).json();
177
- assert.equal(saved.ok, true);
178
- const raw = JSON.parse(fs.readFileSync(path.join(dir, 'uitest.config.json'), 'utf8'));
179
- assert.equal(raw.knowledge.central.url, 'http://127.0.0.1:9');
180
- assert.equal(raw.knowledge.central.groupId, 'test-central');
181
- assert.equal(raw.knowledge.central.batchSize, 1);
182
- const boot = await (await request(routes, '/bootstrap?project=' + encodeURIComponent(dir))).json();
183
- assert.equal(boot.config.knowledgeCentral.url, 'http://127.0.0.1:9');
184
- const tested = await (await request(routes, '/knowledge/central/test', { method: 'POST', body: { project: dir } })).json();
185
- assert.equal(tested.ok, true);
186
- assert.equal(tested.central.enabled, true);
187
- });
188
-
189
- test('studio host: 选择空文件夹并初始化为工作区', async () => {
190
- const empty = fs.mkdtempSync(path.join(os.tmpdir(), 'studio-empty-workspace-'));
191
- const { ctx, routes } = makeConnection(empty);
192
- const panel = createStudioPanel(ctx);
193
- registerStudioRoutes({ ctx, panel });
194
- const opened = await (await request(routes, '/project/open', { method: 'POST', body: { path: empty } })).json();
195
- assert.equal(opened.ok, true);
196
- assert.equal(opened.initialized, false);
197
- assert.equal(opened.entries, 0);
198
- const initialized = await (await request(routes, '/project/init', { method: 'POST', body: { path: empty } })).json();
199
- assert.equal(initialized.ok, true);
200
- assert.equal(initialized.initialized, true);
201
- assert.ok(initialized.created.includes('uitest.config.json'));
202
- assert.ok(fs.existsSync(path.join(empty, 'uitest.config.json')));
203
- assert.ok(fs.statSync(path.join(empty, 'cases')).isDirectory());
204
- assert.ok(fs.statSync(path.join(empty, 'flows')).isDirectory());
205
- const reopened = await (await request(routes, '/project/open', { method: 'POST', body: { path: empty } })).json();
206
- assert.equal(reopened.ok, true);
207
- assert.equal(reopened.initialized, true);
208
- });
209
-
210
- test('studio host: 选择器可用时返回文件夹路径', async () => {
211
- const dir = makeProject('');
212
- const target = fs.mkdtempSync(path.join(os.tmpdir(), 'studio-picked-'));
213
- const script = path.join(dir, 'pick.sh');
214
- fs.writeFileSync(script, '#!/bin/sh\necho "$PICK_RESULT"\n');
215
- fs.chmodSync(script, 0o755);
216
- const previousCommand = process.env.UITEST_PICK_CMD;
217
- const previousResult = process.env.PICK_RESULT;
218
- process.env.UITEST_PICK_CMD = script;
219
- process.env.PICK_RESULT = target;
220
- try {
221
- const { ctx, routes } = makeConnection(dir);
222
- const panel = createStudioPanel(ctx);
223
- registerStudioRoutes({ ctx, panel });
224
- const picked = await (await request(routes, '/pick-path', { method: 'POST', body: { kind: 'dir', title: '选工作区' } })).json();
225
- assert.equal(picked.ok, true);
226
- assert.equal(picked.path, target);
227
- } finally {
228
- if (previousCommand === undefined) delete process.env.UITEST_PICK_CMD; else process.env.UITEST_PICK_CMD = previousCommand;
229
- if (previousResult === undefined) delete process.env.PICK_RESULT; else process.env.PICK_RESULT = previousResult;
230
- }
231
- });
232
-
233
- test('studio host: 项目错误以 projectError 返回而不是 500', async () => {
234
- const dir = makeProject();
235
- const { ctx, routes } = makeConnection(dir);
236
- const panel = createStudioPanel(ctx);
237
- registerStudioRoutes({ ctx, panel });
238
- const boot = await (await request(routes, '/bootstrap?project=' + encodeURIComponent('/tmp/does-not-exist-oms-v2'))).json();
239
- assert.equal(boot.ok, true);
240
- assert.ok(boot.projectError);
241
- assert.match(boot.projectError.message, /不存在|缺少/);
242
- });
243
-
244
- test('studio host: 本地上传用例文档并返回 caseCount', async () => {
245
- const dir = makeProject('');
246
- const { ctx, routes } = makeConnection(dir);
247
- const panel = createStudioPanel(ctx);
248
- registerStudioRoutes({ ctx, panel });
249
- const content = '# 上传用例\n\n## TC-UP-001 上传成功\n\n| 项 | 内容 |\n|---|---|\n| **前置条件** | 系统可访问 |\n| **操作步骤** | 打开页面 |\n| **预期结果** | 页面正常 |\n';
250
- const res = await (await request(routes, '/import-upload', {
251
- method: 'POST',
252
- body: {
253
- project: dir,
254
- name: 'upload.md',
255
- docName: '上传用例',
256
- dataBase64: Buffer.from(content, 'utf8').toString('base64'),
257
- },
258
- })).json();
259
- assert.equal(res.ok, true);
260
- assert.equal(res.caseCount, 1);
261
- assert.equal(res.cases.length, 1);
262
- assert.equal(res.cases[0].tcId, 'TC-UP-001');
263
- assert.ok(res.uploadedFile);
264
- });
265
-
266
- test('studio host: 导入账号文档、保存、设默认、删除', async () => {
267
- const dir = makeProject('');
268
- const { ctx, routes } = makeConnection(dir);
269
- const panel = createStudioPanel(ctx);
270
- registerStudioRoutes({ ctx, panel });
271
- const doc = fs.readFileSync(path.resolve('../docs/角色权限/OMS测试账号.md'), 'utf8');
272
- const imported = await (await request(routes, '/accounts/import-upload', {
273
- method: 'POST',
274
- body: {
275
- project: dir,
276
- name: 'OMS测试账号.md',
277
- dataBase64: Buffer.from(doc, 'utf8').toString('base64'),
278
- },
279
- })).json();
280
- assert.equal(imported.ok, true);
281
- assert.equal(imported.added, 16);
282
- assert.equal(imported.total, 16);
283
- assert.equal(JSON.stringify(imported).includes('zhixun2013'), false);
284
- assert.match(imported.warnings[0].message, /已保存到本地账号配置/);
285
-
286
- const saved = await (await request(routes, '/accounts/save', {
287
- method: 'POST',
288
- body: { project: dir, id: 'wangzhengtao', patch: { notes: '建单主力' } },
289
- })).json();
290
- assert.equal(saved.ok, true);
291
- assert.equal(saved.accounts.accounts.find((item) => item.id === 'wangzhengtao').notes, '建单主力');
292
-
293
- const def = await (await request(routes, '/accounts/default', {
294
- method: 'POST',
295
- body: { project: dir, id: 'weizheyu' },
296
- })).json();
297
- assert.equal(def.accounts.defaultAccountId, 'weizheyu');
298
- const configAfterDefault = JSON.parse(fs.readFileSync(path.join(dir, 'uitest.config.json'), 'utf8'));
299
- assert.equal(configAfterDefault.auth.username, 'weizheyu');
300
- assert.equal(configAfterDefault.auth.storageState, '.auth/oms-weizheyu.json');
301
-
302
- const removed = await (await request(routes, '/accounts/delete', {
303
- method: 'POST',
304
- body: { project: dir, id: 'liuzhan' },
305
- })).json();
306
- assert.equal(removed.accounts.count, 15);
307
- });
308
-
309
-
310
- test('studio host: 批次详情把知识沉淀明细挂到用例结果', async () => {
311
- const dir = makeProject('');
312
- const { ctx, routes } = makeConnection(dir);
313
- const panel = createStudioPanel(ctx);
314
- registerStudioRoutes({ ctx, panel });
315
- const config = loadConfig(dir);
316
- const batch = createBatch(config, {
317
- name: 'knowledge',
318
- caseIds: ['TC-LOGIN-001'],
319
- plan: { items: [{ caseId: 'TC-LOGIN-001', title: '登录', mode: 'agent' }], summary: { total: 1 } },
320
- options: { writeBack: 'none' },
321
- });
322
- saveCaseRun(config, batch.id, {
323
- caseId: 'TC-LOGIN-001',
324
- batchId: batch.id,
325
- title: '登录',
326
- mode: 'agent',
327
- status: 'passed',
328
- startedAt: new Date().toISOString(),
329
- endedAt: new Date().toISOString(),
330
- durationMs: 1,
331
- note: '通过',
332
- steps: [],
333
- evidence: [],
334
- runDir: '',
335
- });
336
- await patchBatch(config, batch.id, {
337
- knowledge: {
338
- at: new Date().toISOString(),
339
- learned: [{
340
- caseId: 'TC-LOGIN-001',
341
- title: '登录',
342
- status: 'passed',
343
- pages: 1,
344
- pagesAdded: 1,
345
- pagesMerged: 0,
346
- pageItems: [{ id: 'login', title: '登录页', added: true, actionsAdded: 2 }],
347
- actions: 2,
348
- waits: 0,
349
- waitPages: [],
350
- suggestions: 0,
351
- suggestionItems: [],
352
- corrections: 0,
353
- process: null,
354
- }],
355
- totals: { pages: 1, actions: 2, corrections: 0 },
356
- },
357
- });
358
- const detail = await (await request(routes, '/batch?project=' + encodeURIComponent(dir) + '&id=' + batch.id)).json();
359
- assert.equal(detail.ok, true);
360
- assert.equal(detail.batch.cases[0].knowledge.pageItems[0].title, '登录页');
361
- assert.equal(detail.batch.cases[0].knowledge.pageItems[0].actionsAdded, 2);
362
- });
363
-
364
- test('studio host: 批次详情带出实时镜像 ws 地址', async () => {
365
- const dir = makeProject('');
366
- const { ctx, routes } = makeConnection(dir);
367
- const panel = createStudioPanel(ctx);
368
- registerStudioRoutes({ ctx, panel });
369
- const config = loadConfig(dir);
370
- const batch = createBatch(config, {
371
- name: 'live',
372
- caseIds: ['TC-LOGIN-001'],
373
- plan: { items: [{ caseId: 'TC-LOGIN-001', title: '登录', mode: 'flow' }], summary: { total: 1 } },
374
- options: { writeBack: 'none' },
375
- });
376
- const liveDir = path.join(config.paths.outputDir, 'batches', batch.id, 'live');
377
- fs.mkdirSync(liveDir, { recursive: true });
378
- fs.writeFileSync(path.join(liveDir, 'TC-LOGIN-001.json'), JSON.stringify({
379
- active: true,
380
- caseId: 'TC-LOGIN-001',
381
- wsUrl: 'ws://127.0.0.1:43210/',
382
- updatedAt: new Date().toISOString(),
383
- }));
384
- const detail = await (await request(routes, '/batch?project=' + encodeURIComponent(dir) + '&id=' + batch.id)).json();
385
- assert.equal(detail.ok, true);
386
- assert.equal(detail.batch.cases[0].live.wsUrl, 'ws://127.0.0.1:43210/');
387
- });
388
-
389
- test('studio host: 批量删除关联 flow,跳过 setup flow 并返回逐项结果', async () => {
390
- const dir = makeProject('');
391
- const { ctx, routes } = makeConnection(dir);
392
- const panel = createStudioPanel(ctx);
393
- registerStudioRoutes({ ctx, panel });
394
- const flowsDir = path.join(dir, 'flows');
395
- fs.mkdirSync(flowsDir, { recursive: true });
396
- fs.writeFileSync(path.join(flowsDir, 'case-a.json'), JSON.stringify({ name: 'case-a', kind: 'case', cases: ['TC-LOGIN-001'], steps: [{ action: 'goto', url: '/' }] }));
397
- fs.writeFileSync(path.join(flowsDir, 'case-b.json'), JSON.stringify({ name: 'case-b', kind: 'precondition', cases: ['TC-LOGIN-001'], steps: [{ action: 'goto', url: '/' }] }));
398
- fs.writeFileSync(path.join(flowsDir, 'setup.json'), JSON.stringify({ name: 'setup', tags: ['setup'], steps: [{ action: 'goto', url: '/' }] }));
399
- const removed = await (await request(routes, '/flows/delete', {
400
- method: 'POST',
401
- body: {
402
- project: dir,
403
- flows: [
404
- { name: 'case-a' },
405
- { name: 'case-b' },
406
- { name: 'setup' },
407
- ],
408
- },
409
- })).json();
410
- assert.equal(removed.ok, true);
411
- assert.equal(removed.deleted, 2);
412
- assert.equal(removed.failed, 1);
413
- assert.equal(fs.existsSync(path.join(flowsDir, 'case-a.json')), false);
414
- assert.equal(fs.existsSync(path.join(flowsDir, 'case-b.json')), false);
415
- assert.equal(fs.existsSync(path.join(flowsDir, 'setup.json')), true);
416
- assert.ok(removed.results.some((item) => item.name === 'setup' && item.error.code === 'FLOW_NOT_CASE'));
417
- });
418
-
419
- test('studio host: 删除与恢复用例', async () => {
420
- const dir = makeProject();
421
- const { ctx, routes } = makeConnection(dir);
422
- const panel = createStudioPanel(ctx);
423
- registerStudioRoutes({ ctx, panel });
424
- const deleted = await (await request(routes, '/case/delete', {
425
- method: 'POST',
426
- body: { project: dir, ids: ['TC-LOGIN-001'] },
427
- })).json();
428
- assert.equal(deleted.ok, true);
429
- assert.equal(deleted.deleted, 1);
430
- const boot = await (await request(routes, '/bootstrap?project=' + encodeURIComponent(dir))).json();
431
- assert.equal(boot.counts.total, 0);
432
- const restored = await (await request(routes, '/case/restore', {
433
- method: 'POST',
434
- body: { project: dir, ids: ['TC-LOGIN-001'] },
435
- })).json();
436
- assert.equal(restored.ok, true);
437
- assert.equal(restored.restored, 1);
438
- const after = await (await request(routes, '/bootstrap?project=' + encodeURIComponent(dir))).json();
439
- assert.equal(after.counts.total, 1);
440
- });
441
-
442
- test('studio host: 同名文档覆盖导入更新对应用例', async () => {
443
- const dir = makeProject();
444
- const { ctx, routes } = makeConnection(dir);
445
- const panel = createStudioPanel(ctx);
446
- registerStudioRoutes({ ctx, panel });
447
- const v1 = path.join(dir, 'v1.md');
448
- fs.writeFileSync(v1, '# 覆盖\n\n## TC-COVER-001 第一条\n\n| 项 | 内容 |\n|---|---|\n| **前置条件** | 无 |\n| **操作步骤** | 打开页面 |\n| **预期结果** | 正常 |\n\n## TC-COVER-002 第二条\n\n| 项 | 内容 |\n|---|---|\n| **前置条件** | 无 |\n| **操作步骤** | 打开页面 |\n| **预期结果** | 正常 |\n');
449
- const first = await (await request(routes, '/import', { method: 'POST', body: { project: dir, file: v1, name: '覆盖文档' } })).json();
450
- assert.equal(first.ok, true);
451
- assert.equal(first.diffSummary.added, 2);
452
- const v2 = path.join(dir, 'v2.md');
453
- fs.writeFileSync(v2, '# 覆盖\n\n## TC-COVER-001 第一条(改)\n\n| 项 | 内容 |\n|---|---|\n| **前置条件** | 无 |\n| **操作步骤** | 打开页面并等待 |\n| **预期结果** | 正常 |\n');
454
- const second = await (await request(routes, '/import', {
455
- method: 'POST',
456
- body: { project: dir, file: v2, name: '覆盖文档', mode: 'overwrite' },
457
- })).json();
458
- assert.equal(second.ok, true);
459
- assert.equal(second.diffSummary.updated, 1);
460
- assert.equal(second.diffSummary.removed, 1);
461
- assert.equal(second.doc.id, first.doc.id);
462
- const boot = await (await request(routes, '/bootstrap?project=' + encodeURIComponent(dir))).json();
463
- assert.equal(boot.counts.total, 2, '默认 cases.md 的 1 条 + 覆盖文档的 1 条');
464
- assert.equal(boot.cases.find((item) => item.tcId === 'TC-COVER-001')?.title, '第一条(改)');
465
- assert.equal(boot.cases.some((item) => item.tcId === 'TC-COVER-002'), false);
466
- assert.equal(boot.docs.length, 1);
467
- });
468
-
469
- test('studio host: 导出用例与结果并下载 xlsx', async () => {
470
- const dir = makeProject();
471
- const { ctx, routes } = makeConnection(dir);
472
- const panel = createStudioPanel(ctx);
473
- registerStudioRoutes({ ctx, panel });
474
- const exported = await (await request(routes, '/export/cases', {
475
- method: 'POST',
476
- body: { project: dir },
477
- })).json();
478
- assert.equal(exported.ok, true);
479
- assert.ok(exported.file && fs.existsSync(exported.file));
480
- assert.equal(exported.count, 1);
481
- assert.match(exported.downloadUrl, /\/export\/download\?/);
482
- const downloaded = await request(routes, '/export/download?project=' + encodeURIComponent(dir) + '&file=' + encodeURIComponent(exported.file) + '&name=' + encodeURIComponent(exported.fileName));
483
- assert.equal(downloaded.status, 200);
484
- assert.match(downloaded.headers.get('content-type'), /spreadsheetml/);
485
- assert.match(downloaded.headers.get('content-disposition'), /attachment/);
486
- const buffer = Buffer.from(await downloaded.arrayBuffer());
487
- assert.equal(buffer.subarray(0, 2).toString(), 'PK');
488
-
489
- const results = await (await request(routes, '/export/results', {
490
- method: 'POST',
491
- body: { project: dir },
492
- })).json();
493
- assert.equal(results.ok, true);
494
- assert.equal(results.count, 1);
495
- assert.ok(fs.existsSync(results.file));
496
-
497
- const forbidden = await request(routes, '/export/download?project=' + encodeURIComponent(dir) + '&file=' + encodeURIComponent(path.join(dir, 'uitest.config.json')));
498
- assert.equal(forbidden.status, 403);
499
- assert.equal((await forbidden.json()).error.code, 'EXPORT_PATH_FORBIDDEN');
500
- });
501
-
502
- test('studio host: 删除已关联 flow,不能越出 flows 目录', async () => {
503
- const dir = makeProject('');
504
- const { ctx, routes } = makeConnection(dir);
505
- const panel = createStudioPanel(ctx);
506
- registerStudioRoutes({ ctx, panel });
507
- const flowFile = path.join(dir, 'flows', 'flow-case.json');
508
- fs.mkdirSync(path.dirname(flowFile), { recursive: true });
509
- fs.writeFileSync(flowFile, JSON.stringify({ name: 'flow-case', cases: ['TC-LOGIN-001'], steps: [{ id: 's1', action: 'goto', url: '/' }] }));
510
- const removed = await (await request(routes, '/flow/delete', { method: 'POST', body: { project: dir, name: 'flow-case', file: flowFile } })).json();
511
- assert.equal(removed.ok, true);
512
- assert.equal(fs.existsSync(flowFile), false);
513
- const missing = await (await request(routes, '/flow/delete', { method: 'POST', body: { project: dir, name: 'flow-case' } })).json();
514
- assert.equal(missing.ok, false);
515
- assert.equal(missing.error.code, 'FLOW_NOT_FOUND');
516
- });
517
-
518
- test('studio host: 删除批次会删除目录并清理结果', async () => {
519
- const dir = makeProject();
520
- const { ctx, routes } = makeConnection(dir);
521
- const panel = createStudioPanel(ctx);
522
- registerStudioRoutes({ ctx, panel });
523
- const config = loadConfig(dir);
524
- const batch = createBatch(config, { name: '待删除', caseIds: ['TC-LOGIN-001'] });
525
- await patchBatch(config, batch.id, { status: 'done' });
526
- const res = await request(routes, '/batch/delete', { method: 'POST', body: { project: dir, id: batch.id } });
527
- const payload = await res.json();
528
- assert.equal(res.status, 200);
529
- assert.equal(payload.ok, true);
530
- assert.equal(payload.deleted.batchId, batch.id);
531
- const list = await (await request(routes, '/batch?project=' + encodeURIComponent(dir))).json();
532
- assert.equal(list.batches.some((item) => item.id === batch.id), false);
533
- });
534
-
535
- test('studio host: 重新沉淀已结束批次,执行中的批次拒绝', async () => {
536
- const dir = makeProject();
537
- const { ctx, routes } = makeConnection(dir);
538
- const panel = createStudioPanel(ctx);
539
- registerStudioRoutes({ ctx, panel });
540
- const config = loadConfig(dir);
541
- const batch = createBatch(config, { name: '待沉淀', caseIds: ['TC-LOGIN-001'] });
542
- await patchBatch(config, batch.id, { status: 'done' });
543
- const res = await request(routes, '/batch/distill', { method: 'POST', body: { project: dir, id: batch.id } });
544
- const payload = await res.json();
545
- assert.equal(res.status, 200);
546
- assert.equal(payload.ok, true);
547
- assert.equal(payload.batch.stages.distill.status, 'done');
548
-
549
- const running = createBatch(config, { name: '执行中', caseIds: ['TC-LOGIN-001'] });
550
- const refused = await request(routes, '/batch/distill', { method: 'POST', body: { project: dir, id: running.id } });
551
- assert.equal(refused.status, 409);
552
- assert.equal((await refused.json()).error.code, 'BATCH_RUNNING');
553
- });
554
-
555
- test('studio host: 中心知识库 browse / episode / import 路由', async () => {
556
- const mock = await makeCentralServer();
557
- const dir = makeProject('');
558
- withCentral(dir, { enabled: true, url: mock.url, groupId: 'test-central', batchSize: 5 });
559
- const { ctx, routes } = makeConnection(dir);
560
- const panel = createStudioPanel(ctx);
561
- registerStudioRoutes({ ctx, panel });
562
- try {
563
- const browse = await (await request(routes, '/knowledge/central/browse?project=' + encodeURIComponent(dir) + '&kind=facts&q=' + encodeURIComponent('履约 单') + '&category=document-flow&limit=5&offset=2')).json();
564
- assert.equal(browse.ok, true);
565
- assert.equal(browse.kind, 'facts');
566
- assert.equal(browse.items[0].name, 'facts 一');
567
- const browseCall = mock.calls.find((call) => call.url.startsWith('/browse'));
568
- const browseUrl = new URL(browseCall.url, 'http://localhost');
569
- assert.equal(browseUrl.searchParams.get('kind'), 'facts');
570
- assert.equal(browseUrl.searchParams.get('group_id'), 'test-central');
571
- assert.equal(browseUrl.searchParams.get('q'), '履约 单');
572
- assert.equal(browseUrl.searchParams.get('category'), 'document-flow');
573
- assert.equal(browseUrl.searchParams.get('limit'), '5');
574
- assert.equal(browseUrl.searchParams.get('offset'), '2');
575
-
576
- const semantic = await (await request(routes, '/knowledge/central/search?project=' + encodeURIComponent(dir) + '&q=' + encodeURIComponent('履约审批'))).json();
577
- assert.equal(semantic.ok, true);
578
- assert.equal(semantic.results[0].fact, '履约单需要先审批');
579
- const searchCall = mock.calls.find((call) => call.url === '/search');
580
- assert.equal(searchCall.body.query, '履约审批');
581
-
582
- const organized = await (await request(routes, '/knowledge/central/categories', { method: 'POST', body: { project: dir } })).json();
583
- assert.equal(organized.ok, true);
584
- assert.equal(organized.updated, 2);
585
-
586
- const extracted = await (await request(routes, '/knowledge/central/extract', { method: 'POST', body: { project: dir, limit: 20 } })).json();
587
- assert.equal(extracted.ok, true);
588
- assert.equal(extracted.scanned, 2);
589
- assert.equal(extracted.remaining, 5);
590
- const indexed = await (await request(routes, '/knowledge/central/semantic-index', { method: 'POST', body: { project: dir, limit: 5 } })).json();
591
- assert.equal(indexed.ok, true);
592
- assert.equal(indexed.indexed, 2);
593
- const extractions = await (await request(routes, '/knowledge/central/extractions?project=' + encodeURIComponent(dir))).json();
594
- assert.equal(extractions.ok, true);
595
- assert.equal(extractions.items[0].category, 'page');
596
-
597
- const episode = await (await request(routes, '/knowledge/central/episode?project=' + encodeURIComponent(dir) + '&uuid=u-1')).json();
598
- assert.equal(episode.ok, true);
599
- assert.equal(episode.item.content, '完整内容');
600
- const episodeCall = mock.calls.find((call) => call.url.startsWith('/episodes/'));
601
- assert.equal(new URL(episodeCall.url, 'http://localhost').searchParams.get('group_id'), 'test-central');
602
-
603
- const docs = path.join(dir, 'docs');
604
- fs.mkdirSync(docs, { recursive: true });
605
- fs.writeFileSync(path.join(docs, 'note.md'), '# 知识\n\n等待表头。\n');
606
- const preview = await (await request(routes, '/knowledge/central/import', {
607
- method: 'POST',
608
- body: { project: dir, paths: [docs], dryRun: true },
609
- })).json();
610
- assert.equal(preview.ok, true);
611
- assert.equal(preview.dryRun, true);
612
- assert.equal(preview.totals.episodes, 1);
613
- assert.equal(mock.calls.filter((call) => call.url === '/ingest').length, 0);
614
-
615
- const imported = await (await request(routes, '/knowledge/central/import', {
616
- method: 'POST',
617
- body: { project: dir, paths: [docs] },
618
- })).json();
619
- assert.equal(imported.ok, true);
620
- assert.equal(imported.totals.ingested, 1);
621
- assert.equal(imported.documents[0].status, 'imported');
622
- assert.equal(mock.calls.filter((call) => call.url === '/ingest').length, 1);
623
- assert.equal(imported.savedDocuments.length, 1);
624
- assert.equal(imported.savedDocuments[0].centralUuid, 'u-docs/note.md');
625
-
626
- const listed = await (await request(routes, '/knowledge/docs?project=' + encodeURIComponent(dir))).json();
627
- assert.equal(listed.ok, true);
628
- assert.equal(listed.documents.length, 1);
629
- const docId = listed.documents[0].id;
630
- const item = await (await request(routes, '/knowledge/docs/item?project=' + encodeURIComponent(dir) + '&id=' + encodeURIComponent(docId))).json();
631
- assert.match(item.content, /等待表头/);
632
-
633
- const updated = await (await request(routes, '/knowledge/docs/update', {
634
- method: 'POST',
635
- body: { project: dir, id: docId, name: 'note.md', category: 'caution', content: '# 注意事项\n\n改单审批不可用。', publish: false },
636
- })).json();
637
- assert.equal(updated.ok, true);
638
- assert.equal(updated.document.category, 'caution');
639
-
640
- const removed = await (await request(routes, '/knowledge/docs/delete', {
641
- method: 'POST',
642
- body: { project: dir, id: docId },
643
- })).json();
644
- assert.equal(removed.ok, true);
645
- assert.equal(removed.deleted, true);
646
- assert.equal(mock.calls.filter((call) => call.method === 'DELETE').length, 1);
647
- const after = await (await request(routes, '/knowledge/docs?project=' + encodeURIComponent(dir))).json();
648
- assert.equal(after.documents.length, 0);
649
- } finally {
650
- await new Promise((resolve) => mock.server.close(resolve));
651
- }
652
- });
653
-
654
- test('studio host: 中心知识库上传导入与参数校验', async () => {
655
- const mock = await makeCentralServer();
656
- const dir = makeProject('');
657
- withCentral(dir, { enabled: true, url: mock.url, groupId: 'test-central', batchSize: 5 });
658
- const { ctx, routes } = makeConnection(dir);
659
- const panel = createStudioPanel(ctx);
660
- registerStudioRoutes({ ctx, panel });
661
- try {
662
- const dataBase64 = Buffer.from('# 上传知识\n\n列表先等表头。\n', 'utf8').toString('base64');
663
- const uploaded = await (await request(routes, '/knowledge/central/import-upload', {
664
- method: 'POST',
665
- body: { project: dir, name: 'upload.md', dataBase64, category: 'page' },
666
- })).json();
667
- assert.equal(uploaded.ok, true);
668
- assert.equal(uploaded.totals.ingested, 1);
669
- assert.equal(uploaded.savedDocuments[0].category, 'page');
670
- assert.ok(uploaded.uploadedFile.startsWith(path.join(dir, '.uitest', 'uploads', 'knowledge')));
671
- assert.equal(fs.existsSync(uploaded.uploadedFile), true);
672
-
673
- const badKind = await request(routes, '/knowledge/central/browse?project=' + encodeURIComponent(dir) + '&kind=bad');
674
- assert.equal(badKind.status, 400);
675
- assert.equal((await badKind.json()).error.code, 'KNOWLEDGE_KIND_INVALID');
676
-
677
- const noUuid = await request(routes, '/knowledge/central/episode?project=' + encodeURIComponent(dir));
678
- assert.equal(noUuid.status, 400);
679
- assert.equal((await noUuid.json()).error.code, 'KNOWLEDGE_EPISODE_REQUIRED');
680
-
681
- const noPaths = await request(routes, '/knowledge/central/import', { method: 'POST', body: { project: dir, paths: [] } });
682
- assert.equal(noPaths.status, 400);
683
- assert.equal((await noPaths.json()).error.code, 'KNOWLEDGE_PATH_REQUIRED');
684
-
685
- const badExt = await request(routes, '/knowledge/central/import-upload', {
686
- method: 'POST',
687
- body: { project: dir, name: 'note.exe', dataBase64 },
688
- });
689
- assert.equal(badExt.status, 400);
690
- assert.equal((await badExt.json()).error.code, 'KNOWLEDGE_UPLOAD_UNSUPPORTED');
691
-
692
- const huge = Buffer.alloc(2 * 1024 * 1024 + 1, 97).toString('base64');
693
- const tooLarge = await request(routes, '/knowledge/central/import-upload', {
694
- method: 'POST',
695
- body: { project: dir, name: 'huge.md', dataBase64: huge },
696
- });
697
- assert.equal(tooLarge.status, 413);
698
- assert.equal((await tooLarge.json()).error.code, 'KNOWLEDGE_UPLOAD_TOO_LARGE');
699
-
700
- const emptyBody = await request(routes, '/knowledge/central/import-upload', {
701
- method: 'POST',
702
- body: { project: dir, name: 'empty.md' },
703
- });
704
- assert.equal(emptyBody.status, 400);
705
- assert.equal((await emptyBody.json()).error.code, 'KNOWLEDGE_UPLOAD_REQUIRED');
706
- } finally {
707
- await new Promise((resolve) => mock.server.close(resolve));
708
- }
709
- });
710
-
711
- test('studio host: 中心知识库不可用时 browse 返回错误而不是 500', async () => {
712
- const dir = makeProject('');
713
- withCentral(dir, { enabled: true, url: 'http://127.0.0.1:9', groupId: 'test-central', batchSize: 5, searchTimeoutMs: 1000 });
714
- const { ctx, routes } = makeConnection(dir);
715
- const panel = createStudioPanel(ctx);
716
- registerStudioRoutes({ ctx, panel });
717
- const res = await request(routes, '/knowledge/central/browse?project=' + encodeURIComponent(dir) + '&kind=episodes');
718
- assert.equal(res.status, 502);
719
- const payload = await res.json();
720
- assert.equal(payload.ok, false);
721
- assert.equal(payload.error.code, 'KNOWLEDGE_BROWSE_FAILED');
722
- assert.ok(payload.error.message);
723
- });