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/studio/store.mjs CHANGED
@@ -320,7 +320,25 @@ export function docsFile(config) {
320
320
  }
321
321
 
322
322
  export function readDocs(config) {
323
- return readJsonIfExists(docsFile(config)) || { version: STUDIO_VERSION, docs: [] };
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) {
@@ -329,6 +347,43 @@ export function saveDocs(config, docs) {
329
347
  return docs;
330
348
  }
331
349
 
350
+ const docsQueues = new Map();
351
+
352
+ /** docs.json 读改写按工作区串行化,避免并发导入互相覆盖。 */
353
+ export function withDocsLock(config, fn) {
354
+ const key = path.resolve(config.projectDir);
355
+ const previous = docsQueues.get(key) || Promise.resolve();
356
+ const current = previous.then(() => fn());
357
+ const stored = current.catch(() => {});
358
+ docsQueues.set(key, stored);
359
+ stored.finally(() => {
360
+ if (docsQueues.get(key) === stored) docsQueues.delete(key);
361
+ });
362
+ return current;
363
+ }
364
+
365
+ /** 文档记录的读改写入口:回调修改 draft,函数负责原子落盘。 */
366
+ export function updateDocs(config, mutate) {
367
+ return withDocsLock(config, () => {
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
+ }
375
+ const draft = {
376
+ ...current,
377
+ version: Number(current.version) || STUDIO_VERSION,
378
+ docs: Array.isArray(current.docs) ? current.docs : [],
379
+ };
380
+ const result = mutate(draft);
381
+ const next = { ...draft, updatedAt: nowIso() };
382
+ saveDocs(config, next);
383
+ return result === undefined ? next : result;
384
+ });
385
+ }
386
+
332
387
  export function lockFile(config, name) {
333
388
  return path.join(studioRoot(config), 'locks', String(name).replace(/[^A-Za-z0-9._-]/g, '_') + '.lock');
334
389
  }
@@ -1,10 +1,14 @@
1
1
  // 批次归档与回写:整个批次结束后只写一次结果文档 / 用例文档。
2
2
  // 这是并发安全的关键:worker 只写自己的 case-run,回写由协调器串行完成。
3
+ import fs from 'node:fs';
3
4
  import path from 'node:path';
4
5
 
5
- import { evidenceOfResult, runBackfill, resolveEvidencePath } from '../lib/backfill.mjs';
6
- import { formatDuration, sleep } from '../lib/util.mjs';
6
+ import { applyMarkdownResults, applyXlsxResults, evidenceOfResult, runBackfill, resolveEvidencePath, selectBackfillResults } from '../lib/backfill.mjs';
7
+ import { loadProjectCases } from '../lib/cases-import.mjs';
8
+ import { parseMarkdownCases } from '../lib/cases-md.mjs';
9
+ import { UitestError, formatDate, formatDuration, nowIso, sleep } from '../lib/util.mjs';
7
10
  import { acquireLock, batchDir, caseRunFile, mergeBatchRuns, patchBatch, patchStage, readBatch, readCaseRuns, writeBatchText } from './store.mjs';
11
+ import { documentWriteTarget, findDocument, recordDocumentWriteback } from './documents.mjs';
8
12
 
