Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

unexpected

Package Overview
Dependencies
Maintainers
1
Versions
330
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

unexpected - npm Package Compare versions

Comparing version 0.0.1 to 0.0.2

625

lib/unexpected.js
// Copyright (c) 2013 Sune Simonsen <sune@we-knowhow.dk>
//
//
// Permission is hereby granted, free of charge, to any person

@@ -10,6 +10,6 @@ // obtaining a copy of this software and associated documentation

// furnished to do so, subject to the following conditions:
//
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
//
// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,

@@ -35,4 +35,4 @@ // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF

var that = this;
var argsString = this.args.map(function (arg) {
return that.inspect(arg);
var argsString = map(this.args, function (arg) {
return inspect(arg);
}).join(', ');

@@ -44,3 +44,3 @@ if (argsString.length > 0) {

throw new Error('expected ' +
this.inspect(this.obj) +
inspect(this.obj) +
' ' + this.testDescription +

@@ -78,3 +78,3 @@ argsString);

for (var i = 1; i < match.length; i += 1) {
var flag = match[i];
var flag = match[i];
if (flag !== undefined) {

@@ -106,3 +106,3 @@ flags[flag] = true;

expect.format = function (message, args) {
args = args.map(function (arg) {
args = map(args, function (arg) {
return inspect(arg);

@@ -176,3 +176,3 @@ });

});
expect.addAssertion('to [not] have length', function (length) {

@@ -192,3 +192,3 @@ if (!this.obj || typeof this.obj.length !== 'number') {

} else if (this.obj && typeof this.obj === 'object') {
this.assert(!Object.keys(this.obj).length);
this.assert(!getKeys(this.obj).length);
} else {

@@ -207,7 +207,7 @@ throw new Error("Assertion '" + this.testDescription +

var hasKeys = obj && keys.every(function (key) {
return obj.hasOwnProperty(key);
var hasKeys = obj && every(keys, function (key) {
return obj.hasOwnProperty(key);
});
if (this.flags.only) {
this.assert(hasKeys && Object.keys(obj).length === keys.length);
this.assert(hasKeys && getKeys(obj).length === keys.length);
} else {

@@ -222,3 +222,3 @@ this.assert(hasKeys);

} else {
this.assert(this.obj && this.obj.indexOf(arg) !== -1);
this.assert(this.obj && indexOf(this.obj, arg) !== -1);
}

@@ -303,76 +303,58 @@ });

function isUndefinedOrNull (value) {
return value === null || value === undefined;
}
Assertion.prototype.inspect = inspect;
expect.inspect = inspect;
Assertion.prototype.eql = eql;
expect.eql = eql;
function isArguments (object) {
return Object.prototype.toString.call(object) == '[object Arguments]';
///////////////////////// Helper functions ///////////////////////////////
function bind(fn, scope) {
return function () {
return fn.apply(scope, arguments);
};
}
function objEquiv (a, b) {
if (isUndefinedOrNull(a) || isUndefinedOrNull(b))
return false;
// an identical "prototype" property.
if (a.prototype !== b.prototype) return false;
//~~~I've managed to break Object.keys through screwy arguments passing.
// Converting to array solves the problem.
if (isArguments(a)) {
if (!isArguments(b)) {
function every (arr, fn, thisObj) {
var scope = thisObj || global;
for (var i = 0, j = arr.length; i < j; ++i) {
if (!fn.call(scope, arr[i], i, arr)) {
return false;
}
a = pSlice.call(a);
b = pSlice.call(b);
return expect.eql(a, b);
}
try{
var ka = Object.keys(a),
kb = Object.keys(b),
key, i;
// having the same number of owned properties (keys incorporates hasOwnProperty)
if (ka.length != kb.length)
return false;
//the same set of keys (although not necessarily the same order),
ka.sort();
kb.sort();
//~~~cheap key test
for (i = ka.length - 1; i >= 0; i--) {
if (ka[i] != kb[i])
return false;
}
//equivalent values for every corresponding key, and
//~~~possibly expensive deep test
for (i = ka.length - 1; i >= 0; i--) {
key = ka[i];
if (!expect.eql(a[key], b[key]))
return false;
}
return true;
} catch (e) {//happens when one is a string literal and the other isn't
return false;
}
return true;
}
function isRegExp(re) {
var s;
try {
s = '' + re;
} catch (e) {
return false;
function indexOf (arr, o, i) {
if (Array.prototype.indexOf) {
return Array.prototype.indexOf.call(arr, o, i);
}
return re instanceof RegExp || // easy case
// duck-type for context-switching evalcx case
typeof(re) === 'function' &&
re.constructor.name === 'RegExp' &&
re.compile &&
re.test &&
re.exec &&
s.match(/^\/.*\/[gim]{0,3}$/);
}
if (arr.length === undefined) {
return -1;
}
function isDate(d) {
if (d instanceof Date) return true;
return false;
for (var j = arr.length, i = i < 0 ? i + j < 0 ? 0 : i + j : i || 0;
i < j && arr[i] !== o; i++);
return j <= i ? -1 : i;
}
// https://gist.github.com/1044128/
var getOuterHTML = function(element) {
if ('outerHTML' in element) return element.outerHTML;
var ns = "http://www.w3.org/1999/xhtml";
var container = document.createElementNS(ns, '_');
var elemProto = (window.HTMLElement || window.Element).prototype;
var xmlSerializer = new XMLSerializer();
var html;
if (document.xmlVersion) {
return xmlSerializer.serializeToString(element);
} else {
container.appendChild(element.cloneNode(false));
html = container.innerHTML.replace('><', '>' + element.innerHTML + '<');
container.innerHTML = '';
return html;
}
};
// Returns true if object is a DOM element.

@@ -389,3 +371,3 @@ var isDOMElement = function (object) {

};
/**

@@ -395,5 +377,4 @@ * Inspects an object.

* @see taken from node.js `util` module (copyright Joyent, MIT license)
* @api private
*/
var inspect = function (obj, showHidden, depth) {
function inspect(obj, showHidden, depth) {
var seen = [];

@@ -422,3 +403,3 @@

case 'string':
var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
var simple = '\'' + json.stringify(value).replace(/^"|"$/g, '')
.replace(/'/g, "\\'")

@@ -448,3 +429,3 @@ .replace(/\\"/g, '"') + '\'';

// Look up the keys of the object.
var visible_keys = Object.keys(value);
var visible_keys = getKeys(value);
var $keys = showHidden ? Object.getOwnPropertyNames(value) : visible_keys;

@@ -504,3 +485,3 @@

var output = $keys.map(function (key) {
var output = map($keys, function (key) {
var name, str;

@@ -520,7 +501,7 @@ if (value.__lookupGetter__) {

}
if (visible_keys.indexOf(key) < 0) {
if (indexOf(visible_keys, key) < 0) {
name = '[' + key + ']';
}
if (!str) {
if (seen.indexOf(value[key]) < 0) {
if (indexOf(seen, value[key]) < 0) {
if (recurseTimes === null) {

@@ -533,7 +514,7 @@ str = format(value[key]);

if (isArray(value)) {
str = str.split('\n').map(function (line) {
str = map(str.split('\n'), function (line) {
return ' ' + line;
}).join('\n').substr(2);
} else {
str = '\n' + str.split('\n').map(function (line) {
str = '\n' + map(str.split('\n'), function (line) {
return ' ' + line;

@@ -551,3 +532,3 @@ }).join('\n');

}
name = JSON.stringify('' + key);
name = json.stringify('' + key);
if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {

@@ -570,5 +551,5 @@ name = name.substr(1, name.length - 2);

var numLinesEst = 0;
var length = output.reduce(function (prev, cur) {
var length = reduce(output, function (prev, cur) {
numLinesEst++;
if (cur.indexOf('\n') >= 0) numLinesEst++;
if (indexOf(cur, '\n') >= 0) numLinesEst++;
return prev + cur.length + 1;

@@ -592,6 +573,102 @@ }, 0);

return format(obj, (typeof depth === 'undefined' ? 2 : depth));
};
Assertion.prototype.inspect = inspect;
expect.inspect = inspect;
}
function isArray (ar) {
return Object.prototype.toString.call(ar) == '[object Array]';
}
function isRegExp(re) {
var s;
try {
s = '' + re;
} catch (e) {
return false;
}
return re instanceof RegExp || // easy case
// duck-type for context-switching evalcx case
typeof(re) === 'function' &&
re.constructor.name === 'RegExp' &&
re.compile &&
re.test &&
re.exec &&
s.match(/^\/.*\/[gim]{0,3}$/);
}
function isDate(d) {
if (d instanceof Date) return true;
return false;
}
function getKeys(obj) {
if (Object.keys) {
return Object.keys(obj);
}
var result = [];
for (var i in obj) {
if (Object.prototype.hasOwnProperty.call(obj, i)) {
result.push(i);
}
}
return result;
}
function map(arr, mapper, that) {
if (Array.prototype.map) {
return Array.prototype.map.call(arr, mapper, that);
}
var other= new Array(arr.length);
for (var i= 0, n = arr.length; i<n; i++)
if (i in arr)
other[i] = mapper.call(that, arr[i], i, arr);
return other;
}
function reduce (arr, fun) {
if (Array.prototype.reduce) {
return Array.prototype.reduce.apply(
arr, Array.prototype.slice.call(arguments, 1)
);
}
var len = +this.length;
if (typeof fun !== "function")
throw new TypeError();
// no value to return if no initial value and an empty array
if (len === 0 && arguments.length === 1)
throw new TypeError();
var i = 0;
var rv;
if (arguments.length >= 2) {
rv = arguments[1];
} else {
do {
if (i in this) {
rv = this[i++];
break;
}
// if array contains no values, no initial value to return
if (++i >= len)
throw new TypeError();
} while (true);
}
for (; i < len; i++) {
if (i in this)
rv = fun.call(null, rv, this[i], i, this);
}
return rv;
}
/**

@@ -601,5 +678,4 @@ * Asserts deep equality

* @see taken from node.js `assert` module (copyright Joyent, MIT license)
* @api private
*/
expect.eql = function eql (actual, expected) {
function eql(actual, expected) {
// 7.1. All identical values are equivalent, as determined by ===.

@@ -637,8 +713,365 @@ if (actual === expected) {

}
};
}
function isArray (ar) {
return Object.prototype.toString.call(ar) == '[object Array]';
function isUndefinedOrNull (value) {
return value === null || value === undefined;
}
function isArguments (object) {
return Object.prototype.toString.call(object) == '[object Arguments]';
}
function objEquiv (a, b) {
if (isUndefinedOrNull(a) || isUndefinedOrNull(b))
return false;
// an identical "prototype" property.
if (a.prototype !== b.prototype) return false;
//~~~I've managed to break Object.keys through screwy arguments passing.
// Converting to array solves the problem.
if (isArguments(a)) {
if (!isArguments(b)) {
return false;
}
a = pSlice.call(a);
b = pSlice.call(b);
return expect.eql(a, b);
}
var ka, kb, key, i;
try{
ka = getKeys(a);
kb = getKeys(b);
} catch (e) {//happens when one is a string literal and the other isn't
return false;
}
// having the same number of owned properties (keys incorporates hasOwnProperty)
if (ka.length != kb.length)
return false;
//the same set of keys (although not necessarily the same order),
ka.sort();
kb.sort();
//~~~cheap key test
for (i = ka.length - 1; i >= 0; i--) {
if (ka[i] != kb[i])
return false;
}
//equivalent values for every corresponding key, and
//~~~possibly expensive deep test
for (i = ka.length - 1; i >= 0; i--) {
key = ka[i];
if (!eql(a[key], b[key]))
return false;
}
return true;
}
var json = (function () {
"use strict";
if ('object' == typeof JSON && JSON.parse && JSON.stringify) {
return {
parse: JSON.parse,
stringify: JSON.stringify
};
}
var JSON = {};
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
function date(d, key) {
return isFinite(d.valueOf()) ?
d.getUTCFullYear() + '-' +
f(d.getUTCMonth() + 1) + '-' +
f(d.getUTCDate()) + 'T' +
f(d.getUTCHours()) + ':' +
f(d.getUTCMinutes()) + ':' +
f(d.getUTCSeconds()) + 'Z' : null;
}
var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
gap,
indent,
meta = { // table of character substitutions
'\b': '\\b',
'\t': '\\t',
'\n': '\\n',
'\f': '\\f',
'\r': '\\r',
'"' : '\\"',
'\\': '\\\\'
},
rep;
function quote(string) {
// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can safely slap some quotes around it.
// Otherwise we must also replace the offending characters with safe escape
// sequences.
escapable.lastIndex = 0;
return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
var c = meta[a];
return typeof c === 'string' ? c :
'\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
}) + '"' : '"' + string + '"';
}
function str(key, holder) {
// Produce a string from holder[key].
var i, // The loop counter.
k, // The member key.
v, // The member value.
length,
mind = gap,
partial,
value = holder[key];
// If the value has a toJSON method, call it to obtain a replacement value.
if (value instanceof Date) {
value = date(key);
}
// If we were called with a replacer function, then call the replacer to
// obtain a replacement value.
if (typeof rep === 'function') {
value = rep.call(holder, key, value);
}
// What happens next depends on the value's type.
switch (typeof value) {
case 'string':
return quote(value);
case 'number':
// JSON numbers must be finite. Encode non-finite numbers as null.
return isFinite(value) ? String(value) : 'null';
case 'boolean':
case 'null':
// If the value is a boolean or null, convert it to a string. Note:
// typeof null does not produce 'null'. The case is included here in
// the remote chance that this gets fixed someday.
return String(value);
// If the type is 'object', we might be dealing with an object or an array or
// null.
case 'object':
// Due to a specification blunder in ECMAScript, typeof null is 'object',
// so watch out for that case.
if (!value) {
return 'null';
}
// Make an array to hold the partial results of stringifying this object value.
gap += indent;
partial = [];
// Is the value an array?
if (Object.prototype.toString.apply(value) === '[object Array]') {
// The value is an array. Stringify every element. Use null as a placeholder
// for non-JSON values.
length = value.length;
for (i = 0; i < length; i += 1) {
partial[i] = str(i, value) || 'null';
}
// Join all of the elements together, separated with commas, and wrap them in
// brackets.
v = partial.length === 0 ? '[]' : gap ?
'[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' :
'[' + partial.join(',') + ']';
gap = mind;
return v;
}
// If the replacer is an array, use it to select the members to be stringified.
if (rep && typeof rep === 'object') {
length = rep.length;
for (i = 0; i < length; i += 1) {
if (typeof rep[i] === 'string') {
k = rep[i];
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
} else {
// Otherwise, iterate through all of the keys in the object.
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
}
// Join all of the member texts together, separated with commas,
// and wrap them in braces.
v = partial.length === 0 ? '{}' : gap ?
'{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' :
'{' + partial.join(',') + '}';
gap = mind;
return v;
}
}
// If the JSON object does not yet have a stringify method, give it one.
JSON.stringify = function (value, replacer, space) {
// The stringify method takes a value and an optional replacer, and an optional
// space parameter, and returns a JSON text. The replacer can be a function
// that can replace values, or an array of strings that will select the keys.
// A default replacer method can be provided. Use of the space parameter can
// produce text that is more easily readable.
var i;
gap = '';
indent = '';
// If the space parameter is a number, make an indent string containing that
// many spaces.
if (typeof space === 'number') {
for (i = 0; i < space; i += 1) {
indent += ' ';
}
// If the space parameter is a string, it will be used as the indent string.
} else if (typeof space === 'string') {
indent = space;
}
// If there is a replacer, it must be a function or an array.
// Otherwise, throw an error.
rep = replacer;
if (replacer && typeof replacer !== 'function' &&
(typeof replacer !== 'object' ||
typeof replacer.length !== 'number')) {
throw new Error('JSON.stringify');
}
// Make a fake root object containing our value under the key of ''.
// Return the result of stringifying the value.
return str('', {'': value});
};
// If the JSON object does not yet have a parse method, give it one.
JSON.parse = function (text, reviver) {
// The parse method takes a text and an optional reviver function, and returns
// a JavaScript value if the text is a valid JSON text.
var j;
function walk(holder, key) {
// The walk method is used to recursively walk the resulting structure so
// that modifications can be made.
var k, v, value = holder[key];
if (value && typeof value === 'object') {
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
v = walk(value, k);
if (v !== undefined) {
value[k] = v;
} else {
delete value[k];
}
}
}
}
return reviver.call(holder, key, value);
}
// Parsing happens in four stages. In the first stage, we replace certain
// Unicode characters with escape sequences. JavaScript handles many characters
// incorrectly, either silently deleting them, or treating them as line endings.
text = String(text);
cx.lastIndex = 0;
if (cx.test(text)) {
text = text.replace(cx, function (a) {
return '\\u' +
('0000' + a.charCodeAt(0).toString(16)).slice(-4);
});
}
// In the second stage, we run the text against regular expressions that look
// for non-JSON patterns. We are especially concerned with '()' and 'new'
// because they can cause invocation, and '=' because it can cause mutation.
// But just to be safe, we want to reject all unexpected forms.
// We split the second stage into 4 regexp operations in order to work around
// crippling inefficiencies in IE's and Safari's regexp engines. First we
// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
// replace all simple value tokens with ']' characters. Third, we delete all
// open brackets that follow a colon or comma or that begin the text. Finally,
// we look to see that the remaining characters are only whitespace or ']' or
// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
if (/^[\],:{}\s]*$/
.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
.replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
// In the third stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.
j = eval('(' + text + ')');
// In the optional fourth stage, we recursively walk the new structure, passing
// each name/value pair to a reviver function for possible transformation.
return typeof reviver === 'function' ?
walk({'': j}, '') : j;
}
// If the text is not JSON parseable, then a SyntaxError is thrown.
throw new SyntaxError('JSON.parse');
};
return JSON;
})();
//////////////////////////////////////////////////////////////////////////
// Support three module loading scenarios

@@ -645,0 +1078,0 @@ if (typeof require === 'function' && typeof exports === 'object' && typeof module === 'object') {

2

package.json
{
"name": "unexpected",
"version": "0.0.1",
"version": "0.0.2",
"author": "Sune Sloth Simonsen <sune@we-knowhow.dk>",

@@ -5,0 +5,0 @@ "keywords": [ "assertion", "test", "assert" ],

@@ -21,3 +21,3 @@ # Unexpected

- Compatible with all test frameworks.
- TODO: Node.JS ready (`require('unexpected')`).
- Node.JS ready (`require('unexpected')`).
- TODO: Cross-browser: works on IE6+, Firefox, Safari, Chrome, Opera.

@@ -106,3 +106,3 @@ - TODO: Standalone. Single global with no prototype extensions or shims.

**a**/**an**: asserts `typeof` with support for `array` type and `instanceof`
**a** / **an**: asserts `typeof` with support for `array` type and `instanceof`

@@ -109,0 +109,0 @@ ```js

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc