doc: improvements to console.markdown copy
[platform/upstream/nodejs.git] / lib / assert.js
1 // http://wiki.commonjs.org/wiki/Unit_Testing/1.0
2 //
3 // THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8!
4 //
5 // Originally from narwhal.js (http://narwhaljs.org)
6 // Copyright (c) 2009 Thomas Robinson <280north.com>
7 //
8 // Permission is hereby granted, free of charge, to any person obtaining a copy
9 // of this software and associated documentation files (the 'Software'), to
10 // deal in the Software without restriction, including without limitation the
11 // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
12 // sell copies of the Software, and to permit persons to whom the Software is
13 // furnished to do so, subject to the following conditions:
14 //
15 // The above copyright notice and this permission notice shall be included in
16 // all copies or substantial portions of the Software.
17 //
18 // THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21 // AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
22 // ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
23 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
24
25 'use strict';
26
27 // UTILITY
28 const compare = process.binding('buffer').compare;
29 const util = require('util');
30 const Buffer = require('buffer').Buffer;
31 const pSlice = Array.prototype.slice;
32
33 // 1. The assert module provides functions that throw
34 // AssertionError's when particular conditions are not met. The
35 // assert module must conform to the following interface.
36
37 const assert = module.exports = ok;
38
39 // 2. The AssertionError is defined in assert.
40 // new assert.AssertionError({ message: message,
41 //                             actual: actual,
42 //                             expected: expected })
43
44 assert.AssertionError = function AssertionError(options) {
45   this.name = 'AssertionError';
46   this.actual = options.actual;
47   this.expected = options.expected;
48   this.operator = options.operator;
49   if (options.message) {
50     this.message = options.message;
51     this.generatedMessage = false;
52   } else {
53     this.message = getMessage(this);
54     this.generatedMessage = true;
55   }
56   var stackStartFunction = options.stackStartFunction || fail;
57   Error.captureStackTrace(this, stackStartFunction);
58 };
59
60 // assert.AssertionError instanceof Error
61 util.inherits(assert.AssertionError, Error);
62
63 function truncate(s, n) {
64   if (typeof s === 'string') {
65     return s.length < n ? s : s.slice(0, n);
66   } else {
67     return s;
68   }
69 }
70
71 function getMessage(self) {
72   return truncate(util.inspect(self.actual), 128) + ' ' +
73          self.operator + ' ' +
74          truncate(util.inspect(self.expected), 128);
75 }
76
77 // At present only the three keys mentioned above are used and
78 // understood by the spec. Implementations or sub modules can pass
79 // other keys to the AssertionError's constructor - they will be
80 // ignored.
81
82 // 3. All of the following functions must throw an AssertionError
83 // when a corresponding condition is not met, with a message that
84 // may be undefined if not provided.  All assertion methods provide
85 // both the actual and expected values to the assertion error for
86 // display purposes.
87
88 function fail(actual, expected, message, operator, stackStartFunction) {
89   throw new assert.AssertionError({
90     message: message,
91     actual: actual,
92     expected: expected,
93     operator: operator,
94     stackStartFunction: stackStartFunction
95   });
96 }
97
98 // EXTENSION! allows for well behaved errors defined elsewhere.
99 assert.fail = fail;
100
101 // 4. Pure assertion tests whether a value is truthy, as determined
102 // by !!guard.
103 // assert.ok(guard, message_opt);
104 // This statement is equivalent to assert.equal(true, !!guard,
105 // message_opt);. To test strictly for the value true, use
106 // assert.strictEqual(true, guard, message_opt);.
107
108 function ok(value, message) {
109   if (!value) fail(value, true, message, '==', assert.ok);
110 }
111 assert.ok = ok;
112
113 // 5. The equality assertion tests shallow, coercive equality with
114 // ==.
115 // assert.equal(actual, expected, message_opt);
116
117 assert.equal = function equal(actual, expected, message) {
118   if (actual != expected) fail(actual, expected, message, '==', assert.equal);
119 };
120
121 // 6. The non-equality assertion tests for whether two objects are not equal
122 // with != assert.notEqual(actual, expected, message_opt);
123
124 assert.notEqual = function notEqual(actual, expected, message) {
125   if (actual == expected) {
126     fail(actual, expected, message, '!=', assert.notEqual);
127   }
128 };
129
130 // 7. The equivalence assertion tests a deep equality relation.
131 // assert.deepEqual(actual, expected, message_opt);
132
133 assert.deepEqual = function deepEqual(actual, expected, message) {
134   if (!_deepEqual(actual, expected, false)) {
135     fail(actual, expected, message, 'deepEqual', assert.deepEqual);
136   }
137 };
138
139 assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) {
140   if (!_deepEqual(actual, expected, true)) {
141     fail(actual, expected, message, 'deepStrictEqual', assert.deepStrictEqual);
142   }
143 };
144
145 function _deepEqual(actual, expected, strict) {
146   // 7.1. All identical values are equivalent, as determined by ===.
147   if (actual === expected) {
148     return true;
149   } else if (actual instanceof Buffer && expected instanceof Buffer) {
150     return compare(actual, expected) === 0;
151
152   // 7.2. If the expected value is a Date object, the actual value is
153   // equivalent if it is also a Date object that refers to the same time.
154   } else if (util.isDate(actual) && util.isDate(expected)) {
155     return actual.getTime() === expected.getTime();
156
157   // 7.3 If the expected value is a RegExp object, the actual value is
158   // equivalent if it is also a RegExp object with the same source and
159   // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`).
160   } else if (util.isRegExp(actual) && util.isRegExp(expected)) {
161     return actual.source === expected.source &&
162            actual.global === expected.global &&
163            actual.multiline === expected.multiline &&
164            actual.lastIndex === expected.lastIndex &&
165            actual.ignoreCase === expected.ignoreCase;
166
167   // 7.4. Other pairs that do not both pass typeof value == 'object',
168   // equivalence is determined by ==.
169   } else if ((actual === null || typeof actual !== 'object') &&
170              (expected === null || typeof expected !== 'object')) {
171     return strict ? actual === expected : actual == expected;
172
173   // 7.5 For all other Object pairs, including Array objects, equivalence is
174   // determined by having the same number of owned properties (as verified
175   // with Object.prototype.hasOwnProperty.call), the same set of keys
176   // (although not necessarily the same order), equivalent values for every
177   // corresponding key, and an identical 'prototype' property. Note: this
178   // accounts for both named and indexed properties on Arrays.
179   } else {
180     return objEquiv(actual, expected, strict);
181   }
182 }
183
184 function isArguments(object) {
185   return Object.prototype.toString.call(object) == '[object Arguments]';
186 }
187
188 function objEquiv(a, b, strict) {
189   if (a === null || a === undefined || b === null || b === undefined)
190     return false;
191   // if one is a primitive, the other must be same
192   if (util.isPrimitive(a) || util.isPrimitive(b))
193     return a === b;
194   if (strict && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b))
195     return false;
196   var aIsArgs = isArguments(a),
197       bIsArgs = isArguments(b);
198   if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs))
199     return false;
200   if (aIsArgs) {
201     a = pSlice.call(a);
202     b = pSlice.call(b);
203     return _deepEqual(a, b, strict);
204   }
205   var ka = Object.keys(a),
206       kb = Object.keys(b),
207       key, i;
208   // having the same number of owned properties (keys incorporates
209   // hasOwnProperty)
210   if (ka.length !== kb.length)
211     return false;
212   //the same set of keys (although not necessarily the same order),
213   ka.sort();
214   kb.sort();
215   //~~~cheap key test
216   for (i = ka.length - 1; i >= 0; i--) {
217     if (ka[i] !== kb[i])
218       return false;
219   }
220   //equivalent values for every corresponding key, and
221   //~~~possibly expensive deep test
222   for (i = ka.length - 1; i >= 0; i--) {
223     key = ka[i];
224     if (!_deepEqual(a[key], b[key], strict)) return false;
225   }
226   return true;
227 }
228
229 // 8. The non-equivalence assertion tests for any deep inequality.
230 // assert.notDeepEqual(actual, expected, message_opt);
231
232 assert.notDeepEqual = function notDeepEqual(actual, expected, message) {
233   if (_deepEqual(actual, expected, false)) {
234     fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual);
235   }
236 };
237
238 assert.notDeepStrictEqual = notDeepStrictEqual;
239 function notDeepStrictEqual(actual, expected, message) {
240   if (_deepEqual(actual, expected, true)) {
241     fail(actual, expected, message, 'notDeepStrictEqual', notDeepStrictEqual);
242   }
243 }
244
245
246 // 9. The strict equality assertion tests strict equality, as determined by ===.
247 // assert.strictEqual(actual, expected, message_opt);
248
249 assert.strictEqual = function strictEqual(actual, expected, message) {
250   if (actual !== expected) {
251     fail(actual, expected, message, '===', assert.strictEqual);
252   }
253 };
254
255 // 10. The strict non-equality assertion tests for strict inequality, as
256 // determined by !==.  assert.notStrictEqual(actual, expected, message_opt);
257
258 assert.notStrictEqual = function notStrictEqual(actual, expected, message) {
259   if (actual === expected) {
260     fail(actual, expected, message, '!==', assert.notStrictEqual);
261   }
262 };
263
264 function expectedException(actual, expected) {
265   if (!actual || !expected) {
266     return false;
267   }
268
269   if (Object.prototype.toString.call(expected) == '[object RegExp]') {
270     return expected.test(actual);
271   }
272
273   try {
274     if (actual instanceof expected) {
275       return true;
276     }
277   } catch (e) {
278     // Ignore.  The instanceof check doesn't work for arrow functions.
279   }
280
281   return expected.call({}, actual) === true;
282 }
283
284 function _throws(shouldThrow, block, expected, message) {
285   var actual;
286
287   if (typeof block !== 'function') {
288     throw new TypeError('block must be a function');
289   }
290
291   if (typeof expected === 'string') {
292     message = expected;
293     expected = null;
294   }
295
296   try {
297     block();
298   } catch (e) {
299     actual = e;
300   }
301
302   message = (expected && expected.name ? ' (' + expected.name + ').' : '.') +
303             (message ? ' ' + message : '.');
304
305   if (shouldThrow && !actual) {
306     fail(actual, expected, 'Missing expected exception' + message);
307   }
308
309   if (!shouldThrow && expectedException(actual, expected)) {
310     fail(actual, expected, 'Got unwanted exception' + message);
311   }
312
313   if ((shouldThrow && actual && expected &&
314       !expectedException(actual, expected)) || (!shouldThrow && actual)) {
315     throw actual;
316   }
317 }
318
319 // 11. Expected to throw an error:
320 // assert.throws(block, Error_opt, message_opt);
321
322 assert.throws = function(block, /*optional*/error, /*optional*/message) {
323   _throws.apply(this, [true].concat(pSlice.call(arguments)));
324 };
325
326 // EXTENSION! This is annoying to write outside this module.
327 assert.doesNotThrow = function(block, /*optional*/message) {
328   _throws.apply(this, [false].concat(pSlice.call(arguments)));
329 };
330
331 assert.ifError = function(err) { if (err) throw err; };