dsh-uitest 2.1.4 → 2.3.0
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 +45 -13
- package/bin/studio.mjs +117 -17
- package/bin/uitest.mjs +3 -3
- package/client.js +2583 -683
- package/index.js +90 -5
- package/lib/ab.mjs +17 -4
- package/lib/backfill.mjs +134 -61
- package/lib/browser-ab.mjs +3 -2
- package/lib/browser.mjs +1 -1
- package/lib/cases-import.mjs +198 -89
- package/lib/cases-md.mjs +5 -0
- package/lib/config.mjs +2 -2
- package/lib/csv.mjs +207 -0
- package/lib/knowledge-central.mjs +16 -0
- package/lib/xlsx.mjs +2 -1
- package/package.json +1 -1
- package/skills/uitest/SKILL.md +9 -4
- package/studio/documents.mjs +332 -0
- package/studio/host.mjs +141 -17
- package/studio/import.mjs +231 -38
- package/studio/model.mjs +3 -0
- package/studio/runner.mjs +55 -0
- package/studio/snapshot.mjs +28 -30
- package/studio/store.mjs +56 -1
- package/studio/writeback.mjs +299 -33
- package/templates/uitest.config.json +1 -1
package/studio/import.mjs
CHANGED
|
@@ -8,20 +8,26 @@ import path from 'node:path';
|
|
|
8
8
|
import {
|
|
9
9
|
clearCaseTombstones,
|
|
10
10
|
deleteCases,
|
|
11
|
+
docIdForKey,
|
|
11
12
|
importCases,
|
|
12
13
|
keepDocumentCases,
|
|
13
14
|
loadImportedCases,
|
|
14
15
|
loadProjectCases,
|
|
16
|
+
normalizeDocumentRecord,
|
|
15
17
|
rekeyDocumentCases,
|
|
16
18
|
removeDocumentCases,
|
|
17
19
|
removeDocumentOverrides,
|
|
18
20
|
} from '../lib/cases-import.mjs';
|
|
21
|
+
import { isMarkdownCaseId } from '../lib/cases-md.mjs';
|
|
19
22
|
import { UitestError, ensureDir, normalizeDocKey, nowIso, slug } from '../lib/util.mjs';
|
|
23
|
+
import { assertDocumentSourceAvailable, findDocument, saveDocumentRecord, updateDocumentRecord } from './documents.mjs';
|
|
20
24
|
import { dataNeedsFromText, normalizeStudioCase, splitNatural } from './model.mjs';
|
|
21
|
-
import { readDocs
|
|
25
|
+
import { readDocs } from './store.mjs';
|
|
26
|
+
import { acquireWritebackLock, writeDocumentResults } from './writeback.mjs';
|
|
22
27
|
|
|
23
28
|
const TEXT_EXT = new Set(['.md', '.markdown', '.txt']);
|
|
24
|
-
const
|
|
29
|
+
const CSV_EXT = new Set(['.csv']);
|
|
30
|
+
const TABLE_EXT = new Set(['.xlsx', '.csv']);
|
|
25
31
|
const JSON_EXT = new Set(['.json']);
|
|
26
32
|
const MAX_FILES = 200;
|
|
27
33
|
const MAX_BYTES = 20 * 1024 * 1024;
|
|
@@ -41,11 +47,6 @@ for (const [field, aliases] of Object.entries(FIELD_ALIASES)) {
|
|
|
41
47
|
for (const alias of aliases) ALIAS_LOOKUP.set(alias.toLowerCase(), field);
|
|
42
48
|
}
|
|
43
49
|
|
|
44
|
-
/** 文档对象 identity:名称归一化(大小写、空白、扩展名不敏感)。 */
|
|
45
|
-
function docIdForKey(docKey) {
|
|
46
|
-
return 'doc-' + crypto.createHash('sha1').update(String(docKey)).digest('hex').slice(0, 10);
|
|
47
|
-
}
|
|
48
|
-
|
|
49
50
|
/** 用例内容摘要:覆盖导入时用来区分「更新」与「未变」。来源路径不属于用例内容。 */
|
|
50
51
|
export function digestCase(caseItem) {
|
|
51
52
|
const remark = String(caseItem?.remark ?? '')
|
|
@@ -161,6 +162,32 @@ function guessIdFromHeading(heading) {
|
|
|
161
162
|
return '';
|
|
162
163
|
}
|
|
163
164
|
|
|
165
|
+
/**
|
|
166
|
+
* 把作者写的编号整理成 cases-md 能读回的形态。
|
|
167
|
+
* 统一大写、下划线转连字符、末段数字补足两位;无法安全修正时返回空串,由调用方生成编号。
|
|
168
|
+
*/
|
|
169
|
+
function normalizeCaseId(value) {
|
|
170
|
+
const raw = String(value || '').trim();
|
|
171
|
+
if (!raw) return '';
|
|
172
|
+
if (isMarkdownCaseId(raw)) return raw;
|
|
173
|
+
let token = raw.toUpperCase().replace(/[^A-Z0-9]+/g, '-').replace(/^-+|-+$/g, '');
|
|
174
|
+
if (!token) return '';
|
|
175
|
+
if (/^[0-9]/.test(token)) token = 'CASE-' + token;
|
|
176
|
+
if (isMarkdownCaseId(token)) return token;
|
|
177
|
+
const parts = token.split('-');
|
|
178
|
+
const last = parts[parts.length - 1];
|
|
179
|
+
if (/^\d$/.test(last)) {
|
|
180
|
+
parts[parts.length - 1] = '0' + last;
|
|
181
|
+
const padded = parts.join('-');
|
|
182
|
+
if (isMarkdownCaseId(padded)) return padded;
|
|
183
|
+
}
|
|
184
|
+
return '';
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
function idRenameWarning(from, to) {
|
|
188
|
+
return '用例编号 ' + from + ' 不能被用例库读取,已改为 ' + to;
|
|
189
|
+
}
|
|
190
|
+
|
|
164
191
|
function titleFromHeading(heading, id) {
|
|
165
192
|
let title = String(heading || '').trim();
|
|
166
193
|
if (id && title.startsWith(id)) title = title.slice(id.length).trim();
|
|
@@ -188,8 +215,10 @@ function docPrefix(name) {
|
|
|
188
215
|
const raw = String(name || 'CASE').toUpperCase();
|
|
189
216
|
const module = raw.match(/M\d+[A-Z]?/);
|
|
190
217
|
if (module) return module[0];
|
|
191
|
-
|
|
192
|
-
|
|
218
|
+
let token = raw.replace(/[^A-Z0-9]+/g, '-').replace(/^-+|-+$/g, '').split('-').slice(0, 2).join('-');
|
|
219
|
+
token = token.slice(0, 12).replace(/-+$/g, '');
|
|
220
|
+
if (!token) return 'CASE';
|
|
221
|
+
return /^[A-Z]/.test(token) ? token : 'CASE-' + token;
|
|
193
222
|
}
|
|
194
223
|
|
|
195
224
|
function ensureUniqueId(base, used) {
|
|
@@ -256,9 +285,11 @@ export function parseNaturalDocument(text, { name = 'CASE', sourcePath = '', use
|
|
|
256
285
|
seq += 1;
|
|
257
286
|
const fields = extractFields(lines, section.heading.index + 1, section.end);
|
|
258
287
|
const body = section.body;
|
|
259
|
-
const
|
|
288
|
+
const rawExplicitId = guessIdFromHeading(section.heading.text);
|
|
289
|
+
const explicitId = normalizeCaseId(rawExplicitId);
|
|
260
290
|
const baseId = explicitId || (prefix + '-' + String(seq).padStart(3, '0'));
|
|
261
291
|
const tcId = ensureUniqueId(baseId, usedIds);
|
|
292
|
+
if (rawExplicitId && rawExplicitId !== tcId) warnings.push(idRenameWarning(rawExplicitId, tcId));
|
|
262
293
|
let steps = fields.steps || [];
|
|
263
294
|
let expected = fields.expected || [];
|
|
264
295
|
if (!steps.length) {
|
|
@@ -282,7 +313,7 @@ export function parseNaturalDocument(text, { name = 'CASE', sourcePath = '', use
|
|
|
282
313
|
warnings.push('跳过无步骤/预期/前置的段落:' + oneLine(section.heading.text, 60));
|
|
283
314
|
continue;
|
|
284
315
|
}
|
|
285
|
-
const title = titleFromHeading(section.heading.text,
|
|
316
|
+
const title = titleFromHeading(section.heading.text, rawExplicitId) || oneLine(section.heading.text, 80) || tcId;
|
|
286
317
|
const remarkParts = [...(fields.remark || [])].filter((part) => !/^\s*来源[::]/.test(part));
|
|
287
318
|
if (sourcePath) remarkParts.push('来源:' + path.relative(projectDir || process.cwd(), sourcePath).split(path.sep).join('/'));
|
|
288
319
|
const caseItem = {
|
|
@@ -347,9 +378,14 @@ function jsonCases(raw, { name, sourcePath, usedIds, docKey = '', docName = '',
|
|
|
347
378
|
const list = Array.isArray(raw) ? raw : Array.isArray(raw?.cases) ? raw.cases : [];
|
|
348
379
|
const prefix = docPrefix(idPrefix || name);
|
|
349
380
|
const cases = [];
|
|
381
|
+
const warnings = [];
|
|
350
382
|
list.forEach((item, index) => {
|
|
351
383
|
if (!item || typeof item !== 'object' || Array.isArray(item)) return;
|
|
352
|
-
const
|
|
384
|
+
const rawId = String(item.tcId || item.id || '');
|
|
385
|
+
const explicitId = normalizeCaseId(rawId);
|
|
386
|
+
const baseId = explicitId || prefix + '-' + String(index + 1).padStart(3, '0');
|
|
387
|
+
const tcId = ensureUniqueId(baseId, usedIds);
|
|
388
|
+
if (rawId && rawId !== tcId) warnings.push(idRenameWarning(rawId, tcId));
|
|
353
389
|
cases.push({
|
|
354
390
|
seq: item.seq || tcId,
|
|
355
391
|
tcId,
|
|
@@ -367,7 +403,7 @@ function jsonCases(raw, { name, sourcePath, usedIds, docKey = '', docName = '',
|
|
|
367
403
|
source: { kind: 'studio-import', file: sourcePath, doc: name, ...(docKey ? { docKey, docName: docName || name } : {}) },
|
|
368
404
|
});
|
|
369
405
|
});
|
|
370
|
-
return cases;
|
|
406
|
+
return { cases, warnings };
|
|
371
407
|
}
|
|
372
408
|
|
|
373
409
|
function existingCaseIds(config, { excludeDoc = '', excludeFile = '', excludeDocKey = '', excludeDocKeys = [] } = {}) {
|
|
@@ -429,22 +465,16 @@ function sameFile(a, b) {
|
|
|
429
465
|
function findPreviousDoc(config, { docKey, sourcePath }) {
|
|
430
466
|
const store = readDocs(config);
|
|
431
467
|
const key = normalizeDocKey(docKey);
|
|
432
|
-
return (store.docs || []).find((item) => {
|
|
433
|
-
|
|
434
|
-
return itemKey === key || normalizeDocKey(item.name) === key || (sourcePath && item.sourcePath === sourcePath);
|
|
468
|
+
return (store.docs || []).map(normalizeDocumentRecord).find((item) => {
|
|
469
|
+
return item.docKey === key || normalizeDocKey(item.name) === key || (sourcePath && item.sourcePath === sourcePath);
|
|
435
470
|
}) || null;
|
|
436
471
|
}
|
|
437
472
|
|
|
438
|
-
function
|
|
439
|
-
|
|
440
|
-
const
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
return itemKey !== key && normalizeDocKey(item.name) !== key && item.sourcePath !== record.sourcePath;
|
|
444
|
-
});
|
|
445
|
-
docs.unshift({ ...record, docKey: key, id: record.id || docIdForKey(key) });
|
|
446
|
-
saveDocs(config, { ...store, version: 2, docs, updatedAt: nowIso() });
|
|
447
|
-
return docs[0];
|
|
473
|
+
function findTargetDoc(config, docId) {
|
|
474
|
+
if (!docId) return null;
|
|
475
|
+
const doc = findDocument(config, { docId });
|
|
476
|
+
if (!doc) throw new UitestError('文档不存在:' + docId, { code: 'DOC_NOT_FOUND', detail: { docId } });
|
|
477
|
+
return doc;
|
|
448
478
|
}
|
|
449
479
|
|
|
450
480
|
function digestsForCases(cases) {
|
|
@@ -512,16 +542,41 @@ function compactDiff(diff) {
|
|
|
512
542
|
};
|
|
513
543
|
}
|
|
514
544
|
|
|
545
|
+
const importQueues = new Map();
|
|
546
|
+
|
|
515
547
|
/**
|
|
516
548
|
* 导入一个文件或目录。
|
|
549
|
+
* 身份预检和随后的用例文件/用例库/注册表写入必须在同一临界区:并发导入都能通过预检时,
|
|
550
|
+
* 后失败者会在落库前已经改过文件与用例库。目录导入的递归走内部实现,避免自锁。
|
|
551
|
+
*/
|
|
552
|
+
export function importDocument(config, options = {}) {
|
|
553
|
+
const key = path.resolve(config.projectDir);
|
|
554
|
+
const previous = importQueues.get(key) || Promise.resolve();
|
|
555
|
+
const current = previous.then(() => importDocumentInner(config, options));
|
|
556
|
+
const stored = current.catch(() => {});
|
|
557
|
+
importQueues.set(key, stored);
|
|
558
|
+
stored.finally(() => {
|
|
559
|
+
if (importQueues.get(key) === stored) importQueues.delete(key);
|
|
560
|
+
});
|
|
561
|
+
return current;
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
/**
|
|
517
565
|
* mode=merge 保留文档中已移除的旧用例;mode=overwrite 以当前文档为准删除旧用例。
|
|
518
566
|
* @returns {Promise<{doc:object, docs:object[], cases:object[], warnings:object[], diff:object}>}
|
|
519
567
|
*/
|
|
520
|
-
|
|
568
|
+
async function importDocumentInner(config, { file, name = '', mode = 'merge', originalName = '', docId = '' } = {}) {
|
|
521
569
|
const sourcePath = path.resolve(config.projectDir, String(file || ''));
|
|
522
570
|
if (!fs.existsSync(sourcePath)) throw new UitestError('路径不存在:' + sourcePath, { code: 'IMPORT_PATH_NOT_FOUND' });
|
|
523
571
|
const stat = fs.statSync(sourcePath);
|
|
572
|
+
const explicitDoc = findTargetDoc(config, docId);
|
|
524
573
|
if (stat.isDirectory()) {
|
|
574
|
+
if (docId) {
|
|
575
|
+
throw new UitestError('重新关联源文件只接受单个文件:' + sourcePath, {
|
|
576
|
+
code: 'IMPORT_TARGET_MUST_BE_FILE',
|
|
577
|
+
detail: { docId },
|
|
578
|
+
});
|
|
579
|
+
}
|
|
525
580
|
const files = scanTextFiles(sourcePath);
|
|
526
581
|
if (!files.length) throw new UitestError('目录内没有 .md/.markdown/.txt 文件', { code: 'IMPORT_EMPTY_DIR' });
|
|
527
582
|
const docs = [];
|
|
@@ -530,7 +585,7 @@ export async function importDocument(config, { file, name = '', mode = 'merge',
|
|
|
530
585
|
const diff = { added: [], updated: [], unchanged: [], removed: [], missing: [], hidden: [] };
|
|
531
586
|
for (const item of files) {
|
|
532
587
|
try {
|
|
533
|
-
const result = await
|
|
588
|
+
const result = await importDocumentInner(config, {
|
|
534
589
|
file: item,
|
|
535
590
|
name: name ? name + '-' + path.basename(item, path.extname(item)) : '',
|
|
536
591
|
mode,
|
|
@@ -547,10 +602,10 @@ export async function importDocument(config, { file, name = '', mode = 'merge',
|
|
|
547
602
|
}
|
|
548
603
|
if (stat.size > MAX_BYTES) throw new UitestError('文件超过 20MB 上限:' + sourcePath, { code: 'IMPORT_TOO_LARGE' });
|
|
549
604
|
const ext = path.extname(sourcePath).toLowerCase();
|
|
550
|
-
const docName = name || path.basename(sourcePath, ext);
|
|
605
|
+
const docName = name || explicitDoc?.name || path.basename(sourcePath, ext);
|
|
551
606
|
const docKey = normalizeDocKey(docName) || normalizeDocKey(path.basename(sourcePath, ext)) || 'document';
|
|
552
607
|
const overwrite = mode === 'overwrite';
|
|
553
|
-
const previousDoc = findPreviousDoc(config, { docKey, sourcePath });
|
|
608
|
+
const previousDoc = explicitDoc || findPreviousDoc(config, { docKey, sourcePath });
|
|
554
609
|
const previousIds = Array.isArray(previousDoc?.caseIds) ? previousDoc.caseIds.map(String) : [];
|
|
555
610
|
const previousLibrary = new Map(loadProjectCases(config).cases.map((item) => [String(item.tcId), item]));
|
|
556
611
|
const previousDigests = { ...digestsForIds(config, previousIds, previousLibrary), ...(previousDoc?.digests || {}) };
|
|
@@ -559,13 +614,19 @@ export async function importDocument(config, { file, name = '', mode = 'merge',
|
|
|
559
614
|
const excludeDocKeys = [...new Set([docKey, ...previousDocKeys])];
|
|
560
615
|
// 改名时沿用旧文档名的编号前缀,避免自动编号随名称变化产生重复用例。
|
|
561
616
|
const idPrefix = previousDoc?.name || '';
|
|
617
|
+
// 身份冲突在写任何用例文件/用例库之前拦下:拒绝一次重新关联不能留下半次导入。
|
|
618
|
+
assertDocumentSourceAvailable(config, {
|
|
619
|
+
id: previousDoc?.id || docIdForKey(docKey),
|
|
620
|
+
docKey,
|
|
621
|
+
sourcePath,
|
|
622
|
+
});
|
|
562
623
|
|
|
563
624
|
let cases = [];
|
|
564
625
|
let warnings = [];
|
|
565
626
|
let generatedPath = '';
|
|
566
627
|
let importId = '';
|
|
567
628
|
|
|
568
|
-
if (
|
|
629
|
+
if (TABLE_EXT.has(ext)) {
|
|
569
630
|
const result = importCases(config.projectDir, {
|
|
570
631
|
file: sourcePath,
|
|
571
632
|
name: docName,
|
|
@@ -573,6 +634,7 @@ export async function importDocument(config, { file, name = '', mode = 'merge',
|
|
|
573
634
|
docName,
|
|
574
635
|
mode: overwrite ? 'overwrite' : 'merge',
|
|
575
636
|
replacesDocKeys: previousDocKeys,
|
|
637
|
+
requireMarkdownIds: CSV_EXT.has(ext),
|
|
576
638
|
});
|
|
577
639
|
importId = result.imports?.find((item) => item.id && item.count > 0)?.id || result.imports?.[0]?.id || '';
|
|
578
640
|
const loaded = loadProjectCases(config);
|
|
@@ -583,6 +645,12 @@ export async function importDocument(config, { file, name = '', mode = 'merge',
|
|
|
583
645
|
source: { ...item.source, docKey, docName },
|
|
584
646
|
}));
|
|
585
647
|
warnings = result.warnings || [];
|
|
648
|
+
if (CSV_EXT.has(ext)) {
|
|
649
|
+
// CSV 是导入来源,回写仍落在生成的 Markdown 用例文件上。
|
|
650
|
+
generatedPath = generatedFileFor(config, sourcePath, docName);
|
|
651
|
+
ensureDir(path.dirname(generatedPath));
|
|
652
|
+
fs.writeFileSync(generatedPath, renderCaseMarkdown(cases, { title: docName, sourcePath }) + '\n');
|
|
653
|
+
}
|
|
586
654
|
} else if (JSON_EXT.has(ext)) {
|
|
587
655
|
let raw;
|
|
588
656
|
try {
|
|
@@ -592,8 +660,10 @@ export async function importDocument(config, { file, name = '', mode = 'merge',
|
|
|
592
660
|
}
|
|
593
661
|
const target = generatedFileFor(config, sourcePath, docName);
|
|
594
662
|
const used = existingCaseIds(config, { excludeDoc: docName, excludeFile: target, excludeDocKey: docKey, excludeDocKeys });
|
|
595
|
-
|
|
596
|
-
if (!cases.length) throw new UitestError('JSON 中没有 cases 数组', { code: 'IMPORT_NO_CASES' });
|
|
663
|
+
const parsed = jsonCases(raw, { name: docName, sourcePath, usedIds: used, docKey, docName, idPrefix });
|
|
664
|
+
if (!parsed.cases.length) throw new UitestError('JSON 中没有 cases 数组', { code: 'IMPORT_NO_CASES' });
|
|
665
|
+
warnings = parsed.warnings;
|
|
666
|
+
cases = parsed.cases;
|
|
597
667
|
ensureDir(path.dirname(target));
|
|
598
668
|
fs.writeFileSync(target, renderCaseMarkdown(cases, { title: docName, sourcePath }) + '\n');
|
|
599
669
|
generatedPath = target;
|
|
@@ -617,7 +687,7 @@ export async function importDocument(config, { file, name = '', mode = 'merge',
|
|
|
617
687
|
generatedPath = sourcePath;
|
|
618
688
|
}
|
|
619
689
|
} else {
|
|
620
|
-
throw new UitestError('暂不支持该格式:' + ext + '(支持 .md/.markdown/.txt/.xlsx/.json)', { code: 'IMPORT_UNSUPPORTED' });
|
|
690
|
+
throw new UitestError('暂不支持该格式:' + ext + '(支持 .md/.markdown/.txt/.xlsx/.csv/.json)', { code: 'IMPORT_UNSUPPORTED' });
|
|
621
691
|
}
|
|
622
692
|
|
|
623
693
|
if (
|
|
@@ -632,6 +702,19 @@ export async function importDocument(config, { file, name = '', mode = 'merge',
|
|
|
632
702
|
}
|
|
633
703
|
|
|
634
704
|
const newIds = cases.map((item) => String(item.tcId));
|
|
705
|
+
// CSV 的回写目标是生成的 Markdown 镜像,编号必须和 Markdown 用例一样可被回写解析;
|
|
706
|
+
// 只有 xlsx 直接回写工作簿,不受这个限制。
|
|
707
|
+
if (ext !== '.xlsx') {
|
|
708
|
+
const badIds = newIds.filter((id) => !isMarkdownCaseId(id));
|
|
709
|
+
const loadable = new Set(loadProjectCases(config).cases.map((item) => String(item.tcId)));
|
|
710
|
+
const lostIds = newIds.filter((id) => !loadable.has(id));
|
|
711
|
+
if (badIds.length || lostIds.length) {
|
|
712
|
+
throw new UitestError('用例编号无法被用例库读回:' + [...new Set([...badIds, ...lostIds])].join('、'), {
|
|
713
|
+
code: 'IMPORT_BAD_CASE_ID',
|
|
714
|
+
detail: { ids: [...new Set([...badIds, ...lostIds])], badIds, lostIds },
|
|
715
|
+
});
|
|
716
|
+
}
|
|
717
|
+
}
|
|
635
718
|
|
|
636
719
|
clearCaseTombstones(config.projectDir, newIds);
|
|
637
720
|
// 同编号用例以文档为准:面板修改与合并保留的旧内容都让位给新文档。
|
|
@@ -687,15 +770,15 @@ export async function importDocument(config, { file, name = '', mode = 'merge',
|
|
|
687
770
|
}
|
|
688
771
|
|
|
689
772
|
const ownedIds = overwrite ? newIds : [...new Set([...previousIds, ...newIds])];
|
|
690
|
-
const doc =
|
|
773
|
+
const doc = await saveDocumentRecord(config, {
|
|
691
774
|
id: previousDoc?.id || docIdForKey(docKey),
|
|
692
775
|
docKey,
|
|
693
776
|
name: docName,
|
|
694
777
|
sourcePath,
|
|
695
778
|
originalName: originalName || previousDoc?.originalName || '',
|
|
696
779
|
generatedPath,
|
|
697
|
-
kind:
|
|
698
|
-
importedAt: nowIso(),
|
|
780
|
+
kind: TABLE_EXT.has(ext) ? (CSV_EXT.has(ext) ? 'csv' : 'xlsx') : JSON_EXT.has(ext) ? 'json' : 'markdown',
|
|
781
|
+
importedAt: previousDoc?.importedAt || nowIso(),
|
|
699
782
|
updatedAt: nowIso(),
|
|
700
783
|
count: ownedIds.length,
|
|
701
784
|
lastCount: newIds.length,
|
|
@@ -706,17 +789,126 @@ export async function importDocument(config, { file, name = '', mode = 'merge',
|
|
|
706
789
|
diff: compactDiff(diff),
|
|
707
790
|
digests: overwrite ? newDigests : { ...(previousDoc?.digests || {}), ...newDigests },
|
|
708
791
|
warnings: (warnings || []).slice(0, 5).map((item) => String(item?.message || item).slice(0, 240)),
|
|
792
|
+
lastRead: previousDoc?.lastRead || null,
|
|
793
|
+
writeback: previousDoc?.writeback || null,
|
|
794
|
+
}, {
|
|
795
|
+
// 导入字段算自导入前快照。锁内重读后版本按磁盘递增,并保留并发重新导读/回写的状态。
|
|
796
|
+
reconcile: (existing, input) => (existing
|
|
797
|
+
? {
|
|
798
|
+
...input,
|
|
799
|
+
version: (Number(existing.version) || 0) + 1,
|
|
800
|
+
lastRead: existing.lastRead ?? input.lastRead,
|
|
801
|
+
writeback: existing.writeback ?? input.writeback,
|
|
802
|
+
archived: existing.archived === true,
|
|
803
|
+
archivedAt: existing.archivedAt || '',
|
|
804
|
+
}
|
|
805
|
+
: input),
|
|
709
806
|
});
|
|
807
|
+
const stamped = cases.map((item) => ({
|
|
808
|
+
...item,
|
|
809
|
+
source: {
|
|
810
|
+
...item.source,
|
|
811
|
+
docId: doc.id,
|
|
812
|
+
docKey: doc.docKey,
|
|
813
|
+
docName: doc.name,
|
|
814
|
+
docKind: doc.kind,
|
|
815
|
+
},
|
|
816
|
+
}));
|
|
710
817
|
return {
|
|
711
818
|
doc,
|
|
712
819
|
docs: [doc],
|
|
713
|
-
cases:
|
|
820
|
+
cases: stamped.map((item) => normalizeStudioCase(item)),
|
|
714
821
|
warnings,
|
|
715
822
|
diff,
|
|
716
823
|
diffSummary: compactDiff(diff),
|
|
717
824
|
};
|
|
718
825
|
}
|
|
719
826
|
|
|
827
|
+
/**
|
|
828
|
+
* 重新导读:按文档 id 重读存储的源文件,保留文档身份;源文件缺失时不改任何状态。
|
|
829
|
+
* Markdown 重新生成用例文件后会尽力重放最近一次结果回写。
|
|
830
|
+
* 全程持有回写锁:重新导读会重写用例文件,不能和批次回写互相覆盖。
|
|
831
|
+
*/
|
|
832
|
+
export async function reReadDocument(config, { docId = '', mode = '', reapplyResults = true } = {}) {
|
|
833
|
+
const lock = await acquireWritebackLock(config);
|
|
834
|
+
try {
|
|
835
|
+
const doc = findTargetDoc(config, docId);
|
|
836
|
+
if (!doc) throw new UitestError('缺少文档 id', { code: 'DOC_NOT_FOUND', detail: { docId } });
|
|
837
|
+
const storedSource = String(doc.sourcePath || '');
|
|
838
|
+
const sourcePath = storedSource
|
|
839
|
+
? (path.isAbsolute(storedSource) ? path.resolve(storedSource) : path.resolve(config.projectDir, storedSource))
|
|
840
|
+
: '';
|
|
841
|
+
let sourceReady = false;
|
|
842
|
+
try {
|
|
843
|
+
sourceReady = Boolean(sourcePath) && fs.existsSync(sourcePath) && fs.statSync(sourcePath).isFile();
|
|
844
|
+
} catch {
|
|
845
|
+
sourceReady = false;
|
|
846
|
+
}
|
|
847
|
+
if (!sourceReady) {
|
|
848
|
+
throw new UitestError('文档源文件不存在:' + (sourcePath || '(未记录)'), {
|
|
849
|
+
code: 'DOC_SOURCE_MISSING',
|
|
850
|
+
detail: { docId: doc.id, path: sourcePath },
|
|
851
|
+
});
|
|
852
|
+
}
|
|
853
|
+
const imported = await importDocument(config, {
|
|
854
|
+
file: sourcePath,
|
|
855
|
+
name: doc.name,
|
|
856
|
+
mode: mode || doc.mode || 'merge',
|
|
857
|
+
originalName: doc.originalName || '',
|
|
858
|
+
docId: doc.id,
|
|
859
|
+
});
|
|
860
|
+
const lastRead = {
|
|
861
|
+
at: nowIso(),
|
|
862
|
+
version: imported.doc.version,
|
|
863
|
+
sourcePath,
|
|
864
|
+
diff: imported.diffSummary || null,
|
|
865
|
+
};
|
|
866
|
+
let nextDoc = await updateDocumentRecord(config, imported.doc.id, (current) => ({
|
|
867
|
+
...current,
|
|
868
|
+
lastRead,
|
|
869
|
+
updatedAt: lastRead.at,
|
|
870
|
+
}));
|
|
871
|
+
const warnings = [...(imported.warnings || [])];
|
|
872
|
+
let resultReapplied = false;
|
|
873
|
+
const recorded = imported.doc.writeback;
|
|
874
|
+
// 重新导读会重建用例文件,按每条用例的最新结果重放;只重放最后一次批次会丢掉更早批次的结果块。
|
|
875
|
+
if (reapplyResults && recorded && Number(recorded.results) > 0 && imported.doc.kind !== 'xlsx') {
|
|
876
|
+
const survivingIds = loadProjectCases(config).cases
|
|
877
|
+
.filter((item) => (item.docId || item.source?.docId) === imported.doc.id)
|
|
878
|
+
.map((item) => String(item.tcId));
|
|
879
|
+
try {
|
|
880
|
+
const reapplied = await writeDocumentResults(config, {
|
|
881
|
+
docId: imported.doc.id,
|
|
882
|
+
caseIds: survivingIds,
|
|
883
|
+
});
|
|
884
|
+
if (reapplied.writeback) {
|
|
885
|
+
resultReapplied = true;
|
|
886
|
+
nextDoc = findDocument(config, { docId: imported.doc.id }) || nextDoc;
|
|
887
|
+
} else {
|
|
888
|
+
warnings.push({
|
|
889
|
+
code: 'WRITEBACK_REAPPLY_SKIPPED',
|
|
890
|
+
message: '最近一次回写的结果已不存在,用例文件已重新导读但未带回结果块',
|
|
891
|
+
});
|
|
892
|
+
}
|
|
893
|
+
} catch (error) {
|
|
894
|
+
warnings.push({
|
|
895
|
+
code: 'WRITEBACK_REAPPLY_FAILED',
|
|
896
|
+
message: '重新回写最近结果失败,用例文件已重新导读:' + String(error.message || error),
|
|
897
|
+
});
|
|
898
|
+
}
|
|
899
|
+
}
|
|
900
|
+
return {
|
|
901
|
+
...imported,
|
|
902
|
+
doc: nextDoc,
|
|
903
|
+
docs: [nextDoc],
|
|
904
|
+
warnings,
|
|
905
|
+
resultReapplied,
|
|
906
|
+
};
|
|
907
|
+
} finally {
|
|
908
|
+
lock.release();
|
|
909
|
+
}
|
|
910
|
+
}
|
|
911
|
+
|
|
720
912
|
/** 从当前用例库读取统一形态;用于 UI 与批次。 */
|
|
721
913
|
export function loadStudioCases(config, { flows = [] } = {}) {
|
|
722
914
|
const loaded = loadProjectCases(config);
|
|
@@ -743,6 +935,7 @@ export function loadStudioCases(config, { flows = [] } = {}) {
|
|
|
743
935
|
})),
|
|
744
936
|
summary: loaded.summary,
|
|
745
937
|
warnings: loaded.warnings,
|
|
938
|
+
deletedCaseIds: loaded.deletedCaseIds || [],
|
|
746
939
|
counts: {
|
|
747
940
|
config: loaded.configCount,
|
|
748
941
|
markdown: loaded.markdownCount,
|
package/studio/model.mjs
CHANGED
|
@@ -150,6 +150,9 @@ export function normalizeStudioCase(caseItem, { flow = null, preconditionFlows =
|
|
|
150
150
|
expected: String(caseItem?.expected || ''),
|
|
151
151
|
remark: String(caseItem?.remark || ''),
|
|
152
152
|
source: caseItem?.source || null,
|
|
153
|
+
docId: String(caseItem?.docId || caseItem?.source?.docId || ''),
|
|
154
|
+
docName: String(caseItem?.docName || caseItem?.source?.docName || ''),
|
|
155
|
+
docKind: String(caseItem?.docKind || caseItem?.source?.docKind || ''),
|
|
153
156
|
mode: inferCaseMode(caseItem, { hasFlow: Boolean(flow) }),
|
|
154
157
|
flow: flow
|
|
155
158
|
? {
|
package/studio/runner.mjs
CHANGED
|
@@ -1350,6 +1350,61 @@ export async function requeueCase({ config, batchId, caseId, panel, planItem })
|
|
|
1350
1350
|
});
|
|
1351
1351
|
}
|
|
1352
1352
|
|
|
1353
|
+
/** 停止后的批次继续执行:只重排没有终态判定的用例,已判定结果保留。 */
|
|
1354
|
+
export async function resumeBatch({ config, batchId, panel }) {
|
|
1355
|
+
const now = nowIso();
|
|
1356
|
+
return withBatchLock(batchId, () => {
|
|
1357
|
+
const current = readBatch(config, batchId);
|
|
1358
|
+
if (['running', 'preparing', 'queued'].includes(String(current.status || '')) || panel?.studioAborts?.has(batchId)) {
|
|
1359
|
+
throw new UitestError('批次正在执行,不能继续执行', { code: 'BATCH_ACTIVE', detail: { batchId } });
|
|
1360
|
+
}
|
|
1361
|
+
if (current.status !== 'stopped') {
|
|
1362
|
+
throw new UitestError('只有已停止的批次可以继续执行', { code: 'BATCH_NOT_STOPPED', detail: { batchId, status: current.status } });
|
|
1363
|
+
}
|
|
1364
|
+
const runs = readCaseRuns(config, batchId);
|
|
1365
|
+
const byId = new Map(mergeBatchRuns(current, runs).map((run) => [String(run.caseId), run]));
|
|
1366
|
+
let queue = queueForBatch(current, runs);
|
|
1367
|
+
const resumedIds = [];
|
|
1368
|
+
for (const item of current.plan?.items || []) {
|
|
1369
|
+
if (item.mode !== 'flow' && item.mode !== 'agent') continue;
|
|
1370
|
+
const caseId = String(item.caseId);
|
|
1371
|
+
const entry = queue.entries[caseId];
|
|
1372
|
+
const run = byId.get(caseId);
|
|
1373
|
+
// 已判定的用例不重跑;停止时还没跑完的入口重新排队,保留历史结果。
|
|
1374
|
+
// 判定结果先落盘、队列项后置 done,崩溃或非活跃停止会留下 stopped 入口,不能只看 entry.state。
|
|
1375
|
+
if (run && ['passed', 'partial', 'failed', 'blocked'].includes(run.status)) continue;
|
|
1376
|
+
if (entry?.state === 'queued') {
|
|
1377
|
+
resumedIds.push(caseId);
|
|
1378
|
+
continue;
|
|
1379
|
+
}
|
|
1380
|
+
if (entry?.state === 'running') queue = finishEntry(queue, caseId, 'stopped', now).queue;
|
|
1381
|
+
const next = enqueue(queue, caseId, now);
|
|
1382
|
+
queue = next.queue;
|
|
1383
|
+
if (next.added) resumedIds.push(caseId);
|
|
1384
|
+
}
|
|
1385
|
+
if (!resumedIds.length) {
|
|
1386
|
+
throw new UitestError('没有需要继续执行的用例', { code: 'NOTHING_TO_RESUME', detail: { batchId } });
|
|
1387
|
+
}
|
|
1388
|
+
const next = {
|
|
1389
|
+
...current,
|
|
1390
|
+
queue,
|
|
1391
|
+
status: 'queued',
|
|
1392
|
+
stage: 'execute',
|
|
1393
|
+
stages: {
|
|
1394
|
+
...(current.stages || {}),
|
|
1395
|
+
execute: { status: 'pending', at: null, startedAt: null, endedAt: null, error: null },
|
|
1396
|
+
},
|
|
1397
|
+
endedAt: null,
|
|
1398
|
+
stopRequested: false,
|
|
1399
|
+
error: null,
|
|
1400
|
+
updatedAt: now,
|
|
1401
|
+
};
|
|
1402
|
+
next.summary = summarizeCaseRuns(mergeBatchRuns(next, runs));
|
|
1403
|
+
saveBatch(config, next);
|
|
1404
|
+
return { batch: next, resumed: resumedIds.length };
|
|
1405
|
+
});
|
|
1406
|
+
}
|
|
1407
|
+
|
|
1353
1408
|
export async function requestCaseStopInBatch({ config, batchId, caseId, panel }) {
|
|
1354
1409
|
const id = String(caseId || '');
|
|
1355
1410
|
await withBatchLock(batchId, () => {
|
package/studio/snapshot.mjs
CHANGED
|
@@ -9,7 +9,8 @@ import { readFlows } from '../host/state.mjs';
|
|
|
9
9
|
import { loadStudioCases } from './import.mjs';
|
|
10
10
|
import { knowledgeSnapshot } from './knowledge.mjs';
|
|
11
11
|
import { readRunFeedbacks } from '../lib/run-feedback.mjs';
|
|
12
|
-
import { listBatches, mergeBatchRuns, readCaseRuns
|
|
12
|
+
import { listBatches, mergeBatchRuns, readCaseRuns } from './store.mjs';
|
|
13
|
+
import { documentRegistry, documentView } from './documents.mjs';
|
|
13
14
|
import { accountsPayload } from './accounts.mjs';
|
|
14
15
|
import { statusFromRun } from './model.mjs';
|
|
15
16
|
|
|
@@ -127,7 +128,8 @@ export function buildStudioSnapshot(config, { caseLimit = 400, batchLimit = 30 }
|
|
|
127
128
|
const activeRuns = active ? mergeBatchRuns(active, readCaseRuns(config, active.id)) : [];
|
|
128
129
|
const activeById = new Map(activeRuns.map((run) => [String(run.caseId), run]));
|
|
129
130
|
|
|
130
|
-
|
|
131
|
+
// 文档视图和用例行共用完整用例库的状态:先切片会让文档汇总漏掉真实结果。
|
|
132
|
+
const enriched = studio.cases.map((item) => {
|
|
131
133
|
const result = latest.get(String(item.tcId));
|
|
132
134
|
const activeRun = activeById.get(String(item.tcId));
|
|
133
135
|
const runKnowledge = knowledgeByCase.get(String(item.tcId)) || null;
|
|
@@ -178,41 +180,34 @@ export function buildStudioSnapshot(config, { caseLimit = 400, batchLimit = 30 }
|
|
|
178
180
|
lastFeedback: feedbackByCase.get(String(item.tcId)) || null,
|
|
179
181
|
};
|
|
180
182
|
});
|
|
181
|
-
|
|
183
|
+
const cases = enriched.slice(0, caseLimit);
|
|
184
|
+
// 文档视图与状态统计必须基于完整用例库计算,先切片会让文档看起来缺用例。
|
|
185
|
+
const docRegistry = documentRegistry(config);
|
|
186
|
+
const docRecords = docRegistry.docs;
|
|
187
|
+
const docIds = new Set(docRecords.map((doc) => doc.id));
|
|
188
|
+
const docs = docRecords.map((doc) => documentView(config, doc, enriched, {
|
|
189
|
+
deletedCaseIds: studio.deletedCaseIds || [],
|
|
190
|
+
}));
|
|
191
|
+
const statusCounts = { passed: 0, partial: 0, failed: 0, blocked: 0, queued: 0, running: 0, stopped: 0, untested: 0 };
|
|
192
|
+
for (const item of enriched) {
|
|
193
|
+
const status = String(item?.status || '');
|
|
194
|
+
const key = Object.hasOwn(statusCounts, status) ? status : 'untested';
|
|
195
|
+
statusCounts[key] += 1;
|
|
196
|
+
}
|
|
182
197
|
const counts = {
|
|
183
198
|
total: studio.cases.length,
|
|
184
199
|
flow: studio.cases.filter((item) => item.mode === 'flow').length,
|
|
185
200
|
agent: studio.cases.filter((item) => item.mode === 'agent').length,
|
|
186
201
|
manual: studio.cases.filter((item) => item.mode === 'manual').length,
|
|
187
|
-
|
|
188
|
-
failed: cases.filter((item) => item.status === 'failed').length,
|
|
189
|
-
blocked: cases.filter((item) => item.status === 'blocked').length,
|
|
190
|
-
untested: cases.filter((item) => item.status === 'untested').length,
|
|
191
|
-
running: cases.filter((item) => item.status === 'running').length,
|
|
202
|
+
...statusCounts,
|
|
192
203
|
feedback: feedbackByCase.size,
|
|
204
|
+
unassigned: enriched.filter((item) => !docIds.has(String(item.docId || item.source?.docId || ''))).length,
|
|
205
|
+
archivedDocs: docs.filter((doc) => doc.archived).length,
|
|
193
206
|
};
|
|
194
207
|
const knowledge = knowledgeSnapshot(config, { limit: 100 });
|
|
195
|
-
const
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
const visibleCount = caseIds.length ? caseIds.filter((id) => visibleIds.has(String(id))).length : (Number(doc.count) || 0);
|
|
199
|
-
return {
|
|
200
|
-
id: doc.id,
|
|
201
|
-
docKey: doc.docKey || '',
|
|
202
|
-
name: doc.name || '',
|
|
203
|
-
sourcePath: doc.sourcePath || '',
|
|
204
|
-
generatedPath: doc.generatedPath || '',
|
|
205
|
-
kind: doc.kind || '',
|
|
206
|
-
count: visibleCount,
|
|
207
|
-
importedCount: Number(doc.count) || caseIds.length,
|
|
208
|
-
lastCount: doc.lastCount ?? caseIds.length,
|
|
209
|
-
version: doc.version || 1,
|
|
210
|
-
mode: doc.mode || 'merge',
|
|
211
|
-
importedAt: doc.importedAt || '',
|
|
212
|
-
updatedAt: doc.updatedAt || doc.importedAt || '',
|
|
213
|
-
diff: doc.diff || null,
|
|
214
|
-
};
|
|
215
|
-
});
|
|
208
|
+
const docsWarning = docRegistry.invalid
|
|
209
|
+
? '文档注册表损坏,文档写入已暂停:' + docRegistry.file + '(' + (docRegistry.error || '无法解析') + ')'
|
|
210
|
+
: '';
|
|
216
211
|
return {
|
|
217
212
|
project: config.projectDir,
|
|
218
213
|
capabilities: { importUpload: true, accountsImport: true, caseDelete: true, export: true },
|
|
@@ -246,9 +241,12 @@ export function buildStudioSnapshot(config, { caseLimit = 400, batchLimit = 30 }
|
|
|
246
241
|
batches: batches.map((batch) => batchSummary(batch, batch.status === 'running' ? readCaseRuns(config, batch.id) : [])),
|
|
247
242
|
activeBatch: active ? batchSummary(active, activeRuns) : null,
|
|
248
243
|
docs,
|
|
244
|
+
docsError: docRegistry.invalid
|
|
245
|
+
? { code: 'DOCS_INVALID', file: docRegistry.file, message: docsWarning }
|
|
246
|
+
: null,
|
|
249
247
|
accounts: accountsPayload(config),
|
|
250
248
|
knowledge,
|
|
251
|
-
warnings: [...(studio.warnings || []), ...(flowResult.errors || [])].slice(0, 30),
|
|
249
|
+
warnings: [docsWarning, ...(studio.warnings || []), ...(flowResult.errors || [])].filter(Boolean).slice(0, 30),
|
|
252
250
|
};
|
|
253
251
|
}
|
|
254
252
|
|