dsh-uitest 2.1.4 → 2.2.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
@@ -329,6 +329,37 @@ export function saveDocs(config, docs) {
329
329
  return docs;
330
330
  }
331
331
 
332
+ const docsQueues = new Map();
333
+
334
+ /** docs.json 读改写按工作区串行化,避免并发导入互相覆盖。 */
335
+ export function withDocsLock(config, fn) {
336
+ const key = path.resolve(config.projectDir);
337
+ const previous = docsQueues.get(key) || Promise.resolve();
338
+ const current = previous.then(() => fn());
339
+ const stored = current.catch(() => {});
340
+ docsQueues.set(key, stored);
341
+ stored.finally(() => {
342
+ if (docsQueues.get(key) === stored) docsQueues.delete(key);
343
+ });
344
+ return current;
345
+ }
346
+
347
+ /** 文档记录的读改写入口:回调修改 draft,函数负责原子落盘。 */
348
+ export function updateDocs(config, mutate) {
349
+ return withDocsLock(config, () => {
350
+ const current = readDocs(config);
351
+ const draft = {
352
+ ...current,
353
+ version: Number(current.version) || STUDIO_VERSION,
354
+ docs: Array.isArray(current.docs) ? current.docs : [],
355
+ };
356
+ const result = mutate(draft);
357
+ const next = { ...draft, updatedAt: nowIso() };
358
+ saveDocs(config, next);
359
+ return result === undefined ? next : result;
360
+ });
361
+ }
362
+
332
363
  export function lockFile(config, name) {
333
364
  return path.join(studioRoot(config), 'locks', String(name).replace(/[^A-Za-z0-9._-]/g, '_') + '.lock');
334
365
  }
@@ -2,9 +2,12 @@
2
2
  // 这是并发安全的关键:worker 只写自己的 case-run,回写由协调器串行完成。
3
3
  import path from 'node:path';
4
4
 
5
- import { evidenceOfResult, runBackfill, resolveEvidencePath } from '../lib/backfill.mjs';
6
- import { formatDuration, sleep } from '../lib/util.mjs';
5
+ import { applyMarkdownResults, applyXlsxResults, evidenceOfResult, runBackfill, resolveEvidencePath, selectBackfillResults } from '../lib/backfill.mjs';
6
+ import { loadProjectCases } from '../lib/cases-import.mjs';
7
+ import { parseMarkdownCases } from '../lib/cases-md.mjs';
8
+ import { UitestError, formatDate, formatDuration, nowIso, sleep } from '../lib/util.mjs';
7
9
  import { acquireLock, batchDir, caseRunFile, mergeBatchRuns, patchBatch, patchStage, readBatch, readCaseRuns, writeBatchText } from './store.mjs';
10
+ import { documentWriteTarget, findDocument, recordDocumentWriteback } from './documents.mjs';
8
11
 
