Code coverage report for lib/Unexpected.js

Statements: 96.94% (317 / 327)      Branches: 92.16% (141 / 153)      Functions: 96.72% (59 / 61)      Lines: 96.94% (317 / 327)      Ignored: none     

All files » lib/ » Unexpected.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 5561 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1   1     38     262     555     7       1 23 23 23 23 23     1 827   827 827   2 2 1   1     826 9723     826 826 558             1 746 746 746 1157 2     1155 1155 3     1152 6927     1152 1152 411 411             746     1 1 1 56 34   22 22 13   9 9 9 9 47 47 19 19 19 7   12     28         22 22 22 22     1 4 4 823 823         4 4034   4 20       1 96 96 96 96 96 103 81 242 5 2     237 237               71     1           1 19 19 1     18 1 2     1       17     18   18     1 5 1     4   4     1 334 334 334     1 363   8       326   29           1 23 23 23 23 23 23 23 23 23 23 23 23 23 23     1 23 23 23     1 363 363   363 363 363       25 25 25     363 363   363       363 363       1 3592 3592 2   3590 1   3589 3589 3585   3585 3585 2985 2985 2985 2618   367 367 364 364 363 363 363     4       3585 2934 2386     2934 2934 2934         3585 3585 3585 3585 3585 3585 3585 51 51 51     3585   3585 3585 3585 3585 3585 3585   446 429   446     4 4     4 4 4       1 50 50 50 495     50 50 25   25         1 6     1 22           22     1 385 385             1 1 1     1 1 199   1 141   1 110 383     1 280 81     199 199 199 58 58 97 97 97         97 97 97         141 29 29 29 70 126             112 236             1 81 81 81 81 81 81 87 87 87   81   81 81 81 247 247   1     80         1 98           98 2276 2276 210   2276 63 2     61 2     59 1   2213 35 2     33 2       2267 75 4         85 2     83 2       1 103 2   101 3     98     1  
var Assertion = require('./Assertion');
var shim = require('./shim');
var utils = require('./utils');
var magicpen = require('magicpen');
var bind = shim.bind;
var forEach = shim.forEach;
var filter = shim.filter;
var map = shim.map;
var trim = shim.trim;
var reduce = shim.reduce;
var getKeys = shim.getKeys;
var indexOf = shim.indexOf;
var truncateStack = utils.truncateStack;
var extend = utils.extend;
var levenshteinDistance = utils.levenshteinDistance;
var isArray = utils.isArray;
var cloneError = utils.cloneError;
 
var anyType = {
    name: 'any',
    identify: function () {
        return true;
    },
    equal: function (a, b) {
        return a === b;
    },
    inspect: function (output, value) {
        return output.text(value);
    },
    diff: function (actual, expected, output, diff, inspect) {
        return null;
    }
};
 
function Unexpected(options) {
    options = options || {};
    this.assertions = options.assertions || {};
    this.types = options.types || [anyType];
    this.output = options.output || magicpen();
    this._outputFormat = options.format || magicpen.defaultFormat;
}
 
Unexpected.prototype.equal = function (actual, expected, depth, seen) {
    var that = this;
 
    depth = depth || 0;
    if (depth > 500) {
        // detect recursive loops in the structure
        seen = seen || [];
        if (seen.indexOf(actual) !== -1) {
            throw new Error('Cannot compare circular structures');
        }
        seen.push(actual);
    }
 
    var matchingCustomType = utils.findFirst(this.types || [], function (type) {
        return type.identify(actual) && type.identify(expected);
    });
 
    Eif (matchingCustomType) {
        return matchingCustomType.equal(actual, expected, function (a, b) {
            return that.equal(a, b, depth + 1, seen);
        });
    }
 
    return false; // we should never get there
};
 
