-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
306 lines (286 loc) · 8.13 KB
/
index.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
const requireg = require('requireg');
const mockttp = require('@kronoslive/mockttp');
const { cropLongData } = require('@kronoslive/codeceptjs-utils');
const path = require('path');
const codeceptjsPath = path.resolve(global.codecept_dir, './node_modules/codeceptjs');
// eslint-disable-next-line import/no-dynamic-require
const { recorder } = require(codeceptjsPath);
let mochawesome;
let utils;
/**
* Helper to manage mockttp
*/
class HTTPMock extends Helper {
/**
*
* @param {object} config
*/
constructor(config) {
super(config);
this._validateConfig(config);
}
/**
*
* @param {object} config
* @private
*/
_validateConfig(config) {
this.options = {
port: 9037,
debug: false,
};
this.isRunning = false;
this.requests = {
get: {},
post: {},
put: {},
delete: {},
patch: {},
options: {},
};
Object.assign(this.options, config);
}
/* eslint-disable consistent-return */
/**
*
* @returns {string[]}
* @private
*/
static _checkRequirements() {
try {
requireg('@kronoslive/mockttp');
} catch (e) {
return ['@kronoslive/mockttp'];
}
}
/* eslint-enable consistent-return */
/**
*
* @returns {boolean}
* @private
*/
_beforeSuite() {
mochawesome = this.helpers.Mochawesome;
utils = this.helpers.Utils;
if (!this.isRunning) {
this.server = mockttp.getLocal();
this.server.debug = this.options.debug;
this.server.start(this.options.port);
this.isRunning = true;
}
return true;
}
/**
* Set up mock for method и urlPath. Response calculates in callback function.
* @param {string} method
* @param {string} urlPath
* @param {function} callback
* @param {object} ctx
*/
async respondWith(method, urlPath, callback = () => {}, ctx = {}) {
method = method.toLowerCase();
urlPath = urlPath.charAt(urlPath.length - 1) === '/'
? urlPath.substring(0, urlPath.length - 1)
: urlPath;
const callbackWithLog = async (req) => {
const reqWithoutBuff = req;
delete reqWithoutBuff.body.buffer;
await mochawesome.addMochawesomeContext({
title: 'Received HTTP request for mock',
value: reqWithoutBuff,
});
const res = await callback(req);
return res;
};
let endpointMock;
try {
switch (method) {
case 'get':
endpointMock = await this.server
.get(urlPath, ctx)
.thenCallback(callbackWithLog);
this.requests.get[urlPath] = endpointMock;
break;
case 'post':
endpointMock = await this.server
.post(urlPath, ctx)
.thenCallback(callbackWithLog);
this.requests.post[urlPath] = endpointMock;
break;
case 'put':
endpointMock = await this.server
.put(urlPath, ctx)
.thenCallback(callbackWithLog);
this.requests.put[urlPath] = endpointMock;
break;
case 'delete':
endpointMock = await this.server
.delete(urlPath, ctx)
.thenCallback(callbackWithLog);
this.requests.delete[urlPath] = endpointMock;
break;
case 'patch':
endpointMock = await this.server
.patch(urlPath, ctx)
.thenCallback(callbackWithLog);
this.requests.patch[urlPath] = endpointMock;
break;
case 'options':
endpointMock = await this.server
.options(urlPath, ctx)
.thenCallback(callbackWithLog);
this.requests.options[urlPath] = endpointMock;
break;
default:
throw new Error('unknown type of method');
}
} catch (err) {
recorder.catch(() => {
throw err;
});
}
}
/**
* Validates that request comes for method and urlpath that satisfies predicate function
* @param {string} method
* @param {string} urlPath
* @param {function} predicate
* @param {number} timeout
*/
async expectRequestUntil(method, urlPath, predicate = msg => msg, timeout) {
method = method.toLowerCase();
urlPath = urlPath.charAt(urlPath.length - 1) === '/'
? urlPath.substring(0, urlPath.length - 1)
: urlPath;
if (this.requests[method][urlPath] === undefined) {
throw new Error(`We should create mock for method ${method} and url ${urlPath} before expecting something!`);
}
const seen = {};
let predicateErr;
try {
await utils.waitUntil(
async () => Promise.resolve((
(await this.requests[method][urlPath].getSeenRequests()) || []
).find((msg, i) => {
try {
if (!seen[i]) {
seen[i] = true;
return predicate(msg);
}
return false;
} catch (err) {
predicateErr = err;
return true;
}
})),
timeout,
'timeout',
100,
);
if (predicateErr) {
throw new Error(`predicate return err (${
predicateErr.code
}), but it should return boolean value`);
}
const messages = await this.requests[method][urlPath].getSeenRequests();
mochawesome.addMochawesomeContext({
title: `Wait request with predicate for method ${method} and url ${urlPath}`,
value: predicate.toString(),
});
const reqWithoutBuff = messages[messages.length - 1];
delete reqWithoutBuff.body.buffer;
mochawesome.addMochawesomeContext({
title: 'Latest request',
value: cropLongData(reqWithoutBuff),
});
} catch (err) {
const messages = await this.requests[method][urlPath].getSeenRequests();
mochawesome.addMochawesomeContext({
title: `Wait request with predicate for method ${method} and url ${urlPath}`,
value: predicate.toString(),
});
const reqWithoutBuff = messages[messages.length - 1];
delete reqWithoutBuff.body.buffer;
mochawesome.addMochawesomeContext({
title: 'Latest request',
value: cropLongData(reqWithoutBuff),
});
if (err.message === 'timeout') {
throw new Error(`http mock timeout while expecting request with method ${method} and url ${urlPath} with ${predicate}`);
} else throw err;
}
}
/**
* Validates that no request comes for method and urlpath that satisfies predicate function
* @param {string} method
* @param {string} urlPath
* @param {function} predicate
* @param {number} timeout
* @returns {Promise<void>}
*/
dontExpectRequestUntil(method, urlPath, predicate, timeout) {
method = method.toLowerCase();
urlPath = urlPath.charAt(urlPath.length - 1) === '/'
? urlPath.substring(0, urlPath.length - 1)
: urlPath;
if (this.requests[method][urlPath] === undefined) {
throw new Error(`We should create mock for method ${method} and url ${urlPath} before expecting something!`);
}
return new Promise((resolve, reject) => {
setTimeout(async () => {
const found = (
(await this.requests[method][urlPath].getSeenRequests()) || []
).find(x => predicate(x));
if (found === undefined) {
resolve();
} else {
reject(new Error(`Found some not expected: ${JSON.stringify(found)}`));
}
}, timeout);
});
}
/**
* Get requests that comes to mock server by method and urlPath
* @param {string} method
* @param {string} urlPath
* @returns {Promise<void>}
*/
grabServerRequests(method, urlPath) {
method = method.toLowerCase();
urlPath = urlPath.charAt(urlPath.length - 1) === '/'
? urlPath.substring(0, urlPath.length - 1)
: urlPath;
return this.requests[method][urlPath].getSeenRequests();
}
/**
*
* @private
* @returns {Promise<void>}
*/
_after() {
this.requests = {
get: {},
post: {},
put: {},
delete: {},
patch: {},
options: {},
};
if (!this.isRunning) {
return true;
}
return this.server.reset();
}
/**
*
* @returns {Promise<void>}
* @private
*/
_finishTest() {
if (!this.isRunning) {
return true;
}
return this.server.stop();
}
}
module.exports = HTTPMock;