Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
80529 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) && !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
// if one is a primitive, the other must be same
229
if (util.isPrimitive(a) || util.isPrimitive(b)) {
230
return a === b;
231
}
232
var aIsArgs = isArguments(a),
233
bIsArgs = isArguments(b);
234
if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs))
235
return false;
236
if (aIsArgs) {
237
a = pSlice.call(a);
238
b = pSlice.call(b);
239
return _deepEqual(a, b);
240
}
241
var ka = objectKeys(a),
242
kb = objectKeys(b),
243
key, i;
244
// having the same number of owned properties (keys incorporates
245
// hasOwnProperty)
246
if (ka.length != kb.length)
247
return false;
248
//the same set of keys (although not necessarily the same order),
249
ka.sort();
250
kb.sort();
251
//~~~cheap key test
252
for (i = ka.length - 1; i >= 0; i--) {
253
if (ka[i] != kb[i])
254
return false;
255
}
256
//equivalent values for every corresponding key, and
257
//~~~possibly expensive deep test
258
for (i = ka.length - 1; i >= 0; i--) {
259
key = ka[i];
260
if (!_deepEqual(a[key], b[key])) return false;
261
}
262
return true;
263
}
264
265
// 8. The non-equivalence assertion tests for any deep inequality.
266
// assert.notDeepEqual(actual, expected, message_opt);
267
268
assert.notDeepEqual = function notDeepEqual(actual, expected, message) {
269
if (_deepEqual(actual, expected)) {
270
fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual);
271
}
272
};
273
274
// 9. The strict equality assertion tests strict equality, as determined by ===.
275
// assert.strictEqual(actual, expected, message_opt);
276
277
assert.strictEqual = function strictEqual(actual, expected, message) {
278
if (actual !== expected) {
279
fail(actual, expected, message, '===', assert.strictEqual);
280
}
281
};
282
283
// 10. The strict non-equality assertion tests for strict inequality, as
284
// determined by !==. assert.notStrictEqual(actual, expected, message_opt);
285
286
assert.notStrictEqual = function notStrictEqual(actual, expected, message) {
287
if (actual === expected) {
288
fail(actual, expected, message, '!==', assert.notStrictEqual);
289
}
290
};
291
292
function expectedException(actual, expected) {
293
if (!actual || !expected) {
294
return false;
295
}
296
297
if (Object.prototype.toString.call(expected) == '[object RegExp]') {
298
return expected.test(actual);
299
} else if (actual instanceof expected) {
300
return true;
301
} else if (expected.call({}, actual) === true) {
302
return true;
303
}
304
305
return false;
306
}
307
308
function _throws(shouldThrow, block, expected, message) {
309
var actual;
310
311
if (util.isString(expected)) {
312
message = expected;
313
expected = null;
314
}
315
316
try {
317
block();
318
} catch (e) {
319
actual = e;
320
}
321
322
message = (expected && expected.name ? ' (' + expected.name + ').' : '.') +
323
(message ? ' ' + message : '.');
324
325
if (shouldThrow && !actual) {
326
fail(actual, expected, 'Missing expected exception' + message);
327
}
328
329
if (!shouldThrow && expectedException(actual, expected)) {
330
fail(actual, expected, 'Got unwanted exception' + message);
331
}
332
333
if ((shouldThrow && actual && expected &&
334
!expectedException(actual, expected)) || (!shouldThrow && actual)) {
335
throw actual;
336
}
337
}
338
339
// 11. Expected to throw an error:
340
// assert.throws(block, Error_opt, message_opt);
341
342
assert.throws = function(block, /*optional*/error, /*optional*/message) {
343
_throws.apply(this, [true].concat(pSlice.call(arguments)));
344
};
345
346
// EXTENSION! This is annoying to write outside this module.
347
assert.doesNotThrow = function(block, /*optional*/message) {
348
_throws.apply(this, [false].concat(pSlice.call(arguments)));
349
};
350
351
assert.ifError = function(err) { if (err) {throw err;}};
352
353
var objectKeys = Object.keys || function (obj) {
354
var keys = [];
355
for (var key in obj) {
356
if (hasOwn.call(obj, key)) keys.push(key);
357
}
358
return keys;
359
};
360
361