gz-laya-pilot 0.1.0 → 0.1.2

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.
Files changed (95) hide show
  1. package/NOTICE.md +20 -2
  2. package/README.md +54 -2
  3. package/dist/agent/bridge.d.ts +21 -0
  4. package/dist/agent/bridge.js +158 -0
  5. package/dist/agent/bridge.js.map +1 -0
  6. package/dist/agent/report.d.ts +54 -0
  7. package/dist/agent/report.js +100 -0
  8. package/dist/agent/report.js.map +1 -0
  9. package/dist/agent/run.d.ts +19 -0
  10. package/dist/agent/run.js +121 -0
  11. package/dist/agent/run.js.map +1 -0
  12. package/dist/agent/schema.d.ts +42 -0
  13. package/dist/agent/schema.js +9 -0
  14. package/dist/agent/schema.js.map +1 -0
  15. package/dist/agent/worker.d.ts +1 -0
  16. package/dist/agent/worker.js +102 -0
  17. package/dist/agent/worker.js.map +1 -0
  18. package/dist/cli.d.ts +2 -0
  19. package/dist/cli.js +7 -0
  20. package/dist/cli.js.map +1 -0
  21. package/dist/index.d.ts +3 -0
  22. package/dist/index.js +2 -0
  23. package/dist/index.js.map +1 -1
  24. package/package.json +14 -6
  25. package/src/agent/bridge.ts +180 -0
  26. package/src/agent/report.ts +139 -0
  27. package/src/agent/run.ts +136 -0
  28. package/src/agent/schema.ts +38 -0
  29. package/src/agent/worker.ts +114 -0
  30. package/src/cli.ts +5 -0
  31. package/src/index.ts +3 -0
  32. package/vendor/.gitattributes +5 -0
  33. package/vendor/UPSTREAM.json +168 -0
  34. package/vendor/laya-pilot/LICENSE +21 -0
  35. package/vendor/laya-pilot/README.en.md +116 -0
  36. package/vendor/laya-pilot/README.md +116 -0
  37. package/vendor/laya-pilot/ROADMAP.md +21 -0
  38. package/vendor/laya-pilot/config.example.json +14 -0
  39. package/vendor/laya-pilot/docs/architecture.md +21 -0
  40. package/vendor/laya-pilot/docs/browser-use-evaluation.md +32 -0
  41. package/vendor/laya-pilot/docs/demo.png +0 -0
  42. package/vendor/laya-pilot/docs/local-runtime.md +88 -0
  43. package/vendor/laya-pilot/docs/pr1-selection.md +33 -0
  44. package/vendor/laya-pilot/docs/retry-policy.md +14 -0
  45. package/vendor/laya-pilot/examples/demo-cases.xlsx +0 -0
  46. package/vendor/laya-pilot/examples/demo-server.mjs +19 -0
  47. package/vendor/laya-pilot/examples/demo.html +733 -0
  48. package/vendor/laya-pilot/lib/auth-state.mjs +141 -0
  49. package/vendor/laya-pilot/lib/browser-provider.mjs +43 -0
  50. package/vendor/laya-pilot/lib/diagnostics.mjs +210 -0
  51. package/vendor/laya-pilot/lib/discovery.mjs +474 -0
  52. package/vendor/laya-pilot/lib/dom.mjs +539 -0
  53. package/vendor/laya-pilot/lib/engine.mjs +879 -0
  54. package/vendor/laya-pilot/lib/form.mjs +377 -0
  55. package/vendor/laya-pilot/lib/language.mjs +273 -0
  56. package/vendor/laya-pilot/lib/model.mjs +271 -0
  57. package/vendor/laya-pilot/lib/page-capabilities.mjs +356 -0
  58. package/vendor/laya-pilot/lib/page-exploration.mjs +372 -0
  59. package/vendor/laya-pilot/lib/page-session.mjs +69 -0
  60. package/vendor/laya-pilot/lib/pending-writes.mjs +50 -0
  61. package/vendor/laya-pilot/lib/planner.mjs +127 -0
  62. package/vendor/laya-pilot/lib/project-config.mjs +95 -0
  63. package/vendor/laya-pilot/lib/readiness.mjs +179 -0
  64. package/vendor/laya-pilot/lib/related-records.mjs +328 -0
  65. package/vendor/laya-pilot/lib/replay-model.mjs +44 -0
  66. package/vendor/laya-pilot/lib/run-state.mjs +133 -0
  67. package/vendor/laya-pilot/lib/test-data.mjs +128 -0
  68. package/vendor/laya-pilot/lib/workflow-policy.mjs +68 -0
  69. package/vendor/laya-pilot/lib/workflow.mjs +2321 -0
  70. package/vendor/laya-pilot/lib/workflow_excel.py +462 -0
  71. package/vendor/laya-pilot/requirements-local.txt +2 -0
  72. package/vendor/laya-pilot/requirements.txt +1 -0
  73. package/vendor/laya-pilot/runner.mjs +452 -0
  74. package/vendor/laya-pilot/tests/api.test.mjs +98 -0
  75. package/vendor/laya-pilot/tests/browser/runtime.test.mjs +847 -0
  76. package/vendor/laya-pilot/tests/config.test.mjs +109 -0
  77. package/vendor/laya-pilot/tests/diagnostics.test.mjs +91 -0
  78. package/vendor/laya-pilot/tests/discovery.test.mjs +76 -0
  79. package/vendor/laya-pilot/tests/fixtures/local-model/laya.py +28 -0
  80. package/vendor/laya-pilot/tests/fixtures/local-model/torch.py +5 -0
  81. package/vendor/laya-pilot/tests/guards.test.mjs +43 -0
  82. package/vendor/laya-pilot/tests/language.test.mjs +39 -0
  83. package/vendor/laya-pilot/tests/planner.test.mjs +129 -0
  84. package/vendor/laya-pilot/tests/readiness.test.mjs +118 -0
  85. package/vendor/laya-pilot/tests/real-model.smoke.mjs +74 -0
  86. package/vendor/laya-pilot/tests/replay-model.test.mjs +90 -0
  87. package/vendor/laya-pilot/tests/retries.test.mjs +270 -0
  88. package/vendor/laya-pilot/tests/run-state.test.mjs +162 -0
  89. package/vendor/laya-pilot/tests/selected-pr1.test.mjs +309 -0
  90. package/vendor/laya-pilot/tests/test-data.test.mjs +83 -0
  91. package/vendor/laya-pilot/tests/test_workflow_excel.py +162 -0
  92. package/vendor/laya-pilot/tests/worker_test.py +33 -0
  93. package/vendor/laya-pilot/tests/workflow.test.mjs +98 -0
  94. package/vendor/laya-pilot/worker.py +135 -0
  95. package/vendor/patches/0001-native-field-recipes.patch +3009 -0
