-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
utils.ts
491 lines (421 loc) · 12.7 KB
/
utils.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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
import { EJSON } from 'bson';
import * as BSON from 'bson';
import { expect } from 'chai';
import { setTimeout } from 'timers';
import { inspect, promisify } from 'util';
import { OP_MSG } from '../../src/cmap/wire_protocol/constants';
import { Document } from '../../src/index';
import { Logger } from '../../src/logger';
import { deprecateOptions, DeprecateOptionsConfig } from '../../src/utils';
import { runUnifiedSuite } from './unified-spec-runner/runner';
import {
CollectionData,
EntityDescription,
ExpectedEventsForClient,
OperationDescription,
RunOnRequirement,
Test,
UnifiedSuite
} from './unified-spec-runner/schema';
export function makeTestFunction(config: DeprecateOptionsConfig) {
const fn = (options: any) => {
if (options) options = null;
};
return deprecateOptions(config, fn);
}
export function ensureCalledWith(stub: any, args: any[]) {
args.forEach((m: any) => expect(stub).to.have.been.calledWith(m));
}
// creation of class with a logger
export function ClassWithLogger() {
this.logger = new Logger('ClassWithLogger');
}
ClassWithLogger.prototype.f = makeTestFunction({
name: 'f',
deprecatedOptions: ['maxScan', 'snapshot', 'fields'],
optionsIndex: 0
});
ClassWithLogger.prototype.getLogger = function () {
return this.logger;
};
// creation of class without a logger
export function ClassWithoutLogger() {
// empty function for class
}
ClassWithoutLogger.prototype.f = makeTestFunction({
name: 'f',
deprecatedOptions: ['maxScan', 'snapshot', 'fields'],
optionsIndex: 0
});
// creation of class where getLogger returns undefined
export function ClassWithUndefinedLogger() {
// empty function for class
}
ClassWithUndefinedLogger.prototype.f = makeTestFunction({
name: 'f',
deprecatedOptions: ['maxScan', 'snapshot', 'fields'],
optionsIndex: 0
});
ClassWithUndefinedLogger.prototype.getLogger = function () {
return undefined;
};
export class EventCollector {
private _events: Record<string, any[]>;
private _timeout: number;
constructor(
obj: { on: (arg0: any, arg1: (event: any) => number) => void },
events: any[],
options?: { timeout: number }
) {
this._events = Object.create(null);
this._timeout = options ? options.timeout : 5000;
events.forEach((eventName: string | number) => {
this._events[eventName] = [];
obj.on(eventName, (event: any) => this._events[eventName].push(event));
});
}
waitForEvent(eventName: string, callback: (error?: Error, events?: any[]) => void): void;
waitForEvent(
eventName: string,
count: number,
callback: (error?: Error, events?: any[]) => void
): void;
waitForEvent(
eventName: string,
count: number | ((error?: Error, events?: any[]) => void),
callback?: (error?: Error, events?: any[]) => void
): void {
if (typeof count === 'function') {
callback = count;
count = 1;
}
this.waitForEventImpl(this, Date.now(), eventName, count, callback);
}
reset(eventName: string) {
if (eventName == null) {
Object.keys(this._events).forEach(eventName => {
this._events[eventName] = [];
});
return;
}
if (this._events[eventName] == null) {
throw new TypeError(`invalid event name "${eventName}" specified for reset`);
}
this._events[eventName] = [];
}
waitForEventImpl(
collector: this,
start: number,
eventName: string | number,
count: number,
callback: (error?: Error, events?: any[]) => void
) {
const events = collector._events[eventName];
if (events.length >= count) {
return callback(undefined, events);
}
if (Date.now() - start >= collector._timeout) {
return callback(new Error(`timed out waiting for event "${eventName}"`));
}
setTimeout(() => this.waitForEventImpl(collector, start, eventName, count, callback), 10);
}
}
export function getSymbolFrom(target: any, symbolName: any, assertExists = true) {
const symbol = Object.getOwnPropertySymbols(target).filter(
s => s.toString() === `Symbol(${symbolName})`
)[0];
if (assertExists && !symbol) {
throw new Error(`Did not find Symbol(${symbolName}) on ${target}`);
}
return symbol;
}
export function getEnvironmentalOptions() {
const options = {};
if (process.env.MONGODB_API_VERSION) {
Object.assign(options, {
serverApi: { version: process.env.MONGODB_API_VERSION }
});
}
if (process.env.SERVERLESS) {
Object.assign(options, {
auth: {
username: process.env.SERVERLESS_ATLAS_USER,
password: process.env.SERVERLESS_ATLAS_PASSWORD
},
tls: true,
compressors: 'snappy,zlib'
});
}
return options;
}
export function shouldRunServerlessTest(testRequirement: any, isServerless: any) {
if (!testRequirement) return true;
switch (testRequirement) {
case 'forbid':
// return true if the configuration is NOT serverless
return !isServerless;
case 'allow':
// always return true
return true;
case 'require':
// only return true if the configuration is serverless
return isServerless;
default:
throw new Error(`Invalid serverless filter: ${testRequirement}`);
}
}
/**
* Use as a template string tag to stringify objects in the template string
* Attempts to use EJSON (to make type information obvious)
* falls back to util.inspect if there's an error (circular reference)
*/
export function ejson(strings: TemplateStringsArray, ...values: any[]) {
const stringParts = [strings[0]];
for (const [idx, value] of values.entries()) {
if (typeof value === 'object') {
let stringifiedObject: string;
try {
stringifiedObject = EJSON.stringify(value, { relaxed: false });
} catch (error) {
stringifiedObject = inspect(value, {
depth: Infinity,
showHidden: true,
compact: true
});
}
stringParts.push(stringifiedObject);
} else {
stringParts.push(String(value));
}
stringParts.push(strings[idx + 1]);
}
return stringParts.join('');
}
/**
* Run an async function after some set timeout
* @param fn - function to run
* @param ms - timeout in MS
*/
export const runLater = (fn: () => Promise<void>, ms: number) => {
return new Promise<void>((resolve, reject) => {
setTimeout(() => fn().then(resolve).catch(reject), ms);
});
};
export const sleep = promisify(setTimeout);
/**
* If you are using sinon fake timers, it can end up blocking queued IO from running
* awaiting a nextTick call will allow the event loop to process Networking/FS callbacks
*/
export const processTick = () => new Promise(resolve => process.nextTick(resolve));
export function getIndicesOfAuthInUrl(connectionString: string | string[]) {
const doubleSlashIndex = connectionString.indexOf('//');
const atIndex = connectionString.indexOf('@');
if (doubleSlashIndex === -1 || atIndex === -1) {
return null;
}
return {
start: doubleSlashIndex + 2,
end: atIndex
};
}
export function removeAuthFromConnectionString(connectionString: string) {
const indices = getIndicesOfAuthInUrl(connectionString);
if (!indices) {
return connectionString;
}
const { start, end } = indices;
if (start === -1 || end === -1) {
return connectionString;
}
return connectionString.slice(0, start) + connectionString.slice(end + 1);
}
export function extractAuthFromConnectionString(connectionString: string | any[]) {
const indices = getIndicesOfAuthInUrl(connectionString);
if (!indices) {
return null;
}
return connectionString.slice(indices.start, indices.end);
}
export interface FailPoint {
configureFailPoint: 'failCommand';
mode: { activationProbability: number } | { times: number } | 'alwaysOn' | 'off';
data: {
failCommands: string[];
errorCode?: number;
closeConnection?: boolean;
blockConnection?: boolean;
blockTimeMS?: number;
writeConcernError?: { code: number; errmsg: string };
threadName?: string;
failInternalCommands?: boolean;
errorLabels?: string[];
appName?: string;
};
}
export class TestBuilder {
private _description: string;
private runOnRequirements: RunOnRequirement[] = [];
private _skipReason?: string;
private _operations: OperationDescription[] = [];
private _expectEvents?: ExpectedEventsForClient[] = [];
private _outcome?: CollectionData[] = [];
static it(title: string) {
return new TestBuilder(title);
}
constructor(description: string) {
this._description = description;
}
operation(operation: OperationDescription): this {
this._operations.push({
object: 'collection0',
arguments: {},
...operation
});
return this;
}
runOnRequirement(requirement: RunOnRequirement): this {
this.runOnRequirements.push(requirement);
return this;
}
expectEvents(event: ExpectedEventsForClient): this {
this._expectEvents.push(event);
return this;
}
toJSON(): Test {
const test: Test = {
description: this._description,
runOnRequirements: this.runOnRequirements,
operations: this._operations,
expectEvents: this._expectEvents,
outcome: this._outcome
};
if (this._skipReason != null) {
test.skipReason = this._skipReason;
}
return test;
}
}
export function generateOpMsgBuffer(document: Document): Buffer {
const header = Buffer.alloc(4 * 4 + 4);
const typeBuffer = Buffer.alloc(1);
typeBuffer[0] = 0;
const docBuffer = BSON.serialize(document);
const totalLength = header.length + typeBuffer.length + docBuffer.length;
header.writeInt32LE(totalLength, 0);
header.writeInt32LE(0, 4);
header.writeInt32LE(0, 8);
header.writeInt32LE(OP_MSG, 12);
header.writeUInt32LE(0, 16);
return Buffer.concat([header, typeBuffer, docBuffer]);
}
export class UnifiedTestSuiteBuilder {
private _description = 'Default Description';
private _schemaVersion = '1.0';
private _createEntities: EntityDescription[];
private _runOnRequirement: RunOnRequirement[] = [];
private _initialData: CollectionData[] = [];
private _tests: Test[] = [];
static describe(title: string) {
return new UnifiedTestSuiteBuilder(title);
}
/**
* Establish common defaults
* - id and name = client0, listens for commandStartedEvent
* - id and name = database0
* - id and name = collection0
*/
static get defaultEntities(): EntityDescription[] {
return [
{
client: {
id: 'client0',
useMultipleMongoses: true,
observeEvents: ['commandStartedEvent']
}
},
{
database: {
id: 'database0',
client: 'client0',
databaseName: 'database0'
}
},
{
collection: {
id: 'collection0',
database: 'database0',
collectionName: 'collection0'
}
}
];
}
constructor(description: string) {
this._description = description;
this._createEntities = [];
}
description(description: string): this {
this._description = description;
return this;
}
test(test: Test): this;
test(test: Test[]): this;
test(test: Test | Test[]): this {
if (Array.isArray(test)) {
this._tests.push(...test);
} else {
this._tests.push(test);
}
return this;
}
createEntities(entity: EntityDescription): this;
createEntities(entity: EntityDescription[]): this;
createEntities(entity: EntityDescription | EntityDescription[]): this {
if (Array.isArray(entity)) {
this._createEntities.push(...entity);
} else {
this._createEntities.push(entity);
}
return this;
}
initialData(data: CollectionData): this;
initialData(data: CollectionData[]): this;
initialData(data: CollectionData | CollectionData[]): this {
if (Array.isArray(data)) {
this._initialData.push(...data);
} else {
this._initialData.push(data);
}
return this;
}
runOnRequirement(requirement: RunOnRequirement): this;
runOnRequirement(requirement: RunOnRequirement[]): this;
runOnRequirement(requirement: RunOnRequirement | RunOnRequirement[]): this {
Array.isArray(requirement)
? this._runOnRequirement.push(...requirement)
: this._runOnRequirement.push(requirement);
return this;
}
schemaVersion(version: string): this {
this._schemaVersion = version;
return this;
}
toJSON(): UnifiedSuite {
return {
description: this._description,
schemaVersion: this._schemaVersion,
runOnRequirements: this._runOnRequirement,
createEntities: this._createEntities,
initialData: this._initialData,
tests: this._tests
};
}
run(): void {
return runUnifiedSuite([this.toJSON()]);
}
toMocha() {
return describe(this._description, () => runUnifiedSuite([this.toJSON()]));
}
clone(): UnifiedSuite {
return JSON.parse(JSON.stringify(this));
}
}