dsh-uitest 2.2.0 → 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 +30 -9
- package/bin/studio.mjs +117 -17
- package/bin/uitest.mjs +3 -3
- package/client.js +888 -177
- 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/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 +103 -14
- package/studio/import.mjs +115 -21
- 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/studio/import.mjs
CHANGED
|
@@ -18,14 +18,16 @@ import {
|
|
|
18
18
|
removeDocumentCases,
|
|
19
19
|
removeDocumentOverrides,
|
|
20
20
|
} from '../lib/cases-import.mjs';
|
|
21
|
+
import { isMarkdownCaseId } from '../lib/cases-md.mjs';
|
|
21
22
|
import { UitestError, ensureDir, normalizeDocKey, nowIso, slug } from '../lib/util.mjs';
|
|
22
|
-
import { findDocument, saveDocumentRecord, updateDocumentRecord } from './documents.mjs';
|
|
23
|
+
import { assertDocumentSourceAvailable, findDocument, saveDocumentRecord, updateDocumentRecord } from './documents.mjs';
|
|
23
24
|
import { dataNeedsFromText, normalizeStudioCase, splitNatural } from './model.mjs';
|
|
24
25
|
import { readDocs } from './store.mjs';
|
|
25
26
|
import { acquireWritebackLock, writeDocumentResults } from './writeback.mjs';
|
|
26
27
|
|
|
27
28
|
const TEXT_EXT = new Set(['.md', '.markdown', '.txt']);
|
|
28
|
-
const
|
|
29
|
+
const CSV_EXT = new Set(['.csv']);
|
|
30
|
+
const TABLE_EXT = new Set(['.xlsx', '.csv']);
|
|
29
31
|
const JSON_EXT = new Set(['.json']);
|
|
30
32
|
const MAX_FILES = 200;
|
|
31
33
|
const MAX_BYTES = 20 * 1024 * 1024;
|
|
@@ -160,6 +162,32 @@ function guessIdFromHeading(heading) {
|
|
|
160
162
|
return '';
|
|
161
163
|
}
|
|
162
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
|
+
|
|
163
191
|
function titleFromHeading(heading, id) {
|
|
164
192
|
let title = String(heading || '').trim();
|
|
165
193
|
if (id && title.startsWith(id)) title = title.slice(id.length).trim();
|
|
@@ -187,8 +215,10 @@ function docPrefix(name) {
|
|
|
187
215
|
const raw = String(name || 'CASE').toUpperCase();
|
|
188
216
|
const module = raw.match(/M\d+[A-Z]?/);
|
|
189
217
|
if (module) return module[0];
|
|
190
|
-
|
|
191
|
-
|
|
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;
|
|
192
222
|
}
|
|
193
223
|
|
|
194
224
|
function ensureUniqueId(base, used) {
|
|
@@ -255,9 +285,11 @@ export function parseNaturalDocument(text, { name = 'CASE', sourcePath = '', use
|
|
|
255
285
|
seq += 1;
|
|
256
286
|
const fields = extractFields(lines, section.heading.index + 1, section.end);
|
|
257
287
|
const body = section.body;
|
|
258
|
-
const
|
|
288
|
+
const rawExplicitId = guessIdFromHeading(section.heading.text);
|
|
289
|
+
const explicitId = normalizeCaseId(rawExplicitId);
|
|
259
290
|
const baseId = explicitId || (prefix + '-' + String(seq).padStart(3, '0'));
|
|
260
291
|
const tcId = ensureUniqueId(baseId, usedIds);
|
|
292
|
+
if (rawExplicitId && rawExplicitId !== tcId) warnings.push(idRenameWarning(rawExplicitId, tcId));
|
|
261
293
|
let steps = fields.steps || [];
|
|
262
294
|
let expected = fields.expected || [];
|
|
263
295
|
if (!steps.length) {
|
|
@@ -281,7 +313,7 @@ export function parseNaturalDocument(text, { name = 'CASE', sourcePath = '', use
|
|
|
281
313
|
warnings.push('跳过无步骤/预期/前置的段落:' + oneLine(section.heading.text, 60));
|
|
282
314
|
continue;
|
|
283
315
|
}
|
|
284
|
-
const title = titleFromHeading(section.heading.text,
|
|
316
|
+
const title = titleFromHeading(section.heading.text, rawExplicitId) || oneLine(section.heading.text, 80) || tcId;
|
|
285
317
|
const remarkParts = [...(fields.remark || [])].filter((part) => !/^\s*来源[::]/.test(part));
|
|
286
318
|
if (sourcePath) remarkParts.push('来源:' + path.relative(projectDir || process.cwd(), sourcePath).split(path.sep).join('/'));
|
|
287
319
|
const caseItem = {
|
|
@@ -346,9 +378,14 @@ function jsonCases(raw, { name, sourcePath, usedIds, docKey = '', docName = '',
|
|
|
346
378
|
const list = Array.isArray(raw) ? raw : Array.isArray(raw?.cases) ? raw.cases : [];
|
|
347
379
|
const prefix = docPrefix(idPrefix || name);
|
|
348
380
|
const cases = [];
|
|
381
|
+
const warnings = [];
|
|
349
382
|
list.forEach((item, index) => {
|
|
350
383
|
if (!item || typeof item !== 'object' || Array.isArray(item)) return;
|
|
351
|
-
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));
|
|
352
389
|
cases.push({
|
|
353
390
|
seq: item.seq || tcId,
|
|
354
391
|
tcId,
|
|
@@ -366,7 +403,7 @@ function jsonCases(raw, { name, sourcePath, usedIds, docKey = '', docName = '',
|
|
|
366
403
|
source: { kind: 'studio-import', file: sourcePath, doc: name, ...(docKey ? { docKey, docName: docName || name } : {}) },
|
|
367
404
|
});
|
|
368
405
|
});
|
|
369
|
-
return cases;
|
|
406
|
+
return { cases, warnings };
|
|
370
407
|
}
|
|
371
408
|
|
|
372
409
|
function existingCaseIds(config, { excludeDoc = '', excludeFile = '', excludeDocKey = '', excludeDocKeys = [] } = {}) {
|
|
@@ -505,16 +542,41 @@ function compactDiff(diff) {
|
|
|
505
542
|
};
|
|
506
543
|
}
|
|
507
544
|
|
|
545
|
+
const importQueues = new Map();
|
|
546
|
+
|
|
508
547
|
/**
|
|
509
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
|
+
/**
|
|
510
565
|
* mode=merge 保留文档中已移除的旧用例;mode=overwrite 以当前文档为准删除旧用例。
|
|
511
566
|
* @returns {Promise<{doc:object, docs:object[], cases:object[], warnings:object[], diff:object}>}
|
|
512
567
|
*/
|
|
513
|
-
|
|
568
|
+
async function importDocumentInner(config, { file, name = '', mode = 'merge', originalName = '', docId = '' } = {}) {
|
|
514
569
|
const sourcePath = path.resolve(config.projectDir, String(file || ''));
|
|
515
570
|
if (!fs.existsSync(sourcePath)) throw new UitestError('路径不存在:' + sourcePath, { code: 'IMPORT_PATH_NOT_FOUND' });
|
|
516
571
|
const stat = fs.statSync(sourcePath);
|
|
572
|
+
const explicitDoc = findTargetDoc(config, docId);
|
|
517
573
|
if (stat.isDirectory()) {
|
|
574
|
+
if (docId) {
|
|
575
|
+
throw new UitestError('重新关联源文件只接受单个文件:' + sourcePath, {
|
|
576
|
+
code: 'IMPORT_TARGET_MUST_BE_FILE',
|
|
577
|
+
detail: { docId },
|
|
578
|
+
});
|
|
579
|
+
}
|
|
518
580
|
const files = scanTextFiles(sourcePath);
|
|
519
581
|
if (!files.length) throw new UitestError('目录内没有 .md/.markdown/.txt 文件', { code: 'IMPORT_EMPTY_DIR' });
|
|
520
582
|
const docs = [];
|
|
@@ -523,7 +585,7 @@ export async function importDocument(config, { file, name = '', mode = 'merge',
|
|
|
523
585
|
const diff = { added: [], updated: [], unchanged: [], removed: [], missing: [], hidden: [] };
|
|
524
586
|
for (const item of files) {
|
|
525
587
|
try {
|
|
526
|
-
const result = await
|
|
588
|
+
const result = await importDocumentInner(config, {
|
|
527
589
|
file: item,
|
|
528
590
|
name: name ? name + '-' + path.basename(item, path.extname(item)) : '',
|
|
529
591
|
mode,
|
|
@@ -540,7 +602,6 @@ export async function importDocument(config, { file, name = '', mode = 'merge',
|
|
|
540
602
|
}
|
|
541
603
|
if (stat.size > MAX_BYTES) throw new UitestError('文件超过 20MB 上限:' + sourcePath, { code: 'IMPORT_TOO_LARGE' });
|
|
542
604
|
const ext = path.extname(sourcePath).toLowerCase();
|
|
543
|
-
const explicitDoc = findTargetDoc(config, docId);
|
|
544
605
|
const docName = name || explicitDoc?.name || path.basename(sourcePath, ext);
|
|
545
606
|
const docKey = normalizeDocKey(docName) || normalizeDocKey(path.basename(sourcePath, ext)) || 'document';
|
|
546
607
|
const overwrite = mode === 'overwrite';
|
|
@@ -553,13 +614,19 @@ export async function importDocument(config, { file, name = '', mode = 'merge',
|
|
|
553
614
|
const excludeDocKeys = [...new Set([docKey, ...previousDocKeys])];
|
|
554
615
|
// 改名时沿用旧文档名的编号前缀,避免自动编号随名称变化产生重复用例。
|
|
555
616
|
const idPrefix = previousDoc?.name || '';
|
|
617
|
+
// 身份冲突在写任何用例文件/用例库之前拦下:拒绝一次重新关联不能留下半次导入。
|
|
618
|
+
assertDocumentSourceAvailable(config, {
|
|
619
|
+
id: previousDoc?.id || docIdForKey(docKey),
|
|
620
|
+
docKey,
|
|
621
|
+
sourcePath,
|
|
622
|
+
});
|
|
556
623
|
|
|
557
624
|
let cases = [];
|
|
558
625
|
let warnings = [];
|
|
559
626
|
let generatedPath = '';
|
|
560
627
|
let importId = '';
|
|
561
628
|
|
|
562
|
-
if (
|
|
629
|
+
if (TABLE_EXT.has(ext)) {
|
|
563
630
|
const result = importCases(config.projectDir, {
|
|
564
631
|
file: sourcePath,
|
|
565
632
|
name: docName,
|
|
@@ -567,6 +634,7 @@ export async function importDocument(config, { file, name = '', mode = 'merge',
|
|
|
567
634
|
docName,
|
|
568
635
|
mode: overwrite ? 'overwrite' : 'merge',
|
|
569
636
|
replacesDocKeys: previousDocKeys,
|
|
637
|
+
requireMarkdownIds: CSV_EXT.has(ext),
|
|
570
638
|
});
|
|
571
639
|
importId = result.imports?.find((item) => item.id && item.count > 0)?.id || result.imports?.[0]?.id || '';
|
|
572
640
|
const loaded = loadProjectCases(config);
|
|
@@ -577,6 +645,12 @@ export async function importDocument(config, { file, name = '', mode = 'merge',
|
|
|
577
645
|
source: { ...item.source, docKey, docName },
|
|
578
646
|
}));
|
|
579
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
|
+
}
|
|
580
654
|
} else if (JSON_EXT.has(ext)) {
|
|
581
655
|
let raw;
|
|
582
656
|
try {
|
|
@@ -586,8 +660,10 @@ export async function importDocument(config, { file, name = '', mode = 'merge',
|
|
|
586
660
|
}
|
|
587
661
|
const target = generatedFileFor(config, sourcePath, docName);
|
|
588
662
|
const used = existingCaseIds(config, { excludeDoc: docName, excludeFile: target, excludeDocKey: docKey, excludeDocKeys });
|
|
589
|
-
|
|
590
|
-
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;
|
|
591
667
|
ensureDir(path.dirname(target));
|
|
592
668
|
fs.writeFileSync(target, renderCaseMarkdown(cases, { title: docName, sourcePath }) + '\n');
|
|
593
669
|
generatedPath = target;
|
|
@@ -611,7 +687,7 @@ export async function importDocument(config, { file, name = '', mode = 'merge',
|
|
|
611
687
|
generatedPath = sourcePath;
|
|
612
688
|
}
|
|
613
689
|
} else {
|
|
614
|
-
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' });
|
|
615
691
|
}
|
|
616
692
|
|
|
617
693
|
if (
|
|
@@ -626,6 +702,19 @@ export async function importDocument(config, { file, name = '', mode = 'merge',
|
|
|
626
702
|
}
|
|
627
703
|
|
|
628
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
|
+
}
|
|
629
718
|
|
|
630
719
|
clearCaseTombstones(config.projectDir, newIds);
|
|
631
720
|
// 同编号用例以文档为准:面板修改与合并保留的旧内容都让位给新文档。
|
|
@@ -688,7 +777,7 @@ export async function importDocument(config, { file, name = '', mode = 'merge',
|
|
|
688
777
|
sourcePath,
|
|
689
778
|
originalName: originalName || previousDoc?.originalName || '',
|
|
690
779
|
generatedPath,
|
|
691
|
-
kind:
|
|
780
|
+
kind: TABLE_EXT.has(ext) ? (CSV_EXT.has(ext) ? 'csv' : 'xlsx') : JSON_EXT.has(ext) ? 'json' : 'markdown',
|
|
692
781
|
importedAt: previousDoc?.importedAt || nowIso(),
|
|
693
782
|
updatedAt: nowIso(),
|
|
694
783
|
count: ownedIds.length,
|
|
@@ -710,6 +799,8 @@ export async function importDocument(config, { file, name = '', mode = 'merge',
|
|
|
710
799
|
version: (Number(existing.version) || 0) + 1,
|
|
711
800
|
lastRead: existing.lastRead ?? input.lastRead,
|
|
712
801
|
writeback: existing.writeback ?? input.writeback,
|
|
802
|
+
archived: existing.archived === true,
|
|
803
|
+
archivedAt: existing.archivedAt || '',
|
|
713
804
|
}
|
|
714
805
|
: input),
|
|
715
806
|
});
|
|
@@ -743,7 +834,10 @@ export async function reReadDocument(config, { docId = '', mode = '', reapplyRes
|
|
|
743
834
|
try {
|
|
744
835
|
const doc = findTargetDoc(config, docId);
|
|
745
836
|
if (!doc) throw new UitestError('缺少文档 id', { code: 'DOC_NOT_FOUND', detail: { docId } });
|
|
746
|
-
const
|
|
837
|
+
const storedSource = String(doc.sourcePath || '');
|
|
838
|
+
const sourcePath = storedSource
|
|
839
|
+
? (path.isAbsolute(storedSource) ? path.resolve(storedSource) : path.resolve(config.projectDir, storedSource))
|
|
840
|
+
: '';
|
|
747
841
|
let sourceReady = false;
|
|
748
842
|
try {
|
|
749
843
|
sourceReady = Boolean(sourcePath) && fs.existsSync(sourcePath) && fs.statSync(sourcePath).isFile();
|
|
@@ -777,14 +871,14 @@ export async function reReadDocument(config, { docId = '', mode = '', reapplyRes
|
|
|
777
871
|
const warnings = [...(imported.warnings || [])];
|
|
778
872
|
let resultReapplied = false;
|
|
779
873
|
const recorded = imported.doc.writeback;
|
|
780
|
-
|
|
874
|
+
// 重新导读会重建用例文件,按每条用例的最新结果重放;只重放最后一次批次会丢掉更早批次的结果块。
|
|
875
|
+
if (reapplyResults && recorded && Number(recorded.results) > 0 && imported.doc.kind !== 'xlsx') {
|
|
781
876
|
const survivingIds = loadProjectCases(config).cases
|
|
782
|
-
.filter((item) => item.source?.docId === imported.doc.id)
|
|
877
|
+
.filter((item) => (item.docId || item.source?.docId) === imported.doc.id)
|
|
783
878
|
.map((item) => String(item.tcId));
|
|
784
879
|
try {
|
|
785
880
|
const reapplied = await writeDocumentResults(config, {
|
|
786
881
|
docId: imported.doc.id,
|
|
787
|
-
batchId: recorded.batchId,
|
|
788
882
|
caseIds: survivingIds,
|
|
789
883
|
});
|
|
790
884
|
if (reapplied.writeback) {
|
|
@@ -793,7 +887,7 @@ export async function reReadDocument(config, { docId = '', mode = '', reapplyRes
|
|
|
793
887
|
} else {
|
|
794
888
|
warnings.push({
|
|
795
889
|
code: 'WRITEBACK_REAPPLY_SKIPPED',
|
|
796
|
-
message: '
|
|
890
|
+
message: '最近一次回写的结果已不存在,用例文件已重新导读但未带回结果块',
|
|
797
891
|
});
|
|
798
892
|
}
|
|
799
893
|
} catch (error) {
|
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
|
@@ -181,25 +181,33 @@ export function buildStudioSnapshot(config, { caseLimit = 400, batchLimit = 30 }
|
|
|
181
181
|
};
|
|
182
182
|
});
|
|
183
183
|
const cases = enriched.slice(0, caseLimit);
|
|
184
|
-
|
|
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
|
+
}
|
|
185
197
|
const counts = {
|
|
186
198
|
total: studio.cases.length,
|
|
187
199
|
flow: studio.cases.filter((item) => item.mode === 'flow').length,
|
|
188
200
|
agent: studio.cases.filter((item) => item.mode === 'agent').length,
|
|
189
201
|
manual: studio.cases.filter((item) => item.mode === 'manual').length,
|
|
190
|
-
|
|
191
|
-
failed: cases.filter((item) => item.status === 'failed').length,
|
|
192
|
-
blocked: cases.filter((item) => item.status === 'blocked').length,
|
|
193
|
-
untested: cases.filter((item) => item.status === 'untested').length,
|
|
194
|
-
running: cases.filter((item) => item.status === 'running').length,
|
|
202
|
+
...statusCounts,
|
|
195
203
|
feedback: feedbackByCase.size,
|
|
196
|
-
unassigned:
|
|
204
|
+
unassigned: enriched.filter((item) => !docIds.has(String(item.docId || item.source?.docId || ''))).length,
|
|
205
|
+
archivedDocs: docs.filter((doc) => doc.archived).length,
|
|
197
206
|
};
|
|
198
207
|
const knowledge = knowledgeSnapshot(config, { limit: 100 });
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
}));
|
|
208
|
+
const docsWarning = docRegistry.invalid
|
|
209
|
+
? '文档注册表损坏,文档写入已暂停:' + docRegistry.file + '(' + (docRegistry.error || '无法解析') + ')'
|
|
210
|
+
: '';
|
|
203
211
|
return {
|
|
204
212
|
project: config.projectDir,
|
|
205
213
|
capabilities: { importUpload: true, accountsImport: true, caseDelete: true, export: true },
|
|
@@ -233,9 +241,12 @@ export function buildStudioSnapshot(config, { caseLimit = 400, batchLimit = 30 }
|
|
|
233
241
|
batches: batches.map((batch) => batchSummary(batch, batch.status === 'running' ? readCaseRuns(config, batch.id) : [])),
|
|
234
242
|
activeBatch: active ? batchSummary(active, activeRuns) : null,
|
|
235
243
|
docs,
|
|
244
|
+
docsError: docRegistry.invalid
|
|
245
|
+
? { code: 'DOCS_INVALID', file: docRegistry.file, message: docsWarning }
|
|
246
|
+
: null,
|
|
236
247
|
accounts: accountsPayload(config),
|
|
237
248
|
knowledge,
|
|
238
|
-
warnings: [...(studio.warnings || []), ...(flowResult.errors || [])].slice(0, 30),
|
|
249
|
+
warnings: [docsWarning, ...(studio.warnings || []), ...(flowResult.errors || [])].filter(Boolean).slice(0, 30),
|
|
239
250
|
};
|
|
240
251
|
}
|
|
241
252
|
|
package/studio/store.mjs
CHANGED
|
@@ -320,7 +320,25 @@ export function docsFile(config) {
|
|
|
320
320
|
}
|
|
321
321
|
|
|
322
322
|
export function readDocs(config) {
|
|
323
|
-
|
|
323
|
+
const file = docsFile(config);
|
|
324
|
+
let text;
|
|
325
|
+
try {
|
|
326
|
+
text = fs.readFileSync(file, 'utf8');
|
|
327
|
+
} catch (error) {
|
|
328
|
+
if (error?.code === 'ENOENT') return { version: STUDIO_VERSION, docs: [] };
|
|
329
|
+
return { version: STUDIO_VERSION, docs: [], invalid: true, error: String(error?.message || error), file };
|
|
330
|
+
}
|
|
331
|
+
let raw;
|
|
332
|
+
try {
|
|
333
|
+
raw = JSON.parse(text);
|
|
334
|
+
} catch (error) {
|
|
335
|
+
return { version: STUDIO_VERSION, docs: [], invalid: true, error: String(error?.message || error), file };
|
|
336
|
+
}
|
|
337
|
+
if (Array.isArray(raw)) return { version: STUDIO_VERSION, docs: raw };
|
|
338
|
+
if (!raw || typeof raw !== 'object' || !Array.isArray(raw.docs)) {
|
|
339
|
+
return { version: STUDIO_VERSION, docs: [], invalid: true, error: 'docs 字段不是数组', file };
|
|
340
|
+
}
|
|
341
|
+
return raw;
|
|
324
342
|
}
|
|
325
343
|
|
|
326
344
|
export function saveDocs(config, docs) {
|
|
@@ -348,6 +366,12 @@ export function withDocsLock(config, fn) {
|
|
|
348
366
|
export function updateDocs(config, mutate) {
|
|
349
367
|
return withDocsLock(config, () => {
|
|
350
368
|
const current = readDocs(config);
|
|
369
|
+
if (current.invalid) {
|
|
370
|
+
throw new UitestError('文档注册表损坏,已停止写入:' + (current.file || docsFile(config)), {
|
|
371
|
+
code: 'DOCS_INVALID',
|
|
372
|
+
detail: { file: current.file || docsFile(config), error: current.error || '' },
|
|
373
|
+
});
|
|
374
|
+
}
|
|
351
375
|
const draft = {
|
|
352
376
|
...current,
|
|
353
377
|
version: Number(current.version) || STUDIO_VERSION,
|
package/studio/writeback.mjs
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
// 批次归档与回写:整个批次结束后只写一次结果文档 / 用例文档。
|
|
2
2
|
// 这是并发安全的关键:worker 只写自己的 case-run,回写由协调器串行完成。
|
|
3
|
+
import fs from 'node:fs';
|
|
3
4
|
import path from 'node:path';
|
|
4
5
|
|
|
5
6
|
import { applyMarkdownResults, applyXlsxResults, evidenceOfResult, runBackfill, resolveEvidencePath, selectBackfillResults } from '../lib/backfill.mjs';
|
|
@@ -27,6 +28,12 @@ function absoluteEvidence(config, file) {
|
|
|
27
28
|
return resolveEvidencePath(config, text) || path.resolve(config.paths.outputDir, text);
|
|
28
29
|
}
|
|
29
30
|
|
|
31
|
+
function projectPath(config, file) {
|
|
32
|
+
const text = String(file || '');
|
|
33
|
+
if (!text) return '';
|
|
34
|
+
return path.isAbsolute(text) ? path.resolve(text) : path.resolve(config.projectDir, text);
|
|
35
|
+
}
|
|
36
|
+
|
|
30
37
|
function relativeToBatch(config, batchId, file) {
|
|
31
38
|
const abs = absoluteEvidence(config, file);
|
|
32
39
|
if (!abs) return '';
|
|
@@ -174,35 +181,55 @@ export async function writeDocumentResults(config, {
|
|
|
174
181
|
const doc = findDocument(config, { docId });
|
|
175
182
|
if (!doc) throw new UitestError('文档不存在:' + docId, { code: 'DOC_NOT_FOUND', detail: { docId } });
|
|
176
183
|
const wanted = new Set((Array.isArray(caseIds) ? caseIds : []).map(String));
|
|
177
|
-
const
|
|
178
|
-
|
|
179
|
-
return !wanted.size || wanted.has(String(item.tcId));
|
|
180
|
-
});
|
|
184
|
+
const allDocCases = loadProjectCases(config).cases.filter((item) => (item.docId || item.source?.docId) === doc.id);
|
|
185
|
+
const docCases = allDocCases.filter((item) => !wanted.size || wanted.has(String(item.tcId)));
|
|
181
186
|
const resultsByCase = docCases.length
|
|
182
187
|
? selectBackfillResults({ config, batchId, caseIds: docCases.map((item) => String(item.tcId)) })
|
|
183
188
|
: new Map();
|
|
184
189
|
if (!docCases.length || !resultsByCase.size) {
|
|
185
|
-
return { docId: doc.id, doc, writeback: null, results: 0, skipped: true, dryRun };
|
|
190
|
+
return { docId: doc.id, doc, writeback: null, results: 0, skipped: true, dryRun, cases: [] };
|
|
186
191
|
}
|
|
192
|
+
const caseSummaries = docCases.map((item) => {
|
|
193
|
+
const result = resultsByCase.get(String(item.tcId));
|
|
194
|
+
return {
|
|
195
|
+
caseId: String(item.tcId),
|
|
196
|
+
title: item.title || item.functionPoint || '',
|
|
197
|
+
status: result?.status || '',
|
|
198
|
+
};
|
|
199
|
+
});
|
|
187
200
|
const target = documentWriteTarget(config, doc, date);
|
|
188
201
|
if (target.kind === 'none') {
|
|
189
202
|
throw new UitestError('文档没有可写回的用例文件:' + doc.name, { code: target.reason || 'DOC_CASE_FILE_MISSING', detail: { docId: doc.id } });
|
|
190
203
|
}
|
|
204
|
+
// docs.json 可能保存相对路径;读写统一按 projectDir 解析,不能只让状态检查认相对路径。
|
|
205
|
+
const targetPath = projectPath(config, target.path);
|
|
206
|
+
const sourceFile = projectPath(config, doc.sourcePath);
|
|
191
207
|
if (target.kind === 'xlsx' && target.sourceState !== 'ready') {
|
|
192
|
-
throw new UitestError('文档源文件不存在,无法生成执行副本:' + (
|
|
208
|
+
throw new UitestError('文档源文件不存在,无法生成执行副本:' + (sourceFile || doc.name), {
|
|
193
209
|
code: 'DOC_SOURCE_MISSING',
|
|
194
|
-
detail: { docId: doc.id, path:
|
|
210
|
+
detail: { docId: doc.id, path: sourceFile },
|
|
195
211
|
});
|
|
196
212
|
}
|
|
213
|
+
if ((target.kind === 'markdown' || target.kind === 'json') && !fs.existsSync(targetPath)) {
|
|
214
|
+
throw new UitestError('文档的用例文件不存在:' + (targetPath || doc.name), {
|
|
215
|
+
code: 'DOC_CASE_FILE_MISSING',
|
|
216
|
+
detail: { docId: doc.id, path: targetPath },
|
|
217
|
+
});
|
|
218
|
+
}
|
|
219
|
+
const mode = batchId ? 'batch' : 'latest';
|
|
220
|
+
const sourceBatchIds = [...new Set([...resultsByCase.values()].map((result) => String(result?.batchId || '')).filter(Boolean))];
|
|
197
221
|
|
|
198
222
|
let summary;
|
|
199
223
|
if (target.kind === 'xlsx') {
|
|
224
|
+
// 同一份执行副本保留其他批次的最近结果,本批次结果覆盖对应行,避免后跑的批次清空先跑的行。
|
|
225
|
+
const mergedResults = selectBackfillResults({ config, caseIds: allDocCases.map((item) => String(item.tcId)) });
|
|
226
|
+
for (const [caseId, result] of resultsByCase) mergedResults.set(caseId, result);
|
|
200
227
|
const xlsx = await applyXlsxResults({
|
|
201
228
|
config,
|
|
202
|
-
cases:
|
|
203
|
-
resultsByCase,
|
|
204
|
-
sourceFile
|
|
205
|
-
outputPath:
|
|
229
|
+
cases: allDocCases,
|
|
230
|
+
resultsByCase: mergedResults,
|
|
231
|
+
sourceFile,
|
|
232
|
+
outputPath: targetPath,
|
|
206
233
|
date,
|
|
207
234
|
dryRun,
|
|
208
235
|
embedShots,
|
|
@@ -210,45 +237,80 @@ export async function writeDocumentResults(config, {
|
|
|
210
237
|
});
|
|
211
238
|
// 用例来源指向别的工作簿时 applyXlsxResults 不写盘;不报失败会让批次误报“已写入”。
|
|
212
239
|
if (!xlsx.written && !xlsx.dryRun) {
|
|
213
|
-
throw new UitestError('文档的用例已不在该工作簿来源中:' + (
|
|
240
|
+
throw new UitestError('文档的用例已不在该工作簿来源中:' + (sourceFile || doc.name), {
|
|
214
241
|
code: 'DOC_CASE_FILE_MISSING',
|
|
215
|
-
detail: { docId: doc.id, path:
|
|
242
|
+
detail: { docId: doc.id, path: sourceFile, reason: xlsx.reason || '' },
|
|
216
243
|
});
|
|
217
244
|
}
|
|
245
|
+
// results 只算本次回写范围内的结果;writtenIds 还包含同日其它批次合并保留下来的行。
|
|
246
|
+
const writtenIds = new Set((xlsx.writtenIds || []).map(String));
|
|
247
|
+
const scopeCaseIds = [...resultsByCase.keys()];
|
|
248
|
+
const skippedCaseIds = scopeCaseIds.filter((caseId) => !writtenIds.has(String(caseId)));
|
|
218
249
|
summary = {
|
|
219
250
|
at: nowIso(),
|
|
220
251
|
batchId,
|
|
221
|
-
|
|
222
|
-
|
|
252
|
+
mode,
|
|
253
|
+
sourceBatchIds,
|
|
254
|
+
results: scopeCaseIds.length - skippedCaseIds.length,
|
|
255
|
+
targetPath: xlsx.path || targetPath,
|
|
223
256
|
kind: 'xlsx',
|
|
224
257
|
files: [],
|
|
225
258
|
markdown: null,
|
|
259
|
+
skippedCaseIds,
|
|
226
260
|
xlsx,
|
|
227
261
|
};
|
|
228
262
|
} else {
|
|
229
|
-
const parsed = parseMarkdownCases(
|
|
263
|
+
const parsed = parseMarkdownCases(targetPath, { rootDir: config.projectDir });
|
|
264
|
+
const parsedIds = new Set(parsed.cases.map((item) => String(item.tcId)));
|
|
265
|
+
const skippedCaseIds = [...resultsByCase.keys()].filter((caseId) => !parsedIds.has(String(caseId)));
|
|
266
|
+
const writableResults = new Map([...resultsByCase].filter(([caseId]) => parsedIds.has(String(caseId))));
|
|
267
|
+
if (!writableResults.size) {
|
|
268
|
+
throw new UitestError('用例文件里找不到要回写的用例:' + skippedCaseIds.join('、') + ';请先重新导读文档', {
|
|
269
|
+
code: 'DOC_CASE_FILE_STALE',
|
|
270
|
+
detail: { docId: doc.id, path: targetPath, caseIds: skippedCaseIds },
|
|
271
|
+
});
|
|
272
|
+
}
|
|
230
273
|
const applied = applyMarkdownResults({
|
|
231
274
|
config,
|
|
232
|
-
file:
|
|
275
|
+
file: targetPath,
|
|
233
276
|
sourceCases: parsed.cases,
|
|
234
|
-
resultsByCase,
|
|
277
|
+
resultsByCase: writableResults,
|
|
235
278
|
maxShotsPerCase,
|
|
236
279
|
dryRun,
|
|
237
280
|
});
|
|
238
|
-
const
|
|
281
|
+
const written = applied.inserted + applied.replaced;
|
|
282
|
+
const files = written ? [targetPath] : [];
|
|
239
283
|
summary = {
|
|
240
284
|
at: nowIso(),
|
|
241
285
|
batchId,
|
|
242
|
-
|
|
243
|
-
|
|
286
|
+
mode,
|
|
287
|
+
sourceBatchIds,
|
|
288
|
+
results: written,
|
|
289
|
+
targetPath,
|
|
244
290
|
kind: doc.kind,
|
|
245
291
|
files,
|
|
246
|
-
markdown: { files: files.length, inserted: applied.inserted, replaced: applied.replaced },
|
|
292
|
+
markdown: { files: files.length, inserted: applied.inserted, replaced: applied.replaced, skipped: skippedCaseIds.length },
|
|
293
|
+
skippedCaseIds,
|
|
247
294
|
xlsx: null,
|
|
248
295
|
};
|
|
249
296
|
}
|
|
250
297
|
const saved = dryRun ? doc : await recordDocumentWriteback(config, doc.id, summary);
|
|
251
|
-
return { docId: doc.id, doc: saved, writeback: summary, results: summary.results, skipped: false, dryRun };
|
|
298
|
+
return { docId: doc.id, doc: saved, writeback: summary, results: summary.results, skipped: false, dryRun, cases: caseSummaries };
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/** 单文档回写预览:使用最近结果或指定批次,只读不落盘。 */
|
|
302
|
+
export async function previewDocumentWriteback(config, docId, { batchId = '', caseIds = [] } = {}) {
|
|
303
|
+
return writeDocumentResults(config, { docId, batchId, caseIds, dryRun: true });
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
/** 单文档回写:持有回写锁,避免和重新导读或批次回写互相覆盖。 */
|
|
307
|
+
export async function applyDocumentWriteback(config, docId, { batchId = '', caseIds = [] } = {}) {
|
|
308
|
+
const lock = await acquireWritebackLock(config);
|
|
309
|
+
try {
|
|
310
|
+
return await writeDocumentResults(config, { docId, batchId, caseIds, dryRun: false });
|
|
311
|
+
} finally {
|
|
312
|
+
lock.release();
|
|
313
|
+
}
|
|
252
314
|
}
|
|
253
315
|
|
|
254
316
|
/** 批次回写计划:按文档分组写各自目标,未归属用例仍走原 runBackfill。 */
|