9
13
  function statusBadge(status) {
10
14
  if (status === 'passed') return '通过';
@@ -24,6 +28,12 @@ function absoluteEvidence(config, file) {
24
28
  return resolveEvidencePath(config, text) || path.resolve(config.paths.outputDir, text);
25
29
  }
26
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
+
27
37
  function relativeToBatch(config, batchId, file) {
28
38
  const abs = absoluteEvidence(config, file);
29
39
  if (!abs) return '';
@@ -105,6 +115,18 @@ export function renderBatchDoc({ config, batch, caseRuns = [] }) {
105
115
  if (batch.writeback.xlsx?.path) lines.push('- xlsx 副本:' + batch.writeback.xlsx.path);
106
116
  lines.push('');
107
117
  }
118
+ if (Array.isArray(batch.writeback?.documents) && batch.writeback.documents.length) {
119
+ lines.push('## 文档回写', '');
120
+ lines.push('| 文档 | 类型 | 结果 | 目标 | 状态 |');
121
+ lines.push('|---|---|---|---|---|');
122
+ for (const doc of batch.writeback.documents) {
123
+ const status = doc.error
124
+ ? '失败:' + String(doc.error.message || doc.error).replace(/\|/g, '\\|')
125
+ : '已写入';
126
+ lines.push('| ' + String(doc.name || doc.id || '').replace(/\|/g, '\\|') + ' | ' + (doc.kind || '-') + ' | ' + (doc.results || 0) + ' | ' + String(doc.targetPath || '-').replace(/\|/g, '\\|') + ' | ' + status + ' |');
127
+ }
128
+ lines.push('');
129
+ }
108
130
  if (batch.knowledge) {
109
131
  lines.push('## 知识沉淀', '');
110
132
  lines.push('- 页面:' + (batch.knowledge.totals?.pages || 0));
@@ -143,28 +165,269 @@ export async function writeBatchResultDoc(config, batchId) {
143
165
  return { file, batch, caseRuns, text };
144
166
  }
145
167
 
168
+ /**
169
+ * 把一批结果写回单个文档:Markdown 写解析出的用例文件,xlsx 生成该文档专属执行副本。
170
+ * 源文件只读;dryRun 不写文件也不写文档记录。
171
+ */
172
+ export async function writeDocumentResults(config, {
173
+ docId = '',
174
+ batchId = '',
175
+ caseIds = [],
176
+ date = formatDate(new Date()),
177
+ dryRun = false,
178
+ embedShots = true,
179
+ maxShotsPerCase = 4,
180
+ } = {}) {
181
+ const doc = findDocument(config, { docId });
182
+ if (!doc) throw new UitestError('文档不存在:' + docId, { code: 'DOC_NOT_FOUND', detail: { docId } });
183
+ const wanted = new Set((Array.isArray(caseIds) ? caseIds : []).map(String));
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)));
186
+ const resultsByCase = docCases.length
187
+ ? selectBackfillResults({ config, batchId, caseIds: docCases.map((item) => String(item.tcId)) })
188
+ : new Map();
189
+ if (!docCases.length || !resultsByCase.size) {
190
+ return { docId: doc.id, doc, writeback: null, results: 0, skipped: true, dryRun, cases: [] };
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
+ });
200
+ const target = documentWriteTarget(config, doc, date);
201
+ if (target.kind === 'none') {
202
+ throw new UitestError('文档没有可写回的用例文件:' + doc.name, { code: target.reason || 'DOC_CASE_FILE_MISSING', detail: { docId: doc.id } });
203
+ }
204
+ // docs.json 可能保存相对路径;读写统一按 projectDir 解析,不能只让状态检查认相对路径。
205
+ const targetPath = projectPath(config, target.path);
206
+ const sourceFile = projectPath(config, doc.sourcePath);
207
+ if (target.kind === 'xlsx' && target.sourceState !== 'ready') {
208
+ throw new UitestError('文档源文件不存在,无法生成执行副本:' + (sourceFile || doc.name), {
209
+ code: 'DOC_SOURCE_MISSING',
210
+ detail: { docId: doc.id, path: sourceFile },
211
+ });
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))];
221
+
222
+ let summary;
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);
227
+ const xlsx = await applyXlsxResults({
228
+ config,
229
+ cases: allDocCases,
230
+ resultsByCase: mergedResults,
231
+ sourceFile,
232
+ outputPath: targetPath,
233
+ date,
234
+ dryRun,
235
+ embedShots,
236
+ maxShotsPerCase,
237
+ });
238
+ // 用例来源指向别的工作簿时 applyXlsxResults 不写盘;不报失败会让批次误报“已写入”。
239
+ if (!xlsx.written && !xlsx.dryRun) {
240
+ throw new UitestError('文档的用例已不在该工作簿来源中:' + (sourceFile || doc.name), {
241
+ code: 'DOC_CASE_FILE_MISSING',
242
+ detail: { docId: doc.id, path: sourceFile, reason: xlsx.reason || '' },
243
+ });
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)));
249
+ summary = {
250
+ at: nowIso(),
251
+ batchId,
252
+ mode,
253
+ sourceBatchIds,
254
+ results: scopeCaseIds.length - skippedCaseIds.length,
255
+ targetPath: xlsx.path || targetPath,
256
+ kind: 'xlsx',
257
+ files: [],
258
+ markdown: null,
259
+ skippedCaseIds,
260
+ xlsx,
261
+ };
262
+ } else {
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
+ }
273
+ const applied = applyMarkdownResults({
274
+ config,
275
+ file: targetPath,
276
+ sourceCases: parsed.cases,
277
+ resultsByCase: writableResults,
278
+ maxShotsPerCase,
279
+ dryRun,
280
+ });
281
+ const written = applied.inserted + applied.replaced;
282
+ const files = written ? [targetPath] : [];
283
+ summary = {
284
+ at: nowIso(),
285
+ batchId,
286
+ mode,
287
+ sourceBatchIds,
288
+ results: written,
289
+ targetPath,
290
+ kind: doc.kind,
291
+ files,
292
+ markdown: { files: files.length, inserted: applied.inserted, replaced: applied.replaced, skipped: skippedCaseIds.length },
293
+ skippedCaseIds,
294
+ xlsx: null,
295
+ };
296
+ }
297
+ const saved = dryRun ? doc : await recordDocumentWriteback(config, doc.id, summary);
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
+ }
314
+ }
315
+
316
+ /** 批次回写计划:按文档分组写各自目标,未归属用例仍走原 runBackfill。 */
317
+ async function planBatchWriteback(config, batchId, { dryRun = false } = {}) {
318
+ const batch = readBatch(config, batchId);
319
+ const inBatch = new Set((batch.caseIds || []).map(String));
320
+ const byDoc = new Map();
321
+ const unassigned = [];
322
+ for (const item of loadProjectCases(config).cases) {
323
+ if (!inBatch.has(String(item.tcId))) continue;
324
+ const docId = String(item.source?.docId || '');
325
+ if (!docId) {
326
+ unassigned.push(item);
327
+ continue;
328
+ }
329
+ if (!byDoc.has(docId)) byDoc.set(docId, []);
330
+ byDoc.get(docId).push(item);
331
+ }
332
+
333
+ const documents = [];
334
+ const errors = [];
335
+ const files = [];
336
+ let results = 0;
337
+ let markdownFiles = 0;
338
+ let inserted = 0;
339
+ let replaced = 0;
340
+ for (const [docId, docCases] of byDoc) {
341
+ const doc = findDocument(config, { docId });
342
+ try {
343
+ const written = await writeDocumentResults(config, {
344
+ docId,
345
+ batchId,
346
+ caseIds: docCases.map((item) => String(item.tcId)),
347
+ dryRun,
348
+ });
349
+ const wb = written.writeback || {};
350
+ documents.push({
351
+ id: docId,
352
+ name: doc?.name || '',
353
+ kind: doc?.kind || '',
354
+ results: Number(wb.results) || 0,
355
+ targetPath: wb.targetPath || '',
356
+ files: wb.files || [],
357
+ markdown: wb.markdown || null,
358
+ xlsx: wb.xlsx || null,
359
+ error: null,
360
+ });
361
+ results += Number(wb.results) || 0;
362
+ markdownFiles += Number(wb.markdown?.files) || 0;
363
+ inserted += Number(wb.markdown?.inserted) || 0;
364
+ replaced += Number(wb.markdown?.replaced) || 0;
365
+ files.push(...(wb.files || []));
366
+ } catch (error) {
367
+ const failure = { code: error?.code || 'WRITEBACK_FAILED', message: String(error?.message || error) };
368
+ documents.push({
369
+ id: docId,
370
+ name: doc?.name || '',
371
+ kind: doc?.kind || '',
372
+ results: 0,
373
+ targetPath: '',
374
+ files: [],
375
+ markdown: null,
376
+ xlsx: null,
377
+ error: failure,
378
+ });
379
+ errors.push({ docId, ...failure });
380
+ }
381
+ }
382
+
383
+ let legacy = null;
384
+ if (unassigned.length) {
385
+ legacy = await runBackfill({
386
+ config,
387
+ batchId,
388
+ caseIds: unassigned.map((item) => String(item.tcId)),
389
+ markdown: true,
390
+ xlsx: true,
391
+ dryRun,
392
+ });
393
+ results += Number(legacy.results) || 0;
394
+ markdownFiles += Number(legacy.markdown?.files) || 0;
395
+ inserted += Number(legacy.markdown?.inserted) || 0;
396
+ replaced += Number(legacy.markdown?.replaced) || 0;
397
+ files.push(...(legacy.markdown?.filesTouched || []));
398
+ }
399
+
400
+ return {
401
+ dryRun,
402
+ documents,
403
+ errors,
404
+ results,
405
+ markdownFiles,
406
+ inserted,
407
+ replaced,
408
+ files,
409
+ xlsx: legacy?.xlsx || null,
410
+ summaryPath: legacy?.summaryPath || null,
411
+ legacyResults: Number(legacy?.results) || 0,
412
+ };
413
+ }
414
+
146
415
  /** 预览回写会修改哪些文件;不写盘。 */
