UNPKG

unexpected

Version:
1,379 lines (1,236 loc) 422 kB
/*! * Copyright (c) 2013 Sune Simonsen <sune@we-knowhow.dk> * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the 'Software'), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * 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, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ !function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var o;"undefined"!=typeof window?o=window:"undefined"!=typeof global?o=global:"undefined"!=typeof self&&(o=self),(o.weknowhow||(o.weknowhow={})).expect=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ var createStandardErrorMessage = require(5); function Assertion(expect, subject, testDescription, flags, alternations, args) { this.expect = expect; this.subject = subject; this.testDescription = testDescription; this.flags = flags; this.alternations = alternations; this.args = args; this.errorMode = 'default'; } Assertion.prototype.standardErrorMessage = function (options) { return createStandardErrorMessage(this.expect.output.clone(), this.expect, this.subject, this.testDescription, this.args, options); }; Assertion.prototype.shift = function (subject, assertionIndex) { if (arguments.length === 3) { // The 3-argument syntax for Assertion.prototype.shift is deprecated, please omit the first (expect) arg subject = arguments[1]; assertionIndex = arguments[2]; } var rest = this.args.slice(assertionIndex); this.args[assertionIndex] = this.expect.output.clone().error(this.args[assertionIndex]); var nextArgumentType = this.expect.findTypeOf(rest[0]); if (nextArgumentType.is('expect.it')) { return rest[0](subject); } else if (nextArgumentType.is('string')) { return this.expect.apply(this.expect, [subject].concat(rest)); } else { throw new Error('The "' + this.testDescription + '" assertion requires parameter #' + (assertionIndex + 2) + ' to be an expect.it function or a string specifying an assertion to delegate to'); } }; module.exports = Assertion; },{}],2:[function(require,module,exports){ var Assertion = require(1); var createStandardErrorMessage = require(5); var utils = require(13); var magicpen = require(30); var extend = utils.extend; var leven = require(26); var makePromise = require(7); var isPendingPromise = require(6); var oathbreaker = require(8); var throwIfNonUnexpectedError = require(11); var UnexpectedError = require(3); var testFrameworkPatch = require(10); var anyType = { name: 'any', identify: function () { return true; }, equal: utils.objectIs, inspect: function (value, depth, output) { if (output && output.isMagicPen) { return output.text(value); } else { // Guard against node.js' require('util').inspect eagerly calling .inspect() on objects return String(value); } }, diff: function (actual, expected, output, diff, inspect) { return null; }, is: function (typeOrTypeName) { var typeName; if (typeof typeOrTypeName === 'string') { typeName = typeOrTypeName; } else { typeName = typeOrTypeName.name; } if (this.name === typeName) { return true; } else if (this.baseType) { return this.baseType.is(typeName); } else { return false; } } }; function Unexpected(options) { testFrameworkPatch.applyPatch(); options = options || {}; this.assertions = options.assertions || {any: {}}; this.typeByName = options.typeByName || {}; this.types = options.types || [anyType]; this.output = options.output || magicpen(); this._outputFormat = options.format || magicpen.defaultFormat; this.installedPlugins = options.installedPlugins || []; // Make bound versions of these two helpers up front to save a bit when creating wrapped expects: var that = this; this.getType = function (typeName) { return utils.findFirst(that.types, function (type) { return type.name === typeName; }); }; this.findTypeOf = function (obj) { return utils.findFirst(that.types || [], function (type) { return type.identify(obj); }); }; this.findCommonType = function (a, b) { var aAncestorIndex = {}; var current = this.findTypeOf(a); while (current) { aAncestorIndex[current.name] = current; current = current.baseType; } current = this.findTypeOf(b); while (current) { if (aAncestorIndex[current.name]) { return current; } current = current.baseType; } }; } var OR = {}; function getOrGroups(expectations) { var orGroups = [[]]; expectations.forEach(function (expectation) { if (expectation === OR) { orGroups.push([]); } else { orGroups[orGroups.length - 1].push(expectation); } }); return orGroups; } function evaluateGroup(expect, subject, orGroup) { return orGroup.map(function (expectation) { var args = Array.prototype.slice.call(expectation); args.unshift(subject); return { expectation: args, promise: makePromise(function () { return expect.apply(expect, args); }) }; }); } function writeGroupEvaluationsToOutput(expect, output, groupEvaluations) { var hasOrClauses = groupEvaluations.length > 1; var hasAndClauses = groupEvaluations.some(function (groupEvaluation) { return groupEvaluation.length > 1; }); groupEvaluations.forEach(function (groupEvaluation, i) { if (i > 0) { if (hasAndClauses) { output.nl(); } else { output.sp(); } output.jsComment('or').nl(); } var groupFailed = false; groupEvaluation.forEach(function (evaluation, j) { if (j > 0) { output.jsComment(' and').nl(); } var isRejected = evaluation.promise.isRejected(); if (isRejected && !groupFailed) { groupFailed = true; var err = evaluation.promise.reason(); if (hasAndClauses || hasOrClauses) { output.error('⨯ '); } output.block(function (output) { output.append(err.getErrorMessage()); }); } else { var style; if (isRejected) { style = 'error'; output.error('⨯ '); } else { style = 'success'; output.success('✓ '); } var expectation = evaluation.expectation; output.block(function (output) { output[style]('expected '); output.append(expect.inspect(expectation[0])).sp(); output[style](expectation[1]); expectation.slice(2).forEach(function (v) { output.sp().append(expect.inspect(v)); }); }); } }); }); } function createExpectIt(expect, expectations) { var orGroups = getOrGroups(expectations); function expectIt(subject) { var groupEvaluations = []; var promises = []; orGroups.forEach(function (orGroup) { var evaluations = evaluateGroup(expect, subject, orGroup); evaluations.forEach(function (evaluation) { promises.push(evaluation.promise); }); groupEvaluations.push(evaluations); }); return oathbreaker(expect.promise.settle(promises).then(function () { var isSuccessful = groupEvaluations.some(function (groupEvaluation) { return groupEvaluation.every(function (evaluation) { return evaluation.promise.isFulfilled(); }); }); if (!isSuccessful) { expect.fail(function (output) { writeGroupEvaluationsToOutput(expect, output, groupEvaluations); }); } })); } expectIt._expectIt = true; expectIt._expectations = expectations; expectIt._OR = OR; expectIt.and = function () { var copiedExpectations = expectations.slice(); copiedExpectations.push(arguments); return createExpectIt(expect, copiedExpectations); }; expectIt.or = function () { var copiedExpectations = expectations.slice(); copiedExpectations.push(OR, arguments); return createExpectIt(expect, copiedExpectations); }; return expectIt; } Unexpected.prototype.it = function () { // ... return createExpectIt(this.expect, [arguments]); }; Unexpected.prototype.equal = function (actual, expected, depth, seen) { var that = this; depth = typeof depth === 'number' ? depth : 100; if (depth <= 0) { // detect recursive loops in the structure seen = seen || []; if (seen.indexOf(actual) !== -1) { throw new Error('Cannot compare circular structures'); } seen.push(actual); } return this.findCommonType(actual, expected).equal(actual, expected, function (a, b) { return that.equal(a, b, depth - 1, seen); }); }; Unexpected.prototype.inspect = function (obj, depth) { var seen = []; var that = this; var printOutput = function (obj, currentDepth, output) { var objType = that.findTypeOf(obj); if (currentDepth === 0 && objType.is('object') && !objType.is('expect.it')) { return output.text('...'); } seen = seen || []; if (seen.indexOf(obj) !== -1) { return output.text('[Circular]'); } return objType.inspect(obj, currentDepth, output, function (v, childDepth) { output = output.clone(); seen.push(obj); if (typeof childDepth === 'undefined') { childDepth = currentDepth - 1; } return printOutput(v, childDepth, output) || output; }); }; var output = this.output.clone(); return printOutput(obj, depth || 3, output) || output; }; var placeholderSplitRegexp = /(\{(?:\d+)\})/g; var placeholderRegexp = /\{(\d+)\}/; Unexpected.prototype.fail = function (arg) { if (arg instanceof UnexpectedError) { arg._hasSerializedErrorMessage = false; throw arg; } if (utils.isError(arg)) { throw arg; } var output = this.output.clone(); var additionalProperties = {}; if (typeof arg === 'function') { arg.call(output, output); } else if (arg && typeof arg === 'object') { if (typeof arg.message !== 'undefined') { if (arg.message.isMagicPen) { output.append(arg.message); } else if (typeof arg.message === 'function') { arg.message.call(output, output); } else { output.text(String(arg.message)); } } else { output.error('Explicit failure'); } Object.keys(arg).forEach(function (key) { var value = arg[key]; if (key === 'diff') { additionalProperties.createDiff = value; } else if (key !== 'message') { additionalProperties[key] = value; } }); } else { var that = this; var message = arg ? String(arg) : 'Explicit failure'; var placeholderArgs = Array.prototype.slice.call(arguments, 1); var tokens = message.split(placeholderSplitRegexp); tokens.forEach(function (token) { var match = placeholderRegexp.exec(token); if (match) { var index = match[1]; if (index in placeholderArgs) { var placeholderArg = placeholderArgs[index]; if (placeholderArg && placeholderArg.isMagicPen) { output.append(placeholderArg); } else { output.append(that.inspect(placeholderArg)); } } else { output.text(match[0]); } } else { output.error(token); } }); } var error = new UnexpectedError(this.expect); error.output = output; Object.keys(additionalProperties).forEach(function (key) { error[key] = additionalProperties[key]; }); throw error; }; // addAssertion(pattern, handler) // addAssertion([pattern, ...]], handler) // addAssertion(typeName, pattern, handler) // addAssertion([typeName, ...], pattern, handler) // addAssertion([typeName, ...], [pattern, pattern...], handler) Unexpected.prototype.addAssertion = function (types, patterns, handler) { if (arguments.length !== 2 && arguments.length !== 3) { throw new Error('addAssertion: Needs 2 or 3 arguments'); } if (typeof patterns === 'function') { handler = patterns; patterns = types; types = [anyType]; } else { var typeByName = this.typeByName; // Normalize to an array of types, but allow types to be specified by name: types = (Array.isArray(types) ? types : [types]).map(function (type) { if (typeof type === 'string') { if (type in typeByName) { return typeByName[type]; } else { throw new Error('No such type: ' + type); } } else { return type; } }); } patterns = utils.isArray(patterns) ? patterns : [patterns]; var assertions = this.assertions; types.forEach(function (type) { var typeName = type.name; var assertionsForType = assertions[typeName]; if (!assertionsForType) { throw new Error('No such type: ' + typeName); } var isSeenByExpandedPattern = {}; patterns.forEach(ensureValidPattern); var expandedPatternArrays = patterns.map(expandPattern); var defaultValueByFlag = {}; expandedPatternArrays.forEach(function(expandedPatterns) { expandedPatterns.forEach(function (expandedPattern) { Object.keys(expandedPattern.flags).forEach(function (flag) { defaultValueByFlag[flag] = false; }); }); }); patterns.forEach(function (pattern, i) { expandedPatternArrays[i].forEach(function (expandedPattern) { if (expandedPattern.text in assertionsForType) { if (!isSeenByExpandedPattern[expandedPattern.text]) { throw new Error('Cannot redefine assertion: ' + expandedPattern.text + (typeName === 'any' ? '' : ' for type ' + typeName)); } } else { isSeenByExpandedPattern[expandedPattern.text] = true; assertionsForType[expandedPattern.text] = { handler: handler, flags: extend({}, defaultValueByFlag, expandedPattern.flags), alternations: expandedPattern.alternations }; } }); }); }); return this.expect; // for chaining }; Unexpected.prototype.addType = function (type) { var that = this; var baseType; if (typeof type.name !== 'string' || !/^[a-z_](?:|[a-z0-9_.-]*[_a-z0-9])$/i.test(type.name)) { throw new Error('A type must be given a non-empty name and must match ^[a-z_](?:|[a-z0-9_.-]*[_a-z0-9])$'); } if (this.getType(type.name)) { throw new Error('The type with the name ' + type.name + ' already exists'); } this.assertions[type.name] = {}; this.typeByName[type.name] = type; if (type.base) { baseType = utils.findFirst(this.types, function (t) { return t.name === type.base; }); if (!baseType) { throw new Error('Unknown base type: ' + type.base); } } else { baseType = anyType; } var output = this.expect.output; var extendedBaseType = Object.create(baseType); extendedBaseType.inspect = function (value, depth) { return baseType.inspect(value, depth, output.clone(), that.inspect.bind(that)); }; extendedBaseType.diff = function (actual, expected) { return baseType.diff(actual, expected, output.clone(), that.diff.bind(that), that.inspect.bind(that), that.equal.bind(that)); }; extendedBaseType.equal = function (actual, expected) { return baseType.equal(actual, expected, that.equal.bind(that)); }; var extendedType = extend({}, baseType, type, { baseType: extendedBaseType }); var inspect = extendedType.inspect; extendedType.inspect = function () { if (arguments.length < 2) { return 'type: ' + type.name; } else { return inspect.apply(this, arguments); } }; if (extendedType.identify === false) { extendedType.identify = function () { return false; }; this.types.push(extendedType); } else { this.types.unshift(extendedType); } return this.expect; }; Unexpected.prototype.addStyle = function () { // ... return this.output.addStyle.apply(this.output, arguments); }; Unexpected.prototype.installTheme = function () { // ... return this.output.installTheme.apply(this.output, arguments); }; Unexpected.prototype.installPlugin = function (plugin) { var alreadyInstalled = this.installedPlugins.some(function (installedPlugin) { return installedPlugin === plugin.name; }); if (alreadyInstalled) { return this.expect; } if (typeof plugin !== 'object' || typeof plugin.name !== 'string' || typeof plugin.installInto !== 'function' || (plugin.dependencies && !Array.isArray(plugin.dependencies))) { throw new Error('Plugins must adhere to the following interface\n' + '{\n' + ' name: <plugin name>,\n' + ' dependencies: <an optional list of dependencies>,\n' + ' installInto: <a function that will update the given expect instance>\n' + '}'); } if (plugin.name === 'unexpected-promise') { throw new Error('The unexpected-promise plugin was pulled into Unexpected as of 8.5.0. This means that the plugin is no longer supported.'); } if (plugin.dependencies) { var installedPlugins = this.installedPlugins; var unfulfilledDependencies = plugin.dependencies.filter(function (dependency) { return !installedPlugins.some(function (plugin) { return plugin === dependency; }); }); if (unfulfilledDependencies.length === 1) { throw new Error(plugin.name + ' requires plugin ' + unfulfilledDependencies[0]); } else if (unfulfilledDependencies.length > 1) { throw new Error(plugin.name + ' requires plugins ' + unfulfilledDependencies.slice(0, -1).join(', ') + ' and ' + unfulfilledDependencies[unfulfilledDependencies.length - 1]); } } this.installedPlugins.push(plugin.name); plugin.installInto(this.expect); return this.expect; // for chaining }; function installExpectMethods(unexpected, expectFunction) { var expect = expectFunction.bind(unexpected); expect.it = unexpected.it.bind(unexpected); expect.equal = unexpected.equal.bind(unexpected); expect.inspect = unexpected.inspect.bind(unexpected); expect.findTypeOf = unexpected.findTypeOf; // Already bound expect.fail = function () { try { unexpected.fail.apply(unexpected, arguments); } catch (e) { if (e && e._isUnexpected) { unexpected.setErrorMessage(e); } throw e; } }; expect.diff = unexpected.diff.bind(unexpected); expect.async = unexpected.async.bind(unexpected); expect.promise = makePromise; expect.addAssertion = unexpected.addAssertion.bind(unexpected); expect.addStyle = unexpected.addStyle.bind(unexpected); expect.installTheme = unexpected.installTheme.bind(unexpected); expect.addType = unexpected.addType.bind(unexpected); expect.getType = unexpected.getType; expect.clone = unexpected.clone.bind(unexpected); expect.toString = unexpected.toString.bind(unexpected); expect.assertions = unexpected.assertions; expect.installPlugin = unexpected.installPlugin.bind(unexpected); expect.output = unexpected.output; expect.outputFormat = unexpected.outputFormat.bind(unexpected); return expect; } function makeExpectFunction(unexpected) { var expect = installExpectMethods(unexpected, unexpected.expect); unexpected.expect = expect; return expect; } Unexpected.prototype.setErrorMessage = function (err) { err.serializeMessage(this.outputFormat()); }; Unexpected.prototype.toString = function () { return this.message; }; Unexpected.prototype.expect = function expect(subject, testDescriptionString) { var that = this; if (arguments.length < 2) { throw new Error('The expect function requires at least two parameters.'); } var serializeErrorsFromWrappedExpect = false; function executeExpect(subject, testDescriptionString, args) { if (typeof testDescriptionString !== 'string') { throw new Error('The expect function requires the second parameter to be a string.'); } var matchingType = that.findTypeOf(subject); var typeWithAssertion = matchingType; var assertionRule = that.assertions[typeWithAssertion.name][testDescriptionString]; while (!assertionRule && typeWithAssertion.name !== anyType.name) { // FIXME: Detect cycles? typeWithAssertion = typeWithAssertion.baseType; assertionRule = that.assertions[typeWithAssertion.name][testDescriptionString]; } if (assertionRule) { var flags = extend({}, assertionRule.flags); var callInNestedContext = function (callback) { try { var result = oathbreaker(callback()); if (isPendingPromise(result)) { testFrameworkPatch.promiseCreated(); return result.then(undefined, function (e) { if (e && e._isUnexpected) { throw new UnexpectedError(that.expect, assertion, e); } throw e; }); } else { return result; } } catch (e) { if (e && e._isUnexpected) { var wrappedError = new UnexpectedError(that.expect, assertion, e); if (serializeErrorsFromWrappedExpect) { that.setErrorMessage(wrappedError); } throw wrappedError; } throw e; } }; var wrappedExpect = function wrappedExpect() { var subject = arguments[0]; var testDescriptionString = arguments[1].replace(/\[(!?)([^\]]+)\] ?/g, function (match, negate, flag) { return Boolean(flags[flag]) !== Boolean(negate) ? flag + ' ' : ''; }).trim(); var args = new Array(arguments.length - 2); for (var i = 0; i < arguments.length - 2; i += 1) { args[i] = arguments[i + 2]; } return callInNestedContext(function () { return executeExpect(subject, testDescriptionString, args); }); }; // Not sure this is the right way to go about this: wrappedExpect.equal = that.equal; wrappedExpect.inspect = that.inspect; wrappedExpect.diff = that.diff; wrappedExpect.findTypeOf = that.findTypeOf.bind(that); wrappedExpect.findCommonType = that.findCommonType.bind(that); wrappedExpect.getType = that.getType; wrappedExpect.output = that.output; wrappedExpect.outputFormat = that.outputFormat; wrappedExpect.fail = function () { var args = arguments; callInNestedContext(function () { that.fail.apply(that, args); }); }; wrappedExpect.promise = makePromise; wrappedExpect.withError = function (body, handler) { return oathbreaker(makePromise(body).caught(function (e) { throwIfNonUnexpectedError(e); return handler(e); })); }; wrappedExpect.format = that.format; wrappedExpect.it = that.it.bind(that); var assertion = new Assertion(wrappedExpect, subject, testDescriptionString, flags, assertionRule.alternations, args); var handler = assertionRule.handler; var result = handler.apply(assertion, [wrappedExpect, subject].concat(args)); return oathbreaker(result); } else { that.fail({ message: function (output) { var definedForIncompatibleTypes = that.types.filter(function (type) { return that.assertions[type.name][testDescriptionString]; }, that); if (definedForIncompatibleTypes.length > 0) { output .append(createStandardErrorMessage(output.clone(), that.expect, subject, testDescriptionString, args)).nl() .indentLines() .i().error("The assertion '").jsString(testDescriptionString) .error("' is not defined for the type '").jsString(matchingType.name).error("',").nl() .i().error('but it is defined for ') .outdentLines(); if (definedForIncompatibleTypes.length === 1) { output.error("the type '").jsString(definedForIncompatibleTypes[0].name).error("'"); } else { output.error('these types: '); definedForIncompatibleTypes.forEach(function (incompatibleType, index) { if (index > 0) { output.error(', '); } output.error("'").jsString(incompatibleType.name).error("'"); }); } } else { var assertionsWithScore = []; var bonusForNextMatchingType = 0; [].concat(that.types).reverse().forEach(function (type) { var typeMatchBonus = 0; if (type.identify(subject)) { typeMatchBonus = bonusForNextMatchingType; bonusForNextMatchingType += 0.9; } Object.keys(that.assertions[type.name]).forEach(function (assertion) { assertionsWithScore.push({ type: type, assertion: assertion, score: typeMatchBonus - leven(testDescriptionString, assertion) }); }); }, that); assertionsWithScore.sort(function (a, b) { var c = b.score - a.score; if (c !== 0) { return c; } if (a.assertion < b.assertion) { return -1; } else if (a.assertion > b.assertion) { return 1; } else { return 0; } }); output.error("Unknown assertion '").jsString(testDescriptionString) .error("', did you mean: '").jsString(assertionsWithScore[0].assertion).error("'"); } }, errorMode: 'bubbleThrough' }); } } var args = Array.prototype.slice.call(arguments, 2); try { var promise = executeExpect(subject, testDescriptionString, args); if (isPendingPromise(promise)) { testFrameworkPatch.promiseCreated(); return promise.then(undefined, function (e) { if (e && e._isUnexpected) { that.setErrorMessage(e); } throw e; }); } else { serializeErrorsFromWrappedExpect = true; } return promise; } catch (e) { if (e && e._isUnexpected) { var newError = e; if (typeof mochaPhantomJS !== 'undefined') { newError = e.clone(); } that.setErrorMessage(newError); throw newError; } throw e; } }; Unexpected.prototype.async = function (cb) { var that = this; function asyncMisusage(message) { that._isAsync = false; that.expect.fail(function (output) { output.error(message).nl() .text("Usage: ").nl() .text("it('test description', expect.async(function () {").nl() .indentLines() .i().text("return expect('test.txt', 'to have content', 'Content read asynchroniously');").nl() .outdentLines() .text("});"); }); } if (typeof cb !== 'function' || cb.length !== 0) { asyncMisusage("expect.async requires a callback without arguments."); } return function (done) { if (that._isAsync) { asyncMisusage("expect.async can't be within a expect.async context."); } that._isAsync = true; if (typeof done !== 'function') { asyncMisusage("expect.async should be called in the context of an it-block\n" + "and the it-block should supply a done callback."); } var result; try { result = cb(); } finally { that._isAsync = false; } if (!result || typeof result.then !== 'function') { asyncMisusage("expect.async requires the block to return a promise or throw an exception."); } result.then(function () { that._isAsync = false; done(); }, function (err) { that._isAsync = false; done(err); }); }; }; Unexpected.prototype.diff = function (a, b, depth, seen) { var output = this.output.clone(); var that = this; depth = typeof depth === 'number' ? depth : 100; if (depth <= 0) { // detect recursive loops in the structure seen = seen || []; if (seen.indexOf(a) !== -1) { throw new Error('Cannot compare circular structures'); } seen.push(a); } return this.findCommonType(a, b).diff(a, b, output, function (actual, expected) { return that.diff(actual, expected, depth - 1, seen); }, function (v, depth) { return that.inspect(v, depth || Infinity); }, function (actual, expected) { return that.equal(actual, expected); }); }; Unexpected.prototype.toString = function () { var assertions = this.assertions; var types = {}; Object.keys(assertions).forEach(function (typeName) { types[typeName] = {}; Object.keys(assertions[typeName]).forEach(function (expandedPattern) { types[typeName][expandedPattern] = true; }); }, this); var pen = magicpen(); Object.keys(types).sort().forEach(function (type) { var assertionsForType = Object.keys(types[type]).sort(); if (assertionsForType.length > 0) { pen.text(type + ':').nl(); pen.indentLines(); assertionsForType.forEach(function (assertion) { pen.i().text(assertion).nl(); }); pen.outdentLines(); } }); return pen.toString(); }; Unexpected.prototype.clone = function () { var clonedAssertions = {}; Object.keys(this.assertions).forEach(function (typeName) { clonedAssertions[typeName] = extend({}, this.assertions[typeName]); }, this); var unexpected = new Unexpected({ assertions: clonedAssertions, types: [].concat(this.types), typeByName: extend({}, this.typeByName), output: this.output.clone(), format: this.outputFormat(), installedPlugins: [].concat(this.installedPlugins) }); return makeExpectFunction(unexpected); }; Unexpected.prototype.outputFormat = function (format) { if (typeof format === 'undefined') { return this._outputFormat; } else { this._outputFormat = format; return this; } }; Unexpected.create = function () { var unexpected = new Unexpected(); return makeExpectFunction(unexpected); }; var expandPattern = (function () { function isFlag(token) { return token.slice(0, 1) === '[' && token.slice(-1) === ']'; } function isAlternation(token) { return token.slice(0, 1) === '(' && token.slice(-1) === ')'; } function removeEmptyStrings(texts) { return texts.filter(function (text) { return text !== ''; }); } function createPermutations(tokens, index) { if (index === tokens.length) { return [{ text: '', flags: {}, alternations: [] }]; } var token = tokens[index]; var tail = createPermutations(tokens, index + 1); if (isFlag(token)) { var flag = token.slice(1, -1); return tail.map(function (pattern) { var flags = {}; flags[flag] = true; return { text: flag + ' ' + pattern.text, flags: extend(flags, pattern.flags), alternations: pattern.alternations }; }).concat(tail.map(function (pattern) { var flags = {}; flags[flag] = false; return { text: pattern.text, flags: extend(flags, pattern.flags), alternations: pattern.alternations }; })); } else if (isAlternation(token)) { return token .substr(1, token.length - 2) // Remove parentheses .split(/\|/) .reduce(function (result, alternation) { return result.concat(tail.map(function (pattern) { return { text: alternation + pattern.text, flags: pattern.flags, alternations: [alternation].concat(pattern.alternations) }; })); }, []); } else { return tail.map(function (pattern) { return { text: token + pattern.text, flags: pattern.flags, alternations: pattern.alternations }; }); } } return function (pattern) { pattern = pattern.replace(/(\[[^\]]+\]) ?/g, '$1'); var splitRegex = /\[[^\]]+\]|\([^\)]+\)/g; var tokens = []; var m; var lastIndex = 0; while ((m = splitRegex.exec(pattern))) { tokens.push(pattern.slice(lastIndex, m.index)); tokens.push(pattern.slice(m.index, splitRegex.lastIndex)); lastIndex = splitRegex.lastIndex; } tokens.push(pattern.slice(lastIndex)); tokens = removeEmptyStrings(tokens); var permutations = createPermutations(tokens, 0); permutations.forEach(function (permutation) { permutation.text = permutation.text.trim(); if (permutation.text === '') { // This can only happen if the pattern only contains flags throw new Error("Assertion patterns must not only contain flags"); } }); return permutations; }; }()); function ensureValidUseOfParenthesesOrBrackets(pattern) { var counts = { '[': 0, ']': 0, '(': 0, ')': 0 }; for (var i = 0; i < pattern.length; i += 1) { var c = pattern.charAt(i); if (c in counts) { counts[c] += 1; } if (c === ']' && counts['['] >= counts[']']) { if (counts['['] === counts[']'] + 1) { throw new Error("Assertion patterns must not contain flags with brackets: '" + pattern + "'"); } if (counts['('] !== counts[')']) { throw new Error("Assertion patterns must not contain flags with parentheses: '" + pattern + "'"); } if (pattern.charAt(i - 1) === '[') { throw new Error("Assertion patterns must not contain empty flags: '" + pattern + "'"); } } else if (c === ')' && counts['('] >= counts[')']) { if (counts['('] === counts[')'] + 1) { throw new Error("Assertion patterns must not contain alternations with parentheses: '" + pattern + "'"); } if (counts['['] !== counts[']']) { throw new Error("Assertion patterns must not contain alternations with brackets: '" + pattern + "'"); } } } if (counts['['] !== counts[']']) { throw new Error("Assertion patterns must not contain unbalanced brackets: '" + pattern + "'"); } if (counts['('] !== counts[')']) { throw new Error("Assertion patterns must not contain unbalanced parentheses: '" + pattern + "'"); } } function ensureValidPattern(pattern) { if (typeof pattern !== 'string' || pattern === '') { throw new Error("Assertion patterns must be a non-empty string"); } if (/^\(?<[a-z.-]+>/.test(pattern)) { throw new Error("Assertion patterns cannot use type signature syntax (reserved for future expansion), ^\\(?<[a-z.-]+>"); } if (pattern.match(/^\s|\s$/)) { throw new Error("Assertion patterns can't start or end with whitespace"); } ensureValidUseOfParenthesesOrBrackets(pattern); } module.exports = Unexpected; },{}],3:[function(require,module,exports){ var utils = require(13); var errorMethodBlacklist = ['message', 'line', 'sourceId', 'sourceURL', 'stack', 'stackArray'].reduce(function (result, prop) { result[prop] = true; return result; }, {}); function UnexpectedError(expect, assertion, parent) { this.errorMode = (assertion && assertion.errorMode) || 'default'; var base = Error.call(this, ''); if (Error.captureStackTrace) { Error.captureStackTrace(this, UnexpectedError); } else { // Throw the error to make sure it has its stack serialized: try { throw base; } catch (err) {} this.stack = base.stack; } this.expect = expect; this.assertion = assertion || null; this.parent = parent || null; this.name = 'UnexpectedError'; } UnexpectedError.prototype = Object.create(Error.prototype); UnexpectedError.prototype._isUnexpected = true; UnexpectedError.prototype.isUnexpected = true; UnexpectedError.prototype.buildDiff = function () { var expect = this.expect; return this.createDiff && this.createDiff(expect.output.clone(), function (actual, expected) { return expect.diff(actual, expected); }, function (v, depth) { return expect.inspect(v, depth || Infinity); }, function (actual, expected) { return expect.equal(actual, expected); }); }; UnexpectedError.prototype.getDefaultErrorMessage = function (options) { var message = this.expect.output.clone(); if (this.assertion) { message.append(this.assertion.standardErrorMessage(options)); } else { message.append(this.output); } var errorWithDiff = this; while (!errorWithDiff.createDiff && errorWithDiff.parent) { errorWithDiff = errorWithDiff.parent; } if (errorWithDiff && errorWithDiff.createDiff) { var comparison = errorWithDiff.buildDiff(); if (comparison) { message.nl(2).append(comparison.diff); } } return message; }; UnexpectedError.prototype.getNestedErrorMessage = function (options) { var message = this.expect.output.clone(); if (this.assertion) { message.append(this.assertion.standardErrorMessage(options)); } else { message.append(this.output); } var parent = this.parent; while (parent.getErrorMode() === 'bubble') { parent = parent.parent; } message.nl() .indentLines() .i().block(parent.getErrorMessage(utils.extend({}, options || {}, { compact: this.assertion && parent.assertion && this.assertion.subject === parent.assertion.subject }))); return message; }; UnexpectedError.prototype.getDiffMethod = function () { var errorWithDiff = this; while (!errorWithDiff.createDiff && errorWithDiff.parent) { errorWithDiff = errorWithDiff.parent; } return errorWithDiff && errorWithDiff.createDiff || null; }; UnexpectedError.prototype.getDiff = function () { var errorWithDiff = this; while (!errorWithDiff.createDiff && errorWithDiff.parent) { errorWithDiff = errorWithDiff.parent; } if (errorWithDiff) { var diffResult = errorWithDiff.buildDiff(); if (diffResult && diffResult.diff) { return diffResult; } else { return null; } } else { return null; } }; UnexpectedError.prototype.getDiffMessage = function () { var message = this.expect.output.clone(); var comparison = this.getDiff(); if (comparison) { message.append(comparison.diff); } else if (this.assertion) { message.append(this.assertion.standardErrorMessage()); } else { message.append(this.output); } return message; }; UnexpectedError.prototype.getErrorMode = function () { if (!this.parent) { switch (this.errorMode) { case 'default': case 'bubbleThrough': return this.errorMode; default: return 'default'; } } else { return this.errorMode; } }; UnexpectedError.prototype.getErrorMessage = function (options) { // Search for any parent error that has mode bubble through on the // error these should be bubbled to the top var errorWithBubbleThough = this.parent; while (errorWithBubbleThough && errorWithBubbleThough.getErrorMode() !== 'bubbleThrough') { errorWithBubbleThough = errorWithBubbleThough.parent; } if (errorWithBubbleThough) { return errorWithBubbleThough.getErrorMessage(); } var errorMode = this.getErrorMode(); switch (errorMode) { case 'nested': return this.getNestedErrorMessage(options); case 'default': return this.getDefaultErrorMessage(options); case 'bubbleThrough': return this.getDefaultErrorMessage(); case 'bubble': return this.parent.getErrorMessage(options); case 'diff': return this.getDiffMessage(); default: throw new Error("Unknown error mode: '" + errorMode + "'"); } }; UnexpectedError.prototype.serializeMessage = function (outputFormat) { if (!this._hasSerializedErrorMessage) { var message = this.getErrorMessage(); if (outputFormat === 'html') { outputFormat = 'text'; this.htmlMessage = message.toString('html'); } this.message = '\n' + message.toString(outputFormat); this._hasSerializedErrorMessage = true; } }; UnexpectedError.prototype.clone = function () { var that = this; var newError = new UnexpectedError(this.expect); Object.keys(that).forEach(function (key) { if (!errorMethodBlacklist[key]) { newError[key] = that[key]; } }); return newError; }; UnexpectedError.prototype.getLabel = function () { var currentError = this; while (currentError && !currentError.label) { currentError = currentError.parent; } return (currentError && currentError.label) || null; }; UnexpectedError.prototype.getParents = function () { var result = []; var parent = this.parent; while (parent) { result.push(parent); parent = parent.parent; } return result; }; UnexpectedError.prototype.getAllErrors = function () { var result = this.getParents(); result.unshift(this); return result; }; module.exports = UnexpectedError; },{}],4:[function(require,module,exports){ (function (Buffer){ var ansiRegex = require(16)(); var utils = require(13); var objectIs = utils.objectIs; var isRegExp = utils.isRegExp; var isArray = utils.isArray; var extend = utils.extend; module.exports = function (expect) { expect.addAssertion('[not] to be (ok|truthy)', function (expect, subject) { var not = !!this.flags.not; var condition = !!subject; if (condition === not) { expect.fail(); } }); expect.addAssertion('[not] to be', function (expect, subject, value) { expect(objectIs(subject, value), '[not] to be truthy'); }); expect.addAssertion('string', '[not] to be', function (expect, subject, value) { expect(subject, '[not] to equal', value); }); expect.addAssertion('boolean', '[not] to be true', function (expect, subject) { expect(subject, '[not] to be', true); }); expect.addAssertion('boolean', '[not] to be false', function (expect, subject) { expect(subject, '[not] to be', false); }); expect.addAssertion('[not] to be falsy', function (expect, subject) { expect(subject, '[!not] to be truthy'); }); expect.addAssertion('[not] to be null', function (expect, subject) { expect(subject, '[not] to be', null); }); expect.addAssertion('[not] to be undefined', function (expect, subject) { expect(typeof subject === 'undefined', '[not] to be truthy'); }); expect.addAssertion('to be defined', function (expect, subject) { expect(subject, 'not to be undefined'); }); expect.addAssertion(['number', 'NaN'], '[not] to be NaN', function (expect, subject) { expect(isNaN(subject), '[not] to be truthy'); }); expect.addAssertion('number', '[not] to be close to', function (expect, subject, value, epsilon) { this.errorMode = 'bubble'; if (typeof epsilon !== 'number') { epsilon = 1e-9; } var testDescription = this.testDescription; expect.withError(function () { expect(Math.abs(subject - value), '[not] to be less than or equal to', epsilon); }, function (e) { expect.fail(function (output) { output.error('expected ') .append(expect.inspect(subject)).sp() .error(testDescription).sp() .append(expect.inspect(va