Unexpected.prototype.inspect = function (obj, depth) {
    var types = this.types;
    var seen = [];
    var printOutput = function (output, obj, depth) {
        if (depth === 0 && typeof obj === 'object') {
            return output.text('...');
        }
 
        seen = seen || [];
        if (indexOf(seen, obj) !== -1) {
            return output.text('[Circular]');
        }
 
        var matchingCustomType = utils.findFirst(types || [], function (type) {
            return type.identify(obj);
        });
 
        Eif (matchingCustomType) {
            return matchingCustomType.inspect(output, obj, function (output, v) {
                seen.push(obj);
                return printOutput(output, v, depth - 1);
            }, depth);
        } else {
            return output;
        }
    };
 
    return printOutput(this.output.clone(), obj, depth || 3);
};
 
var placeholderSplitRegexp = /(\{(?:\d+)\})/g;
var placeholderRegexp = /\{(\d+)\}/;
Unexpected.prototype.fail = function (arg) {
    if (utils.isError(arg)) {
        throw arg;
    }
    var output = this.output.clone();
    if (typeof arg === 'function') {
        arg.call(this, output);
    } else {
        var message = arg || "explicit failure";
        var args = Array.prototype.slice.call(arguments, 1);
        var tokens = message.split(placeholderSplitRegexp);
        forEach(tokens, function (token) {
            var match = placeholderRegexp.exec(token);
            if (match) {
                var index = match[1];
                var placeholderArg = index in args ?  args[index] : match[0];
                if (placeholderArg.isMagicPen) {
                    output.append(placeholderArg);
                } else {
                    output.text(placeholderArg);
                }
            } else {
                output.text(token);
            }
        });
    }
 
    var error =  new Error();
    error._isUnexpected = true;
    error.output = output;
    throw error;
};
 
Unexpected.prototype.findAssertionSimilarTo = function (text) {
    var editDistrances = [];
    forEach(getKeys(this.assertions), function (assertion) {
        var distance = levenshteinDistance(text, assertion);
        editDistrances.push({
            assertion: assertion,
            distance: distance
        });
    });
    editDistrances.sort(function (x, y) {
        return x.distance - y.distance;
    });
    return map(editDistrances.slice(0, 5), function (editDistrance) {
        return editDistrance.assertion;
    });
};
 
Unexpected.prototype.addAssertion = function () {
    var assertions = this.assertions;
    var patterns = Array.prototype.slice.call(arguments, 0, -1);
    var handler = Array.prototype.slice.call(arguments, -1)[0];
    var isSeenByExpandedPattern = {};
    forEach(patterns, function (pattern) {
        ensureValidPattern(pattern);
        forEach(expandPattern(pattern), function (expandedPattern) {
            if (expandedPattern.text in assertions) {
                if (!isSeenByExpandedPattern[expandedPattern.text]) {
                    throw new Error('Cannot redefine assertion: ' + expandedPattern.text);
                }
            } else {
                isSeenByExpandedPattern[expandedPattern.text] = true;
                assertions[expandedPattern.text] = {
                    handler: handler,
                    flags: expandedPattern.flags
                };
            }
        });
    });
 
    return this.expect; // for chaining
};
 
Unexpected.prototype.getType = function (typeName) {
    return utils.findFirst(this.types, function (type) {
        return type.name === typeName;
    });
};
 
Unexpected.prototype.addType = function (type) {
    var baseType;
    if (typeof type.name !== 'string' || trim(type.name) === '') {
        throw new Error('A custom type must be given a non-empty name');
    }
 
    if (type.base) {
        baseType = utils.findFirst(this.types, function (t) {
            return t.name === type.base;
        });
 
        Iif (!baseType) {
            throw new Error('Unknown base type: ' + type.base);
        }
    } else {
        baseType = anyType;
    }
 
    this.types.unshift(extend({}, baseType, type, { baseType: baseType }));
 
    return this.expect;
};
 
Unexpected.prototype.installPlugin = function (plugin) {
    if (typeof plugin !== 'function') {
        throw new Error('Expected first argument given to installPlugin to be a function');
    }
 
    plugin(this.expect);
 
    return this.expect; // for chaining
};
 
