@zalosai/zalos-cli 0.2.34 → 0.2.36
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 +7 -1
- package/dist/client.js +9 -0
- package/dist/commands/close.js +15 -0
- package/dist/commands/codepack.js +115 -2
- package/dist/commands/execution.js +96 -0
- package/dist/commands/file.js +23 -10
- package/dist/commands/workflow.js +109 -5
- package/dist/main.js +4 -0
- package/dist/utils/codepack-cases.js +655 -0
- package/dist/utils/codepack-scaffold.js +23 -0
- package/dist/utils/codepack.js +6 -3
- package/package.json +1 -1
- package/skills/codepack-authoring/SKILL.md +55 -9
- package/skills/zl-ops/SKILL.md +11 -0
|
@@ -0,0 +1,655 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { access, mkdtemp, readdir, readFile, rm, writeFile } from 'node:fs/promises';
|
|
3
|
+
import { tmpdir } from 'node:os';
|
|
4
|
+
import { join, relative, resolve, sep } from 'node:path';
|
|
5
|
+
import { parse as parseYaml } from 'yaml';
|
|
6
|
+
import { ValidationError } from './errors.js';
|
|
7
|
+
import { validateCodepackConfig } from './codepack.js';
|
|
8
|
+
/**
|
|
9
|
+
* Codepack test cases, run locally by `zl codepack test`.
|
|
10
|
+
*
|
|
11
|
+
* A case is a folder under `tests/cases/<name>/`:
|
|
12
|
+
*
|
|
13
|
+
* case.json optional: {"description", "parameters", "expectError"}
|
|
14
|
+
* inputs/<fileInput>/<file> one file per declared file input
|
|
15
|
+
* expected/<output>.<ext> expected content of a declared output
|
|
16
|
+
*
|
|
17
|
+
* Locally, process.py runs with the author's Python exactly as the executor
|
|
18
|
+
* calls it (required inputs positional, optional ones and parameters as
|
|
19
|
+
* --<fieldName>, OUTPUT_DIR set), and the harness compares each registered
|
|
20
|
+
* output with its expected file: CSV and workbook cells, JSON values, other
|
|
21
|
+
* files byte for byte. `--remote` sends the folder to Mesh, which runs the same
|
|
22
|
+
* cases through financial-executor on the production runtime.
|
|
23
|
+
*
|
|
24
|
+
* Mirrors `packages/cli/src/services/codepacks/codepack-cases.ts`. Keep the
|
|
25
|
+
* layout rules and CODEPACK_CASES_HARNESS identical in both.
|
|
26
|
+
*/
|
|
27
|
+
export const CASES_ROOT = 'tests/cases';
|
|
28
|
+
const CASE_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/;
|
|
29
|
+
const SAFE_FILE_NAME = /^(?!\.)[A-Za-z0-9 ._()-]{1,180}$/;
|
|
30
|
+
const EXPECTED_FILE_PATTERN = /^([A-Za-z_][A-Za-z0-9_]{0,63})(\.[A-Za-z0-9]{1,10})$/;
|
|
31
|
+
const CASE_KEYS = new Set(['description', 'parameters', 'expectError']);
|
|
32
|
+
const UNIT_TEST_PATTERN = /^tests\/(.+\/)?test_[^/]*\.py$/;
|
|
33
|
+
const DEFAULT_TIMEOUT_SECONDS = 600;
|
|
34
|
+
const LOG_TAIL = 4000;
|
|
35
|
+
export function readCodepackContract(configYaml) {
|
|
36
|
+
const templateKey = validateCodepackConfig(configYaml);
|
|
37
|
+
const config = parseYaml(configYaml)[templateKey];
|
|
38
|
+
const list = (value) => Array.isArray(value) ? value.filter(isRecord) : [];
|
|
39
|
+
const outputContract = isRecord(config.output_contract) ? config.output_contract : {};
|
|
40
|
+
const resources = isRecord(config.resources) ? config.resources : {};
|
|
41
|
+
return {
|
|
42
|
+
fileInputs: list(config.file_inputs).map((field) => ({
|
|
43
|
+
fieldName: String(field.fieldName),
|
|
44
|
+
required: field.required !== false,
|
|
45
|
+
})),
|
|
46
|
+
parameters: list(config.parameters).map((field) => ({
|
|
47
|
+
fieldName: String(field.fieldName),
|
|
48
|
+
fieldType: typeof field.fieldType === 'string' ? field.fieldType : 'text',
|
|
49
|
+
required: field.required === true,
|
|
50
|
+
})),
|
|
51
|
+
outputs: list(outputContract.files)
|
|
52
|
+
.map((file) => file.fieldName)
|
|
53
|
+
.filter((name) => typeof name === 'string'),
|
|
54
|
+
...(typeof resources.timeoutSeconds === 'number'
|
|
55
|
+
? { timeoutSeconds: resources.timeoutSeconds }
|
|
56
|
+
: {}),
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
/** True when a path is test-case data rather than a unit test file. */
|
|
60
|
+
export function isCasePath(path) {
|
|
61
|
+
return path === CASES_ROOT || path.startsWith(`${CASES_ROOT}/`);
|
|
62
|
+
}
|
|
63
|
+
/** Finds and checks every case against config.yaml before anything runs. */
|
|
64
|
+
export function discoverCodepackCases(files, contract) {
|
|
65
|
+
const byCase = new Map();
|
|
66
|
+
for (const path of files.keys()) {
|
|
67
|
+
if (!path.startsWith(`${CASES_ROOT}/`))
|
|
68
|
+
continue;
|
|
69
|
+
const [name, ...rest] = path.slice(CASES_ROOT.length + 1).split('/');
|
|
70
|
+
if (rest.length === 0) {
|
|
71
|
+
throw new ValidationError('cases', `${path}: put each case in its own folder, ${CASES_ROOT}/<case>/`);
|
|
72
|
+
}
|
|
73
|
+
byCase.set(name, [...(byCase.get(name) ?? []), rest.join('/')]);
|
|
74
|
+
}
|
|
75
|
+
const fileInputs = new Map(contract.fileInputs.map((field) => [field.fieldName, field]));
|
|
76
|
+
const declaredParameters = new Set(contract.parameters.map((field) => field.fieldName));
|
|
77
|
+
const outputs = new Set(contract.outputs);
|
|
78
|
+
return [...byCase.keys()].sort().map((name) => {
|
|
79
|
+
const fail = (message) => {
|
|
80
|
+
throw new ValidationError('cases', `Case ${name}: ${message}`);
|
|
81
|
+
};
|
|
82
|
+
if (!CASE_NAME_PATTERN.test(name)) {
|
|
83
|
+
fail('case folder names use letters, digits, _, . or - (at most 64)');
|
|
84
|
+
}
|
|
85
|
+
const root = `${CASES_ROOT}/${name}`;
|
|
86
|
+
const testCase = { name, inputs: {}, parameters: {}, expected: {} };
|
|
87
|
+
for (const relativePath of (byCase.get(name) ?? []).sort()) {
|
|
88
|
+
const path = `${root}/${relativePath}`;
|
|
89
|
+
const parts = relativePath.split('/');
|
|
90
|
+
if (relativePath === 'case.json') {
|
|
91
|
+
Object.assign(testCase, parseCaseJson(files.get(path), fail));
|
|
92
|
+
}
|
|
93
|
+
else if (parts[0] === 'inputs' && parts.length === 3) {
|
|
94
|
+
const [, fieldName, fileName] = parts;
|
|
95
|
+
if (!fileInputs.has(fieldName)) {
|
|
96
|
+
fail(`inputs/${fieldName}: config.yaml declares no file input named ${fieldName}`);
|
|
97
|
+
}
|
|
98
|
+
if (!SAFE_FILE_NAME.test(fileName))
|
|
99
|
+
fail(`inputs/${fieldName}: unsafe file name`);
|
|
100
|
+
if (testCase.inputs[fieldName])
|
|
101
|
+
fail(`inputs/${fieldName} must hold exactly one file`);
|
|
102
|
+
testCase.inputs[fieldName] = path;
|
|
103
|
+
}
|
|
104
|
+
else if (parts[0] === 'expected' && parts.length === 2) {
|
|
105
|
+
const match = EXPECTED_FILE_PATTERN.exec(parts[1]);
|
|
106
|
+
if (!match)
|
|
107
|
+
fail(`expected/${parts[1]}: name it <output fieldName>.<extension>`);
|
|
108
|
+
const fieldName = match[1];
|
|
109
|
+
if (!outputs.has(fieldName)) {
|
|
110
|
+
fail(`expected/${parts[1]}: output_contract declares no output named ${fieldName}`);
|
|
111
|
+
}
|
|
112
|
+
if (testCase.expected[fieldName])
|
|
113
|
+
fail(`expected/ has two files for ${fieldName}`);
|
|
114
|
+
testCase.expected[fieldName] = path;
|
|
115
|
+
}
|
|
116
|
+
else {
|
|
117
|
+
fail(`unexpected file ${relativePath}; a case holds case.json, inputs/<fileInput>/<file> and expected/<output>.<ext>`);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
for (const parameter of Object.keys(testCase.parameters)) {
|
|
121
|
+
if (!declaredParameters.has(parameter)) {
|
|
122
|
+
fail(`case.json: config.yaml declares no parameter named ${parameter}`);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
if (testCase.expectError === undefined) {
|
|
126
|
+
for (const [fieldName, field] of fileInputs) {
|
|
127
|
+
if (field.required && !testCase.inputs[fieldName]) {
|
|
128
|
+
fail(`missing required file input inputs/${fieldName}/`);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
for (const parameter of contract.parameters) {
|
|
132
|
+
if (parameter.required && !(parameter.fieldName in testCase.parameters)) {
|
|
133
|
+
fail(`case.json: missing required parameter ${parameter.fieldName}`);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
else if (Object.keys(testCase.expected).length > 0) {
|
|
138
|
+
fail('a case that expects an error cannot also expect outputs');
|
|
139
|
+
}
|
|
140
|
+
return testCase;
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
function parseCaseJson(raw, fail) {
|
|
144
|
+
let data;
|
|
145
|
+
try {
|
|
146
|
+
data = JSON.parse(raw.toString('utf8'));
|
|
147
|
+
}
|
|
148
|
+
catch {
|
|
149
|
+
return fail('case.json is not valid JSON');
|
|
150
|
+
}
|
|
151
|
+
if (!isRecord(data))
|
|
152
|
+
return fail('case.json must be an object');
|
|
153
|
+
for (const key of Object.keys(data)) {
|
|
154
|
+
if (!CASE_KEYS.has(key))
|
|
155
|
+
fail(`case.json: unknown key ${key}`);
|
|
156
|
+
}
|
|
157
|
+
const parameters = data.parameters ?? {};
|
|
158
|
+
if (!isRecord(parameters))
|
|
159
|
+
return fail('case.json: parameters must be an object');
|
|
160
|
+
for (const [name, value] of Object.entries(parameters)) {
|
|
161
|
+
if (!['string', 'number', 'boolean'].includes(typeof value)) {
|
|
162
|
+
fail(`case.json: parameter ${name} must be a string, number or boolean`);
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
if (data.description !== undefined && typeof data.description !== 'string') {
|
|
166
|
+
fail('case.json: description must be a string');
|
|
167
|
+
}
|
|
168
|
+
if (data.expectError !== undefined && typeof data.expectError !== 'string') {
|
|
169
|
+
fail('case.json: expectError must be a string');
|
|
170
|
+
}
|
|
171
|
+
return {
|
|
172
|
+
...(typeof data.description === 'string' ? { description: data.description } : {}),
|
|
173
|
+
parameters: parameters,
|
|
174
|
+
...(typeof data.expectError === 'string' ? { expectError: data.expectError } : {}),
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
/** process.py's command line, as financial-executor builds it. */
|
|
178
|
+
export function processArguments(testCase, contract, directory) {
|
|
179
|
+
const args = [];
|
|
180
|
+
for (const field of contract.fileInputs) {
|
|
181
|
+
const path = testCase.inputs[field.fieldName];
|
|
182
|
+
if (path && field.required)
|
|
183
|
+
args.push(resolve(directory, path));
|
|
184
|
+
}
|
|
185
|
+
for (const field of contract.fileInputs) {
|
|
186
|
+
const path = testCase.inputs[field.fieldName];
|
|
187
|
+
if (path && !field.required)
|
|
188
|
+
args.push(`--${field.fieldName}`, resolve(directory, path));
|
|
189
|
+
}
|
|
190
|
+
for (const field of contract.parameters) {
|
|
191
|
+
if (!(field.fieldName in testCase.parameters))
|
|
192
|
+
continue;
|
|
193
|
+
const value = testCase.parameters[field.fieldName];
|
|
194
|
+
if (field.fieldType === 'boolean') {
|
|
195
|
+
if (value === true || value === 'true')
|
|
196
|
+
args.push(`--${field.fieldName}`);
|
|
197
|
+
}
|
|
198
|
+
else {
|
|
199
|
+
args.push(`--${field.fieldName}`, String(value));
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
return args;
|
|
203
|
+
}
|
|
204
|
+
/** The folder's contract and cases, checked; unit test files listed separately. */
|
|
205
|
+
export async function loadCodepackCases(directory) {
|
|
206
|
+
const root = resolve(directory);
|
|
207
|
+
const configYaml = await readFile(join(root, 'config.yaml'), 'utf8').catch(() => {
|
|
208
|
+
throw new ValidationError('config.yaml', `No config.yaml in ${root}`);
|
|
209
|
+
});
|
|
210
|
+
const contract = readCodepackContract(configYaml);
|
|
211
|
+
const testFiles = await readTree(root, 'tests');
|
|
212
|
+
return {
|
|
213
|
+
contract,
|
|
214
|
+
cases: discoverCodepackCases(testFiles, contract),
|
|
215
|
+
unitTestFiles: [...testFiles.keys()].filter((path) => UNIT_TEST_PATTERN.test(path) && !isCasePath(path)),
|
|
216
|
+
};
|
|
217
|
+
}
|
|
218
|
+
/** Runs the unit tests, then every case, with the author's Python. */
|
|
219
|
+
export async function runLocalCodepackTests(directory, options = {}) {
|
|
220
|
+
const root = resolve(directory);
|
|
221
|
+
const loaded = await loadCodepackCases(root);
|
|
222
|
+
const { contract, unitTestFiles } = loaded;
|
|
223
|
+
const cases = selectCases(loaded.cases, options.cases);
|
|
224
|
+
if (unitTestFiles.length === 0 && cases.length === 0) {
|
|
225
|
+
throw new ValidationError('tests', 'No tests: add tests/test_*.py files or cases under tests/cases/<case>/');
|
|
226
|
+
}
|
|
227
|
+
const python = options.python ?? (await defaultPython(root));
|
|
228
|
+
const work = await mkdtemp(join(tmpdir(), 'zl-codepack-test-'));
|
|
229
|
+
try {
|
|
230
|
+
const unitTests = unitTestFiles.length === 0 || options.cases
|
|
231
|
+
? { status: 'not_run' }
|
|
232
|
+
: await runUnitTests(python, root, join(work, 'unit-outputs'));
|
|
233
|
+
let caseResults = [];
|
|
234
|
+
if (cases.length > 0) {
|
|
235
|
+
const timeoutSeconds = options.timeoutSeconds ?? contract.timeoutSeconds ?? DEFAULT_TIMEOUT_SECONDS;
|
|
236
|
+
const plan = {
|
|
237
|
+
cases: cases.map((testCase, index) => ({
|
|
238
|
+
name: testCase.name,
|
|
239
|
+
command: [python, 'process.py', ...processArguments(testCase, contract, root)],
|
|
240
|
+
cwd: root,
|
|
241
|
+
env: { OUTPUT_DIR: join(work, String(index), 'outputs') },
|
|
242
|
+
outputDir: join(work, String(index), 'outputs'),
|
|
243
|
+
results: 'registration',
|
|
244
|
+
timeoutSeconds,
|
|
245
|
+
expected: Object.fromEntries(Object.entries(testCase.expected).map(([field, path]) => [field, resolve(root, path)])),
|
|
246
|
+
...(testCase.expectError !== undefined ? { expectError: testCase.expectError } : {}),
|
|
247
|
+
})),
|
|
248
|
+
};
|
|
249
|
+
await writeFile(join(work, 'run_cases.py'), CODEPACK_CASES_HARNESS);
|
|
250
|
+
await writeFile(join(work, 'cases-plan.json'), JSON.stringify(plan));
|
|
251
|
+
const run = await runProcess(python, [join(work, 'run_cases.py'), join(work, 'cases-plan.json')], root);
|
|
252
|
+
caseResults = parseCasesReport(run.stdout);
|
|
253
|
+
if (caseResults.length !== cases.length) {
|
|
254
|
+
throw new ValidationError('python', `The case harness did not finish with ${python}: ${(run.stderr || run.stdout).slice(-LOG_TAIL)}`);
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
return { python, unitTests, cases: caseResults };
|
|
258
|
+
}
|
|
259
|
+
finally {
|
|
260
|
+
await rm(work, { recursive: true, force: true });
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
/** Keeps only the named cases; an unknown name is an error. */
|
|
264
|
+
export function selectCases(cases, names) {
|
|
265
|
+
if (!names || names.length === 0)
|
|
266
|
+
return cases;
|
|
267
|
+
const known = new Set(cases.map((testCase) => testCase.name));
|
|
268
|
+
const unknown = names.filter((name) => !known.has(name));
|
|
269
|
+
if (unknown.length > 0) {
|
|
270
|
+
throw new ValidationError('case', `No case named ${unknown.join(', ')} under ${CASES_ROOT}/ (have: ${[...known].join(', ') || 'none'})`);
|
|
271
|
+
}
|
|
272
|
+
return cases.filter((testCase) => names.includes(testCase.name));
|
|
273
|
+
}
|
|
274
|
+
export function parseCasesReport(stdout) {
|
|
275
|
+
const line = stdout.trim().split('\n').at(-1) ?? '';
|
|
276
|
+
let parsed;
|
|
277
|
+
try {
|
|
278
|
+
parsed = JSON.parse(line);
|
|
279
|
+
}
|
|
280
|
+
catch {
|
|
281
|
+
return [];
|
|
282
|
+
}
|
|
283
|
+
if (!isRecord(parsed) || !Array.isArray(parsed.cases))
|
|
284
|
+
return [];
|
|
285
|
+
return parsed.cases.filter(isRecord).map((entry) => ({
|
|
286
|
+
name: String(entry.name ?? ''),
|
|
287
|
+
status: entry.status === 'passed' ? 'passed' : 'failed',
|
|
288
|
+
seconds: typeof entry.seconds === 'number' ? entry.seconds : 0,
|
|
289
|
+
problems: Array.isArray(entry.problems) ? entry.problems.map(String) : [],
|
|
290
|
+
log: typeof entry.log === 'string' ? entry.log : '',
|
|
291
|
+
}));
|
|
292
|
+
}
|
|
293
|
+
async function runUnitTests(python, root, outputDir) {
|
|
294
|
+
const run = await runProcess(python, ['-m', 'pytest', 'tests', '-q', '-p', 'no:cacheprovider', '--ignore=tests/cases'], root, { OUTPUT_DIR: outputDir, PYTHONPATH: root });
|
|
295
|
+
const log = `${run.stdout}${run.stderr}`.slice(-LOG_TAIL);
|
|
296
|
+
if (/No module named pytest/.test(log)) {
|
|
297
|
+
return {
|
|
298
|
+
status: 'failed',
|
|
299
|
+
exitCode: run.exitCode,
|
|
300
|
+
log: `pytest is not installed for ${python}; install it (pip install pytest) or pass --python`,
|
|
301
|
+
};
|
|
302
|
+
}
|
|
303
|
+
return { status: run.exitCode === 0 ? 'passed' : 'failed', exitCode: run.exitCode, log };
|
|
304
|
+
}
|
|
305
|
+
async function defaultPython(root) {
|
|
306
|
+
const venv = join(root, '.venv', 'bin', 'python');
|
|
307
|
+
return access(venv).then(() => venv, () => 'python3');
|
|
308
|
+
}
|
|
309
|
+
function runProcess(command, args, cwd, env = {}) {
|
|
310
|
+
return new Promise((resolvePromise, reject) => {
|
|
311
|
+
const child = spawn(command, args, { cwd, env: { ...process.env, ...env } });
|
|
312
|
+
let stdout = '';
|
|
313
|
+
let stderr = '';
|
|
314
|
+
child.stdout.on('data', (chunk) => {
|
|
315
|
+
stdout += chunk.toString('utf8');
|
|
316
|
+
});
|
|
317
|
+
child.stderr.on('data', (chunk) => {
|
|
318
|
+
stderr += chunk.toString('utf8');
|
|
319
|
+
});
|
|
320
|
+
child.on('error', (error) => {
|
|
321
|
+
reject(error.code === 'ENOENT'
|
|
322
|
+
? new ValidationError('python', `Python not found: ${command}; pass --python <path>`)
|
|
323
|
+
: error);
|
|
324
|
+
});
|
|
325
|
+
child.on('close', (code) => resolvePromise({ exitCode: code ?? 1, stdout, stderr }));
|
|
326
|
+
});
|
|
327
|
+
}
|
|
328
|
+
/** Files under `<root>/<subdirectory>` keyed by their path from root, dotfiles skipped. */
|
|
329
|
+
async function readTree(root, subdirectory) {
|
|
330
|
+
const files = new Map();
|
|
331
|
+
const walk = async (directory) => {
|
|
332
|
+
const entries = await readdir(directory, { withFileTypes: true }).catch((error) => {
|
|
333
|
+
if (error.code === 'ENOENT')
|
|
334
|
+
return [];
|
|
335
|
+
throw error;
|
|
336
|
+
});
|
|
337
|
+
for (const entry of entries) {
|
|
338
|
+
if (entry.name.startsWith('.') || entry.name === '__pycache__')
|
|
339
|
+
continue;
|
|
340
|
+
const absolute = join(directory, entry.name);
|
|
341
|
+
if (entry.isDirectory())
|
|
342
|
+
await walk(absolute);
|
|
343
|
+
else if (entry.isFile()) {
|
|
344
|
+
files.set(relative(root, absolute).split(sep).join('/'), await readFile(absolute));
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
};
|
|
348
|
+
await walk(join(root, subdirectory));
|
|
349
|
+
return files;
|
|
350
|
+
}
|
|
351
|
+
function isRecord(value) {
|
|
352
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
353
|
+
}
|
|
354
|
+
/**
|
|
355
|
+
* Runs each case in a plan and compares its outputs with the expected files.
|
|
356
|
+
* Identical copy of packages/cli/src/services/codepacks/codepack-cases.ts.
|
|
357
|
+
*/
|
|
358
|
+
export const CODEPACK_CASES_HARNESS = String.raw `
|
|
359
|
+
import csv
|
|
360
|
+
import json
|
|
361
|
+
import os
|
|
362
|
+
import signal
|
|
363
|
+
import subprocess
|
|
364
|
+
import sys
|
|
365
|
+
import time
|
|
366
|
+
from pathlib import Path
|
|
367
|
+
|
|
368
|
+
MAX_PROBLEMS = 20
|
|
369
|
+
LOG_TAIL = 4000
|
|
370
|
+
|
|
371
|
+
|
|
372
|
+
class TimeLimit(BaseException):
|
|
373
|
+
"""The run's time limit sent SIGTERM; report what finished instead of nothing."""
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
def stop(_signum, _frame):
|
|
377
|
+
raise TimeLimit()
|
|
378
|
+
|
|
379
|
+
|
|
380
|
+
def main():
|
|
381
|
+
plan = json.loads(Path(sys.argv[1]).read_text(encoding="utf-8"))
|
|
382
|
+
signal.signal(signal.SIGTERM, stop)
|
|
383
|
+
cases = plan["cases"]
|
|
384
|
+
results = []
|
|
385
|
+
try:
|
|
386
|
+
for case in cases:
|
|
387
|
+
results.append(run_case_safely(case))
|
|
388
|
+
except TimeLimit:
|
|
389
|
+
for case in cases[len(results):]:
|
|
390
|
+
results.append({
|
|
391
|
+
"name": case["name"],
|
|
392
|
+
"status": "failed",
|
|
393
|
+
"seconds": 0,
|
|
394
|
+
"problems": ["Not finished: the test run hit its time limit"],
|
|
395
|
+
"log": "",
|
|
396
|
+
})
|
|
397
|
+
failed = sum(1 for result in results if result["status"] != "passed")
|
|
398
|
+
print(json.dumps({"cases": results, "passed": len(results) - failed, "failed": failed}))
|
|
399
|
+
return 1 if failed else 0
|
|
400
|
+
|
|
401
|
+
|
|
402
|
+
def run_case_safely(case):
|
|
403
|
+
"""One case's error never costs the others their results."""
|
|
404
|
+
started = time.monotonic()
|
|
405
|
+
try:
|
|
406
|
+
return run_case(case)
|
|
407
|
+
except Exception as error:
|
|
408
|
+
return finish(case, started, [f"The case could not be checked: {error!r}"], "")
|
|
409
|
+
|
|
410
|
+
|
|
411
|
+
def run_case(case):
|
|
412
|
+
started = time.monotonic()
|
|
413
|
+
for path, content in (case.get("writeFiles") or {}).items():
|
|
414
|
+
Path(path).parent.mkdir(parents=True, exist_ok=True)
|
|
415
|
+
Path(path).write_text(json.dumps(content), encoding="utf-8")
|
|
416
|
+
output_dir = Path(case["outputDir"])
|
|
417
|
+
output_dir.mkdir(parents=True, exist_ok=True)
|
|
418
|
+
env = {**os.environ, **(case.get("env") or {})}
|
|
419
|
+
timeout = case.get("timeoutSeconds")
|
|
420
|
+
try:
|
|
421
|
+
completed = subprocess.run(
|
|
422
|
+
case["command"],
|
|
423
|
+
cwd=case.get("cwd") or None,
|
|
424
|
+
env=env,
|
|
425
|
+
capture_output=True,
|
|
426
|
+
text=True,
|
|
427
|
+
timeout=timeout,
|
|
428
|
+
)
|
|
429
|
+
except subprocess.TimeoutExpired:
|
|
430
|
+
return finish(case, started, [f"Timed out after {timeout}s"], "")
|
|
431
|
+
except OSError as error:
|
|
432
|
+
return finish(case, started, [f"Could not start the run: {error}"], "")
|
|
433
|
+
|
|
434
|
+
if case.get("results") == "executor":
|
|
435
|
+
outputs, error, log = executor_outputs(completed.stdout)
|
|
436
|
+
log = "\n".join(part for part in (log, completed.stderr) if part)
|
|
437
|
+
else:
|
|
438
|
+
outputs, error = registered_outputs(output_dir), None
|
|
439
|
+
log = "\n".join(part for part in (completed.stdout, completed.stderr) if part)
|
|
440
|
+
failed = completed.returncode != 0 or error is not None
|
|
441
|
+
|
|
442
|
+
problems = []
|
|
443
|
+
expect_error = case.get("expectError")
|
|
444
|
+
if expect_error is not None:
|
|
445
|
+
if not failed:
|
|
446
|
+
problems.append("Expected the run to fail, but it succeeded")
|
|
447
|
+
elif expect_error and expect_error not in "\n".join([log, error or ""]):
|
|
448
|
+
problems.append(f"The run failed, but its message does not contain {expect_error!r}")
|
|
449
|
+
elif failed:
|
|
450
|
+
problems.append(
|
|
451
|
+
f"The run failed (exit code {completed.returncode})" + (f": {error}" if error else "")
|
|
452
|
+
)
|
|
453
|
+
else:
|
|
454
|
+
for field, expected in sorted(case.get("expected", {}).items()):
|
|
455
|
+
actual = outputs.get(field)
|
|
456
|
+
if actual is None:
|
|
457
|
+
problems.append(f"{field}: the run registered no {field} output")
|
|
458
|
+
continue
|
|
459
|
+
try:
|
|
460
|
+
found = compare(Path(expected), Path(actual))
|
|
461
|
+
except Exception as error:
|
|
462
|
+
found = [f"could not be compared: {error!r}"]
|
|
463
|
+
problems.extend(f"{field}: {problem}" for problem in found)
|
|
464
|
+
return finish(case, started, problems, log)
|
|
465
|
+
|
|
466
|
+
|
|
467
|
+
def finish(case, started, problems, log):
|
|
468
|
+
return {
|
|
469
|
+
"name": case["name"],
|
|
470
|
+
"status": "failed" if problems else "passed",
|
|
471
|
+
"seconds": round(time.monotonic() - started, 2),
|
|
472
|
+
"problems": problems[:MAX_PROBLEMS]
|
|
473
|
+
+ ([f"... and {len(problems) - MAX_PROBLEMS} more"] if len(problems) > MAX_PROBLEMS else []),
|
|
474
|
+
"log": log[-LOG_TAIL:] if problems else "",
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
|
|
478
|
+
def executor_outputs(stdout):
|
|
479
|
+
"""financial-executor prints one JSON result: outputFiles with logicalName and localPath."""
|
|
480
|
+
payload = None
|
|
481
|
+
for line in reversed(stdout.strip().splitlines()):
|
|
482
|
+
try:
|
|
483
|
+
payload = json.loads(line)
|
|
484
|
+
break
|
|
485
|
+
except ValueError:
|
|
486
|
+
continue
|
|
487
|
+
if not isinstance(payload, dict):
|
|
488
|
+
return {}, "financial-executor printed no result", stdout
|
|
489
|
+
outputs = {
|
|
490
|
+
str(item.get("logicalName")): item.get("localPath")
|
|
491
|
+
for item in payload.get("outputFiles") or []
|
|
492
|
+
if isinstance(item, dict) and item.get("localPath")
|
|
493
|
+
}
|
|
494
|
+
error = payload.get("error")
|
|
495
|
+
if isinstance(error, dict):
|
|
496
|
+
error = error.get("message")
|
|
497
|
+
if not payload.get("ok", False) and not error:
|
|
498
|
+
error = f"status {payload.get('status')}"
|
|
499
|
+
return outputs, (str(error) if error else None), str(payload.get("stdout") or "")
|
|
500
|
+
|
|
501
|
+
|
|
502
|
+
def registered_outputs(output_dir):
|
|
503
|
+
"""What register_output wrote: OUTPUT_DIR/.zalos_outputs.json."""
|
|
504
|
+
manifest = output_dir / ".zalos_outputs.json"
|
|
505
|
+
if not manifest.is_file():
|
|
506
|
+
return {}
|
|
507
|
+
entries = json.loads(manifest.read_text(encoding="utf-8")).get("files", [])
|
|
508
|
+
return {entry["fieldName"]: str(output_dir / entry["path"]) for entry in entries}
|
|
509
|
+
|
|
510
|
+
|
|
511
|
+
def compare(expected, actual):
|
|
512
|
+
suffix = expected.suffix.lower()
|
|
513
|
+
if actual.suffix.lower() != suffix:
|
|
514
|
+
return [f"expected a {suffix} file, got {actual.name}"]
|
|
515
|
+
if suffix in (".csv", ".tsv"):
|
|
516
|
+
return compare_tables(read_delimited(expected, suffix), read_delimited(actual, suffix), None)
|
|
517
|
+
if suffix == ".json":
|
|
518
|
+
return compare_values(load_json(expected), load_json(actual), "$")
|
|
519
|
+
if suffix == ".jsonl":
|
|
520
|
+
return compare_rows([load_json_line(l) for l in lines(expected)], [load_json_line(l) for l in lines(actual)])
|
|
521
|
+
if suffix in (".xlsx", ".xlsm"):
|
|
522
|
+
return compare_workbooks(expected, actual)
|
|
523
|
+
if expected.read_bytes() != actual.read_bytes():
|
|
524
|
+
return [f"content differs ({expected.stat().st_size} bytes expected, {actual.stat().st_size} written)"]
|
|
525
|
+
return []
|
|
526
|
+
|
|
527
|
+
|
|
528
|
+
def read_delimited(path, suffix):
|
|
529
|
+
with path.open(newline="", encoding="utf-8-sig") as handle:
|
|
530
|
+
return list(csv.reader(handle, delimiter="\t" if suffix == ".tsv" else ","))
|
|
531
|
+
|
|
532
|
+
|
|
533
|
+
def load_json(path):
|
|
534
|
+
return json.loads(path.read_text(encoding="utf-8"))
|
|
535
|
+
|
|
536
|
+
|
|
537
|
+
def lines(path):
|
|
538
|
+
return [line for line in path.read_text(encoding="utf-8").splitlines() if line.strip()]
|
|
539
|
+
|
|
540
|
+
|
|
541
|
+
def load_json_line(line):
|
|
542
|
+
return json.loads(line)
|
|
543
|
+
|
|
544
|
+
|
|
545
|
+
def compare_rows(expected, actual):
|
|
546
|
+
problems = []
|
|
547
|
+
if len(expected) != len(actual):
|
|
548
|
+
problems.append(f"{len(expected)} lines expected, {len(actual)} written")
|
|
549
|
+
for index, (want, got) in enumerate(zip(expected, actual), start=1):
|
|
550
|
+
problems.extend(compare_values(want, got, f"line {index}"))
|
|
551
|
+
if len(problems) > MAX_PROBLEMS:
|
|
552
|
+
break
|
|
553
|
+
return problems
|
|
554
|
+
|
|
555
|
+
|
|
556
|
+
def compare_values(expected, actual, where):
|
|
557
|
+
if isinstance(expected, dict) and isinstance(actual, dict):
|
|
558
|
+
problems = []
|
|
559
|
+
for key in sorted(set(expected) | set(actual), key=str):
|
|
560
|
+
if key not in actual:
|
|
561
|
+
problems.append(f"{where}.{key}: missing")
|
|
562
|
+
elif key not in expected:
|
|
563
|
+
problems.append(f"{where}.{key}: not expected, got {actual[key]!r}")
|
|
564
|
+
else:
|
|
565
|
+
problems.extend(compare_values(expected[key], actual[key], f"{where}.{key}"))
|
|
566
|
+
return problems
|
|
567
|
+
if isinstance(expected, list) and isinstance(actual, list):
|
|
568
|
+
problems = [] if len(expected) == len(actual) else [f"{where}: {len(expected)} items expected, {len(actual)} written"]
|
|
569
|
+
for index, (want, got) in enumerate(zip(expected, actual)):
|
|
570
|
+
problems.extend(compare_values(want, got, f"{where}[{index}]"))
|
|
571
|
+
return problems
|
|
572
|
+
if is_number(expected) and is_number(actual):
|
|
573
|
+
# JSON does not distinguish 350 from 350.0; compare amounts by value.
|
|
574
|
+
return [] if expected == actual else [f"{where}: expected {expected!r}, got {actual!r}"]
|
|
575
|
+
if expected != actual or type(expected) is not type(actual):
|
|
576
|
+
return [f"{where}: expected {expected!r}, got {actual!r}"]
|
|
577
|
+
return []
|
|
578
|
+
|
|
579
|
+
|
|
580
|
+
def is_number(value):
|
|
581
|
+
return isinstance(value, (int, float)) and not isinstance(value, bool)
|
|
582
|
+
|
|
583
|
+
|
|
584
|
+
def compare_tables(expected, actual, sheet):
|
|
585
|
+
"""Row by row; columns are named by the header row when there is one."""
|
|
586
|
+
prefix = f"sheet {sheet!r} " if sheet is not None else ""
|
|
587
|
+
problems = []
|
|
588
|
+
if len(expected) != len(actual):
|
|
589
|
+
problems.append(f"{prefix}{len(expected)} rows expected, {len(actual)} written")
|
|
590
|
+
header = expected[0] if expected else []
|
|
591
|
+
for row_index, (want, got) in enumerate(zip(expected, actual), start=1):
|
|
592
|
+
for column in range(max(len(want), len(got))):
|
|
593
|
+
want_cell = want[column] if column < len(want) else None
|
|
594
|
+
got_cell = got[column] if column < len(got) else None
|
|
595
|
+
if want_cell != got_cell:
|
|
596
|
+
if sheet is not None:
|
|
597
|
+
place = f"{column_letter(column)}{row_index}"
|
|
598
|
+
elif row_index > 1 and column < len(header) and header[column]:
|
|
599
|
+
place = f"row {row_index}, column {header[column]!r}"
|
|
600
|
+
else:
|
|
601
|
+
place = f"row {row_index}, column {column + 1}"
|
|
602
|
+
problems.append(f"{prefix}{place}: expected {want_cell!r}, got {got_cell!r}")
|
|
603
|
+
if len(problems) > MAX_PROBLEMS:
|
|
604
|
+
return problems
|
|
605
|
+
return problems
|
|
606
|
+
|
|
607
|
+
|
|
608
|
+
def compare_workbooks(expected, actual):
|
|
609
|
+
"""Cell values and formulas, sheet by sheet; workbook metadata is ignored."""
|
|
610
|
+
try:
|
|
611
|
+
import openpyxl
|
|
612
|
+
except ImportError:
|
|
613
|
+
return ["install openpyxl to compare workbooks"]
|
|
614
|
+
want = sheets(openpyxl, expected)
|
|
615
|
+
got = sheets(openpyxl, actual)
|
|
616
|
+
if list(want) != list(got):
|
|
617
|
+
return [f"sheets {list(want)} expected, got {list(got)}"]
|
|
618
|
+
problems = []
|
|
619
|
+
for name in want:
|
|
620
|
+
problems.extend(compare_tables(want[name], got[name], name))
|
|
621
|
+
if len(problems) > MAX_PROBLEMS:
|
|
622
|
+
break
|
|
623
|
+
return problems
|
|
624
|
+
|
|
625
|
+
|
|
626
|
+
def sheets(openpyxl, path):
|
|
627
|
+
workbook = openpyxl.load_workbook(path, read_only=True, data_only=False)
|
|
628
|
+
try:
|
|
629
|
+
result = {}
|
|
630
|
+
for sheet in workbook.worksheets:
|
|
631
|
+
rows = [list(row) for row in sheet.iter_rows(values_only=True)]
|
|
632
|
+
for row in rows:
|
|
633
|
+
while row and row[-1] is None:
|
|
634
|
+
row.pop()
|
|
635
|
+
while rows and not rows[-1]:
|
|
636
|
+
rows.pop()
|
|
637
|
+
result[sheet.title] = rows
|
|
638
|
+
return result
|
|
639
|
+
finally:
|
|
640
|
+
workbook.close()
|
|
641
|
+
|
|
642
|
+
|
|
643
|
+
def column_letter(index):
|
|
644
|
+
letters = ""
|
|
645
|
+
index += 1
|
|
646
|
+
while index:
|
|
647
|
+
index, remainder = divmod(index - 1, 26)
|
|
648
|
+
letters = chr(65 + remainder) + letters
|
|
649
|
+
return letters
|
|
650
|
+
|
|
651
|
+
|
|
652
|
+
if __name__ == "__main__":
|
|
653
|
+
sys.exit(main())
|
|
654
|
+
`;
|
|
655
|
+
//# sourceMappingURL=codepack-cases.js.map
|