/
shared.js
268 lines (237 loc) · 6.7 KB
/
shared.js
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
'use strict';
const MongoClient = require('../../').MongoClient;
const expect = require('chai').expect;
function filterForCommands(commands, bag) {
commands = Array.isArray(commands) ? commands : [commands];
return function(event) {
if (commands.indexOf(event.commandName) !== -1) bag.push(event);
};
}
function filterOutCommands(commands, bag) {
commands = Array.isArray(commands) ? commands : [commands];
return function(event) {
if (commands.indexOf(event.commandName) === -1) bag.push(event);
};
}
function connectToDb(url, db, options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
}
MongoClient.connect(url, options || {}, function(err, client) {
if (err) return callback(err);
callback(null, client.db(db), client);
});
}
function setupDatabase(configuration, dbsToClean) {
dbsToClean = Array.isArray(dbsToClean) ? dbsToClean : [];
var configDbName = configuration.db;
var client = configuration.newClient(configuration.writeConcernMax(), {
poolSize: 1
});
dbsToClean.push(configDbName);
return client
.connect()
.then(() =>
dbsToClean.reduce(
(result, dbName) =>
result
.then(() =>
client.db(dbName).command({ dropAllUsersFromDatabase: 1, writeConcern: { w: 1 } })
)
.then(() => client.db(dbName).dropDatabase({ writeConcern: { w: 1 } })),
Promise.resolve()
)
)
.then(
() => client.close(),
err => client.close(() => Promise.reject(err))
);
}
function makeCleanupFn(client) {
return function(err) {
return new Promise((resolve, reject) => {
try {
client.close(closeErr => {
const finalErr = err || closeErr;
if (finalErr) {
return reject(finalErr);
}
return resolve();
});
} catch (e) {
return reject(err || e);
}
});
};
}
function withTempDb(name, options, client, operation, errorHandler) {
return withClient(
client,
client => done => {
const db = client.db(name, options);
operation.call(this, db)(() => db.dropDatabase(done));
},
errorHandler
);
}
/**
* Safely perform a test with provided MongoClient, ensuring client won't leak.
*
* @param {MongoClient} client
* @param {Function|Promise} operation
* @param {Function|Promise} [errorHandler]
*/
function withClient(client, operation, errorHandler) {
const cleanup = makeCleanupFn(client);
return client
.connect()
.then(operation, errorHandler)
.then(() => cleanup(), cleanup);
}
var assert = {
equal: function(a, b) {
expect(a).to.equal(b);
},
deepEqual: function(a, b) {
expect(a).to.eql(b);
},
strictEqual: function(a, b) {
expect(a).to.eql(b);
},
notEqual: function(a, b) {
expect(a).to.not.equal(b);
},
ok: function(a) {
expect(a).to.be.ok;
},
throws: function(func) {
expect(func).to.throw;
}
};
var delay = function(timeout) {
return new Promise(function(resolve) {
setTimeout(function() {
resolve();
}, timeout);
});
};
function ignoreNsNotFound(err) {
if (!err.message.match(/ns not found/)) throw err;
}
function dropCollection(dbObj, collectionName) {
return dbObj.dropCollection(collectionName).catch(ignoreNsNotFound);
}
/**
* A class for listening on specific events
*
* @example
* beforeEach(function() {
* // capture all commandStarted events from client. Get by doing this.commandStarted.events;
* this.commandStarted = new EventCollector(this.client, 'commandStarted');
* });
* @example
* beforeEach(function() {
* // same as above, but only allows 'insert' and 'find' events
* this.commandStarted = new EventCollector(this.client, 'commandStarted', {
* include: ['insert', 'find']
* });
* });
* @example
* beforeEach(function() {
* // same as above, but excludes 'ismaster' events
* this.commandStarted = new EventCollector(this.client, 'commandStarted', {
* exclude: ['ismaster']
* });
* });
*/
class EventCollector {
constructor(client, eventName, options) {
this._client = client;
this._eventName = eventName;
this._events = [];
this._listener = e => this._events.push(e);
this._client.on(this._eventName, this._listener);
options = options || {};
const include = this._buildSet(options.include);
if (include.size > 0) {
this._include = include;
}
this._exclude = this._buildSet(options.exclude);
}
_buildSet(input) {
if (Array.isArray(input)) {
return new Set(input.map(x => x.toLowerCase()));
} else if (typeof input === 'string') {
return new Set([input.toLowerCase()]);
}
return new Set();
}
get events() {
let events = this._events;
if (this._include) {
events = events.filter(e => this._include.has(e.commandName.toLowerCase()));
}
return events.filter(e => !this._exclude.has(e.commandName.toLowerCase()));
}
clear() {
this._events = [];
}
teardown() {
this._client.removeListener(this._eventName, this._listener);
}
}
/**
* Perform a test with a monitored MongoClient that will filter for certain commands.
*
* @param {string|Array} commands commands to filter for
* @param {object} [options] options to pass on to configuration.newClient
* @param {object} [options.queryOptions] connection string options
* @param {object} [options.clientOptions] MongoClient options
* @param {withMonitoredClientCallback} callback the test function
*/
function withMonitoredClient(commands, options, callback) {
if (arguments.length === 2) {
callback = options;
options = {};
}
if (!Object.prototype.hasOwnProperty.call(callback, 'prototype')) {
throw new Error('withMonitoredClient callback can not be arrow function');
}
return function(done) {
const configuration = this.configuration;
const client = configuration.newClient(
Object.assign({}, options.queryOptions),
Object.assign({ monitorCommands: true }, options.clientOptions)
);
const events = [];
client.on('commandStarted', filterForCommands(commands, events));
client.connect((err, client) => {
expect(err).to.not.exist;
function _done(err) {
client.close(err2 => done(err || err2));
}
callback.bind(this)(client, events, _done);
});
};
}
/**
* @callback withMonitoredClientCallback
* @param {MongoClient} client monitored client
* @param {Array} events record of monitored commands
* @param {Function} done trigger end of test and cleanup
*/
module.exports = {
connectToDb,
setupDatabase,
assert,
delay,
withClient,
withMonitoredClient,
withTempDb,
filterForCommands,
filterOutCommands,
ignoreNsNotFound,
dropCollection,
EventCollector
};