Debian Codegraph @

debian/tests/test_modules/llparse-test-fixture/src/result.ts

raw symbols SCIP
1 import * as assert from 'assert';
2 import { Buffer } from 'buffer';
3 import { spawn } from 'child_process';
4 import * as path from 'path';
5
6 export type FixtureExpected = string | RegExp | ReadonlyArray<string | RegExp>;
7
8 interface IRange {
9 readonly from: number;
10 readonly to: number;
11 }
12
13 interface ISingleRun {
14 readonly name: string;
15 readonly outputs: ReadonlyArray<string>;
16 }
17
18 export interface IFixtureResultOptions {
19 readonly noScan?: boolean;
20 readonly scan?: number;
21 }
22
23 export class FixtureResult {
24 constructor(private readonly executables: ReadonlyArray<string>,
25 private readonly maxParallel: number) {
26 }
27
28 public async check(input: string, expected: FixtureExpected,
29 options: IFixtureResultOptions = {}): Promise<void> {
30 const ranges: IRange[] = [];
31 const maxParallel = this.maxParallel;
32
33 const rawLength = Buffer.byteLength(input);
34 const len = Math.ceil(rawLength / maxParallel);
35
36 if (options.noScan === true) {
37 ranges.push({ from: rawLength, to: rawLength + 1 });
38 } else if (options.scan) {
39 ranges.push({ from: options.scan, to: options.scan + 1 });
40 } else {
41 for (let i = 1; i <= rawLength; i += len) {
42 ranges.push({
43 from: i,
44 to: Math.min(i + len, rawLength + 1),
45 });
46 }
47 }
48
49 await Promise.all(ranges.map(async (range) => {
50 for (const single of await this.spawn(range, input)) {
51 for (const [ index, output ] of single.outputs.entries()) {
52 this.checkScan(single.name, index + 1, output, expected);
53 }
54 }
55 }));
56 }
57
58 private async spawn(range: IRange, input: string)
59 : Promise<ReadonlyArray<ISingleRun>> {
60 return await Promise.all(this.executables.map((executable) => {
61 return this.spawnSingle(executable, range, input);
62 }));
63 }
64
65 private async spawnSingle(executable: string, range: IRange, input: string)
66 : Promise<ISingleRun> {
67 const name = path.basename(executable);
68
69 const proc = spawn(executable, [
70 `${range.from}:${range.to}`,
71 input,
72 ], {
73 shell: process.platform === 'win32',
74 stdio: [ null, 'pipe', 'pipe' ],
75 });
76
77 const stdout: Buffer[] = [];
78 proc.stdout.on('data', (chunk: Buffer) => stdout.push(chunk));
79 const stderr: Buffer[] = [];
80 proc.stderr.on('data', (chunk: Buffer) => stderr.push(chunk));
81
82 const onEnd =
83 new Promise((resolve) => proc.stdout.once('end', () => resolve()));
84 const { code, signal } = await (new Promise((resolve) => {
85 proc.once('exit', (exitCode, exitSignal) => {
86 resolve({ code: exitCode!, signal: exitSignal! });
87 });
88 }) as Promise<{ code: number, signal: string }>);
89
90 await onEnd;
91
92 const stdoutText = Buffer.concat(stdout).toString();
93 const stderrText = Buffer.concat(stderr).toString();
94 const stdOutErr = `stdout: ${stdoutText}\nstderr: ${stderrText}`;
95
96 if (signal) {
97 throw new Error(`Test "${name}" killed with signal: "${signal}".\n${stdOutErr}`);
98 }
99
100 if (code !== 0) {
101 throw new Error(`Test "${name}" exited with code: "${code}".\n${stdOutErr}`);
102 }
103
104 const out = stdoutText.split(/===== SCAN \d+ START =====\n/g).slice(1);
105
106 return {
107 name,
108 outputs: out.map((part) => this.normalizeSpans(part)),
109 };
110 }
111
112 private checkScan(name: string, scan: number, actual: string,
113 expected: FixtureExpected): void {
114 if (typeof expected === 'string') {
115 assert.strictEqual(actual, expected,
116 `Executable: ${name}\n` +
117 `Scan value: ${scan}`);
118 return;
119 }
120
121 if (expected instanceof RegExp) {
122 expected.lastIndex = 0;
123 assert.ok(expected.test(actual),
124 `Executable: ${name}\n` +
125 `Scan value: ${scan}\n` +
126 ` got : ${JSON.stringify(actual)}\n` +
127 ` against : ${expected}`);
128 return;
129 }
130
131 assert(
132 Array.isArray(expected) &&
133 expected.every((line) => {
134 return typeof line === 'string' || line instanceof RegExp;
135 }),
136 '`expected` must be a string, RegExp, or Array[String|RegExp]');
137
138 const lines = actual.split('\n');
139 while (lines.length && lines[lines.length - 1]) {
140 lines.pop();
141 }
142
143 // If they differ - we are going to fail
144 while (lines.length < expected.length) {
145 lines.push('');
146 }
147
148 // Just make it fail, there shouldn't be extra lines
149 const expectedArr = (expected as ReadonlyArray<string | RegExp>).slice();
150 while (expectedArr.length < lines.length) {
151 expectedArr.push(/$^/);
152 }
153
154 lines.forEach((line, lineNum) => {
155 const expectedLine = expectedArr[lineNum];
156
157 if (typeof expectedLine === 'string') {
158 assert.strictEqual(line, expectedLine,
159 `Executable: ${name}\n` +
160 `Scan value: ${scan} at line: ${lineNum + 1}\n` +
161 ` output : ${lines.join('\n')}`);
162 return;
163 }
164
165 expectedLine.lastIndex = 0;
166 assert.ok(expectedLine.test(line),
167 `Executable: ${name}\n` +
168 `Scan value: ${scan} at line: ${lineNum + 1}\n` +
169 ` got : ${JSON.stringify(line)}\n` +
170 ` against : ${expectedLine}\n` +
171 ` output : ${lines.join('\n')}`);
172 });
173 }
174
175 private normalizeSpans(source: string): string {
176 const lines = source.split(/\n/g);
177
178 type NormalizeItem = { type: 'raw', value: string } |
179 { type: 'span', off: number, len: number, span: string, value: string };
180 const parse = (line: string): NormalizeItem => {
181 const match = line.match(
182 /^off=(\d+)\s+len=(\d+)\s+span\[([^\]]+)\]="(.*)"$/);
183 if (!match) {
184 return { type: 'raw', value: line };
185 }
186
187 return {
188 len: parseInt(match[2], 10),
189 off: parseInt(match[1], 10),
190 span: match[3],
191 type: 'span',
192 value: match[4],
193 };
194 };
195
196 const parsed = lines.filter((l) => l).map(parse);
197 const lastMap = new Map();
198 const res: NormalizeItem[] = [];
199
200 parsed.forEach((obj) => {
201 if (obj.type === 'raw') {
202 res.push(obj);
203 return;
204 }
205
206 if (lastMap.has(obj.span)) {
207 const last = lastMap.get(obj.span);
208 if (last.off + last.len === obj.off) {
209 last.len += obj.len;
210 last.value += obj.value;
211
212 // Move it to the end
213 res.splice(res.indexOf(last), 1);
214 res.push(last);
215 return;
216 }
217 }
218 res.push(obj);
219 lastMap.set(obj.span, obj);
220 });
221
222 const stringify = (obj: NormalizeItem): string => {
223 if (obj.type === 'raw') {
224 return obj.value;
225 }
226
227 return `off=${obj.off} len=${obj.len} span[${obj.span}]="${obj.value}"`;
228 };
229 return res.map(stringify).join('\n') + '\n';
230 }
231 }