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,309 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { EventEmitter } from 'node:events';
4
+ import vm from 'node:vm';
5
+ import { PendingWrites } from '../lib/pending-writes.mjs';
6
+ import { Workflow, validateWorkflow } from '../lib/workflow.mjs';
7
+ import { observe } from '../lib/dom.mjs';
8
+ import { inspectLooseRequired, looseInputRef, formErrors } from '../lib/form.mjs';
9
+ const tick = () => new Promise((resolve) => setImmediate(resolve));
10
+ const quietPage = () => ({
11
+ waitForLoadState: async () => {},
12
+ waitForTimeout: async () => {},
13
+ locator: () => ({ first: () => ({ waitFor: async () => {} }) }),
14
+ });
15
+ test('sibling labels name input fields without renaming save/cancel buttons', async () => {
16
+ const node = (tag, text, previous = null) => ({
17
+ tagName: tag,
18
+ innerText: text,
19
+ previousElementSibling: previous,
20
+ parentElement: null,
21
+ getAttribute: () => null,
22
+ hasAttribute: () => false,
23
+ setAttribute: () => {},
24
+ closest: () => null,
25
+ querySelector: () => null,
26
+ matches: () => false,
27
+ getBoundingClientRect: () => ({
28
+ width: 100,
29
+ height: 30,
30
+ left: 0,
31
+ right: 100,
32
+ top: 0,
33
+ bottom: 30,
34
+ }),
35
+ classList: { contains: () => false },
36
+ });
37
+ const label = node('LABEL', '名称'),
38
+ input = node('INPUT', '', label),
39
+ save = node('BUTTON', '保存', input),
40
+ cancel = node('BUTTON', '取消', save);
41
+ const document = {
42
+ querySelectorAll: (selector) =>
43
+ selector === '*'
44
+ ? [label, input, save, cancel]
45
+ : selector.startsWith('button,a[href],input')
46
+ ? [input, save, cancel]
47
+ : [],
48
+ getElementById: () => null,
49
+ };
50
+ const frame = {
51
+ evaluate: async (fn, args) =>
52
+ vm.runInNewContext(`(${fn.toString()})(args)`, {
53
+ args,
54
+ document,
55
+ getComputedStyle: () => ({ display: 'block', visibility: 'visible' }),
56
+ }),
57
+ };
58
+ const result = await observe({ frames: () => [frame], url: () => 'https://test.local' });
59
+ assert.deepEqual(
60
+ result.controls.map((c) => c.name),
61
+ ['名称', '保存', '取消'],
62
+ );
63
+ });
64
+
65
+ test('create retries use fresh refs and reach the second live entry', async () => {
66
+ let generation = 0;
67
+ const clicked = [];
68
+ const fake = {
69
+ checkInterrupted: () => {},
70
+ page: quietPage(),
71
+ snapshot: async () => {
72
+ generation++;
73
+ return {
74
+ controls: ['新增甲', '新增乙'].map((name, i) => ({
75
+ name,
76
+ role: 'button',
77
+ ref: generation + '-' + i,
78
+ frame: 0,
79
+ })),
80
+ frames: [
81
+ {
82
+ locator: (selector) => ({
83
+ count: async () => (selector.includes('"' + generation + '-') ? 1 : 0),
84
+ isVisible: async () => true,
85
+ evaluate: async () => false, // Entries in this fixture are outside a tree.
86
+ }),
87
+ },
88
+ ],
89
+ };
90
+ },
91
+ safeClick: async (_, name) => clicked.push(name),
92
+ record: () => {},
93
+ waitForEditor: async () => {
94
+ if (!clicked.includes('新增乙')) throw Error('No editor opened');
95
+ },
96
+ editorPresent: async () => clicked.includes('新增乙'),
97
+ chooseFromSnapshot: async (snap, candidates) => {
98
+ const control = candidates[0];
99
+ const locator = snap.frames[control.frame].locator(
100
+ `[data-laya-live-ref="${control.ref}"]`,
101
+ );
102
+ assert.equal(await locator.count(), 1, 'must select the current observed reference');
103
+ return { control, locator };
104
+ },
105
+ dismissModal: async () => {},
106
+ };
107
+ await Workflow.prototype.withAttempts.call(fake, 'clickCreate', () =>
108
+ Workflow.prototype.clickCreate.call(fake),
109
+ );
110
+ assert.deepEqual(clicked, ['新增甲', '新增乙']);
111
+ });
112
+
113
+ test('disabled assertions reject enabled and ambiguous targets and never click', async () => {
114
+ const step = { kind: 'assert-disabled', target: { name: '保存', role: 'button' } };
115
+ for (const states of [[true], [false], [true, false], []]) {
116
+ const fake = {
117
+ snapshot: async () => ({
118
+ controls: states.map((disabled) => ({ name: '保存', role: 'button', disabled })),
119
+ }),
120
+ record: () => {},
121
+ safeClick: () => assert.fail('assertion clicked'),
122
+ };
123
+ if (states.length === 1 && states[0]) await Workflow.prototype.replayStep.call(fake, step);
124
+ else await assert.rejects(Workflow.prototype.replayStep.call(fake, step));
125
+ }
126
+ });
127
+
128
+ test('writes wait for completion while GET polling does not block', async () => {
129
+ const page = new EventEmitter(),
130
+ writes = new PendingWrites(page),
131
+ post = { method: () => 'POST' },
132
+ poll = { method: () => 'GET' };
133
+ page.emit('request', post);
134
+ page.emit('request', poll);
135
+ let finished = false;
136
+ const waiting = writes.wait().then(() => {
137
+ finished = true;
138
+ });
139
+ await tick();
140
+ assert.equal(finished, false);
141
+ page.emit('requestfinished', post);
142
+ await waiting;
143
+ assert.equal(finished, true);
144
+ const deletion = { method: () => 'DELETE' };
145
+ page.emit('request', deletion);
146
+ await assert.rejects(writes.wait(5), /拒绝刷新/);
147
+ page.emit('requestfailed', deletion);
148
+ await writes.wait();
149
+ });
150
+
151
+ test('save and delete-confirm replay cannot reload until modal and writes finish', async () => {
152
+ for (const purpose of ['save', 'confirm', 'delete']) {
153
+ const page = new EventEmitter(),
154
+ writes = new PendingWrites(page),
155
+ request = { method: () => 'POST' };
156
+ page.emit('request', request);
157
+ const events = [];
158
+ page.reload = async () => {
159
+ events.push('reload');
160
+ throw Error('reached reload');
161
+ };
162
+ const fake = {
163
+ case: { steps: [{ kind: 'click', purpose }] },
164
+ config: { pageTimeout: 1000 },
165
+ page,
166
+ pendingWrites: writes,
167
+ waitModalClosed: async () => events.push('modal closed'),
168
+ };
169
+ const attempt = assert.rejects(Workflow.prototype.reload.call(fake), /reached reload/);
170
+ await tick();
171
+ assert.deepEqual(events, ['modal closed']);
172
+ page.emit('requestfinished', request);
173
+ await attempt;
174
+ assert.deepEqual(events, ['modal closed', 'reload']);
175
+ }
176
+ });
177
+
178
+ test('modal timeout and intercepted clicks remain failures', async () => {
179
+ let reloaded = false;
180
+ await assert.rejects(
181
+ Workflow.prototype.reload.call({
182
+ case: { steps: [{ kind: 'click', purpose: 'save' }] },
183
+ waitModalClosed: async () => {
184
+ throw Error('modal timeout');
185
+ },
186
+ page: {
187
+ reload: () => {
188
+ reloaded = true;
189
+ },
190
+ },
191
+ }),
192
+ /modal timeout/,
193
+ );
194
+ assert.equal(reloaded, false);
195
+ let attempts = 0;
196
+ await assert.rejects(
197
+ Workflow.prototype.safeClick.call(
198
+ {},
199
+ {
200
+ click: async () => {
201
+ throw Error(++attempts === 1 ? 'intercepts pointer events' : 'detached');
202
+ },
203
+ evaluate: async () => true,
204
+ },
205
+ ),
206
+ /intercepts pointer events/,
207
+ );
208
+ });
209
+
210
+ test('native required inputs retain stable label identity after required is removed', async () => {
211
+ const attributes = new Map();
212
+ let required = true;
213
+ const label = { tagName: 'LABEL', innerText: '邮箱' };
214
+ const input = {
215
+ tagName: 'INPUT',
216
+ previousElementSibling: label,
217
+ value: '',
218
+ disabled: false,
219
+ readOnly: false,
220
+ getBoundingClientRect: () => ({ width: 100, height: 30 }),
221
+ closest: () => null,
222
+ getAttribute: (name) =>
223
+ name === 'placeholder'
224
+ ? 'email'
225
+ : name === 'type'
226
+ ? 'email'
227
+ : attributes.get(name) || null,
228
+ setAttribute: (name, value) => attributes.set(name, value),
229
+ };
230
+ const root = {
231
+ getBoundingClientRect: input.getBoundingClientRect,
232
+ querySelectorAll: (selector) => (selector === 'input,textarea' || required ? [input] : []),
233
+ };
234
+ const document = { querySelectorAll: () => [root] };
235
+ const page = {
236
+ evaluate: async (fn, args) =>
237
+ vm.runInNewContext(`(${fn.toString()})(args)`, {
238
+ args,
239
+ document,
240
+ getComputedStyle: () => ({ display: 'block', visibility: 'visible' }),
241
+ }),
242
+ };
243
+ const fields = await inspectLooseRequired(page);
244
+ assert.equal(fields.length, 1);
245
+ assert.equal(fields[0].label, '邮箱');
246
+ required = false;
247
+ input.value = 'a@example.com';
248
+ assert.ok(await looseInputRef(page, fields[0]));
249
+ assert.equal((await inspectLooseRequired(page)).length, 0);
250
+ });
251
+
252
+ test('native validity messages identify inputs without component error wrappers', async () => {
253
+ const input = {
254
+ tagName: 'INPUT',
255
+ labels: [],
256
+ previousElementSibling: { tagName: 'LABEL', innerText: '邮箱' },
257
+ validationMessage: 'Please fill out this field.',
258
+ getAttribute: () => null,
259
+ getBoundingClientRect: () => ({ width: 50, height: 20 }),
260
+ };
261
+ const root = {
262
+ getBoundingClientRect: input.getBoundingClientRect,
263
+ querySelectorAll: (selector) =>
264
+ selector === 'input:invalid,textarea:invalid,select:invalid' ? [input] : [],
265
+ };
266
+ const page = {
267
+ evaluate: async (fn, args) =>
268
+ vm.runInNewContext(`(${fn.toString()})(args)`, {
269
+ args,
270
+ document: { querySelectorAll: () => [root] },
271
+ getComputedStyle: () => ({ display: 'block', visibility: 'visible' }),
272
+ }),
273
+ };
274
+ const errors = await formErrors(page);
275
+ assert.equal(errors.open, true);
276
+ assert.equal(errors.labels[0], '邮箱');
277
+ assert.equal(errors.messages[0], input.validationMessage);
278
+ });
279
+
280
+ test('saved disabled assertions reject missing targets and legacy required steps still validate', () => {
281
+ const file = {
282
+ schemaVersion: 1,
283
+ moduleUrl: 'https://app.test',
284
+ cases: [
285
+ {
286
+ id: 'validation',
287
+ operation: 'form-validation',
288
+ steps: [{ kind: 'assert-disabled', target: { name: '保存', role: 'button' } }],
289
+ },
290
+ ],
291
+ };
292
+ assert.equal(validateWorkflow(file), file);
293
+ delete file.cases[0].steps[0].target;
294
+ assert.throws(() => validateWorkflow(file), /禁用态断言/);
295
+ file.cases = [
296
+ {
297
+ id: 'create',
298
+ operation: 'create',
299
+ steps: [
300
+ {
301
+ kind: 'form-fill-required',
302
+ target: { placeholder: '邮箱', index: 0 },
303
+ value: 'a@example.com',
304
+ },
305
+ ],
306
+ },
307
+ ];
308
+ assert.equal(validateWorkflow(file), file);
309
+ });
@@ -0,0 +1,83 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import {
4
+ optionGroups,
5
+ chooseTestOption,
6
+ chooseFieldValue,
7
+ tomorrowDate,
8
+ } from '../lib/test-data.mjs';
9
+
10
+ test('candidate generation excludes administrator roles and preserves observed values', async () => {
11
+ const options = ['超级管理员', '普通用户', '测试用户'].map((name) => ({ name }));
12
+ const groups = optionGroups('角色', options);
13
+ assert.equal(
14
+ [...groups.values()].flat().some((x) => x.name === '超级管理员'),
15
+ false,
16
+ );
17
+ const laya = {
18
+ choose: async (_, criteria) => {
19
+ assert.equal(JSON.stringify(criteria).includes('超级管理员'), false);
20
+ return {
21
+ choice: '普通或只读选项',
22
+ probabilities: { 普通或只读选项: 0.9 },
23
+ margin: 0.8,
24
+ };
25
+ },
26
+ };
27
+ assert.equal((await chooseTestOption(laya, '角色', options)).name, '普通用户');
28
+ await assert.rejects(chooseTestOption(laya, '角色', [{ name: '超级管理员' }]), /没有适合/);
29
+ });
30
+
31
+ test('equivalent test options prefer a visible leaf and low confidence stops selection', async () => {
32
+ const options = [
33
+ { name: 'test', branch: true },
34
+ { name: 'test_leaf', branch: false },
35
+ ];
36
+ const laya = {
37
+ choose: async (_, criteria, meta) => {
38
+ assert.equal(meta.phase, 'form-option');
39
+ assert.ok(criteria['测试用途选项']);
40
+ return { choice: '测试用途选项', probabilities: { 测试用途选项: 0.9 }, margin: 0.8 };
41
+ },
42
+ };
43
+ assert.equal((await chooseTestOption(laya, '机构', options)).name, 'test_leaf');
44
+ await assert.rejects(
45
+ chooseTestOption(
46
+ {
47
+ choose: async () => ({
48
+ choice: '测试用途选项',
49
+ probabilities: { 测试用途选项: 0.3 },
50
+ margin: 0.02,
51
+ }),
52
+ },
53
+ '角色',
54
+ options,
55
+ ),
56
+ /模型未能确定/,
57
+ );
58
+ });
59
+
60
+ test('field semantics reach the model and preserve fresh replay variables', async () => {
61
+ const calls = [];
62
+ const model = {
63
+ choose: async (state, criteria, meta) => {
64
+ calls.push(meta);
65
+ assert.ok(criteria.账号);
66
+ return { choice: '账号', probabilities: { 账号: 0.92 }, margin: 0.8 };
67
+ },
68
+ };
69
+ assert.equal((await chooseFieldValue(model, { label: '登录账号' })).value, '${recordAccount}');
70
+ assert.equal(calls[0].phase, 'form-field');
71
+ await assert.rejects(
72
+ chooseFieldValue(
73
+ { choose: async () => ({ choice: '编造', probabilities: { 编造: 1 }, margin: 1 }) },
74
+ { label: '未知' },
75
+ ),
76
+ /模型未能确定/,
77
+ );
78
+ });
79
+
80
+ test('relative expiry rolls into the following month and year', () => {
81
+ assert.equal(tomorrowDate(new Date(2026, 8, 30, 12)), '2026-10-01');
82
+ assert.equal(tomorrowDate(new Date(2026, 11, 31, 12)), '2027-01-01');
83
+ });
@@ -0,0 +1,162 @@
1
+ import importlib.util
2
+ import tempfile
3
+ import unittest
4
+ from pathlib import Path
5
+
6
+ spec = importlib.util.spec_from_file_location(
7
+ 'workflow_excel', Path(__file__).resolve().parents[1] / 'lib/workflow_excel.py'
8
+ )
9
+ excel = importlib.util.module_from_spec(spec)
10
+ spec.loader.exec_module(excel)
11
+
12
+
13
+ class WorkbookTests(unittest.TestCase):
14
+ def test_generation_report_keeps_failed_and_skipped_cases(self):
15
+ with tempfile.TemporaryDirectory(prefix='laya-report-') as directory:
16
+ output = str(Path(directory) / '执行结果.xlsx')
17
+ rows = [
18
+ {
19
+ 'id': 'ok',
20
+ 'title': '=unsafe',
21
+ 'status': '已验证',
22
+ 'steps': [{'kind': 'assert-control', 'target': {'name': '名称'}}],
23
+ 'reason': '通过',
24
+ },
25
+ {
26
+ 'id': 'failed',
27
+ 'status': '未生成',
28
+ 'steps': [],
29
+ 'reason': '\x1b[2m错误',
30
+ 'diagnosis': None,
31
+ },
32
+ {
33
+ 'id': 'blocked',
34
+ 'status': '未执行(依赖阻断)',
35
+ 'steps': [],
36
+ 'reason': '依赖未通过',
37
+ },
38
+ ]
39
+ excel.report({'mode': 'generate', 'output': output, 'results': rows})
40
+ book = excel.load_workbook(output)
41
+ sheet = book['生成验证结果']
42
+ self.assertEqual(sheet.max_row, 4)
43
+ self.assertEqual([sheet.cell(i, 11).value for i in (2, 3, 4)], ['pass', 'fail', 'skip'])
44
+ self.assertEqual(sheet.cell(2, 4).data_type, 's')
45
+ self.assertEqual(sheet.cell(2, 14).value, '生成时验证')
46
+ book.close()
47
+
48
+ def test_discovery_roundtrip_includes_readable_assertions(self):
49
+ with tempfile.TemporaryDirectory(prefix='laya-discovery-') as directory:
50
+ source = str(Path(directory) / 'cases.xlsx')
51
+ step = {
52
+ 'kind': 'assert-discovery',
53
+ 'spec': {
54
+ 'check': 'field-invalid',
55
+ 'label': '数量',
56
+ 'constraint': 'min',
57
+ 'bound': 1,
58
+ },
59
+ }
60
+ case = {
61
+ 'id': 'discovered',
62
+ 'operation': 'discover',
63
+ 'title': '数量下界校验',
64
+ 'steps': [step],
65
+ }
66
+ excel.write(
67
+ {
68
+ 'path': source,
69
+ 'file': {
70
+ 'schemaVersion': 1,
71
+ 'generatedAt': 'test',
72
+ 'moduleUrl': 'https://app.test/users',
73
+ 'coverage': [],
74
+ 'cases': [case],
75
+ },
76
+ }
77
+ )
78
+ self.assertEqual(excel.read({'path': source})['cases'][0], case)
79
+ self.assertIn('min=1', excel.expected_text(case))
80
+
81
+ def test_relative_date_step_roundtrip(self):
82
+ with tempfile.TemporaryDirectory(prefix='laya-date-') as directory:
83
+ source = str(Path(directory) / 'cases.xlsx')
84
+ step = {'kind': 'form-date', 'target': {'label': '过期时间'}, 'value': '${expiryDate}'}
85
+ case = {
86
+ 'id': 'create',
87
+ 'operation': 'create',
88
+ 'steps': [step, {'kind': 'assert-row', 'value': '${recordName}'}],
89
+ }
90
+ excel.write(
91
+ {
92
+ 'path': source,
93
+ 'file': {
94
+ 'schemaVersion': 1,
95
+ 'generatedAt': 'test',
96
+ 'moduleUrl': 'https://app.test/users',
97
+ 'coverage': [],
98
+ 'cases': [case],
99
+ },
100
+ }
101
+ )
102
+ self.assertEqual(excel.read({'path': source})['cases'][0]['steps'][0], step)
103
+ self.assertIn('选择日期', excel.step_text(step))
104
+
105
+ def test_disabled_assertion_and_retry_report_roundtrip(self):
106
+ with tempfile.TemporaryDirectory(prefix='laya-excel-') as directory:
107
+ source = str(Path(directory) / '用例.xlsx')
108
+ output = str(Path(directory) / '结果.xlsx')
109
+ case = {
110
+ 'id': '001',
111
+ 'operation': 'form-validation',
112
+ 'steps': [
113
+ {'kind': 'assert-disabled', 'target': {'name': '保存\x1b[2m', 'role': 'button'}}
114
+ ],
115
+ }
116
+ excel.write(
117
+ {
118
+ 'path': source,
119
+ 'file': {
120
+ 'schemaVersion': 1,
121
+ 'generatedAt': 'test',
122
+ 'moduleUrl': 'https://app.test/records',
123
+ 'coverage': [],
124
+ 'cases': [case],
125
+ },
126
+ }
127
+ )
128
+ loaded = excel.read({'path': source})
129
+ self.assertEqual(loaded['cases'][0], case)
130
+ excel.results(
131
+ {
132
+ 'path': source,
133
+ 'output': output,
134
+ 'results': [
135
+ {
136
+ 'id': '001',
137
+ 'status': '失败',
138
+ 'reason': '失败\x1b[31m',
139
+ 'attempts': [
140
+ {
141
+ 'step': 'assert-disabled',
142
+ 'attempt': n,
143
+ 'status': '失败',
144
+ 'reason': '未禁用\x00',
145
+ }
146
+ for n in range(1, 4)
147
+ ],
148
+ }
149
+ ],
150
+ }
151
+ )
152
+ book = excel.load_workbook(output)
153
+ note = book['生成用例'].cell(2, 16).value
154
+ self.assertIn('第3次', note)
155
+ self.assertNotIn('\x1b', note)
156
+ self.assertNotIn('\x00', note)
157
+ self.assertEqual(book['生成用例'].cell(2, 11).value, 'fail')
158
+ book.close()
159
+
160
+
161
+ if __name__ == '__main__':
162
+ unittest.main()
@@ -0,0 +1,33 @@
1
+ import importlib.util
2
+ import io
3
+ from pathlib import Path
4
+ import sys
5
+ import tempfile
6
+ import unittest
7
+ from unittest.mock import patch
8
+ from openpyxl import Workbook
9
+
10
+ spec = importlib.util.spec_from_file_location('worker', Path(__file__).parents[1] / 'worker.py')
11
+ worker = importlib.util.module_from_spec(spec)
12
+ with patch.object(sys, 'stdin', io.StringIO('')):
13
+ spec.loader.exec_module(worker)
14
+
15
+
16
+ class ImportResultTest(unittest.TestCase):
17
+ def test_source_result_is_not_execution_status_or_expected_result(self):
18
+ wb = Workbook()
19
+ ws = wb.active
20
+ ws.append(['测试编号', '测试步骤', '预期结果', '实际执行结果', '执行状态'])
21
+ ws.append(['1', '点击查询', '页面显示结果', 'pass', '未执行'])
22
+ ws.append(['2', '点击查询', 'pass', 'fail', '已执行'])
23
+ ws.append(['3', '点击查询', '页面显示结果', '废弃', '已执行'])
24
+ with tempfile.TemporaryDirectory() as directory:
25
+ filename = Path(directory) / 'input.xlsx'
26
+ wb.save(filename)
27
+ cases = worker.read_excel(filename)['cases']
28
+ self.assertEqual([c['source_result'] for c in cases], ['pass', 'fail', '废弃'])
29
+ self.assertEqual([c['id'] for c in cases if c['source_result'] == 'pass'], ['001'])
30
+
31
+
32
+ if __name__ == '__main__':
33
+ unittest.main()
@@ -0,0 +1,98 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { validateWorkflow } from '../lib/workflow.mjs';
4
+ import { generatedInputValue, invalidExampleValue } from '../lib/form.mjs';
5
+
6
+ const file = () => ({
7
+ schemaVersion: 1,
8
+ moduleUrl: 'http://127.0.0.1:8765/customers',
9
+ cases: [
10
+ {
11
+ id: 'delete',
12
+ operation: 'delete',
13
+ steps: [
14
+ {
15
+ kind: 'click',
16
+ purpose: 'delete',
17
+ target: { name: '删除', role: 'button', scope: 'owned-row' },
18
+ },
19
+ { kind: 'assert-absent', value: '${updatedName}' },
20
+ ],
21
+ },
22
+ ],
23
+ });
24
+
25
+ test('saved workflows accept only row-scoped deletion of the run-owned record', () => {
26
+ assert.equal(validateWorkflow(file()).cases.length, 1);
27
+ const changed = file();
28
+ changed.cases[0].steps[0].target.scope = 'page';
29
+ assert.throws(() => validateWorkflow(changed), /本轮独立记录/);
30
+ });
31
+
32
+ test('saved workflows reject executable content outside the supported step grammar', () => {
33
+ const changed = file();
34
+ changed.cases[0].steps.push({ kind: 'script', value: 'alert(1)' });
35
+ assert.throws(() => validateWorkflow(changed), /不支持的步骤/);
36
+ });
37
+
38
+ test('generated form steps preserve discovered choices and reject incomplete validation recipes', () => {
39
+ const generated = {
40
+ schemaVersion: 1,
41
+ moduleUrl: 'http://127.0.0.1:8765/customers',
42
+ cases: [
43
+ {
44
+ id: 'required',
45
+ operation: 'form-validation',
46
+ steps: [
47
+ {
48
+ kind: 'click',
49
+ purpose: 'create',
50
+ target: { name: '新增', role: 'button', scope: 'page' },
51
+ },
52
+ {
53
+ kind: 'click',
54
+ purpose: 'save',
55
+ target: { name: '保存', role: 'button', scope: 'form' },
56
+ },
57
+ { kind: 'assert-form-errors', value: ['客户名称'] },
58
+ ],
59
+ },
60
+ ],
61
+ };
62
+ assert.equal(validateWorkflow(generated).cases.length, 1);
63
+ generated.cases[0].steps[2].value = [];
64
+ assert.throws(() => validateWorkflow(generated), /校验步骤/);
65
+ });
66
+
67
+ test('generated input values use visible interval examples and fresh-record variables', () => {
68
+ assert.equal(
69
+ generatedInputValue('区间', '数值区间, 例如[0, 100)', '', '${recordName}'),
70
+ '[0, 100)',
71
+ );
72
+ assert.equal(generatedInputValue('默认值', '', '', '${recordName}'), '默认_${recordName}');
73
+ assert.equal(invalidExampleValue('数值区间, 例如[0, 100)'), '【0, 100)');
74
+ assert.equal(invalidExampleValue('普通文本'), null);
75
+ });
76
+
77
+ test('confirm-as-save is restricted to a form and an allowed write/validation case', () => {
78
+ const generated = file();
79
+ generated.cases = [
80
+ {
81
+ id: 'required',
82
+ operation: 'form-validation',
83
+ steps: [
84
+ {
85
+ kind: 'click',
86
+ purpose: 'save',
87
+ target: { name: '确定', role: 'button', scope: 'form' },
88
+ },
89
+ ],
90
+ },
91
+ ];
92
+ assert.equal(validateWorkflow(generated).cases.length, 1);
93
+ generated.cases[0].steps[0].target.scope = 'page';
94
+ assert.throws(() => validateWorkflow(generated), /当前表单/);
95
+ generated.cases[0].steps[0].target.scope = 'form';
96
+ generated.cases[0].operation = 'table';
97
+ assert.throws(() => validateWorkflow(generated), /保存步骤/);
98
+ });