-
Notifications
You must be signed in to change notification settings - Fork 112
/
Copy pathhttp.js
607 lines (543 loc) · 17 KB
/
http.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
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
/*!
* chai-http
* Copyright(c) 2011-2012 Jake Luer <jake@alogicalparadox.com>
* MIT Licensed
*/
/**
* ## Assertions
*
* The Chai HTTP module provides a number of assertions
* for the `expect` and `should` interfaces.
*/
module.exports = function (chai, _) {
/*!
* Module dependencies.
*/
var net = require('net');
var qs = require('qs');
var url = require('url');
var Cookie = require('cookiejar');
var charset = require("charset");
/*!
* Aliases.
*/
var Assertion = chai.Assertion
, flag = chai.util.flag
, transferFlags = chai.util.transferFlags
, i = _.inspect;
/*!
* Expose request builder
*/
chai.request = require('./request');
/*!
* Content types hash. Used to
* define `Assertion` properties.
*
* @type {Object}
*/
var contentTypes = {
json: 'application/json'
, text: 'text/plain'
, html: 'text/html'
};
/*!
* Return a header from `Request` or `Response` object.
*
* @param {Request|Response} object
* @param {String} Header
* @returns {String|Undefined}
*/
function getHeader(obj, key) {
if (key) key = key.toLowerCase();
if (obj.getHeader) return obj.getHeader(key);
if (obj.headers) return obj.headers[key];
};
/**
* ### .status (code)
*
* Assert that a response has a supplied status.
*
* ```js
* expect(res).to.have.status(200);
* ```
*
* @param {Number} status number
* @name status
* @api public
*/
Assertion.addMethod('status', function (code) {
var hasStatus = Boolean('status' in this._obj || 'statusCode' in this._obj);
new Assertion(hasStatus).assert(
hasStatus
, "expected #{act} to have keys 'status', or 'statusCode'"
, null // never negated
, hasStatus // expected
, this._obj // actual
, false // no diff
);
var status = this._obj.status || this._obj.statusCode;
this.assert(
status == code
, 'expected #{this} to have status code #{exp} but got #{act}'
, 'expected #{this} to not have status code #{act}'
, code
, status
);
});
/**
* ### .header (key[, value])
*
* Assert that a `Response` or `Request` object has a header.
* If a value is provided, equality to value will be asserted.
* You may also pass a regular expression to check.
*
* __Note:__ When running in a web browser, the
* [same-origin policy](https://tools.ietf.org/html/rfc6454#section-3)
* only allows Chai HTTP to read
* [certain headers](https://www.w3.org/TR/cors/#simple-response-header),
* which can cause assertions to fail.
*
* ```js
* expect(req).to.have.header('x-api-key');
* expect(req).to.have.header('content-type', 'text/plain');
* expect(req).to.have.header('content-type', /^text/);
* ```
*
* @param {String} header key (case insensitive)
* @param {String|RegExp} header value (optional)
* @name header
* @api public
*/
Assertion.addMethod('header', function (key, value) {
var header = getHeader(this._obj, key);
if (arguments.length < 2) {
this.assert(
'undefined' !== typeof header || null === header
, 'expected header \'' + key + '\' to exist'
, 'expected header \'' + key + '\' to not exist'
);
} else if (arguments[1] instanceof RegExp) {
this.assert(
value.test(header)
, 'expected header \'' + key + '\' to match ' + value + ' but got ' + i(header)
, 'expected header \'' + key + '\' not to match ' + value + ' but got ' + i(header)
, value
, header
);
} else {
this.assert(
header == value
, 'expected header \'' + key + '\' to have value ' + value + ' but got ' + i(header)
, 'expected header \'' + key + '\' to not have value ' + value
, value
, header
);
}
});
/**
* ### .headers
*
* Assert that a `Response` or `Request` object has headers.
*
* __Note:__ When running in a web browser, the
* [same-origin policy](https://tools.ietf.org/html/rfc6454#section-3)
* only allows Chai HTTP to read
* [certain headers](https://www.w3.org/TR/cors/#simple-response-header),
* which can cause assertions to fail.
*
* ```js
* expect(req).to.have.headers;
* ```
*
* @name headers
* @api public
*/
Assertion.addProperty('headers', function () {
this.assert(
this._obj.headers || this._obj.getHeader
, 'expected #{this} to have headers or getHeader method'
, 'expected #{this} to not have headers or getHeader method'
);
});
/**
* ### .ip
*
* Assert that a string represents valid ip address.
*
* ```js
* expect('127.0.0.1').to.be.an.ip;
* expect('2001:0db8:85a3:0000:0000:8a2e:0370:7334').to.be.an.ip;
* ```
*
* @name ip
* @api public
*/
Assertion.addProperty('ip', function () {
this.assert(
net.isIP(this._obj)
, 'expected #{this} to be an ip'
, 'expected #{this} to not be an ip'
);
});
/**
* ### .json / .text / .html
*
* Assert that a `Response` or `Request` object has a given content-type.
*
* ```js
* expect(req).to.be.json;
* expect(req).to.be.html;
* expect(req).to.be.text;
* ```
*
* @name json
* @name html
* @name text
* @api public
*/
function checkContentType (name) {
var val = contentTypes[name];
Assertion.addProperty(name, function () {
new Assertion(this._obj).to.have.headers;
var ct = getHeader(this._obj, 'content-type')
, ins = i(ct) === 'undefined'
? 'headers'
: i(ct);
this.assert(
ct && ~ct.indexOf(val)
, 'expected ' + ins + ' to include \'' + val + '\''
, 'expected ' + ins + ' to not include \'' + val + '\''
);
});
}
Object
.keys(contentTypes)
.forEach(checkContentType);
/**
* ### .charset
*
* Assert that a `Response` or `Request` object has a given charset.
*
* ```js
* expect(req).to.have.charset('utf-8');
* ```
*
* @name charset
* @api public
*/
Assertion.addMethod('charset', function (value) {
value = value.toLowerCase();
var headers = this._obj.headers;
var cs = charset(headers);
/*
* Fix charset() treating "utf8" as a special case
* See https://github.com/node-modules/charset/issues/12
*/
if (cs === "utf8") {
cs = "utf-8";
}
this.assert(
cs != null && value === cs
, 'expected content type to have ' + value + ' charset'
, 'expected content type to not have ' + value + ' charset'
)
});
/**
* ### .redirect
*
* Assert that a `Response` object has a redirect status code.
*
* ```js
* expect(res).to.redirect;
* ```
*
* @name redirect
* @api public
*/
Assertion.addProperty('redirect', function() {
var redirectCodes = [301, 302, 303, 307, 308]
, status = this._obj.status
, redirects = this._obj.redirects;
this.assert(
redirectCodes.indexOf(status) >= 0 || redirects && redirects.length
, "expected redirect with 30X status code but got " + status
, "expected not to redirect but got " + status + " status"
);
});
/**
* ### .redirectTo
*
* Assert that a `Response` object redirects to the supplied location.
*
* ```js
* expect(res).to.redirectTo('http://example.com');
* ```
*
* @param {String|RegExp} location url
* @name redirectTo
* @api public
*/
Assertion.addMethod('redirectTo', function(destination) {
var redirects = this._obj.redirects;
new Assertion(this._obj).to.redirect;
if(redirects && redirects.length) {
var hasRedirected;
if (Object.prototype.toString.call(destination) === '[object RegExp]') {
hasRedirected = redirects.some(redirect => destination.test(redirect));
} else {
hasRedirected = redirects.indexOf(destination) > -1;
}
this.assert(
hasRedirected
, 'expected redirect to ' + destination + ' but got ' + redirects.join(' then ')
, 'expected not to redirect to ' + destination + ' but got ' + redirects.join(' then ')
);
} else {
var assertion = new Assertion(this._obj);
_.transferFlags(this, assertion);
assertion.with.header('location', destination);
}
});
/**
* ### .param
*
* Assert that a `Request` object has a query string parameter with a given
* key, (optionally) equal to value
*
* ```js
* expect(req).to.have.param('orderby');
* expect(req).to.have.param('orderby', 'date');
* expect(req).to.not.have.param('limit');
* ```
*
* @param {String} parameter name
* @param {String} parameter value
* @name param
* @api public
*/
Assertion.addMethod('param', function(name, value) {
var assertion = new Assertion();
_.transferFlags(this, assertion);
assertion._obj = qs.parse(url.parse(this._obj.url).query);
assertion.property.apply(assertion, arguments);
});
/**
* ### .cookie
*
* Assert that a `Request`, `Response` or `Agent` object has a cookie header
* with a given key. Optionally, the value and attributes of the cookie can
* also be checked. Usually, asserting cookie attributes only makes sense
* when in the context of the `Response` object. Attribute key comparison is
* case insensitive.
*
* This assertion changes the context of the assertion to the cookie itself
* in order to allow chaining with cookie specific assertions (see below).
*
* ```js
* expect(req).to.have.cookie('session_id');
* expect(req).to.have.cookie('session_id', '1234');
* expect(req).to.not.have.cookie('PHPSESSID');
*
* expect(res).to.have.cookie('session_id');
* expect(res).to.have.cookie('session_id', '1234');
* expect(res).to.have.cookie('session_id', '1234', {
* 'Path': '/',
* 'Domain': '.abc.xyz'
* });
* expect(res).to.not.have.cookie('PHPSESSID');
*
* expect(agent).to.have.cookie('session_id');
* expect(agent).to.have.cookie('session_id', '1234');
* expect(agent).to.not.have.cookie('PHPSESSID');
* ```
*
* @param {String} parameter key
* @param {String} parameter value
* @param {Object} parameter attributes
* @name param
* @api public
*/
Assertion.addMethod('cookie', function (key, value, attributes) {
var header = getHeader(this._obj, 'set-cookie')
, cookie;
if (!header) {
header = (getHeader(this._obj, 'cookie') || '').split(';');
}
if (this._obj instanceof chai.request.agent && this._obj.jar) {
cookie = this._obj.jar.getCookie(key, Cookie.CookieAccessInfo.All);
} else {
cookie = Cookie.CookieJar();
cookie.setCookies(header);
cookie = cookie.getCookie(key, Cookie.CookieAccessInfo.All);
}
// Unfortunatelly, we can't fully rely on the Cookie object retrieved
// above, as the library doesn't have support to some cookie attributes,
// like the `Max-Age`. Also, it uses some defaults, which are totally
// fine, but would affect the assertions and potentially give false
// positives (Path=/, for example, would pass the assertion, even if not
// set in the original cookie).
// For these reasons, we collect the raw cookie to parse it manually.
var rawCookie = '';
header.forEach(function(cookieHeader) {
if (cookieHeader.startsWith(key + '=')) {
rawCookie = cookieHeader;
}
});
// If the above failed, we use this string representation of Cookie as a
// fallback. It's better than nothing...
if (!rawCookie && cookie instanceof Cookie.Cookie) {
rawCookie = cookie.toString();
}
// First check: cookie existence
var cookieExists = 'undefined' !== typeof cookie || null === cookie;
// Second check: cookie value correctness
var isValueCorrect = true;
if (arguments.length >= 2) {
isValueCorrect = cookieExists && cookie.value == value;
}
// Third check: all the cookie attributes should match
var areAttributesCorrect = isValueCorrect;
if (arguments.length >= 3 && 'object' === typeof attributes) {
// null can still be an object...
Object.keys(attributes || {}).forEach(function(attr) {
var expected = attributes[attr];
var actual = getCookieAttribute(rawCookie, attr);
areAttributesCorrect = areAttributesCorrect && actual === expected;
});
}
if (arguments.length === 3) {
this.assert(
areAttributesCorrect
, "expected cookie '" + key + "' to have the following attributes:"
, "expected cookie '" + key + "' to not have the following attributes:"
, prepareAttributesOutput(attributes, key, value)
, rawCookieToObj(rawCookie)
, true
);
} else if (arguments.length === 2) {
this.assert(
isValueCorrect
, 'expected cookie \'' + key + '\' to have value #{exp} but got #{act}'
, 'expected cookie \'' + key + '\' to not have value #{exp}'
, value
, cookie.value
);
} else {
this.assert(
cookieExists
, 'expected cookie \'' + key + '\' to exist'
, 'expected cookie \'' + key + '\' to not exist'
);
}
// Change the assertion context to the cookie itself,
// in order to make chaining possible
var cookieCtx = new Assertion();
transferFlags(this, cookieCtx);
flag(cookieCtx, 'object', cookie);
flag(cookieCtx, 'rawCookie', rawCookie);
flag(cookieCtx, 'key', key);
return cookieCtx;
});
/**
* ### .attribute
*
* Assert existence or value of a cookie attribute. It requires to be
* chained after previous assertion about cookie existence or key/value.
*
* As this method doesn't change the assertion context, it can be chained
* multiple times.
*
* This method is created using `overwriteMethod` in order to avoid
* conflicts with other chai libraries potentially implementing custom
* assertions with the name "attribute". Of course, the other library
* would have to do the same, but here we are doing our part :)
*
* ```js
* expect(res).to.have.cookie('session_id')
* .with.attribute('Path', '/foo');
*
* expect(res).to.have.cookie('session_id')
* .with.attribute('Path', '/foo')
* .and.with.attribute('Domain', '.abc.xyz');
*
* expect(res).to.have.cookie('session_id', '123')
* .with.attribute('HttpOnly');
*
* expect(res).to.have.cookie('session_id')
* .but.not.with.attribute('HttpOnly');
* ```
*
* @param {String} attr
* @param {String} [expected=true]
* @api public
*/
Assertion.overwriteMethod('attribute', function (_super) {
return function(attr, expected) {
if (this._obj instanceof Cookie.Cookie) {
var cookie = this._obj;
var key = flag(this, 'key');
var rawCookie = flag(this, 'rawCookie');
var actual = getCookieAttribute(rawCookie, attr);
// If only one argument was passed, we are checking
// for a boolean attribute
if (arguments.length === 1) expected = true;
this.assert(
actual === expected
, "cookie '" + key + "' expected #{exp} but got #{act}"
, "cookie '" + key + "' expected attribute to not be #{exp}"
, attr + '=' + expected
, attr + '=' + actual
);
} else {
_super.apply(this, arguments);
}
}
});
function getCookieAttribute(rawCookie, attr) {
// Try to capture attribute with value
var pattern = new RegExp('(?<=^|;) ?' + attr + '=([^;]+)(?:;|$)', 'i');
var matches = rawCookie.match(pattern);
if (matches) return matches[1];
// If it didn't match the previous line, it can still be a boolean
pattern = new RegExp('(?<=^|;) ?' + attr + '(?:;|$)', 'i');
matches = rawCookie.match(pattern);
if (matches) return true;
return false;
}
/**
* Prepares the raw cookie for the assertion failure output. All the keys
* will be converted to lowercase, with exception of the cookie key. The
* values won't pass through any conversion.
*
* @param {String} rawCookie
*/
function rawCookieToObj(rawCookie) {
var obj = {};
rawCookie.split(';').forEach(function(pair, index) {
var entry = pair.trim().split('=');
// We shouldn't convert the case of the first key (the cookie key)
var key = index === 0 ? entry[0] : entry[0].toLowerCase();
obj[key] = entry[1] ? entry[1] : true;
});
return obj;
}
/**
* This function prepares the "attributes" object (passed as an argument
* to .cookie(...)) for the assertion failure output. All keys are converted
* to lowercase and the cookie key/value is added to the output (without
* case convertion) in order to make inspection of the failure easier.
*
* @param {Object} attributes
* @param {String} key - the cookie key
* @param {String} value - the expected cookie value
* @api private
*/
function prepareAttributesOutput(obj, key, value) {
var newObj = {};
newObj[key] = value;
Object.keys(obj).forEach(function(key) {
newObj[key.toLowerCase()] = obj[key];
});
return newObj;
}
};