9
12
  function statusBadge(status) {
10
13
  if (status === 'passed') return '通过';
@@ -105,6 +108,18 @@ export function renderBatchDoc({ config, batch, caseRuns = [] }) {
105
108
  if (batch.writeback.xlsx?.path) lines.push('- xlsx 副本:' + batch.writeback.xlsx.path);
106
109
  lines.push('');
107
110
  }
111
+ if (Array.isArray(batch.writeback?.documents) && batch.writeback.documents.length) {
112
+ lines.push('## 文档回写', '');
113
+ lines.push('| 文档 | 类型 | 结果 | 目标 | 状态 |');
114
+ lines.push('|---|---|---|---|---|');
115
+ for (const doc of batch.writeback.documents) {
116
+ const status = doc.error
117
+ ? '失败:' + String(doc.error.message || doc.error).replace(/\|/g, '\\|')
118
+ : '已写入';
119
+ lines.push('| ' + String(doc.name || doc.id || '').replace(/\|/g, '\\|') + ' | ' + (doc.kind || '-') + ' | ' + (doc.results || 0) + ' | ' + String(doc.targetPath || '-').replace(/\|/g, '\\|') + ' | ' + status + ' |');
120
+ }
121
+ lines.push('');
122
+ }
108
123
  if (batch.knowledge) {
109
124
  lines.push('## 知识沉淀', '');
110
125
  lines.push('- 页面:' + (batch.knowledge.totals?.pages || 0));
@@ -143,28 +158,214 @@ export async function writeBatchResultDoc(config, batchId) {
143
158
  return { file, batch, caseRuns, text };
144
159
  }
145
160
 
161
+ /**
162
+ * 把一批结果写回单个文档:Markdown 写解析出的用例文件,xlsx 生成该文档专属执行副本。
163
+ * 源文件只读;dryRun 不写文件也不写文档记录。
164
+ */
165
+ export async function writeDocumentResults(config, {
166
+ docId = '',
167
+ batchId = '',
168
+ caseIds = [],
169
+ date = formatDate(new Date()),
170
+ dryRun = false,
171
+ embedShots = true,
172
+ maxShotsPerCase = 4,
173
+ } = {}) {
174
+ const doc = findDocument(config, { docId });
175
+ if (!doc) throw new UitestError('文档不存在:' + docId, { code: 'DOC_NOT_FOUND', detail: { docId } });
176
+ const wanted = new Set((Array.isArray(caseIds) ? caseIds : []).map(String));
177
+ const docCases = loadProjectCases(config).cases.filter((item) => {
178
+ if (item.source?.docId !== doc.id) return false;
179
+ return !wanted.size || wanted.has(String(item.tcId));
180
+ });
181
+ const resultsByCase = docCases.length
182
+ ? selectBackfillResults({ config, batchId, caseIds: docCases.map((item) => String(item.tcId)) })
183
+ : new Map();
184
+ if (!docCases.length || !resultsByCase.size) {
185
+ return { docId: doc.id, doc, writeback: null, results: 0, skipped: true, dryRun };
186
+ }
187
+ const target = documentWriteTarget(config, doc, date);
188
+ if (target.kind === 'none') {
189
+ throw new UitestError('文档没有可写回的用例文件:' + doc.name, { code: target.reason || 'DOC_CASE_FILE_MISSING', detail: { docId: doc.id } });
190
+ }
191
+ if (target.kind === 'xlsx' && target.sourceState !== 'ready') {
192
+ throw new UitestError('文档源文件不存在,无法生成执行副本:' + (target.sourcePath || doc.name), {
193
+ code: 'DOC_SOURCE_MISSING',
194
+ detail: { docId: doc.id, path: target.sourcePath || '' },
195
+ });
196
+ }
197
+
198
+ let summary;
199
+ if (target.kind === 'xlsx') {
200
+ const xlsx = await applyXlsxResults({
201
+ config,
202
+ cases: docCases,
203
+ resultsByCase,
204
+ sourceFile: doc.sourcePath,
205
+ outputPath: target.path,
206
+ date,
207
+ dryRun,
208
+ embedShots,
209
+ maxShotsPerCase,
210
+ });
211
+ // 用例来源指向别的工作簿时 applyXlsxResults 不写盘;不报失败会让批次误报“已写入”。
212
+ if (!xlsx.written && !xlsx.dryRun) {
213
+ throw new UitestError('文档的用例已不在该工作簿来源中:' + (doc.sourcePath || doc.name), {
214
+ code: 'DOC_CASE_FILE_MISSING',
215
+ detail: { docId: doc.id, path: doc.sourcePath || '', reason: xlsx.reason || '' },
216
+ });
217
+ }
218
+ summary = {
219
+ at: nowIso(),
220
+ batchId,
221
+ results: Number(xlsx.cases) || 0,
222
+ targetPath: xlsx.path || target.path,
223
+ kind: 'xlsx',
224
+ files: [],
225
+ markdown: null,
226
+ xlsx,
227
+ };
228
+ } else {
229
+ const parsed = parseMarkdownCases(target.path, { rootDir: config.projectDir });
230
+ const applied = applyMarkdownResults({
231
+ config,
232
+ file: target.path,
233
+ sourceCases: parsed.cases,
234
+ resultsByCase,
235
+ maxShotsPerCase,
236
+ dryRun,
237
+ });
238
+ const files = applied.inserted || applied.replaced ? [target.path] : [];
239
+ summary = {
240
+ at: nowIso(),
241
+ batchId,
242
+ results: resultsByCase.size,
243
+ targetPath: target.path,
244
+ kind: doc.kind,
245
+ files,
246
+ markdown: { files: files.length, inserted: applied.inserted, replaced: applied.replaced },
247
+ xlsx: null,
248
+ };
249
+ }
250
+ 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 };
252
+ }
253
+
254
+ /** 批次回写计划:按文档分组写各自目标,未归属用例仍走原 runBackfill。 */
255
+ async function planBatchWriteback(config, batchId, { dryRun = false } = {}) {
256
+ const batch = readBatch(config, batchId);
257
+ const inBatch = new Set((batch.caseIds || []).map(String));
258
+ const byDoc = new Map();
259
+ const unassigned = [];
260
+ for (const item of loadProjectCases(config).cases) {
261
+ if (!inBatch.has(String(item.tcId))) continue;
262
+ const docId = String(item.source?.docId || '');
263
+ if (!docId) {
264
+ unassigned.push(item);
265
+ continue;
266
+ }
267
+ if (!byDoc.has(docId)) byDoc.set(docId, []);
268
+ byDoc.get(docId).push(item);
269
+ }
270
+
271
+ const documents = [];
272
+ const errors = [];
273
+ const files = [];
274
+ let results = 0;
275
+ let markdownFiles = 0;
276
+ let inserted = 0;
277
+ let replaced = 0;
278
+ for (const [docId, docCases] of byDoc) {
279
+ const doc = findDocument(config, { docId });
280
+ try {
281
+ const written = await writeDocumentResults(config, {
282
+ docId,
283
+ batchId,
284
+ caseIds: docCases.map((item) => String(item.tcId)),
285
+ dryRun,
286
+ });
287
+ const wb = written.writeback || {};
288
+ documents.push({
289
+ id: docId,
290
+ name: doc?.name || '',
291
+ kind: doc?.kind || '',
292
+ results: Number(wb.results) || 0,
293
+ targetPath: wb.targetPath || '',
294
+ files: wb.files || [],
295
+ markdown: wb.markdown || null,
296
+ xlsx: wb.xlsx || null,
297
+ error: null,
298
+ });
299
+ results += Number(wb.results) || 0;
300
+ markdownFiles += Number(wb.markdown?.files) || 0;
301
+ inserted += Number(wb.markdown?.inserted) || 0;
302
+ replaced += Number(wb.markdown?.replaced) || 0;
303
+ files.push(...(wb.files || []));
304
+ } catch (error) {
305
+ const failure = { code: error?.code || 'WRITEBACK_FAILED', message: String(error?.message || error) };
306
+ documents.push({
307
+ id: docId,
308
+ name: doc?.name || '',
309
+ kind: doc?.kind || '',
310
+ results: 0,
311
+ targetPath: '',
312
+ files: [],
313
+ markdown: null,
314
+ xlsx: null,
315
+ error: failure,
316
+ });
317
+ errors.push({ docId, ...failure });
318
+ }
319
+ }
320
+
321
+ let legacy = null;
322
+ if (unassigned.length) {
323
+ legacy = await runBackfill({
324
+ config,
325
+ batchId,
326
+ caseIds: unassigned.map((item) => String(item.tcId)),
327
+ markdown: true,
328
+ xlsx: true,
329
+ dryRun,
330
+ });
331
+ results += Number(legacy.results) || 0;
332
+ markdownFiles += Number(legacy.markdown?.files) || 0;
333
+ inserted += Number(legacy.markdown?.inserted) || 0;
334
+ replaced += Number(legacy.markdown?.replaced) || 0;
335
+ files.push(...(legacy.markdown?.filesTouched || []));
336
+ }
337
+
338
+ return {
339
+ dryRun,
340
+ documents,
341
+ errors,
342
+ results,
343
+ markdownFiles,
344
+ inserted,
345
+ replaced,
346
+ files,
347
+ xlsx: legacy?.xlsx || null,
348
+ summaryPath: legacy?.summaryPath || null,
349
+ legacyResults: Number(legacy?.results) || 0,
350
+ };
351
+ }
352
+
146
353
  /** 预览回写会修改哪些文件;不写盘。 */
147
354
  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
- });
355
+ const plan = await planBatchWriteback(config, batchId, { dryRun: true });
157
356
  return {
158
357
  batchId,
159
358
  dryRun: true,
160
- results: result.results,
161
- markdown: result.markdown,
162
- xlsx: result.xlsx,
163
- files: result.markdown?.filesTouched || [],
359
+ results: plan.results,
360
+ markdown: { files: plan.markdownFiles, inserted: plan.inserted, replaced: plan.replaced, filesTouched: plan.files },
361
+ xlsx: plan.xlsx,
362
+ files: plan.files,
363
+ documents: plan.documents,
364
+ errors: plan.errors,
164
365
  };
