Repository navigation
Expand file tree
/
Copy pathscope.js
More file actions
326 lines (270 loc) · 8.87 KB
/
Copy pathscope.js
File metadata and controls
326 lines (270 loc) · 8.87 KB
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
var path = require('path')
, fs = require('fs')
, globalIntercept = require('./intercept')
, mixin = require('./mixin')
, assert = require('assert')
, url = require('url');
var noop = function() {};
function isStream(obj) {
return (typeof obj !== 'undefined') && (typeof a !== 'string') && (! Buffer.isBuffer(obj)) && (typeof obj.setEncoding == 'function');
}
function startScope(basePath, options) {
var interceptors = {},
scope,
transformPathFunction,
transformRequestBodyFunction,
matchHeaders = [],
logger = noop,
scopeOptions = options || {},
urlParts = url.parse(basePath),
port = urlParts.port || ((urlParts.protocol === 'http:') ? 80 : 443);
basePath = urlParts.protocol + '//' + urlParts.hostname + ':' + port;
function add(key, interceptor) {
if (! interceptors.hasOwnProperty(key)) {
interceptors[key] = [];
}
interceptors[key].push(interceptor);
globalIntercept(basePath, interceptor);
}
function remove(key, interceptor) {
var arr = interceptors[key];
if (arr) {
arr.splice(arr.indexOf(interceptor), 1);
if (arr.length === 0) { delete interceptors[key]; }
}
}
function intercept(uri, method, requestBody, interceptorOptions) {
var interceptorMatchHeaders = [];
var key = method.toUpperCase() + ' ' + basePath + uri;
if (typeof(requestBody) != 'undefined' && typeof(requestBody) !== 'string') {
try {
requestBody = JSON.stringify(requestBody);
} catch(err) {
throw new Error('Error encoding request body into JSON');
}
}
if (requestBody) { key += (' ' + requestBody); }
function reply(statusCode, body, headers) {
this.statusCode = statusCode;
this.options = interceptorOptions || {};
for(var opt in scopeOptions) {
if(typeof this.options[opt] === 'undefined') {
this.options[opt] = scopeOptions[opt];
}
}
if (typeof(body) !== 'string' && typeof(body) !== 'function' && !Buffer.isBuffer(body) && !isStream(body)) {
try {
body = JSON.stringify(body);
} catch(err) {
throw new Error('Error encoding response body into JSON');
}
}
if (scope._defaultReplyHeaders) {
headers || (headers = {});
headers = mixin(scope._defaultReplyHeaders, headers);
}
if (headers !== undefined) {
this.headers = {};
// makes sure all keys in headers are in lower case
for (var key2 in headers) {
if (headers.hasOwnProperty(key2)) {
this.headers[key2.toLowerCase()] = headers[key2];
}
}
}
this.body = body;
add(key, this);
return scope;
}
function replyWithFile(statusCode, filePath, headers) {
var readStream = fs.createReadStream(filePath);
readStream.pause();
return reply.call(this, statusCode, readStream, headers);
}
function match(options, body) {
var method = options.method || 'GET'
, path = options.path
, matches
, proto = options.proto;
if (transformPathFunction) { path = transformPathFunction(path); }
if (typeof(body) !== 'string') {
body = body.toString();
}
if (transformRequestBodyFunction) { body = transformRequestBodyFunction(body); }
var checkHeaders = function(header) {
return options.getHeader(header.name) === header.value;
};
if (!matchHeaders.every(checkHeaders) ||
!interceptorMatchHeaders.every(checkHeaders)) {
return false;
}
var matchKey = method.toUpperCase() + ' ' + proto + '://' + options.host;
if (
options.port && options.host.indexOf(':') < 0 &&
(options.port !== 80 || options.proto !== 'http') &&
(options.port !== 443 || options.proto !== 'https')
) {
matchKey += ":" + options.port;
}
matchKey += path;
if (body) { matchKey += (' ' + body); }
matches = matchKey === this._key;
logger('matching ' + matchKey + ' to ' + this._key + ': ' + matches);
return matches;
}
function matchIndependentOfBody(options) {
var method = options.method || 'GET'
, path = options.path
, matches
, proto = options.proto;
if (transformPathFunction) { path = transformPathFunction(path); }
var checkHeaders = function(header) {
return options.getHeader && options.getHeader(header.name) === header.value;
};
if (!matchHeaders.every(checkHeaders) ||
!interceptorMatchHeaders.every(checkHeaders)) {
return false;
}
var matchKey = method + ' ' + proto + '://' + options.host + path;
return this._key === matchKey
}
function filteringPath() {
if (typeof arguments[0] === 'function') {
this.transformFunction = arguments[0];
}
return this;
}
function discard() {
remove(this._key, this);
}
function matchHeader(name, value) {
interceptorMatchHeaders.push({ name: name, value: value });
return this;
}
var interceptor = {
_key: key
, reply: reply
, replyWithFile: replyWithFile
, discard: discard
, match: match
, matchIndependentOfBody: matchIndependentOfBody
, filteringPath: filteringPath
, matchHeader: matchHeader
};
return interceptor;
}
function get(uri, requestBody, options) {
return intercept(uri, 'GET', requestBody, options);
}
function post(uri, requestBody, options) {
return intercept(uri, 'POST', requestBody, options);
}
function put(uri, requestBody, options) {
return intercept(uri, 'PUT', requestBody, options);
}
function head(uri, requestBody, options) {
return intercept(uri, 'HEAD', requestBody, options);
}
function _delete(uri, requestBody, options) {
return intercept(uri, 'DELETE', requestBody, options);
}
function pendingMocks() {
return Object.keys(interceptors);
}
function isDone() {
// if nock is turned off, it always says it's done
if (! globalIntercept.isOn()) { return true; }
var keys = Object.keys(interceptors);
if (keys.length === 0) {
return true;
} else {
var doneHostCount = 0;
keys.forEach(function(key) {
var doneInterceptorCount = 0;
interceptors[key].forEach(function(interceptor) {
var isDefined = (typeof interceptor.options.requireDone !== 'undefined');
if (isDefined && interceptor.options.requireDone === false) {
doneInterceptorCount += 1;
}
});
if( doneInterceptorCount === interceptors[key].length ) {
doneHostCount += 1;
}
});
return (doneHostCount === keys.length);
}
}
function done() {
assert.ok(isDone(), "Mocks not yet satisfied:\n" + pendingMocks().join("\n"));
}
function filteringPath() {
var filteringArguments = arguments;
if (arguments[0] instanceof RegExp) {
transformPathFunction = function(path) {
if (path) {
path = path.replace(filteringArguments[0], filteringArguments[1]);
}
return path;
}
} else {
if (typeof (arguments[0]) === 'function') {
transformPathFunction = arguments[0];
} else {
throw new Error('Invalid arguments: filtering path should be a function or a regular expression');
}
}
return this;
}
function filteringRequestBody() {
var filteringArguments = arguments;
if (arguments[0] instanceof RegExp) {
transformRequestBodyFunction = function(path) {
if (path) {
path = path.replace(filteringArguments[0], filteringArguments[1]);
}
return path;
}
} else {
if (typeof (arguments[0]) === 'function') {
transformRequestBodyFunction = arguments[0];
} else {
throw new Error('Invalid arguments: filtering request body should be a function or a regular expression');
}
}
return this;
}
function matchHeader(name, value) {
matchHeaders.push({ name: name, value: value });
return this;
}
function defaultReplyHeaders(headers) {
this._defaultReplyHeaders = headers;
return this;
}
function log(newLogger) {
logger = newLogger;
return this;
}
scope = {
get: get
, post: post
, delete: _delete
, put: put
, head: head
, intercept: intercept
, done: done
, isDone: isDone
, filteringPath: filteringPath
, filteringRequestBody: filteringRequestBody
, matchHeader: matchHeader
, defaultReplyHeaders: defaultReplyHeaders
, log: log
};
return scope;
}
function cleanAll() {
globalIntercept.removeAll();
return module.exports;
}
module.exports = startScope;
module.exports.cleanAll = cleanAll;