-
-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
common.js
255 lines (204 loc) · 5.72 KB
/
common.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
'use strict';
/**
* Module dependencies.
*/
const mongoose = require('../');
const Collection = mongoose.Collection;
const assert = require('assert');
const collectionNames = new Map();
if (process.env.D === '1') {
mongoose.set('debug', true);
}
if (process.env.PRINT_COLLECTIONS) {
after(function() {
console.log('Colls', Array.from(collectionNames.entries()).sort((a, b) => a[1] - b[1]));
});
}
/**
* Override all Collection related queries to keep count
*/
[
'createIndex',
'findAndModify',
'findOne',
'find',
'insert',
'save',
'update',
'remove',
'count',
'distinct',
'isCapped',
'options'
].forEach(function(method) {
const oldMethod = Collection.prototype[method];
Collection.prototype[method] = function() {
return oldMethod.apply(this, arguments);
};
});
/**
* Override Collection#onOpen to keep track of connections
*/
const oldOnOpen = Collection.prototype.onOpen;
Collection.prototype.onOpen = function() {
return oldOnOpen.apply(this, arguments);
};
/**
* Override Collection#onClose to keep track of disconnections
*/
const oldOnClose = Collection.prototype.onClose;
Collection.prototype.onClose = function() {
return oldOnClose.apply(this, arguments);
};
/**
* Create a connection to the test database.
* You can set the environment variable MONGOOSE_TEST_URI to override this.
*
* @api private
*/
module.exports = function(options) {
options || (options = {});
let uri;
if (options.uri) {
uri = options.uri;
delete options.uri;
} else {
uri = module.exports.uri;
}
const noErrorListener = !!options.noErrorListener;
delete options.noErrorListener;
options.enableUtf8Validation = false;
const conn = mongoose.createConnection(uri, options);
const model = conn.model;
conn.model = function(name, schema, collection) {
if (schema == null || schema._baseSchema != null) {
// 2 cases: if calling `db.model(name)` to retrieve a model,
// or if declaring a discriminator, skip adding the model name.
return model.apply(this, arguments);
}
const collName = collection == null ? mongoose.pluralize(name) : collection;
let count = collectionNames.get(collName) || 0;
collectionNames.set(collName, ++count);
return model.apply(this, arguments);
};
if (noErrorListener) {
return conn;
}
conn.on('error', function(err) {
assert.ok(err);
});
return conn;
};
function getUri(default_uri, db) {
const env = process.env.START_REPLICA_SET ? process.env.MONGOOSE_REPLSET_URI : process.env.MONGOOSE_TEST_URI;
const use = env ? env : default_uri;
const lastIndex = use.lastIndexOf('/');
// use length if lastIndex is 9 or lower, because that would mean it found the last character of "mongodb://"
return use.slice(0, lastIndex <= 9 ? use.length : lastIndex) + `/${db}`;
}
/*!
* testing uri
*/
// the following has to be done, otherwise mocha will evaluate this before running the global-setup, where it becomes the default
Object.defineProperty(module.exports, 'uri', {
get: () => getUri('mongodb://127.0.0.1:27017/', 'mongoose_test')
});
/*!
* testing uri for 2nd db
*/
Object.defineProperty(module.exports, 'uri2', {
get: () => getUri('mongodb://127.0.0.1:27017/', 'mongoose_test_2')
});
/**
* expose mongoose
*/
module.exports.mongoose = mongoose;
/**
* expose mongod version helper
*/
module.exports.mongodVersion = async function() {
return new Promise((resolve, reject) => {
const db = module.exports();
db.on('error', reject);
db.on('open', function() {
const admin = db.db.admin();
admin.serverStatus(function(err, info) {
if (err) {
return reject(err);
}
const version = info.version.split('.').map(function(n) {
return parseInt(n, 10);
});
db.close(function() {
resolve(version);
});
});
});
});
};
async function dropDBs() {
this.timeout(60000);
const db = await module.exports({ noErrorListener: true }).asPromise();
await db.dropDatabase();
await db.close();
}
before(async function() {
this.timeout(60000);
if (process.env.START_REPLICA_SET) {
// const uri = await startReplicaSet();
// module.exports.uri = uri;
// module.exports.uri2 = uri.replace('mongoose_test', 'mongoose_test2');
// process.env.REPLICA_SET = 'rs0';
// const conn = mongoose.createConnection(uri);
// await conn.asPromise();
// await conn.db.collection('test').findOne();
// await conn.close();
}
});
before(dropDBs);
after(dropDBs);
beforeEach(function() {
if (this.currentTest) {
global.CURRENT_TEST = this.currentTest.title;
if (this.currentTest.parent.title) {
global.CURRENT_TEST = this.currentTest.parent.title + global.CURRENT_TEST;
}
} else {
global.CURRENT_TEST = 'N/A';
}
});
process.on('unhandledRejection', function(error, promise) {
if (error.$expected) {
return;
}
if (promise.originalStack) {
console.log('UnhandledRejection: ', promise.originalStack);
}
throw error;
});
// async function startReplicaSet() {
// const ReplSet = require('mongodb-memory-server').MongoMemoryReplSet;
// // Create new instance
// const replSet = new ReplSet({
// binary: {
// version: '5.0.4'
// },
// instanceOpts: [
// // Set the expiry job in MongoDB to run every second
// {
// port: 27017,
// args: ['--setParameter', 'ttlMonitorSleepSecs=1']
// }
// ],
// dbName: 'mongoose_test',
// replSet: {
// name: 'rs0',
// count: 2,
// storageEngine: 'wiredTiger'
// }
// });
// await replSet.start();
// await replSet.waitUntilRunning();
// await new Promise(resolve => setTimeout(resolve, 10000));
// return replSet.getUri('mongoose_test');
// }