165
366
  }
166
367
 
167
- /** 整个批次结束后回写一次;由单写者锁保护。 */
368
+ /** 整个批次结束后回写一次;由单写者锁保护,单个文档失败不影响其它文档。 */
168
369
  export async function applyBatchWriteback(config, batchId, { dryRun = false } = {}) {
169
370
  const batch = readBatch(config, batchId);
170
371
  if (batch.status === 'queued' || batch.status === 'preparing' || batch.status === 'running') {
@@ -174,26 +375,29 @@ export async function applyBatchWriteback(config, batchId, { dryRun = false } =
174
375
  const lock = await acquireWritebackLock(config);
175
376
  try {
176
377
  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
- });
378
+ const plan = await planBatchWriteback(config, batchId, { dryRun: false });
185
379
  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,
380
+ at: nowIso(),
381
+ results: plan.results,
382
+ markdownFiles: plan.markdownFiles,
383
+ inserted: plan.inserted,
384
+ replaced: plan.replaced,
385
+ files: plan.files,
386
+ xlsx: plan.xlsx,
387
+ summaryPath: plan.summaryPath,
388
+ documents: plan.documents,
389
+ errors: plan.errors,
194
390
  };
195
391
  await patchBatch(config, batchId, { writeback: summary });
196
- await patchStage(config, batchId, 'writeback', { status: 'done', at: summary.at, files: summary.files.length });
392
+ const allFailed = plan.documents.length > 0
393
+ && plan.documents.every((item) => item.error)
394
+ && plan.legacyResults === 0;
395
+ await patchStage(config, batchId, 'writeback', {
396
+ status: allFailed ? 'failed' : 'done',
397
+ at: summary.at,
398
+ files: summary.files.length,
399
+ ...(allFailed ? { error: plan.errors.map((item) => item.message).join(';') } : {}),
400
+ });
197
401
  return summary;
198
402
  } catch (error) {
199
403
  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"