147
416
  export async function previewBatchWriteback(config, batchId) {
148
- const batch = readBatch(config, batchId);
149
- const result = await runBackfill({
150
- config,
151
- batchId,
152
- caseIds: batch.caseIds,
153
- markdown: true,
154
- xlsx: true,
155
- dryRun: true,
156
- });
417
+ const plan = await planBatchWriteback(config, batchId, { dryRun: true });
157
418
  return {
158
419
  batchId,
159
420
  dryRun: true,
160
- results: result.results,
161
- markdown: result.markdown,
162
- xlsx: result.xlsx,
163
- files: result.markdown?.filesTouched || [],
421
+ results: plan.results,
422
+ markdown: { files: plan.markdownFiles, inserted: plan.inserted, replaced: plan.replaced, filesTouched: plan.files },
423
+ xlsx: plan.xlsx,
424
+ files: plan.files,
425
+ documents: plan.documents,
426
+ errors: plan.errors,
164
427
  };
165
428
  }
166
429
 
167
- /** 整个批次结束后回写一次;由单写者锁保护。 */
430
+ /** 整个批次结束后回写一次;由单写者锁保护,单个文档失败不影响其它文档。 */
168
431
  export async function applyBatchWriteback(config, batchId, { dryRun = false } = {}) {
169
432
  const batch = readBatch(config, batchId);
170
433
  if (batch.status === 'queued' || batch.status === 'preparing' || batch.status === 'running') {
@@ -174,26 +437,29 @@ export async function applyBatchWriteback(config, batchId, { dryRun = false } =
174
437
  const lock = await acquireWritebackLock(config);
175
438
  try {
176
439
  await patchStage(config, batchId, 'writeback', { status: 'running', error: null });
177
- const result = await runBackfill({
178
- config,
179
- batchId,
180
- caseIds: batch.caseIds,
181
- markdown: true,
182
- xlsx: true,
183
- dryRun: false,
184
- });
440
+ const plan = await planBatchWriteback(config, batchId, { dryRun: false });
185
441
  const summary = {
186
- at: new Date().toISOString(),
187
- results: result.results,
188
- markdownFiles: result.markdown?.files || 0,
189
- inserted: result.markdown?.inserted || 0,
190
- replaced: result.markdown?.replaced || 0,
191
- files: result.markdown?.filesTouched || [],
192
- xlsx: result.xlsx || null,
193
- summaryPath: result.summaryPath || null,
442
+ at: nowIso(),
443
+ results: plan.results,
444
+ markdownFiles: plan.markdownFiles,
445
+ inserted: plan.inserted,
446
+ replaced: plan.replaced,
447
+ files: plan.files,
448
+ xlsx: plan.xlsx,
449
+ summaryPath: plan.summaryPath,
450
+ documents: plan.documents,
451
+ errors: plan.errors,
194
452
  };
195
453
  await patchBatch(config, batchId, { writeback: summary });
196
- await patchStage(config, batchId, 'writeback', { status: 'done', at: summary.at, files: summary.files.length });
454
+ const allFailed = plan.documents.length > 0
455
+ && plan.documents.every((item) => item.error)
456
+ && plan.legacyResults === 0;
457
+ await patchStage(config, batchId, 'writeback', {
458
+ status: allFailed ? 'failed' : 'done',
459
+ at: summary.at,
460
+ files: summary.files.length,
461
+ ...(allFailed ? { error: plan.errors.map((item) => item.message).join(';') } : {}),
462
+ });
197
463
  return summary;
198
464
  } catch (error) {
199
465
  patchStage(config, batchId, 'writeback', { status: 'failed', error: String(error.message || error) });
@@ -3,7 +3,7 @@
3
3
  "browser": {
4
4
  "executablePath": "/usr/bin/chromium",
5
5
  "headless": true,
6
- "viewport": { "width": 1600, "height": 1000 },
6
+ "viewport": { "width": 1920, "height": 1280 },
7
7
  "args": ["--no-sandbox", "--disable-dev-shm-usage"],
8
8
  "locale": "zh-CN",
9
9
  "timezoneId": "Asia/Shanghai"