function errorWithMessage(e, message) {
    var newError = cloneError(e);
    newError.output = message;
    return newError;
}
 
function handleNestedExpects(e, assertion) {
    switch (assertion.errorMode) {
    case 'nested':
        return errorWithMessage(e, assertion.standardErrorMessage().nl()
                                .indentLines()
                                .i().block(e.output));
    case 'default':
        return errorWithMessage(e, assertion.standardErrorMessage());
    case 'bubble':
        return e;
    default:
        throw new Error("Unknown error mode: '" + assertion.errorMode + "'");
    }
}
 
function installExpectMethods(unexpected, expectFunction) {
    var expect = bind(expectFunction, unexpected);
    expect.equal = bind(unexpected.equal, unexpected);
    expect.inspect = bind(unexpected.inspect, unexpected);
    expect.fail = bind(unexpected.fail, unexpected);
    expect.diff = bind(unexpected.diff, unexpected);
    expect.addAssertion = bind(unexpected.addAssertion, unexpected);
    expect.addType = bind(unexpected.addType, unexpected);
    expect.clone = bind(unexpected.clone, unexpected);
    expect.toString = bind(unexpected.toString, unexpected);
    expect.assertions = unexpected.assertions;
    expect.installPlugin = bind(unexpected.installPlugin, unexpected);
    expect.output = unexpected.output;
    expect.outputFormat = bind(unexpected.outputFormat, unexpected);
    return expect;
}
 
function makeExpectFunction(unexpected) {
    var expect = installExpectMethods(unexpected, unexpected.expect);
    unexpected.expect = expect;
    return expect;
}
 
Unexpected.prototype.setErrorMessage = function (err) {
    var outputFormat = this.outputFormat();
    var message = err.output.clone().append(err.output);
 
    var actual = err.actual;
    var expected = err.expected;
    if (actual && expected &&
        typeof actual === typeof expected &&
        isArray(actual) === isArray(expected) &&
        (typeof actual === 'object' || typeof actual === 'string')) {
        var comparison = this.diff(actual, expected);
        Eif (comparison) {
            message.nl(2).blue('Diff:').nl(2).append(comparison.diff);
        }
    }
    delete err.actual;
    delete err.expected;
 
    Iif (outputFormat === 'html') {
        outputFormat = 'text';
        err.htmlMessage = message.toString('html');
    }
    err.output = message;
    err.message = '\n' + message.toString(outputFormat);
};
 
 
Unexpected.prototype.expect = function expect(subject, testDescriptionString) {
    var that = this;
    if (arguments.length < 2) {
        throw new Error('The expect functions requires at least two parameters.');
    }
    if (typeof testDescriptionString !== 'string') {
        throw new Error('The expect functions requires second parameter to be a string.');
    }
    var assertionRule = this.assertions[testDescriptionString];
    if (assertionRule) {
        var flags = extend({}, assertionRule.flags);
 
        var nestingLevel = 0;
        var callInNestedContext = function (callback) {
            nestingLevel += 1;
            try {
                callback();
                nestingLevel -= 1;
            } catch (e) {
                nestingLevel -= 1;
                if (e._isUnexpected) {
                    truncateStack(e, wrappedExpect);
                    if (nestingLevel === 0) {
                        var wrappedError = handleNestedExpects(e, assertion);
                        that.setErrorMessage(wrappedError);
                        throw wrappedError;
                    }
                }
                throw e;
            }
        };
 
        var wrappedExpect = function wrappedExpect(subject, testDescriptionString) {
            testDescriptionString = trim(testDescriptionString.replace(/\[(!?)([^\]]+)\] ?/g, function (match, negate, flag) {
                return Boolean(flags[flag]) !== Boolean(negate) ? flag + ' ' : '';
            }));
 
            var args = Array.prototype.slice.call(arguments, 2);
            callInNestedContext(function () {
                that.expect.apply(that, [subject, testDescriptionString].concat(args));
            });
        };
 
        // Not sure this is the right way to go about this:
        wrappedExpect.equal = this.equal;
        wrappedExpect.types = this.types;
        wrappedExpect.inspect = this.inspect;
        wrappedExpect.diff = this.diff;
        wrappedExpect.output = this.output;
        wrappedExpect.outputFormat = this.outputFormat;
        wrappedExpect.fail = function () {
            var args = arguments;
            callInNestedContext(function () {
                that.fail.apply(that, args);
            });
        };
        wrappedExpect.format = this.format;
 
        var args = Array.prototype.slice.call(arguments, 2);
        args.unshift(wrappedExpect, subject);
        var assertion = new Assertion(wrappedExpect, subject, testDescriptionString, flags, args.slice(2));
        var handler = assertionRule.handler;
        try {
            handler.apply(assertion, args);
        } catch (e) {
            if (e._isUnexpected) {
                truncateStack(e, this.expect);
            }
            throw e;
        }
    } else {
        var similarAssertions = this.findAssertionSimilarTo(testDescriptionString);
        var message =
            'Unknown assertion "' + testDescriptionString + '", ' +
            'did you mean: "' + similarAssertions[0] + '"';
        var err = new Error(message);
        truncateStack(err, this.expect);
        throw err;
    }
};
 
