Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
80713 views
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
// when used in node, this will actually load the util module we depend on
26
// versus loading the builtin util module as happens otherwise
27
// this is a bug in node module loading as far as I am concerned
28
var util = require('util/');
29
30
var pSlice = Array.prototype.slice;
31
var hasOwn = Object.prototype.hasOwnProperty;
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
var 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
58
if (Error.captureStackTrace) {
59
Error.captureStackTrace(this, stackStartFunction);
60
}
61
else {
62
// non v8 browsers so we can have a stacktrace
63
var err = new Error();
64
if (err.stack) {
65
var out = err.stack;
66
67
// try to strip useless frames
68
var fn_name = stackStartFunction.name;
69
var idx = out.indexOf('\n' + fn_name);
70
if (idx >= 0) {
71
// once we have located the function frame
72
// we need to strip out everything before it (and its line)
73
var next_line = out.indexOf('\n', idx + 1);
74
out = out.substring(next_line + 1);
75
}
76
77
this.stack = out;
78
}
79
}
80
};
81
82
// assert.AssertionError instanceof Error
83
util.inherits(assert.AssertionError, Error);
84
85
function replacer(key, value) {
86
if (util.isUndefined(value)) {
87
return '' + value;
88
}
89
if (util.isNumber(value) && (isNaN(value) || !isFinite(value))) {
90
return value.toString();
91
}
92
if (util.isFunction(value) || util.isRegExp(value)) {
93
return value.toString();
94
}
95
return value;
96
}
97
98
function truncate(s, n) {
99
if (util.isString(s)) {
100
return s.length < n ? s : s.slice(0, n);
101
} else {
102
return s;
103
}
104
}
105
106
function getMessage(self) {
107
return truncate(JSON.stringify(self.actual, replacer), 128) + ' ' +
108
self.operator + ' ' +
109
truncate(JSON.stringify(self.expected, replacer), 128);
110
}
111
112
// At present only the three keys mentioned above are used and
113
// understood by the spec. Implementations or sub modules can pass
114
// other keys to the AssertionError's constructor - they will be
115
// ignored.
116
117
// 3. All of the following functions must throw an AssertionError
118
// when a corresponding condition is not met, with a message that
119
// may be undefined if not provided. All assertion methods provide
120
// both the actual and expected values to the assertion error for
121
// display purposes.
122
123
function fail(actual, expected, message, operator, stackStartFunction) {
124
throw new assert.AssertionError({
125
message: message,
126
actual: actual,
127
expected: expected,
128
operator: operator,
129
stackStartFunction: stackStartFunction
130
});
131
}
132
133
// EXTENSION! allows for well behaved errors defined elsewhere.
134
assert.fail = fail;
135
136
// 4. Pure assertion tests whether a value is truthy, as determined
137
// by !!guard.
138
// assert.ok(guard, message_opt);
139
// This statement is equivalent to assert.equal(true, !!guard,
140
// message_opt);. To test strictly for the value true, use
141
// assert.strictEqual(true, guard, message_opt);.
142
143
function ok(value, message) {
144
if (!value) fail(value, true, message, '==', assert.ok);
145
}
146
assert.ok = ok;
147
148
// 5. The equality assertion tests shallow, coercive equality with
149
// ==.
150
// assert.equal(actual, expected, message_opt);
151
152
assert.equal = function equal(actual, expected, message) {
153
if (actual != expected) fail(actual, expected, message, '==', assert.equal);
154
};
155
156
// 6. The non-equality assertion tests for whether two objects are not equal
157
// with != assert.notEqual(actual, expected, message_opt);
158
159
assert.notEqual = function notEqual(actual, expected, message) {
160
if (actual == expected) {
161
fail(actual, expected, message, '!=', assert.notEqual);
162
}
163
};
164
165
// 7. The equivalence assertion tests a deep equality relation.
166
// assert.deepEqual(actual, expected, message_opt);
167
168
assert.deepEqual = function deepEqual(actual, expected, message) {
169
if (!_deepEqual(actual, expected)) {
170
fail(actual, expected, message, 'deepEqual', assert.deepEqual);
171
}
172
};
173
174
function _deepEqual(actual, expected) {
175
// 7.1. All identical values are equivalent, as determined by ===.
176
if (actual === expected) {
177
return true;
178
179
} else if (util.isBuffer(actual) && util.isBuffer(expected)) {
180
if (actual.length != expected.length) return false;
181
182
for (var i = 0; i < actual.length; i++) {
183
if (actual[i] !== expected[i]) return false;
184
}
185
186
return true;
187
188
// 7.2. If the expected value is a Date object, the actual value is
189
// equivalent if it is also a Date object that refers to the same time.
190
} else if (util.isDate(actual) && util.isDate(expected)) {
191
return actual.getTime() === expected.getTime();
192
193
// 7.3 If the expected value is a RegExp object, the actual value is
194
// equivalent if it is also a RegExp object with the same source and
195
// properties (`global`, `multiline`, `lastIndex`, `ignoreCase`).
196
} else if (util.isRegExp(actual) && util.isRegExp(expected)) {
197
return actual.source === expected.source &&
198
actual.global === expected.global &&
199
actual.multiline === expected.multiline &&
200
actual.lastIndex === expected.lastIndex &&
201
actual.ignoreCase === expected.ignoreCase;
202
203
// 7.4. Other pairs that do not both pass typeof value == 'object',
204
// equivalence is determined by ==.
205
} else if (!util.isObject(actual) && !util.isObject(expected)) {
206
return actual == expected;
207
208
// 7.5 For all other Object pairs, including Array objects, equivalence is
209
// determined by having the same number of owned properties (as verified
210
// with Object.prototype.hasOwnProperty.call), the same set of keys
211
// (although not necessarily the same order), equivalent values for every
212
// corresponding key, and an identical 'prototype' property. Note: this
213
// accounts for both named and indexed properties on Arrays.
214
} else {
215
return objEquiv(actual, expected);
216
}
217
}
218
219
function isArguments(object) {
220
return Object.prototype.toString.call(object) == '[object Arguments]';
221
}
222
223
function objEquiv(a, b) {
224
if (util.isNullOrUndefined(a) || util.isNullOrUndefined(b))
225
return false;
226
// an identical 'prototype' property.
227
if (a.prototype !== b.prototype) return false;
228
//~~~I've managed to break Object.keys through screwy arguments passing.
229
// Converting to array solves the problem.
230
if (isArguments(a)) {
231
if (!isArguments(b)) {
232
return false;
233
}
234
a = pSlice.call(a);
235
b = pSlice.call(b);
236
return _deepEqual(a, b);
237
}
238
try {
239
var ka = objectKeys(a),
240
kb = objectKeys(b),
241
key, i;
242
} catch (e) {//happens when one is a string literal and the other isn't
243
return false;
244
}
245
// having the same number of owned properties (keys incorporates
246
// hasOwnProperty)
247
if (ka.length != kb.length)
248
return false;
249
//the same set of keys (although not necessarily the same order),
250
ka.sort();
251
kb.sort();
252
//~~~cheap key test
253
for (i = ka.length - 1; i >= 0; i--) {
254
if (ka[i] != kb[i])
255
return false;
256
}
257
//equivalent values for every corresponding key, and
258
//~~~possibly expensive deep test
259
for (i = ka.length - 1; i >= 0; i--) {
260
key = ka[i];
261
if (!_deepEqual(a[key], b[key])) return false;
262
}
263
return true;
264
}
265
266
// 8. The non-equivalence assertion tests for any deep inequality.
267
// assert.notDeepEqual(actual, expected, message_opt);
268
269
assert.notDeepEqual = function notDeepEqual(actual, expected, message) {
270
if (_deepEqual(actual, expected)) {
271
fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual);
272
}
273
};
274
275
// 9. The strict equality assertion tests strict equality, as determined by ===.
276
// assert.strictEqual(actual, expected, message_opt);
277
278
assert.strictEqual = function strictEqual(actual, expected, message) {
279
if (actual !== expected) {
280
fail(actual, expected, message, '===', assert.strictEqual);
281
}
282
};
283
284
// 10. The strict non-equality assertion tests for strict inequality, as
285
// determined by !==. assert.notStrictEqual(actual, expected, message_opt);
286
287
assert.notStrictEqual = function notStrictEqual(actual, expected, message) {
288
if (actual === expected) {
289
fail(actual, expected, message, '!==', assert.notStrictEqual);
290
}
291
};
292
293
function expectedException(actual, expected) {
294
if (!actual || !expected) {
295
return false;
296
}
297
298
if (Object.prototype.toString.call(expected) == '[object RegExp]') {
299
return expected.test(actual);
300
} else if (actual instanceof expected) {
301
return true;
302
} else if (expected.call({}, actual) === true) {
303
return true;
304
}
305
306
return false;
307
}
308
309
function _throws(shouldThrow, block, expected, message) {
310
var actual;
311
312
if (util.isString(expected)) {
313
message = expected;
314
expected = null;
315
}
316
317
try {
318
block();
319
} catch (e) {
320
actual = e;
321
}
322
323
message = (expected && expected.name ? ' (' + expected.name + ').' : '.') +
324
(message ? ' ' + message : '.');
325
326
if (shouldThrow && !actual) {
327
fail(actual, expected, 'Missing expected exception' + message);
328
}
329
330
if (!shouldThrow && expectedException(actual, expected)) {
331
fail(actual, expected, 'Got unwanted exception' + message);
332
}
333
334
if ((shouldThrow && actual && expected &&
335
!expectedException(actual, expected)) || (!shouldThrow && actual)) {
336
throw actual;
337
}
338
}
339
340
// 11. Expected to throw an error:
341
// assert.throws(block, Error_opt, message_opt);
342
343
assert.throws = function(block, /*optional*/error, /*optional*/message) {
344
_throws.apply(this, [true].concat(pSlice.call(arguments)));
345
};
346
347
// EXTENSION! This is annoying to write outside this module.
348
assert.doesNotThrow = function(block, /*optional*/message) {
349
_throws.apply(this, [false].concat(pSlice.call(arguments)));
350
};
351
352
assert.ifError = function(err) { if (err) {throw err;}};
353
354
var objectKeys = Object.keys || function (obj) {
355
var keys = [];
356
for (var key in obj) {
357
if (hasOwn.call(obj, key)) keys.push(key);
358
}
359
return keys;
360
};
361
362