dsh-uitest 2.2.0 → 2.3.1
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.
- package/README.md +35 -10
- package/bin/studio.mjs +117 -17
- package/bin/uitest.mjs +3 -3
- package/client.js +1030 -192
- package/index.js +90 -5
- package/lib/backfill.mjs +37 -22
- package/lib/cases-import.mjs +67 -43
- package/lib/cases-md.mjs +5 -0
- package/lib/csv.mjs +207 -0
- package/lib/knowledge-central.mjs +29 -5
- package/lib/xlsx.mjs +2 -1
- package/package.json +1 -1
- package/skills/uitest/SKILL.md +9 -4
- package/studio/documents.mjs +86 -16
- package/studio/host.mjs +126 -17
- package/studio/import.mjs +115 -21
- package/studio/knowledge.mjs +93 -6
- package/studio/runner.mjs +55 -0
- package/studio/snapshot.mjs +23 -12
- package/studio/store.mjs +25 -1
- package/studio/writeback.mjs +85 -23
package/index.js
CHANGED
|
@@ -16,17 +16,18 @@ import { fileURLToPath } from 'node:url';
|
|
|
16
16
|
|
|
17
17
|
import { loadConfig } from './lib/config.mjs';
|
|
18
18
|
import { readFlows } from './host/state.mjs';
|
|
19
|
-
import { importDocument } from './studio/import.mjs';
|
|
19
|
+
import { importDocument, reReadDocument } from './studio/import.mjs';
|
|
20
|
+
import { deleteDocumentRecord, setDocumentArchived } from './studio/documents.mjs';
|
|
20
21
|
import { accountsPayload, deleteAccount, importAccountsText, saveAccount, setDefaultAccount } from './studio/accounts.mjs';
|
|
21
22
|
import { buildStudioPlan, compactPlan } from './studio/plan.mjs';
|
|
22
23
|
import { buildStudioSnapshot } from './studio/snapshot.mjs';
|
|
23
24
|
import { knowledgeSnapshot } from './studio/knowledge.mjs';
|
|
24
25
|
import { knowledgeContextForCase } from './lib/knowledge-query.mjs';
|
|
25
26
|
import { centralSearch } from './lib/knowledge-central.mjs';
|
|
26
|
-
import { createBatch, mergeBatchRuns, patchBatch, readBatch, readCaseRuns } from './studio/store.mjs';
|
|
27
|
+
import { acquireLock, createBatch, mergeBatchRuns, patchBatch, readBatch, readCaseRuns } from './studio/store.mjs';
|
|
27
28
|
import { summarizeCaseRuns } from './studio/model.mjs';
|
|
28
29
|
import { requestBatchStop, runBatch } from './studio/runner.mjs';
|
|
29
|
-
import { applyBatchWriteback, previewBatchWriteback } from './studio/writeback.mjs';
|
|
30
|
+
import { applyBatchWriteback, applyDocumentWriteback, previewBatchWriteback, previewDocumentWriteback } from './studio/writeback.mjs';
|
|
30
31
|
import { registerTestApprovalAnswerer } from './host/agent-test.mjs';
|
|
31
32
|
import {
|
|
32
33
|
activeBatchFor,
|
|
@@ -158,7 +159,7 @@ function toolDefinitions(ctx, panel) {
|
|
|
158
159
|
return [
|
|
159
160
|
{
|
|
160
161
|
name: 'uitest_import',
|
|
161
|
-
description: 'Import a test-case document into the project and generate natural-language cases. Supports .md/.markdown/.txt/.xlsx/.json or a directory. Markdown/text is parsed into cases with 前置条件 / 测试过程 / 预期结果 and written to cases/studio/*.md; xlsx
|
|
162
|
+
description: 'Import a test-case document into the project and generate natural-language cases. Supports .md/.markdown/.txt/.xlsx/.csv/.json or a directory. Markdown/text is parsed into cases with 前置条件 / 测试过程 / 预期结果 and written to cases/studio/*.md; xlsx and CSV are imported into the project case overlay, and CSV also gets a generated Markdown write-back mirror; the source file is never modified. Returns the document record, generated case ids, warnings, and the refreshed case counts. Use this as the first step of the Test Studio story.',
|
|
162
163
|
parameters: {
|
|
163
164
|
type: 'object',
|
|
164
165
|
additionalProperties: false,
|
|
@@ -167,6 +168,8 @@ function toolDefinitions(ctx, panel) {
|
|
|
167
168
|
project: { type: 'string', description: 'Test project directory containing uitest.config.json. Defaults to the session cwd.' },
|
|
168
169
|
file: { type: 'string', description: 'Document file or directory, absolute or relative to the project.' },
|
|
169
170
|
name: { type: 'string', description: 'Optional document name used for the generated case prefix.' },
|
|
171
|
+
docId: { type: 'string', description: 'Re-associate this existing document instead of matching by name/path. Only a single file is accepted.' },
|
|
172
|
+
mode: { type: 'string', enum: ['merge', 'overwrite'], description: 'merge keeps cases removed from the source; overwrite removes them. Defaults to merge.' },
|
|
170
173
|
},
|
|
171
174
|
},
|
|
172
175
|
output: textOutput(),
|
|
@@ -175,7 +178,12 @@ function toolDefinitions(ctx, panel) {
|
|
|
175
178
|
const { cwd } = projectContext(ctx, exec, input.project);
|
|
176
179
|
const config = loadConfig(cwd);
|
|
177
180
|
const file = isAbsolute(String(input.file)) ? String(input.file) : resolve(config.projectDir, String(input.file));
|
|
178
|
-
const result = await importDocument(config, {
|
|
181
|
+
const result = await importDocument(config, {
|
|
182
|
+
file,
|
|
183
|
+
name: input.name || '',
|
|
184
|
+
docId: input.docId || '',
|
|
185
|
+
mode: input.mode === 'overwrite' ? 'overwrite' : 'merge',
|
|
186
|
+
});
|
|
179
187
|
return {
|
|
180
188
|
ok: true,
|
|
181
189
|
doc: result.doc,
|
|
@@ -185,6 +193,83 @@ function toolDefinitions(ctx, panel) {
|
|
|
185
193
|
};
|
|
186
194
|
},
|
|
187
195
|
},
|
|
196
|
+
{
|
|
197
|
+
name: 'uitest_docs',
|
|
198
|
+
description: 'Manage the imported test-case document layer above natural-language cases. Each document keeps a stable id, its source file, the generated case file, ownership of case ids, archive state, read history and the last write-back summary. action=list returns documents with visible/owned/tombstoned/stale counts, source and case-file state, per-status counts, last run and archive flag. action=writeback previews or applies result write-back for one document (optionally one batch or selected cases); Markdown/JSON/CSV writes into the generated case file, xlsx writes a separate execution copy and never touches the source workbook. action=re-read re-reads the stored source file, keeps the document identity, and best-effort re-applies the latest results. action=archive/restore hide or restore a document and its cases without deleting data. action=delete removes only the document record (confirm=true required); its cases stay in the library as unassigned.',
|
|
199
|
+
parameters: {
|
|
200
|
+
type: 'object',
|
|
201
|
+
additionalProperties: false,
|
|
202
|
+
required: ['action'],
|
|
203
|
+
properties: {
|
|
204
|
+
action: { type: 'string', enum: ['list', 'writeback', 're-read', 'archive', 'restore', 'delete'] },
|
|
205
|
+
project: { type: 'string', description: 'Test project directory. Defaults to the session cwd.' },
|
|
206
|
+
docId: { type: 'string', description: 'Document id. Required for every action except list.' },
|
|
207
|
+
includeArchived: { type: 'boolean', description: 'For list: include archived documents. Defaults to false.' },
|
|
208
|
+
batchId: { type: 'string', description: 'For writeback: use this batch instead of the latest result per case.' },
|
|
209
|
+
caseIds: { type: 'array', items: { type: 'string' }, description: 'For writeback: restrict to these case ids.' },
|
|
210
|
+
dryRun: { type: 'boolean', description: 'For writeback: preview only. Defaults to true unless apply=true or dryRun=false.' },
|
|
211
|
+
apply: { type: 'boolean', description: 'For writeback: actually write. Defaults to false (preview).' },
|
|
212
|
+
mode: { type: 'string', enum: ['merge', 'overwrite'], description: 'For re-read: merge keeps cases removed from the source; overwrite removes them. Defaults to the document mode.' },
|
|
213
|
+
confirm: { type: 'boolean', description: 'For delete: must be true; deletion cannot be undone from the tool.' },
|
|
214
|
+
},
|
|
215
|
+
},
|
|
216
|
+
output: textOutput(),
|
|
217
|
+
async execute(args, exec) {
|
|
218
|
+
const input = asRecord(args);
|
|
219
|
+
const { cwd } = projectContext(ctx, exec, input.project);
|
|
220
|
+
const config = loadConfig(cwd);
|
|
221
|
+
if (input.action === 'list') {
|
|
222
|
+
const snapshot = buildStudioSnapshot(config, { caseLimit: 1 });
|
|
223
|
+
if (snapshot.docsError) throw toolError(snapshot.docsError.message);
|
|
224
|
+
const docs = input.includeArchived === true
|
|
225
|
+
? snapshot.docs
|
|
226
|
+
: snapshot.docs.filter((doc) => !doc.archived);
|
|
227
|
+
return { ok: true, docs, total: snapshot.docs.length, archived: snapshot.counts.archivedDocs };
|
|
228
|
+
}
|
|
229
|
+
const docId = String(input.docId || '');
|
|
230
|
+
if (!docId) throw toolError('uitest_docs ' + input.action + ' requires docId');
|
|
231
|
+
if (input.action === 'writeback') {
|
|
232
|
+
const active = activeBatchFor(config);
|
|
233
|
+
if (active) throw toolError('已有批次在执行(' + (active.name || active.id) + ');请先停止或等待完成');
|
|
234
|
+
const options = {
|
|
235
|
+
batchId: input.batchId || '',
|
|
236
|
+
caseIds: Array.isArray(input.caseIds) ? input.caseIds.map(String) : [],
|
|
237
|
+
};
|
|
238
|
+
if (input.apply === true || input.dryRun === false) {
|
|
239
|
+
return { ok: true, writeback: await applyDocumentWriteback(config, docId, options) };
|
|
240
|
+
}
|
|
241
|
+
return { ok: true, preview: await previewDocumentWriteback(config, docId, options) };
|
|
242
|
+
}
|
|
243
|
+
if (input.action === 're-read') {
|
|
244
|
+
const active = activeBatchFor(config);
|
|
245
|
+
if (active) throw toolError('已有批次在执行(' + (active.name || active.id) + ');请先停止或等待完成');
|
|
246
|
+
const result = await reReadDocument(config, { docId, mode: input.mode || '' });
|
|
247
|
+
return {
|
|
248
|
+
ok: true,
|
|
249
|
+
doc: result.doc,
|
|
250
|
+
caseCount: (result.cases || []).length,
|
|
251
|
+
diff: result.diffSummary || null,
|
|
252
|
+
warnings: result.warnings || [],
|
|
253
|
+
resultReapplied: result.resultReapplied === true,
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
if (input.action === 'archive' || input.action === 'restore') {
|
|
257
|
+
return { ok: true, doc: await setDocumentArchived(config, docId, input.action === 'archive') };
|
|
258
|
+
}
|
|
259
|
+
if (input.action === 'delete') {
|
|
260
|
+
if (input.confirm !== true) throw toolError('uitest_docs delete requires confirm=true; cases stay in the library but the document record and its case ownership are lost');
|
|
261
|
+
const active = activeBatchFor(config);
|
|
262
|
+
if (active) throw toolError('已有批次在执行(' + (active.name || active.id) + ');请先停止或等待完成');
|
|
263
|
+
const lock = acquireLock(config, 'writeback');
|
|
264
|
+
try {
|
|
265
|
+
return { ok: true, doc: await deleteDocumentRecord(config, docId) };
|
|
266
|
+
} finally {
|
|
267
|
+
lock.release();
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
throw toolError('Unknown uitest_docs action: ' + String(input.action));
|
|
271
|
+
},
|
|
272
|
+
},
|
|
188
273
|
{
|
|
189
274
|
name: 'uitest_accounts',
|
|
190
275
|
description: 'Read or configure Test Studio test accounts. Accounts store username, name, roles, department, area, part-time department, password environment variable, storage-state file and notes. action=import parses an OMS-test-account Markdown table from a server path and merges by username; action=list returns configured accounts; action=save creates/updates one account; action=default sets the default account; action=delete removes one. Plaintext passwords in the source document are never stored or returned; only passwordEnv is kept.',
|
package/lib/backfill.mjs
CHANGED
|
@@ -296,9 +296,9 @@ function xlsxOriginOf(caseItem) {
|
|
|
296
296
|
return null;
|
|
297
297
|
}
|
|
298
298
|
|
|
299
|
-
function applySheetCases(config, worksheet, sheetCases, resultsByCase, { maxShotsPerCase = 4 } = {}) {
|
|
299
|
+
function applySheetCases(config, worksheet, sheetCases, resultsByCase, { maxShotsPerCase = 4, dryRun = false } = {}) {
|
|
300
300
|
const header = findHeaderRow(worksheet);
|
|
301
|
-
if (!header) return { changed: 0, evidenceByName: new Map(), sheet: worksheet.name, headers: null };
|
|
301
|
+
if (!header) return { changed: 0, evidenceByName: new Map(), writtenIds: [], sheet: worksheet.name, headers: null };
|
|
302
302
|
const resultCol = columnOf(header.texts, [/^测试结果$/, /^执行结果$/, /^结果$/]) || header.texts.length + 1;
|
|
303
303
|
const timeCol = columnOf(header.texts, [/^执行时间$/]) || Math.max(resultCol, header.texts.length) + 1;
|
|
304
304
|
const noteCol = columnOf(header.texts, [/^执行备注$/, /^实测观察$/]) || Math.max(timeCol, header.texts.length) + 1;
|
|
@@ -313,12 +313,14 @@ function applySheetCases(config, worksheet, sheetCases, resultsByCase, { maxShot
|
|
|
313
313
|
[keyShotCol, '关键步骤截图'],
|
|
314
314
|
[errorShotCol, '错误截图'],
|
|
315
315
|
];
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
316
|
+
if (!dryRun) {
|
|
317
|
+
for (const [col, title] of extraHeaders) {
|
|
318
|
+
if (!header.texts[col - 1]) {
|
|
319
|
+
const cell = setCell(worksheet, header.rowNumber, col, title);
|
|
320
|
+
cell.font = { bold: true };
|
|
321
|
+
cell.fill = { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FFE7E6E6' } };
|
|
322
|
+
worksheet.getColumn(col).width = title.includes('截图') ? 36 : title === '执行备注' ? 60 : 20;
|
|
323
|
+
}
|
|
322
324
|
}
|
|
323
325
|
}
|
|
324
326
|
|
|
@@ -354,15 +356,17 @@ function applySheetCases(config, worksheet, sheetCases, resultsByCase, { maxShot
|
|
|
354
356
|
if (!result) continue;
|
|
355
357
|
const rowNumber = rowCache.get(id);
|
|
356
358
|
if (!rowNumber) continue;
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
359
|
+
if (!dryRun) {
|
|
360
|
+
const evidence = evidenceListFor(config, result, { maxKey: maxShotsPerCase, maxError: maxShotsPerCase });
|
|
361
|
+
evidenceByName.set(id, evidence);
|
|
362
|
+
const statusCell = setCell(worksheet, rowNumber, resultCol, result.status || '');
|
|
363
|
+
styleStatus(statusCell, result.status);
|
|
364
|
+
setCell(worksheet, rowNumber, timeCol, result.at ? formatDateTime(new Date(result.at)) : '');
|
|
365
|
+
setCell(worksheet, rowNumber, noteCol, truncate(result.note || '', 800));
|
|
366
|
+
setCell(worksheet, rowNumber, batchCol, result.batchId || '');
|
|
367
|
+
setCell(worksheet, rowNumber, keyShotCol, evidence.key.map((item) => path.basename(item.absolute)).join('; '));
|
|
368
|
+
setCell(worksheet, rowNumber, errorShotCol, evidence.error.map((item) => path.basename(item.absolute)).join('; '));
|
|
369
|
+
}
|
|
366
370
|
writtenIds.push(id);
|
|
367
371
|
changed += 1;
|
|
368
372
|
}
|
|
@@ -402,10 +406,6 @@ export async function applyXlsxResults({
|
|
|
402
406
|
}
|
|
403
407
|
if (!xlsxCases.length) return { path: null, written: false, reason: '没有来自 xlsx 的用例' };
|
|
404
408
|
const target = outputXlsxPath({ config, date, outputPath, sourceFile: source });
|
|
405
|
-
if (dryRun) {
|
|
406
|
-
const count = xlsxCases.filter((item) => resultForCase(resultsByCase, item)).length;
|
|
407
|
-
return { path: target, written: false, dryRun: true, cases: count, shots: 0, sourceFile: source };
|
|
408
|
-
}
|
|
409
409
|
|
|
410
410
|
const mod = await import('exceljs');
|
|
411
411
|
const ExcelJS = mod.default || mod;
|
|
@@ -433,7 +433,7 @@ export async function applyXlsxResults({
|
|
|
433
433
|
for (const [sheetName, sheetCases] of bySheet) {
|
|
434
434
|
const worksheet = sheetName ? workbook.getWorksheet(sheetName) : fallbackSheet();
|
|
435
435
|
if (!worksheet) continue;
|
|
436
|
-
const applied = applySheetCases(config, worksheet, sheetCases, resultsByCase, { maxShotsPerCase });
|
|
436
|
+
const applied = applySheetCases(config, worksheet, sheetCases, resultsByCase, { maxShotsPerCase, dryRun });
|
|
437
437
|
if (!applied.headers) continue;
|
|
438
438
|
firstHeaders = firstHeaders || applied.headers;
|
|
439
439
|
changed += applied.changed;
|
|
@@ -441,6 +441,20 @@ export async function applyXlsxResults({
|
|
|
441
441
|
for (const [id, evidence] of applied.evidenceByName) evidenceByName.set(id, evidence);
|
|
442
442
|
sheets.push({ sheet: applied.sheet, cases: applied.changed });
|
|
443
443
|
}
|
|
444
|
+
// 预览也按真实工作表定位行:找不到工作表/表头的结果不能算进可回写条数。
|
|
445
|
+
if (dryRun) {
|
|
446
|
+
return {
|
|
447
|
+
path: target,
|
|
448
|
+
written: false,
|
|
449
|
+
dryRun: true,
|
|
450
|
+
cases: written.size,
|
|
451
|
+
writtenIds: [...written],
|
|
452
|
+
shots: 0,
|
|
453
|
+
sheet: sheets[0]?.sheet,
|
|
454
|
+
sheets,
|
|
455
|
+
sourceFile: source,
|
|
456
|
+
};
|
|
457
|
+
}
|
|
444
458
|
if (!sheets.length) throw new ConfigError(`xlsx 中没有可回填的工作表:${source}`);
|
|
445
459
|
// 摘要和截图只列真正写进用例表的行;找不到工作表或表头的用例不能出现在执行副本里。
|
|
446
460
|
const summaryCases = xlsxCases.filter((item) => written.has(String(item.tcId)));
|
|
@@ -533,6 +547,7 @@ export async function applyXlsxResults({
|
|
|
533
547
|
path: target,
|
|
534
548
|
written: true,
|
|
535
549
|
cases: changed,
|
|
550
|
+
writtenIds: [...written],
|
|
536
551
|
shots: shotsAdded,
|
|
537
552
|
sheet: sheets[0].sheet,
|
|
538
553
|
sheets,
|
package/lib/cases-import.mjs
CHANGED
|
@@ -6,7 +6,8 @@ import path from 'node:path';
|
|
|
6
6
|
|
|
7
7
|
import { UitestError, ensureDir, normalizeDocKey, nowIso, timeStamp, writeFileAtomic } from './util.mjs';
|
|
8
8
|
import { deriveTcId, listSheets, loadCases } from './xlsx.mjs';
|
|
9
|
-
import {
|
|
9
|
+
import { loadCsvCases } from './csv.mjs';
|
|
10
|
+
import { isMarkdownCaseId, loadMarkdownCases } from './cases-md.mjs';
|
|
10
11
|
|
|
11
12
|
export class CasesImportError extends UitestError {
|
|
12
13
|
constructor(message, { code = 'CASES_IMPORT_ERROR', detail = {} } = {}) {
|
|
@@ -17,7 +18,7 @@ export class CasesImportError extends UitestError {
|
|
|
17
18
|
|
|
18
19
|
const IMPORT_LIMIT_FILES = 50;
|
|
19
20
|
const IMPORT_LIMIT_BYTES = 50 * 1024 * 1024;
|
|
20
|
-
const
|
|
21
|
+
const TABLE_EXTS = new Set(['.xlsx', '.csv']);
|
|
21
22
|
const NON_CASE_SHEETS = /^(发行控制|结果汇总|测试计划)$/;
|
|
22
23
|
|
|
23
24
|
export const CASE_EDIT_FIELDS = [
|
|
@@ -670,7 +671,7 @@ function lstatOrNull(target) {
|
|
|
670
671
|
}
|
|
671
672
|
}
|
|
672
673
|
|
|
673
|
-
function
|
|
674
|
+
function scanTableDirectory(dir) {
|
|
674
675
|
const files = [];
|
|
675
676
|
let totalBytes = 0;
|
|
676
677
|
const walk = (current) => {
|
|
@@ -691,19 +692,19 @@ function scanXlsxDirectory(dir) {
|
|
|
691
692
|
walk(absolute);
|
|
692
693
|
continue;
|
|
693
694
|
}
|
|
694
|
-
if (!entry.isFile() || path.extname(entry.name).toLowerCase()
|
|
695
|
+
if (!entry.isFile() || !TABLE_EXTS.has(path.extname(entry.name).toLowerCase())) continue;
|
|
695
696
|
const stat = lstatOrNull(absolute);
|
|
696
697
|
if (!stat) continue;
|
|
697
698
|
totalBytes += stat.size;
|
|
698
699
|
files.push({ path: absolute, size: stat.size });
|
|
699
700
|
if (files.length > IMPORT_LIMIT_FILES) {
|
|
700
|
-
throw new CasesImportError(
|
|
701
|
+
throw new CasesImportError(`目录内表格文件超过上限(最多 ${IMPORT_LIMIT_FILES} 个)`, {
|
|
701
702
|
code: 'CASES_IMPORT_LIMIT',
|
|
702
703
|
detail: { dir, maxFiles: IMPORT_LIMIT_FILES },
|
|
703
704
|
});
|
|
704
705
|
}
|
|
705
706
|
if (totalBytes > IMPORT_LIMIT_BYTES) {
|
|
706
|
-
throw new CasesImportError('
|
|
707
|
+
throw new CasesImportError('目录内表格文件总大小超过 50MB 上限', {
|
|
707
708
|
code: 'CASES_IMPORT_LIMIT',
|
|
708
709
|
detail: { dir, maxBytes: IMPORT_LIMIT_BYTES },
|
|
709
710
|
});
|
|
@@ -721,10 +722,26 @@ function normalizeSheetCases(result, sheet, file) {
|
|
|
721
722
|
}));
|
|
722
723
|
}
|
|
723
724
|
|
|
724
|
-
/** 导入一个 xlsx;sheet 指定时只导该 sheet,否则逐 sheet 自动尝试。 */
|
|
725
|
-
function
|
|
725
|
+
/** 导入一个 xlsx 或 CSV;xlsx 的 sheet 指定时只导该 sheet,否则逐 sheet 自动尝试。 */
|
|
726
|
+
function parseTableFile(file, { sheet } = {}) {
|
|
726
727
|
const warnings = [];
|
|
727
728
|
const parsedSheets = [];
|
|
729
|
+
if (path.extname(file).toLowerCase() === '.csv') {
|
|
730
|
+
if (sheet) {
|
|
731
|
+
return { parsedSheets, warnings, fatal: new CasesImportError('CSV 不支持选择工作表:' + file, { code: 'CSV_NO_SHEET', detail: { file, sheet } }) };
|
|
732
|
+
}
|
|
733
|
+
try {
|
|
734
|
+
const loaded = loadCsvCases({ file });
|
|
735
|
+
if (!loaded.cases.length) {
|
|
736
|
+
warnings.push({ sheet: loaded.sheet, code: 'CSV_EMPTY', message: 'CSV 中没有用例' });
|
|
737
|
+
return { parsedSheets, warnings };
|
|
738
|
+
}
|
|
739
|
+
parsedSheets.push({ sheet: loaded.sheet, headerRow: loaded.headerRow, cases: loaded.cases });
|
|
740
|
+
return { parsedSheets, warnings };
|
|
741
|
+
} catch (err) {
|
|
742
|
+
return { parsedSheets, warnings, fatal: err };
|
|
743
|
+
}
|
|
744
|
+
}
|
|
728
745
|
if (sheet) {
|
|
729
746
|
try {
|
|
730
747
|
const loaded = loadCases({ file, sheet });
|
|
@@ -756,20 +773,20 @@ function parseWorkbookFile(file, { sheet } = {}) {
|
|
|
756
773
|
}
|
|
757
774
|
|
|
758
775
|
/**
|
|
759
|
-
* 导入 xlsx 用例(单文件或目录)。
|
|
776
|
+
* 导入 xlsx / CSV 用例(单文件或目录)。
|
|
760
777
|
* @returns {Promise<object>} 同步实现(保留 async 兼容 Host await)
|
|
761
778
|
*/
|
|
762
|
-
export function importCases(project, { file, files, dir, sheet, name, docKey = '', docName = '', mode = 'merge', replacesDocKeys = [] } = {}) {
|
|
779
|
+
export function importCases(project, { file, files, dir, sheet, name, docKey = '', docName = '', mode = 'merge', replacesDocKeys = [], requireMarkdownIds = false } = {}) {
|
|
763
780
|
const projectDir = typeof project === 'string' ? path.resolve(project) : project.projectDir;
|
|
764
781
|
const requested = file || dir || (Array.isArray(files) ? files[0] : undefined);
|
|
765
782
|
if (!requested && !Array.isArray(files)) {
|
|
766
|
-
throw new CasesImportError('cases import 需要 <xlsx|目录>', { code: 'PATH_NOT_FOUND' });
|
|
783
|
+
throw new CasesImportError('cases import 需要 <xlsx|csv|目录>', { code: 'PATH_NOT_FOUND' });
|
|
767
784
|
}
|
|
768
785
|
const sourcePath = path.resolve(projectDir, String(requested));
|
|
769
|
-
let
|
|
786
|
+
let tableFiles;
|
|
770
787
|
let isDirectory = false;
|
|
771
788
|
if (Array.isArray(files) && files.length) {
|
|
772
|
-
|
|
789
|
+
tableFiles = [];
|
|
773
790
|
let totalBytes = 0;
|
|
774
791
|
for (const item of files) {
|
|
775
792
|
const absolute = path.resolve(projectDir, String(item));
|
|
@@ -777,13 +794,13 @@ export function importCases(project, { file, files, dir, sheet, name, docKey = '
|
|
|
777
794
|
if (!stat || !stat.isFile()) {
|
|
778
795
|
throw new CasesImportError(`路径不存在:${absolute}`, { code: 'PATH_NOT_FOUND', detail: { path: absolute } });
|
|
779
796
|
}
|
|
780
|
-
if (path.extname(absolute).toLowerCase()
|
|
781
|
-
throw new CasesImportError(`不是 xlsx 文件:${absolute}`, { code: 'XLSX_NO_CASES', detail: { file: absolute } });
|
|
797
|
+
if (!TABLE_EXTS.has(path.extname(absolute).toLowerCase())) {
|
|
798
|
+
throw new CasesImportError(`不是 xlsx/CSV 文件:${absolute}`, { code: 'XLSX_NO_CASES', detail: { file: absolute } });
|
|
782
799
|
}
|
|
783
800
|
totalBytes += stat.size;
|
|
784
|
-
|
|
801
|
+
tableFiles.push(absolute);
|
|
785
802
|
}
|
|
786
|
-
if (
|
|
803
|
+
if (tableFiles.length > IMPORT_LIMIT_FILES || totalBytes > IMPORT_LIMIT_BYTES) {
|
|
787
804
|
throw new CasesImportError('files 超过 50 个 / 50MB 上限', { code: 'CASES_IMPORT_LIMIT' });
|
|
788
805
|
}
|
|
789
806
|
} else {
|
|
@@ -793,18 +810,18 @@ export function importCases(project, { file, files, dir, sheet, name, docKey = '
|
|
|
793
810
|
}
|
|
794
811
|
if (stat.isDirectory()) {
|
|
795
812
|
isDirectory = true;
|
|
796
|
-
|
|
797
|
-
if (!
|
|
798
|
-
throw new CasesImportError(`目录内没有 xlsx 文件:${sourcePath}`, {
|
|
813
|
+
tableFiles = scanTableDirectory(sourcePath).map((item) => item.path);
|
|
814
|
+
if (!tableFiles.length) {
|
|
815
|
+
throw new CasesImportError(`目录内没有 xlsx/CSV 文件:${sourcePath}`, {
|
|
799
816
|
code: 'XLSX_NO_CASES',
|
|
800
817
|
detail: { dir: sourcePath },
|
|
801
818
|
});
|
|
802
819
|
}
|
|
803
820
|
} else if (stat.isFile()) {
|
|
804
|
-
if (path.extname(sourcePath).toLowerCase()
|
|
805
|
-
throw new CasesImportError(`不是 xlsx 文件:${sourcePath}`, { code: 'XLSX_NO_CASES', detail: { file: sourcePath } });
|
|
821
|
+
if (!TABLE_EXTS.has(path.extname(sourcePath).toLowerCase())) {
|
|
822
|
+
throw new CasesImportError(`不是 xlsx/CSV 文件:${sourcePath}`, { code: 'XLSX_NO_CASES', detail: { file: sourcePath } });
|
|
806
823
|
}
|
|
807
|
-
|
|
824
|
+
tableFiles = [sourcePath];
|
|
808
825
|
} else {
|
|
809
826
|
throw new CasesImportError(`不是文件或目录:${sourcePath}`, { code: 'PATH_NOT_FOUND', detail: { path: sourcePath } });
|
|
810
827
|
}
|
|
@@ -812,7 +829,7 @@ export function importCases(project, { file, files, dir, sheet, name, docKey = '
|
|
|
812
829
|
|
|
813
830
|
const store = loadImportedCases(project);
|
|
814
831
|
const linkIndex = documentLinkIndex(readDocsIndex(projectDir), projectDir);
|
|
815
|
-
const casesById = new Map(store.cases.map((item) => [
|
|
832
|
+
const casesById = new Map(store.cases.map((item) => [caseKey(item.tcId), item]));
|
|
816
833
|
const seenBatch = new Set();
|
|
817
834
|
const imports = [];
|
|
818
835
|
const allWarnings = [];
|
|
@@ -823,15 +840,15 @@ export function importCases(project, { file, files, dir, sheet, name, docKey = '
|
|
|
823
840
|
let successfulFiles = 0;
|
|
824
841
|
const replaceKeys = new Set(replacesDocKeys.filter(Boolean));
|
|
825
842
|
|
|
826
|
-
for (const
|
|
843
|
+
for (const tableFile of tableFiles) {
|
|
827
844
|
const importId = newImportId();
|
|
828
845
|
const sourceName = name
|
|
829
|
-
?
|
|
846
|
+
? tableFiles.length === 1
|
|
830
847
|
? String(name)
|
|
831
|
-
: `${name}-${path.basename(
|
|
832
|
-
: path.basename(
|
|
848
|
+
: `${name}-${path.basename(tableFile, path.extname(tableFile))}`
|
|
849
|
+
: path.basename(tableFile, path.extname(tableFile));
|
|
833
850
|
const importRecord = {
|
|
834
|
-
file:
|
|
851
|
+
file: tableFile,
|
|
835
852
|
name: sourceName,
|
|
836
853
|
id: importId,
|
|
837
854
|
docKey: docKey || '',
|
|
@@ -846,15 +863,15 @@ export function importCases(project, { file, files, dir, sheet, name, docKey = '
|
|
|
846
863
|
};
|
|
847
864
|
let parsed;
|
|
848
865
|
try {
|
|
849
|
-
parsed =
|
|
866
|
+
parsed = parseTableFile(tableFile, { sheet });
|
|
850
867
|
} catch (err) {
|
|
851
868
|
parsed = { parsedSheets: [], warnings: [], fatal: err };
|
|
852
869
|
}
|
|
853
870
|
if (parsed.fatal) {
|
|
854
871
|
if (!isDirectory) {
|
|
855
|
-
throw new CasesImportError(
|
|
872
|
+
throw new CasesImportError(`表格解析失败:${tableFile}:${parsed.fatal.message}`, {
|
|
856
873
|
code: 'XLSX_NO_CASES',
|
|
857
|
-
detail: { file:
|
|
874
|
+
detail: { file: tableFile },
|
|
858
875
|
});
|
|
859
876
|
}
|
|
860
877
|
importRecord.warnings.push({ sheet: null, code: 'XLSX_FILE_SKIPPED', message: `文件解析失败,已跳过:${parsed.fatal.message}` });
|
|
@@ -865,33 +882,40 @@ export function importCases(project, { file, files, dir, sheet, name, docKey = '
|
|
|
865
882
|
}
|
|
866
883
|
for (const warning of parsed.warnings) {
|
|
867
884
|
importRecord.warnings.push(warning);
|
|
868
|
-
allWarnings.push({ file:
|
|
885
|
+
allWarnings.push({ file: tableFile, ...warning });
|
|
869
886
|
}
|
|
870
887
|
let fileCases = 0;
|
|
871
888
|
for (const parsedSheet of parsed.parsedSheets) {
|
|
872
889
|
const sheetStat = { sheet: parsedSheet.sheet, headerRow: parsedSheet.headerRow, added: 0, replaced: 0, skipped: 0, warnings: [] };
|
|
873
890
|
for (const rawCase of parsedSheet.cases) {
|
|
874
891
|
const tcId = String(rawCase.tcId || deriveTcId(rawCase));
|
|
892
|
+
if (requireMarkdownIds && !isMarkdownCaseId(tcId)) {
|
|
893
|
+
throw new CasesImportError('用例编号无法用于 Markdown 回写:' + tcId, {
|
|
894
|
+
code: 'IMPORT_BAD_CASE_ID',
|
|
895
|
+
detail: { file: tableFile, sheet: parsedSheet.sheet, id: tcId },
|
|
896
|
+
});
|
|
897
|
+
}
|
|
875
898
|
const caseItem = {
|
|
876
899
|
...rawCase,
|
|
877
900
|
tcId,
|
|
878
901
|
source: {
|
|
879
902
|
kind: 'import',
|
|
880
|
-
file:
|
|
903
|
+
file: tableFile,
|
|
881
904
|
sheet: parsedSheet.sheet,
|
|
882
905
|
importId,
|
|
883
906
|
...(docKey ? { docKey } : {}),
|
|
884
907
|
...(docName ? { docName } : {}),
|
|
885
908
|
},
|
|
886
909
|
};
|
|
887
|
-
|
|
910
|
+
const key = caseKey(tcId);
|
|
911
|
+
if (seenBatch.has(key)) {
|
|
888
912
|
sheetStat.skipped += 1;
|
|
889
913
|
totalSkipped += 1;
|
|
890
914
|
continue;
|
|
891
915
|
}
|
|
892
|
-
seenBatch.add(
|
|
893
|
-
if (casesById.has(
|
|
894
|
-
const existing = casesById.get(
|
|
916
|
+
seenBatch.add(key);
|
|
917
|
+
if (casesById.has(key)) {
|
|
918
|
+
const existing = casesById.get(key);
|
|
895
919
|
const linkedExisting = linkCaseToDocument(existing, linkIndex);
|
|
896
920
|
const existingDocKey = linkedExisting?.source?.docKey
|
|
897
921
|
|| existing?.source?.docKey
|
|
@@ -910,15 +934,15 @@ export function importCases(project, { file, files, dir, sheet, name, docKey = '
|
|
|
910
934
|
message: `用例编号 ${tcId} 已属于文档 ${existingDocKey},本次跳过;请改用唯一编号或先删除旧文档`,
|
|
911
935
|
};
|
|
912
936
|
importRecord.warnings.push(warning);
|
|
913
|
-
allWarnings.push({ file:
|
|
937
|
+
allWarnings.push({ file: tableFile, ...warning });
|
|
914
938
|
}
|
|
915
939
|
continue;
|
|
916
940
|
}
|
|
917
|
-
casesById.set(
|
|
941
|
+
casesById.set(key, caseItem);
|
|
918
942
|
sheetStat.replaced += 1;
|
|
919
943
|
totalReplaced += 1;
|
|
920
944
|
} else {
|
|
921
|
-
casesById.set(
|
|
945
|
+
casesById.set(key, caseItem);
|
|
922
946
|
sheetStat.added += 1;
|
|
923
947
|
totalAdded += 1;
|
|
924
948
|
}
|
|
@@ -935,7 +959,7 @@ export function importCases(project, { file, files, dir, sheet, name, docKey = '
|
|
|
935
959
|
store.sources.push({
|
|
936
960
|
id: importId,
|
|
937
961
|
name: sourceName,
|
|
938
|
-
file:
|
|
962
|
+
file: tableFile,
|
|
939
963
|
docKey: docKey || '',
|
|
940
964
|
docName: docName || sourceName,
|
|
941
965
|
mode: mode === 'overwrite' ? 'overwrite' : 'merge',
|
|
@@ -958,7 +982,7 @@ export function importCases(project, { file, files, dir, sheet, name, docKey = '
|
|
|
958
982
|
detail: { path: sourcePath, conflicts: totalConflicts, imports },
|
|
959
983
|
});
|
|
960
984
|
}
|
|
961
|
-
throw new CasesImportError(`没有可解析的 xlsx 用例:${sourcePath}`, {
|
|
985
|
+
throw new CasesImportError(`没有可解析的 xlsx/CSV 用例:${sourcePath}`, {
|
|
962
986
|
code: 'XLSX_NO_CASES',
|
|
963
987
|
detail: { path: sourcePath, imports },
|
|
964
988
|
});
|
package/lib/cases-md.mjs
CHANGED
|
@@ -10,6 +10,11 @@ const HEADING_RE = /^(#{2,4})\s+(\S+)\s*(.*)$/;
|
|
|
10
10
|
const TABLE_ROW_RE = /^\s*\|(.+)\|\s*$/;
|
|
11
11
|
const MD_MAX_FILES = 200;
|
|
12
12
|
|
|
13
|
+
/** 写入 case 文件前用它校验编号,保证导入结果能被同一个读取器读回。 */
|
|
14
|
+
export function isMarkdownCaseId(value) {
|
|
15
|
+
return CASE_ID_RE.test(String(value || ''));
|
|
16
|
+
}
|
|
17
|
+
|
|
13
18
|
const FIELD_ALIASES = new Map([
|
|
14
19
|
['优先级', 'priority'],
|
|
15
20
|
['前置', 'precondition'],
|