-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
460 lines (411 loc) · 11.9 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
import { randomBytes } from 'crypto';
import { mkdir, writeFile } from 'node:fs/promises';
import { structuredPatch } from 'diff';
import chalk from 'chalk';
import stripAnsi from 'strip-ansi';
import yargs from 'yargs';
import { hideBin } from 'yargs/helpers';
import {
type Test,
serializeExpectedOutputEntry,
type ServerAction,
} from './src/actions';
import {
buildImage,
cleanup,
applyActionClient,
applyActionServer,
setupContainer,
type ClientContainer,
getNetwork,
type ContainerHandle,
} from './src/docker';
import KvRpcTests from './tests/basic/kv';
import EchoTests from './tests/basic/echo';
import UploadTests from './tests/basic/upload';
import NetworkTests from './tests/network';
import DisconnectNotifsTests from './tests/disconnect_notifs';
import VolumeTests from './tests/volume';
import InterleavingTests from './tests/interleaving';
import InstanceMismatchTests from './tests/instance_mismatch';
import v2BackwardsCompat from './tests/v2_backwards_compat_server';
import { PRESET_TIMER, type ListrTask } from 'listr2';
import { Manager } from '@listr2/manager';
import { constants, open } from 'fs/promises';
import assert from 'assert';
const {
client: clientImpl,
server: serverImpl,
name: nameFilters,
parallel,
bail,
} = yargs(hideBin(process.argv))
.options({
client: {
type: 'string',
demandOption: true,
},
server: {
type: 'string',
demandOption: true,
},
name: {
type: 'array',
string: true,
default: [] as string[],
description: 'only run tests that contain the specified string',
},
parallel: {
type: 'number',
default: 16,
description: 'number of tests to run in parallel',
},
bail: {
type: 'boolean',
default: false,
description: 'stop running tests after the first failure',
},
})
.parseSync();
process
.on('unhandledRejection', async (reason) => {
console.error(chalk.red('uh oh, uncaught promise rejection'));
console.error(reason);
await cleanup();
process.exit(1);
})
.on('uncaughtException', async (err) => {
console.error(chalk.red('uh oh, something went wrong!'));
console.error(err);
await cleanup();
process.exit(1);
});
process.on('SIGINT', async () => {
await cleanup();
process.exit(1);
});
function constructDiffString(
expected: string,
actual: string,
unordered: boolean,
): [string, boolean] {
if (unordered) {
const actualLines = actual.split('\n');
actualLines.sort();
actual = actualLines.join('\n');
const expectedLines = expected.split('\n');
expectedLines.sort();
expected = expectedLines.join('\n');
}
const patch = structuredPatch(
'expected',
'actual',
expected.trimEnd() + '\n',
actual.trimEnd() + '\n',
);
if (patch.hunks.length === 0) {
return ['', false];
}
const diff: string[] = ['diff'];
for (const hunk of patch.hunks) {
diff.push('--- expected');
diff.push('+++ actual');
diff.push(
chalk.blue(
`@@ -${hunk.oldStart},${hunk.oldLines} +${hunk.newStart},${hunk.newLines}`,
),
);
for (const line of hunk.lines) {
if (line.startsWith('+')) {
diff.push(chalk.green(line));
} else if (line.startsWith('-')) {
diff.push(chalk.red(line));
} else {
diff.push(line);
}
}
}
return [diff.join('\n'), true];
}
async function runTest(
test: Test,
title: string,
log: (msg: string) => void,
): Promise<{
clientContainers: Record<string, ClientContainer>;
serverContainer: ContainerHandle;
}> {
const { network, cleanupNetwork } = await getNetwork(title, log);
log('status: setup');
const testId = randomBytes(8).toString('hex');
const serverContainer = await setupContainer(
testId,
clientImpl,
serverImpl,
'server',
'server',
network,
log,
);
const serverActions: ServerAction[] = test.server?.serverActions ?? [];
const clientContainers: Record<string, ClientContainer> = {};
for (const [clientName, testEntry] of Object.entries(test.clients)) {
// client case
const { actions, expectedOutput } = testEntry;
const container = await setupContainer(
testId,
clientImpl,
serverImpl,
'client',
clientName,
network,
log,
);
clientContainers[clientName] = {
...container,
actions,
expectedOutput,
};
}
// build the map of syncpoints to promises.
const syncPromises: Record<
string,
Record<string, { promise: Promise<unknown>; resolve: () => unknown }>
> = {};
const processSyncAction = (name: string, label: string) => {
if (!(label in syncPromises)) {
syncPromises[label] = {};
}
let resolve: (() => void) | undefined = undefined;
const promise = new Promise<void>((_resolve) => {
resolve = _resolve;
});
assert(resolve, `We're missing the resolve here! ${name}: ${label}`);
syncPromises[label][name] = {
resolve,
promise,
};
};
for (const action of serverActions) {
if (action.type !== 'sync') continue;
processSyncAction('server', action.label);
}
for (const [clientName, client] of Object.entries(clientContainers)) {
for (const action of client.actions) {
if (action.type !== 'sync') continue;
processSyncAction(clientName, action.label);
}
}
// build the barriers out of the sync promises.
const syncBarriers: Record<string, Promise<unknown>> = {};
for (const [label, promises] of Object.entries(syncPromises)) {
const promiseArray: Promise<unknown>[] = [];
for (const { promise } of Object.values(promises)) {
promiseArray.push(promise);
}
syncBarriers[label] = Promise.all(promiseArray);
// install the barriers in all containers.
for (const [label, peers] of Object.entries(syncPromises)) {
for (const [peer, { resolve }] of Object.entries(peers)) {
if (peer === 'server') {
serverContainer.syncBarriers[label] = () => {
resolve();
return syncBarriers[label];
};
} else {
const client = clientContainers[peer];
client.syncBarriers[label] = () => {
resolve();
return syncBarriers[label];
};
}
}
}
}
log('status: run');
await Promise.all([
(async () => {
for (const action of serverActions) {
await applyActionServer(network, serverContainer, action, log);
}
})(),
...Object.values(clientContainers).map(async (client) => {
for (const action of client.actions) {
await applyActionClient(network, client, action, log);
}
}),
]);
// wait a little bit to finish processing
log('status: cleanup');
await new Promise((resolve) => setTimeout(resolve, 2000));
await Promise.all(
Object.values(clientContainers).map(
async (client) => await client.cleanup(),
),
);
await serverContainer.cleanup();
await cleanupNetwork();
return {
clientContainers,
serverContainer,
};
}
async function runSuite(
tests: Record<string, Test>,
ignore: Test[],
): Promise<number> {
await buildImage(clientImpl, 'client');
await buildImage(serverImpl, 'server');
const suiteStart = new Date();
console.log('Starting Tests');
console.log('Client:', clientImpl, 'Server:', serverImpl);
console.log(chalk.reset());
const testsFailed = new Set<string>();
const testsFlaked = new Set<string>();
const logsDir = `./logs/${clientImpl}-${serverImpl}/${Date.now()}/`;
await mkdir(logsDir, { recursive: true });
let numTests = 0;
const tasks = Object.entries(tests)
.sort(([nameA], [nameB]) => nameA.localeCompare(nameB))
.map(
([name, test]): ListrTask => ({
title: name,
rendererOptions: {
outputBar: Infinity,
persistentOutput: true,
},
skip: () => {
if (
(nameFilters.length &&
!nameFilters.some((filter) => name.includes(filter))) ||
ignore.includes(test)
) {
return true;
}
numTests++;
return false;
},
task: async (_ctx, task) => {
const stdout = task.stdout();
const log = (msg: string) => {
stdout.write(msg);
};
const { clientContainers, serverContainer } = await runTest(
test,
task.title,
log,
);
log('status: writing results');
const stderrLogFilePath = `${logsDir}/${name}.log`;
const logFileHandle = await open(
stderrLogFilePath,
constants.O_APPEND | constants.O_WRONLY | constants.O_CREAT,
);
for (const [clientName, client] of Object.entries(clientContainers)) {
const expectedOutput = client.expectedOutput
.map(serializeExpectedOutputEntry)
.join('\n');
const actualOutput = await client.stdout;
const [diff, hasDiff] = constructDiffString(
expectedOutput,
actualOutput,
test.unordered ?? false,
);
let diffMsg: string | undefined = undefined;
if (hasDiff) {
const failMessage = test.flaky
? chalk.black.bgYellow(' FLAKED ')
: chalk.black.bgRed(' FAIL ');
diffMsg = `
clientName: ${chalk.red(clientName)} ${failMessage}
diff:
${diff}
`;
if (test.flaky) {
testsFlaked.add(name);
} else {
testsFailed.add(name);
}
}
const logOutput = stripAnsi(`
${diffMsg ?? 'SUCCESS'}
clientName: ${clientName} logs:
${await client.stderr}
end logs for ${clientName}
server logs:
${await serverContainer.stderr}
end logs for server
`);
log(`${!!diffMsg ? logOutput : 'SUCCESS'}
logs will be written to ${stderrLogFilePath}
`);
await logFileHandle.appendFile(logOutput);
}
await logFileHandle.close();
if (testsFailed.has(name)) {
throw new Error('test failed');
} else if (testsFlaked.has(name)) {
task.skip('flaked');
}
},
}),
);
const taskrunner = new Manager({
concurrent: parallel,
rendererOptions: {
collapseSkips: false,
collapseErrors: false,
suffixSkips: true,
suffixRetries: true,
indentation: 4,
clearOutput: false,
removeEmptyLines: false,
timer: PRESET_TIMER,
},
exitOnError: bail,
});
taskrunner.add(tasks);
await taskrunner.runAll();
// Sometimes task runner can take a bit to flush the output
// we log and wait for a second
console.log('');
await new Promise((resolve) => setTimeout(resolve, 1000));
// print summary
const summary = `${chalk.black.bgYellow(' SUMMARY ')}
total time: ${(new Date().getTime() - suiteStart.getTime()) / 1000} seconds
passed ${numTests - (testsFailed.size + testsFlaked.size)}/${numTests}
${chalk.magenta(`flaked:`)}
${Array.from(testsFlaked)
.map((name) => chalk.magenta(`- ${name}`))
.join('\n')}
${chalk.red(`failed:`)}
${Array.from(testsFailed)
.map((name) => chalk.red(`- ${name}\n`))
.join('\n')}
`;
await writeFile(`${logsDir}/summary.txt`, stripAnsi(summary));
console.log(summary);
console.log('logs written to ', logsDir);
await mkdir('tests/results', { recursive: true });
return testsFailed.size;
}
// run the test suite with specific ignore lists
const ignoreLists: Record<string, Test[]> = {
python: [EchoTests.RepeatEchoPrefixTest],
};
const numFailed = await runSuite(
{
...KvRpcTests,
...EchoTests,
...UploadTests,
...InterleavingTests,
...NetworkTests,
...DisconnectNotifsTests,
...VolumeTests,
...InstanceMismatchTests,
...v2BackwardsCompat,
},
[...(ignoreLists[clientImpl] ?? []), ...(ignoreLists[serverImpl] ?? [])],
);
await cleanup();
process.exit(numFailed > 0 ? 1 : 0);