Debian Codegraph @

third_party/python/aiohttp/vendor/llhttp/test/md-test.ts

raw
1 import * as assert from 'node:assert';
2 import { describe, test } from 'node:test';
3 import * as fs from 'fs';
4 import { LLParse } from 'llparse';
5 import { Group, MDGator, Metadata, Test } from 'mdgator';
6 import * as path from 'path';
7 import * as vm from 'vm';
8
9 import * as llhttp from '../src/llhttp';
10 import { allowedTypes, build, FixtureResult, Node, TestType } from './fixtures';
11
12 //
13 // Cache nodes/llparse instances ahead of time
14 // (different types of tests will re-use them)
15 //
16
17 const modeCache = new Map<string, FixtureResult>();
18
19 function buildNode() {
20 const p = new LLParse();
21 const instance = new llhttp.HTTP(p);
22
23 return { llparse: p, entry: instance.build().entry };
24 }
25
26 function buildURL() {
27 const p = new LLParse();
28 const instance = new llhttp.URL(p, true);
29
30 const node = instance.build();
31
32 // Loop
33 node.exit.toHTTP.otherwise(node.entry.normal);
34 node.exit.toHTTP09.otherwise(node.entry.normal);
35
36 return { llparse: p, entry: node.entry.normal };
37 }
38
39 //
40 // Build binaries using cached nodes/llparse
41 //
42
43 async function buildMode(ty: TestType, meta: Metadata): Promise<FixtureResult> {
44 const cacheKey = `${ty}:${JSON.stringify(meta || {})}`;
45 let entry = modeCache.get(cacheKey);
46
47 if (entry) {
48 return entry;
49 }
50
51 let node: { llparse: LLParse; entry: Node };
52 let prefix: string;
53 let extra: string[];
54 if (ty === 'url') {
55 node = buildURL();
56 prefix = 'url';
57 extra = [];
58 } else {
59 node = buildNode();
60 prefix = 'http';
61 extra = [
62 '-DLLHTTP__TEST_HTTP',
63 path.join(__dirname, '..', 'src', 'native', 'http.c'),
64 ];
65 }
66
67 if (meta.pause) {
68 extra.push(`-DLLHTTP__TEST_PAUSE_${meta.pause.toUpperCase()}=1`);
69 }
70
71 if (meta.skipBody) {
72 extra.push('-DLLHTTP__TEST_SKIP_BODY=1');
73 }
74
75 entry = await build(node.llparse, node.entry, `${prefix}-${ty}`, {
76 extra,
77 }, ty);
78
79 modeCache.set(cacheKey, entry);
80 return entry;
81 }
82
83 //
84 // Run test suite
85 //
86
87 function run(name: string): void {
88 const md = new MDGator();
89
90 const raw = fs.readFileSync(path.join(__dirname, name + '.md')).toString();
91 const groups = md.parse(raw);
92
93 function runSingleTest(ty: TestType, meta: Metadata,
94 input: string,
95 expected: ReadonlyArray<string | RegExp>): void {
96 test(`should pass for type="${ty}"`, { timeout: 60000 }, async () => {
97 const binary = await buildMode(ty, meta);
98 await binary.check(input, expected, {
99 noScan: meta.noScan === true,
100 });
101 });
102 }
103
104 function runTest(test: Test) {
105 describe(test.name + ` at ${name}.md:${test.line + 1}`, () => {
106 let types: TestType[] = [];
107
108 const isURL = test.values.has('url');
109 const inputKey = isURL ? 'url' : 'http';
110
111 assert(test.values.has(inputKey),
112 `Missing "${inputKey}" code in md file`);
113 assert.strictEqual(test.values.get(inputKey)!.length, 1,
114 `Expected just one "${inputKey}" input`);
115
116 let meta: Metadata;
117 if (test.meta.has(inputKey)) {
118 meta = test.meta.get(inputKey)![0]!;
119 } else {
120 assert(isURL, 'Missing required http metadata');
121 meta = {};
122 }
123
124 if (isURL) {
125 types = [ 'url' ];
126 } else {
127 assert(Object.prototype.hasOwnProperty.call(meta, 'type'), 'Missing required `type` metadata');
128
129 if (meta.type) {
130 if (!allowedTypes.includes(meta.type)) {
131 throw new Error(`Invalid value of \`type\` metadata: "${meta.type}"`);
132 }
133
134 types.push(meta.type);
135 }
136 }
137
138 assert(test.values.has('log'), 'Missing `log` code in md file');
139
140 assert.strictEqual(test.values.get('log')!.length, 1,
141 'Expected just one output');
142
143 let input: string = test.values.get(inputKey)![0];
144 let expected: string = test.values.get('log')![0];
145
146 // Remove trailing newline
147 input = input.replace(/\n$/, '');
148
149 // Remove escaped newlines
150 input = input.replace(/\\(\r\n|\r|\n)/g, '');
151
152 // Normalize all newlines
153 input = input.replace(/\r\n|\r|\n/g, '\r\n');
154
155 // Replace escaped CRLF, tabs, form-feed
156 input = input.replace(/\\r/g, '\r');
157 input = input.replace(/\\n/g, '\n');
158 input = input.replace(/\\t/g, '\t');
159 input = input.replace(/\\f/g, '\f');
160 input = input.replace(/\\x([0-9a-fA-F]+)/g, (all, hex) => {
161 return String.fromCharCode(parseInt(hex, 16));
162 });
163
164 // Useful in token tests
165 input = input.replace(/\\([0-7]{1,3})/g, (_, digits) => {
166 return String.fromCharCode(parseInt(digits, 8));
167 });
168
169 // Evaluate inline JavaScript
170 input = input.replace(/\$\{(.+?)\}/g, (_, code) => {
171 return vm.runInNewContext(code) + '';
172 });
173
174 // Escape first symbol `\r` or `\n`, `|`, `&` for Windows
175 if (process.platform === 'win32') {
176 const firstByte = Buffer.from(input)[0];
177 if (firstByte === 0x0a || firstByte === 0x0d) {
178 input = '\\' + input;
179 }
180
181 input = input.replace(/\|/g, '^|');
182 input = input.replace(/&/g, '^&');
183 }
184
185 // Replace escaped tabs/form-feed in expected too
186 expected = expected.replace(/\\t/g, '\t');
187 expected = expected.replace(/\\f/g, '\f');
188
189 // Split
190 const expectedLines = expected.split(/\n/g).slice(0, -1);
191
192 const fullExpected = expectedLines.map((line) => {
193 if (line.startsWith('/')) {
194 return new RegExp(line.trim().slice(1, -1));
195 } else {
196 return line;
197 }
198 });
199
200 for (const ty of types) {
201 if (meta.skip === true || (process.env.ONLY === 'true' && !meta.only)) {
202 continue;
203 }
204
205 runSingleTest(ty, meta, input, fullExpected);
206 }
207 });
208 }
209
210 function runGroup(group: Group) {
211 describe(group.name + ` at ${name}.md:${group.line + 1}`, function () {
212 for (const child of group.children) {
213 runGroup(child);
214 }
215
216 for (const test of group.tests) {
217 runTest(test);
218 }
219 });
220 }
221
222 for (const group of groups) {
223 runGroup(group);
224 }
225 }
226
227 run('request/sample');
228 run('request/lenient-headers');
229 run('request/lenient-version');
230 run('request/method');
231 run('request/uri');
232 run('request/connection');
233 run('request/content-length');
234 run('request/transfer-encoding');
235 run('request/invalid');
236 run('request/finish');
237 run('request/pausing');
238 run('request/pipelining');
239
240 run('response/sample');
241 run('response/connection');
242 run('response/content-length');
243 run('response/transfer-encoding');
244 run('response/invalid');
245 run('response/finish');
246 run('response/lenient-version');
247 run('response/pausing');
248 run('response/pipelining');
249
250 run('url');