This repository has been archived by the owner on Oct 19, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathutils.js
498 lines (453 loc) · 13 KB
/
utils.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
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
492
493
494
495
496
497
498
const _ = require('underscore'),
auth = require('./auth')(),
constants = require('./constants'),
http = require('http'),
path = require('path'),
htmlScreenshotReporter = require('protractor-jasmine2-screenshot-reporter'),
userSettingsDocId = `org.couchdb.user:${auth.user}`;
const PouchDB = require('pouchdb-core');
PouchDB.plugin(require('pouchdb-adapter-http'));
PouchDB.plugin(require('pouchdb-mapreduce'));
const db = new PouchDB(
`http://${auth.user}:${auth.pass}@${constants.COUCH_HOST}:${
constants.COUCH_PORT
}/${constants.DB_NAME}`
);
let originalSettings;
// First Object is passed to http.request, second is for specific options / flags
// for this wrapper
const request = (options, { debug, noAuth, notJson } = {}) => {
if (typeof options === 'string') {
options = {
path: options,
};
}
const deferred = protractor.promise.defer();
options.hostname = constants.API_HOST;
options.port = constants.API_PORT;
if (!noAuth) {
options.auth = options.auth || auth.user + ':' + auth.pass;
}
if (debug) {
console.log('!!!!!!!REQUEST!!!!!!!');
console.log('!!!!!!!REQUEST!!!!!!!');
console.log(JSON.stringify(options));
console.log('!!!!!!!REQUEST!!!!!!!');
console.log('!!!!!!!REQUEST!!!!!!!');
}
const req = http.request(options, res => {
res.setEncoding('utf8');
let body = '';
res.on('data', chunk => {
body += chunk;
});
res.on('end', () => {
try {
if (notJson) {
return deferred.fulfill(body);
}
body = JSON.parse(body);
if (body.error) {
const err = new Error(
`Request failed: ${options.path},\n body: ${JSON.stringify(
options.body
)}\n response: ${JSON.stringify(body)}`
);
err.responseBody = body;
err.statusCode = res.statusCode;
deferred.reject(err);
} else {
deferred.fulfill(body);
}
} catch (e) {
let errorMessage = `Server returned an error for request: ${JSON.stringify(
options
)}\n `;
if (body === 'Server error') {
errorMessage += 'Check medic-api logs for details.';
} else {
errorMessage += `Response body: ${body}`;
}
const err = new Error(errorMessage);
err.responseBody = body;
deferred.reject(err);
}
});
});
req.on('error', e => {
console.log('Request failed: ' + e.message);
deferred.reject(e);
});
if (options.body) {
if (typeof options.body === 'string') {
req.write(options.body);
} else {
req.write(JSON.stringify(options.body));
}
}
req.end();
return deferred.promise;
};
// Update both ddocs, to avoid instability in tests.
// Note that API will be copying changes to medic over to medic-client, so change
// medic-client first (api does nothing) and medic after (api copies changes over to
// medic-client, but the changes are already there.)
const updateSettings = updates => {
if (originalSettings) {
throw new Error('A previous test did not call revertSettings');
}
return request({
path: '/api/v1/settings',
method: 'GET',
})
.then(settings => {
originalSettings = settings;
// Make sure all updated fields are present in originalSettings, to enable reverting later.
Object.keys(updates).forEach(updatedField => {
if (!_.has(originalSettings, updatedField)) {
originalSettings[updatedField] = null;
}
});
return;
})
.then(() => {
return request({
path: '/api/v1/settings?replace=1',
method: 'PUT',
body: JSON.stringify(updates),
headers: { 'Content-Type': 'application/json' },
});
});
};
const revertSettings = () => {
if (!originalSettings) {
return Promise.resolve(false);
}
return request({
path: '/api/v1/settings?replace=1',
method: 'PUT',
body: JSON.stringify(originalSettings),
headers: { 'Content-Type': 'application/json' },
}).then(() => {
originalSettings = null;
return true;
});
};
const deleteAll = (except = []) => {
// Generate a list of functions to filter documents over
const ignorables = except.concat(
doc =>
['translations', 'translations-backup', 'user-settings', 'info'].includes(
doc.type
),
'appcache',
'migration-log',
'resources',
'settings',
/^_design/
);
const ignoreFns = [];
const ignoreStrings = [];
const ignoreRegex = [];
ignorables.forEach(i => {
if (typeof i === 'function') {
ignoreFns.push(i);
} else if (typeof i === 'object') {
ignoreRegex.push(i);
} else {
ignoreStrings.push(i);
}
});
ignoreFns.push(doc => ignoreStrings.includes(doc._id));
ignoreFns.push(doc => ignoreRegex.find(r => doc._id.match(r)));
// Get, filter and delete documents
return module.exports
.request({
path: path.join('/', constants.DB_NAME, '_all_docs?include_docs=true'),
method: 'GET',
})
.then(({ rows }) =>
rows
.filter(({ doc }) => !ignoreFns.find(fn => fn(doc)))
.map(({ doc }) => {
doc._deleted = true;
doc.type = 'tombstone'; // circumvent tombstones being created when DB is cleaned up
return doc;
})
)
.then(toDelete => {
const ids = toDelete.map(doc => doc._id);
console.log(`Deleting docs: ${ids}`);
return module.exports
.request({
path: path.join('/', constants.DB_NAME, '_bulk_docs'),
method: 'POST',
body: JSON.stringify({ docs: toDelete }),
headers: { 'content-type': 'application/json' },
})
.then(response => {
console.log(`Deleted docs: ${JSON.stringify(response)}`);
});
});
};
const refreshToGetNewSettings = () => {
// wait for the updates to replicate
const dialog = element(by.css('#update-available .submit:not(.disabled)'));
return browser
.wait(protractor.ExpectedConditions.elementToBeClickable(dialog), 10000)
.then(() => {
dialog.click();
})
.catch(() => {
// sometimes there's a double update which causes the dialog to be redrawn
// retry with the new dialog
dialog.isPresent().then(function(result) {
if (result) {
dialog.click();
}
});
})
.then(() => {
return browser.wait(
protractor.ExpectedConditions.elementToBeClickable(
element(by.id('contacts-tab'))
),
10000
);
});
};
const revertDb = (except, ignoreRefresh) => {
return revertSettings().then(needsRefresh => {
return deleteAll(except).then(() => {
// only need to refresh if the settings were changed
if (!ignoreRefresh && needsRefresh) {
return refreshToGetNewSettings();
}
});
});
};
const deleteUsers = usernames => {
const userIds = JSON.stringify(
usernames.map(user => `org.couchdb.user:${user}`)
),
method = 'POST',
headers = { 'Content-Type': 'application/json' };
return Promise.all([
request(
`/${constants.DB_NAME}/_all_docs?include_docs=true&keys=${userIds}`
),
request(`/_users/_all_docs?include_docs=true&keys=${userIds}`),
]).then(results => {
const docs = results.map(result =>
result.rows
.map(row => {
if (row.doc) {
row.doc._deleted = true;
row.doc.type = 'tombstone';
return row.doc;
}
})
.filter(doc => doc)
);
return Promise.all([
request({
path: `/${constants.DB_NAME}/_bulk_docs`,
body: { docs: docs[0] },
method,
headers,
}),
request({
path: `/_users/_bulk_docs`,
body: { docs: docs[1] },
method,
headers,
}),
]);
});
};
module.exports = {
db: db,
request: request,
reporter: new htmlScreenshotReporter({
reportTitle: 'e2e Test Report',
inlineImages: true,
showConfiguration: true,
captureOnlyFailedSpecs: true,
reportOnlyFailedSpecs: false,
showQuickLinks: true,
dest: 'tests/results',
filename: 'report.html',
pathBuilder: function(currentSpec) {
return currentSpec.fullName
.toLowerCase()
.replace(/[^a-z0-9\s]/g, '')
.replace(/\s+/g, '_');
},
}),
requestOnTestDb: (options, debug, notJson) => {
if (typeof options === 'string') {
options = {
path: options,
};
}
options.path = '/' + constants.DB_NAME + (options.path || '');
return request(options, { debug: debug, notJson: notJson });
},
saveDoc: doc => {
const postData = JSON.stringify(doc);
return module.exports.requestOnTestDb({
path: '/', // so audit picks this up
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': postData.length,
},
body: postData,
});
},
saveDocs: docs =>
module.exports
.requestOnTestDb({
path: '/_bulk_docs',
method: 'POST',
body: { docs: docs },
headers: { 'content-type': 'application/json' },
})
.then(results => {
if (results.find(r => !r.ok)) {
throw Error(JSON.stringify(results, null, 2));
} else {
return results;
}
}),
getDoc: id => {
return module.exports.requestOnTestDb({
path: `/${id}`,
method: 'GET',
});
},
deleteDoc: id => {
return module.exports.getDoc(id).then(doc => {
doc._deleted = true;
return module.exports.saveDoc(doc);
});
},
/**
* Deletes all docs in the database, except some core docs (read the code) and
* any docs that you specify.
*
* NB: this is back-end only, it does *not* care about the front-end, and will
* not detect if it needs to refresh
*
* @param {Array} except array of: exact document name; or regex; or
* predicate function that returns true if you
* wish to keep the document
* @return {Promise} completion promise
*/
deleteAllDocs: deleteAll,
/**
* Update settings and refresh if required
*
* @param {Object} updates Object containing all updates you wish to
* make
* @param {Boolean} ignoreRefresh don't bother refreshing
* @return {Promise} completion promise
*/
updateSettings: (updates, ignoreRefresh) =>
updateSettings(updates).then(() => {
if (!ignoreRefresh) {
return refreshToGetNewSettings();
}
}),
/**
* Revert settings and refresh if required
*
* @param {Boolean} ignoreRefresh don't bother refreshing
* @return {Promise} completion promise
*/
revertSettings: ignoreRefresh =>
revertSettings().then(() => {
if (!ignoreRefresh) {
return refreshToGetNewSettings();
}
}),
seedTestData: (done, contactId, documents) => {
protractor.promise
.all(documents.map(module.exports.saveDoc))
.then(() => module.exports.getDoc(userSettingsDocId))
.then(user => {
user.contact_id = contactId;
return module.exports.saveDoc(user);
})
.then(done)
.catch(done.fail);
},
/**
* Cleans up DB after each test. Works with the given callback
* and also returns a promise - pick one!
*/
afterEach: done => {
return revertDb()
.then(() => {
if (done) {
done();
}
})
.catch(err => {
if (done) {
done.fail(err);
} else {
throw err;
}
});
},
//check for the update modal before
beforeEach: () => {
if (element(by.css('#update-available')).isPresent()) {
$('body').sendKeys(protractor.Key.ENTER);
}
},
/**
* Reverts the db's settings and documents
*
* @param {Array} except documents to ignore, see deleteAllDocs
* @param {Boolean} ignoreRefresh don't bother refreshing
* @return {Promise} promise
*/
revertDb: revertDb,
resetBrowser: () => {
browser.driver
.navigate()
.refresh()
.then(() => {
return browser.wait(() => {
return element(by.css('#messages-tab')).isPresent();
}, 10000);
});
},
countOf: count => {
return c => {
return c === count;
};
},
getCouchUrl: () =>
`http://${auth.user}:${auth.pass}@${constants.COUCH_HOST}:${
constants.COUCH_PORT
}/${constants.DB_NAME}`,
getBaseUrl: () =>
`http://${constants.API_HOST}:${constants.API_PORT}/${
constants.DB_NAME
}/_design/medic/_rewrite/#/`,
getAdminBaseUrl: () =>
`http://${constants.API_HOST}:${constants.API_PORT}/${
constants.DB_NAME
}/_design/medic-admin/_rewrite/#/`,
getLoginUrl: () =>
`http://${constants.API_HOST}:${constants.API_PORT}/${
constants.DB_NAME
}/login`,
// Deletes _users docs and medic/user-settings docs for specified users
// @param {Array} usernames - list of users to be deleted
// @return {Promise}
deleteUsers: deleteUsers,
};