@@ -0,0 +1,462 @@
1
+ """Standalone XLSX contract for generated browser workflows."""
2
+
3
+ import copy
4
+ import hashlib
5
+ import json
6
+ import math
7
+ import sys
8
+ import unicodedata
9
+ from datetime import datetime
10
+ from pathlib import Path
11
+
12
+ from openpyxl import Workbook, load_workbook
13
+ from openpyxl.utils import get_column_letter
14
+
15
+
16
+ HEADERS = [
17
+ '测试编号',
18
+ '模块名称',
19
+ '子模块名称',
20
+ '测试用例名称',
21
+ '优先级',
22
+ '用例类型',
23
+ '用例类别',
24
+ '前提条件',
25
+ '测试步骤',
26
+ '预期结果',
27
+ '实际执行结果',
28
+ '执行测试人员',
29
+ '执行状态',
30
+ '用例引入阶段',
31
+ '执行日期',
32
+ '备注',
33
+ '是否提bug',
34
+ ]
35
+ META = '__laya_steps__'
36
+ TITLES = {
37
+ 'tabs': '页签入口可见',
38
+ 'tab-switch': '页签切换后可见并可切回',
39
+ 'table': '列表列头可见',
40
+ 'filters': '名称筛选控件可见',
41
+ 'form-validation': '新增表单必填项为空时阻止保存',
42
+ 'form-invalid': '数值区间示例的非法括号触发校验',
43
+ 'create': '新增独立测试记录',
44
+ 'search': '按名称查询刚创建的记录',
45
+ 'view': '查看独立测试记录',
46
+ 'edit': '修改独立测试记录名称',
47
+ 'delete': '删除独立测试记录',
48
+ 'discover': '模型发现的补充测试',
49
+ }
50
+ OPERATIONS = {'create': '新增', 'search': '查询', 'view': '查看', 'edit': '修改', 'delete': '删除'}
51
+
52
+
53
+ def cell_text(value):
54
+ return '' if value is None else str(value)
55
+
56
+
57
+ def visible_fields(sheet, row):
58
+ return [cell_text(sheet.cell(row, col).value) for col in (1, 4, 8, 9, 10)]
59
+
60
+
61
+ def digest(fields):
62
+ return hashlib.sha256(
63
+ json.dumps(fields, ensure_ascii=False, separators=(',', ':')).encode()
64
+ ).hexdigest()
65
+
66
+
67
+ def step_text(step):
68
+ kind = step['kind']
69
+ target = step.get('target', {}).get('name', '')
70
+ value = step.get('value', '')
71
+ if kind in ('assert-persisted-row', 'assert-persisted-absent'):
72
+ state = '存在唯一记录' if kind == 'assert-persisted-row' else '记录不存在'
73
+ return f'在独立后台浏览器会话重新打开相同模块,查询并核对{state}:{value}(不刷新当前主子应用)'
74
+ if kind == 'expand-tree':
75
+ node = step['target']
76
+ return f'在「{node["tree"]}」树中展开「{" → ".join(node["path"])}」,核对节点已展开'
77
+ if kind == 'open-owned-record':
78
+ return f'点击本轮独立记录「{value}」的名称入口,原地打开详情'
79
+ if kind == 'assert-record-detail':
80
+ return f'核对列表之外的详情标题或定义内容包含本轮记录「{value}」,不能用列表同名文本代替'
81
+ if kind == 'assert-query-result':
82
+ return f'核对唯一关键词查询只返回本轮记录「{value}」,不能只检查输入框文字'
83
+ if kind == 'assert-tab-panel':
84
+ return f'核对「{target}」页签选中且 aria-controls 关联的内容面板已显示'
85
+ if kind == 'assert-disclosure':
86
+ return f'在「{step["target"]["tab"]}」面板内展开「{target}」,核对新控件出现,再收起并核对状态恢复'
87
+ if kind == 'assert-related-records':
88
+ return (f'在本轮父记录的「{step["target"]["tab"]}」面板点击「{step["target"]["add"]}」;'
89
+ f'选择唯一数据「{step["item"]}」并确认;断言关联列表显示该记录,在独立会话重新打开并核对;'
90
+ f'选中该关联记录,点击「{step["target"]["remove"]}」;断言列表恢复为空,并再次独立校验。')
91
+ if kind == 'assert-discovery':
92
+ spec = step['spec']
93
+ check = spec['check']
94
+ if check == 'filter-empty':
95
+ search = (
96
+ f'点击「{spec["search"]["name"]}」' if spec.get('search') else '等待输入触发筛选'
97
+ )
98
+ return (
99
+ f'在「{spec["field"]["name"]}」输入本轮唯一不存在的关键词,{search},核对列表为空'
100
+ )
101
+ if check == 'filter-reset':
102
+ return f'先查询不存在的关键词并核对列表为空,再点击「{spec["reset"]["name"]}」,核对条件清空且原列表记录恢复'
103
+ if check == 'cancel-create':
104
+ return f'展开当前列表中的分类,点击「{spec["create"]["name"]}」,填写「{spec["label"]}」,点击「{spec["cancel"]["name"]}」,核对编辑区关闭且当前页面、独立会话均无新增记录,最后原地恢复筛选条件'
105
+ if check == 'field-invalid':
106
+ return f'打开新增表单,向「{spec["label"]}」输入违反 {spec["constraint"]}={spec.get("bound", "邮箱格式")} 的值,核对浏览器约束校验失败,再取消(不提交)'
107
+ raise ValueError('不支持的补充测试:' + check)
108
+ if kind == 'click':
109
+ return f'点击「{target}」' + (
110
+ '(本轮记录所在行)' if step.get('target', {}).get('scope') == 'owned-row' else ''
111
+ )
112
+ if kind == 'fill':
113
+ if isinstance(value, dict):
114
+ value = '${' + value['fixture'] + '}'
115
+ return f'在「{target}」输入「{value}」'
116
+ if kind == 'form-fill':
117
+ return f'在表单「{step["target"]["label"]}」第{step["target"]["index"] + 1}个输入框输入「{value}」'
118
+ if kind == 'form-fill-required':
119
+ return f'在必填输入框「{step["target"]["placeholder"]}」第{step["target"]["index"] + 1}项输入「{value}」'
120
+ if kind == 'form-select':
121
+ return f'在表单「{step["target"]["label"]}」依次选择:' + ' → '.join(step['path'])
122
+ if kind == 'form-date':
123
+ return f'在表单「{step["target"]["label"]}」选择日期「{value}」'
124
+ if kind == 'assert-form-errors':
125
+ return '核对表单未关闭,必填字段显示校验错误:' + '、'.join(value)
126
+ if kind == 'assert-input-invalid':
127
+ return f'核对必填输入框「{step["target"]["placeholder"]}」第{step["target"]["index"] + 1}项显示格式错误'
128
+ if kind == 'reload':
129
+ return '重新加载页面,验证数据已保存'
130
+ if kind == 'assert-row':
131
+ return f'核对列表存在「{value}」'
132
+ if kind == 'assert-absent':
133
+ return f'核对列表不存在「{value}」'
134
+ if kind == 'assert-text':
135
+ return f'核对详情显示「{value}」'
136
+ if kind == 'assert-control':
137
+ return f'核对「{target}」控件可见'
138
+ if kind == 'assert-selected':
139
+ return f'核对「{target}」Tab已选中'
140
+ if kind == 'assert-headers':
141
+ return '核对列表列头包含:' + '、'.join(value)
142
+ if kind == 'assert-disabled':
143
+ return f'核对必填项为空时「{target}」按钮处于禁用状态(阻止保存)'
144
+ raise ValueError('不支持的步骤:' + kind)
145
+
146
+
147
+ def expected_text(case):
148
+ checks = [step_text(step) for step in case['steps'] if step['kind'].startswith('assert-')]
149
+ if not checks:
150
+ raise ValueError('用例没有页面断言:' + case['id'])
151
+ return '\n'.join(f'{i}、{text}' for i, text in enumerate(checks, 1))
152
+
153
+
154
+ def load_template(path):
155
+ if not path:
156
+ source = Workbook()
157
+ sheet = source.active
158
+ sheet.title = '测试用例'
159
+ sheet.append(HEADERS)
160
+ return source, sheet
161
+ path = Path(path)
162
+ if not path.is_file():
163
+ raise ValueError('找不到原 Excel 模板,请传 --template-excel:' + str(path))
164
+ source = load_workbook(path, read_only=False)
165
+ sheet = source.active
166
+ actual = [sheet.cell(1, i).value for i in range(1, 18)]
167
+ if actual != HEADERS:
168
+ raise ValueError('模板表头不是之前的 17 列用例格式')
169
+ return source, sheet
170
+
171
+
172
+ def write(payload):
173
+ file = payload['file']
174
+ # 失败原因常含 ANSI 转义序列(\u001b[2m 等)与其它控制字符,openpyxl 会抛
175
+ # IllegalCharacterError 并把整个用例文件写出炸掉。统一在入口清洗。
176
+ from openpyxl.cell.cell import ILLEGAL_CHARACTERS_RE
177
+
178
+ def clean(v):
179
+ return ILLEGAL_CHARACTERS_RE.sub('', v) if isinstance(v, str) else v
180
+
181
+ source, old = load_template(payload.get('template'))
182
+ book = Workbook()
183
+ sheet = book.active
184
+ sheet.title = '生成用例'
185
+ sheet.sheet_view.showGridLines = old.sheet_view.showGridLines
186
+ sheet.freeze_panes = 'A2'
187
+ for col in range(1, 18):
188
+ original = old.cell(1, col)
189
+ cell = sheet.cell(1, col, original.value)
190
+ if original.has_style:
191
+ cell._style = copy.copy(original._style)
192
+ cell.alignment = copy.copy(original.alignment)
193
+ letter = get_column_letter(col)
194
+ sheet.column_dimensions[letter].width = old.column_dimensions[letter].width or 16
195
+ # The source hides several case-identifying columns. Generated cases
196
+ # should expose their ID and module while retaining source widths.
197
+ sheet.column_dimensions[letter].hidden = False
198
+ sheet.row_dimensions[1].height = old.row_dimensions[1].height
199
+ meta = book.create_sheet(META)
200
+ meta.sheet_state = 'veryHidden'
201
+ meta['A1'] = json.dumps(
202
+ {
203
+ 'schemaVersion': file['schemaVersion'],
204
+ 'generatedAt': file['generatedAt'],
205
+ 'moduleUrl': file['moduleUrl'],
206
+ 'coverage': file['coverage'],
207
+ 'exploration': file.get('exploration'),
208
+ },
209
+ ensure_ascii=False,
210
+ )
211
+ meta.append(['id', 'visible_sha256', 'case_json'])
212
+ module = Path(file['moduleUrl'].split('?')[0].rstrip('/')).name or '目标页面'
213
+ if file.get('exploration'):
214
+ scope = book.create_sheet('探索范围')
215
+ scope.append(['已观察状态', '入口', '未验证原因'])
216
+ scope.append(['说明', '用例通过不代表页面功能全覆盖', '以下入口未计入通过用例'])
217
+ for gap in file['exploration'].get('gaps', []):
218
+ scope.append([clean(gap.get('state')), clean(gap.get('name')), clean(gap.get('reason'))])
219
+ scope.freeze_panes = 'A2'
220
+ for letter, width in [('A', 32), ('B', 35), ('C', 65)]:
221
+ scope.column_dimensions[letter].width = width
222
+ for index, case in enumerate(file['cases'], 2):
223
+ uses_owned_record = case['operation'] in ('create', 'search', 'view', 'related-records', 'edit', 'delete')
224
+ precondition = (
225
+ '已登录并进入目标模块;使用本轮唯一命名的独立测试记录'
226
+ if uses_owned_record
227
+ else '已登录并进入目标模块'
228
+ )
229
+ remark = (
230
+ '生成时已执行并验证;执行模式将使用新的独立测试记录'
231
+ if uses_owned_record
232
+ else '生成时已执行并验证;执行模式将重新检查页面,不创建记录'
233
+ )
234
+ values = [
235
+ f'{index - 1:03d}',
236
+ module,
237
+ module,
238
+ f'{module} - {case.get("title") or TITLES[case["operation"]]}',
239
+ '中',
240
+ '正案例',
241
+ '功能',
242
+ precondition,
243
+ '\n'.join(f'{n}、{step_text(step)}' for n, step in enumerate(case['steps'], 1)),
244
+ expected_text(case),
245
+ None,
246
+ None,
247
+ '未执行',
248
+ '自动生成',
249
+ None,
250
+ remark,
251
+ None,
252
+ ]
253
+ values = [clean(v) for v in values]
254
+ for col, value in enumerate(values, 1):
255
+ dest = sheet.cell(index, col, value)
256
+ sample = old.cell(2, col)
257
+ if sample.has_style:
258
+ dest._style = copy.copy(sample._style)
259
+ dest.alignment = copy.copy(sample.alignment)
260
+ if col == 1:
261
+ dest.number_format = '@'
262
+ elif isinstance(value, str):
263
+ # Names and page text are untrusted workbook input. Keep them
264
+ # literal even if a site label begins with an Excel formula.
265
+ dest.data_type = 's'
266
+ sheet.row_dimensions[index].height = min(
267
+ 280, max(42, 18 * max(values[8].count('\n') + 1, values[9].count('\n') + 1))
268
+ )
269
+ meta.append(
270
+ [
271
+ values[0],
272
+ digest(visible_fields(sheet, index)),
273
+ clean(json.dumps(case, ensure_ascii=False)),
274
+ ]
275
+ )
276
+ sheet.auto_filter.ref = f'A1:Q{max(2, sheet.max_row)}'
277
+ Path(payload['path']).parent.mkdir(parents=True, exist_ok=True)
278
+ book.save(payload['path'])
279
+ source.close()
280
+ return {'path': payload['path'], 'cases': len(file['cases'])}
281
+
282
+
283
+ def read(payload):
284
+ book = load_workbook(payload['path'], read_only=False, data_only=False)
285
+ if META not in book or book[META].sheet_state not in ('hidden', 'veryHidden'):
286
+ raise ValueError('没有隐藏的 Laya 回放步骤,不能仅凭可见文字执行写入操作')
287
+ sheet = book['生成用例']
288
+ if [sheet.cell(1, i).value for i in range(1, 18)] != HEADERS:
289
+ raise ValueError('生成用例表头已改变,无法安全读取')
290
+ meta = book[META]
291
+ header = json.loads(meta['A1'].value)
292
+ cases = []
293
+ for row in range(3, meta.max_row + 1):
294
+ case_id, saved_hash, recipe = [meta.cell(row, col).value for col in (1, 2, 3)]
295
+ visible_row = row - 1
296
+ if digest(visible_fields(sheet, visible_row)) != saved_hash:
297
+ raise ValueError(
298
+ f'第{visible_row}行可见用例已修改,与隐藏回放步骤不一致,请重新生成或校对后再执行'
299
+ )
300
+ case = json.loads(recipe)
301
+ if case_id != sheet.cell(visible_row, 1).value:
302
+ raise ValueError(f'第{visible_row}行用例编号不一致')
303
+ cases.append(case)
304
+ book.close()
305
+ return {
306
+ 'schemaVersion': header['schemaVersion'],
307
+ 'moduleUrl': header['moduleUrl'],
308
+ 'cases': cases,
309
+ 'coverage': header.get('coverage', []),
310
+ 'exploration': header.get('exploration'),
311
+ }
312
+
313
+
314
+ def report(payload):
315
+ """All attempted cases, including generation failures and interrupted runs."""
316
+ from openpyxl.cell.cell import ILLEGAL_CHARACTERS_RE
317
+ from openpyxl.styles import Alignment, Font
318
+
319
+ book = Workbook()
320
+ sheet = book.active
321
+ sheet.title = '生成验证结果' if payload['mode'] == 'generate' else '执行结果'
322
+ sheet.append(HEADERS)
323
+ sheet.freeze_panes = 'A2'
324
+ sheet.auto_filter.ref = f'A1:Q{max(1, len(payload["results"]) + 1)}'
325
+ stage = '生成时验证' if payload['mode'] == 'generate' else '回放执行'
326
+ run_at = (
327
+ datetime.fromisoformat(payload['runAt'].replace('Z', '+00:00'))
328
+ .astimezone()
329
+ .replace(tzinfo=None)
330
+ if payload.get('runAt')
331
+ else datetime.now()
332
+ )
333
+ for i, result in enumerate(payload['results'], 1):
334
+ status = result['status']
335
+ steps = result.get('steps', [])
336
+ texts = [step_text(s) for s in steps]
337
+ assertions = [step_text(s) for s in steps if s['kind'].startswith('assert-')]
338
+ notes = [stage, result.get('reason', '')]
339
+ if result.get('evidence'):
340
+ notes.append('证据:' + result['evidence'])
341
+ if result.get('diagnosis', {}).get('category') if result.get('diagnosis') else False:
342
+ notes.append('原因分类:' + result['diagnosis']['category'])
343
+ values = [
344
+ result.get('id', str(i)),
345
+ payload.get('moduleUrl', ''),
346
+ '',
347
+ result.get('title', ''),
348
+ '中',
349
+ '负案例' if result.get('operation') in ('form-validation', 'form-invalid') else '功能',
350
+ result.get('operation', ''),
351
+ '已登录并进入目标模块',
352
+ '\n'.join(texts),
353
+ '\n'.join(assertions),
354
+ 'pass'
355
+ if status in ('已验证', '通过')
356
+ else 'skip'
357
+ if status in ('不适用', '未执行(依赖阻断)')
358
+ else 'fail',
359
+ '',
360
+ status,
361
+ stage,
362
+ run_at,
363
+ '\n'.join(notes),
364
+ '',
365
+ ]
366
+ sheet.append(
367
+ [ILLEGAL_CHARACTERS_RE.sub('', v) if isinstance(v, str) else v for v in values]
368
+ )
369
+ for cell in sheet[i + 1]:
370
+ if isinstance(cell.value, str):
371
+ cell.data_type = 's'
372
+ cell.alignment = Alignment(wrap_text=True, vertical='top')
373
+ sheet.row_dimensions[i + 1].height = min(300, max(45, len(texts) * 18))
374
+ for cell in sheet[1]:
375
+ cell.font = Font(bold=True)
376
+ for i in range(1, 18):
377
+ sheet.column_dimensions[get_column_letter(i)].width = (
378
+ 60 if i in (9, 10, 16) else 24 if i in (2, 4) else 16
379
+ )
380
+ Path(payload['output']).parent.mkdir(parents=True, exist_ok=True)
381
+ book.save(payload['output'])
382
+ return {'path': payload['output'], 'cases': len(payload['results'])}
383
+
384
+
385
+ def results(payload):
386
+ book = load_workbook(payload['path'])
387
+ sheet = book['生成用例']
388
+ sheet.column_dimensions['P'].width = max(sheet.column_dimensions['P'].width or 0, 70)
389
+ for row, result in enumerate(payload['results'], 2):
390
+ if (
391
+ row > sheet.max_row
392
+ or result['id'] != json.loads(book[META].cell(row + 1, 3).value)['id']
393
+ ):
394
+ raise ValueError('执行结果与生成用例顺序不一致')
395
+ sheet.cell(row, 11).value = (
396
+ 'pass'
397
+ if result['status'] == '通过'
398
+ else 'skip'
399
+ if result['status'] == '未执行(依赖阻断)'
400
+ else 'fail'
401
+ )
402
+ sheet.cell(row, 13).value = (
403
+ '未执行' if result['status'] == '未执行(依赖阻断)' else '已执行'
404
+ )
405
+ sheet.cell(row, 15).value = (
406
+ None if result['status'] == '未执行(依赖阻断)' else datetime.now()
407
+ )
408
+ diagnosis = result.get('diagnosis') or {}
409
+ step = result.get('failedStep') or {}
410
+ notes = [f'原因分类:{diagnosis["category"]}'] if diagnosis.get('category') else []
411
+ if step.get('number'):
412
+ notes.append(
413
+ f'失败步骤:{step["number"]}({step.get("action", "")} {step.get("target", "")})'
414
+ )
415
+ if not diagnosis.get('primary') or diagnosis['primary'] not in result['reason']:
416
+ notes.append(f'执行错误:{result["reason"]}')
417
+ if diagnosis.get('assessment'):
418
+ notes.append(f'判断:{diagnosis["assessment"]}')
419
+ if diagnosis.get('primary'):
420
+ notes.append(f'同期证据:{diagnosis["primary"]}')
421
+ for attempt in result.get('attempts', []):
422
+ notes.append(
423
+ f'尝试:{attempt["step"]} 第{attempt["attempt"]}次 {attempt["status"]} {attempt.get("reason", "")}'
424
+ )
425
+ note = '\n'.join(notes)[:3000]
426
+ # 回放失败原因含 ANSI 转义(\u001b[2m 等),openpyxl 会抛 IllegalCharacterError
427
+ from openpyxl.cell.cell import ILLEGAL_CHARACTERS_RE
428
+
429
+ note = ILLEGAL_CHARACTERS_RE.sub('', note)
430
+ remark = sheet.cell(row, 16)
431
+ remark.value = note
432
+ alignment = copy.copy(remark.alignment)
433
+ alignment.wrap_text = True
434
+ alignment.vertical = 'top'
435
+ remark.alignment = alignment
436
+ visual_lines = sum(
437
+ max(
438
+ 1,
439
+ math.ceil(
440
+ sum(2 if unicodedata.east_asian_width(ch) in 'WF' else 1 for ch in line) / 66
441
+ ),
442
+ )
443
+ for line in note.split('\n')
444
+ )
445
+ sheet.row_dimensions[row].height = min(
446
+ 300, max(sheet.row_dimensions[row].height or 0, visual_lines * 18 + 12)
447
+ )
448
+ Path(payload['output']).parent.mkdir(parents=True, exist_ok=True)
449
+ book.save(payload['output'])
450
+ return {'path': payload['output'], 'cases': len(payload['results'])}
451
+
452
+
453
+ if __name__ == '__main__':
454
+ try:
455
+ data = json.load(sys.stdin)
456
+ result = {'write': write, 'read': read, 'results': results, 'report': report}[sys.argv[1]](
457
+ data
458
+ )
459
+ print(json.dumps(result, ensure_ascii=False))
460
+ except Exception as exc:
461
+ print(f'{type(exc).__name__}: {exc}', file=sys.stderr)
462
+ sys.exit(1)
@@ -0,0 +1,2 @@
1
+ -r requirements.txt
2
+ laya==0.3.5
@@ -0,0 +1 @@
1
+ openpyxl>=3.1,<4