Unexpected.prototype.diff = function (a, b) {
    var output = this.output.clone();
    var that = this;
    var matchingCustomType = utils.findFirst(this.types || [], function (type) {
        return type.identify(a) && type.identify(b);
    });
 
    Eif (matchingCustomType) {
        return matchingCustomType.diff(a, b, output, function (actual, expected) {
            return that.diff(actual, expected);
        }, function (v) {
            return that.inspect(v, Infinity);
        });
    }
};
 
Unexpected.prototype.toString = function () {
    return getKeys(this.assertions).sort().join('\n');
};
 
Unexpected.prototype.clone = function () {
    var unexpected = new Unexpected({
        assertions: extend({}, this.assertions),
        types: [].concat(this.types),
        output: this.output.clone(),
        format: this.outputFormat()
    });
    return makeExpectFunction(unexpected);
};
 
Unexpected.prototype.outputFormat = function (format) {
    Eif (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 filter(texts, function (text) {
            return text !== '';
        });
    }
    function createPermutations(tokens, index) {
        if (index === tokens.length) {
            return [{ text: '', flags: {}}];
        }
 
        var token = tokens[index];
        var tail = createPermutations(tokens, index + 1);
        if (isFlag(token)) {
            var flag = token.slice(1, -1);
            return map(tail, function (pattern) {
                var flags = {};
                flags[flag] = true;
                return {
                    text: flag + ' ' + pattern.text,
                    flags: extend(flags, pattern.flags)
                };
            }).concat(map(tail, function (pattern) {
                var flags = {};
                flags[flag] = false;
                return {
                    text: pattern.text,
                    flags: extend(flags, pattern.flags)
                };
            }));
        } else if (isAlternation(token)) {
            var alternations = token.split(/\(|\)|\|/);
            alternations = removeEmptyStrings(alternations);
            return reduce(alternations, function (result, alternation) {
                return result.concat(map(tail, function (pattern) {
                    return {
                        text: alternation + pattern.text,
                        flags: pattern.flags
                    };
                }));
            }, []);
        } else {
            return map(tail, function (pattern) {
                return {
                    text: token + pattern.text,
                    flags: pattern.flags
                };
            });
        }
    }
    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);
        forEach(permutations, function (permutation) {
            permutation.text = trim(permutation.text);
            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 ((c === ')' || c === '|') && counts['('] >= counts[')']) {
            if (pattern.charAt(i - 1) === '(' || pattern.charAt(i - 1) === '|') {
                throw new Error("Assertion patterns must not contain empty alternations: '" + 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 (pattern.match(/^\s|\s$/)) {
        throw new Error("Assertion patterns can't start or end with whitespace");
    }
 
    ensureValidUseOfParenthesesOrBrackets(pattern);
}
 
module.exports = Unexpected;