Code coverage report for lib/Unexpected.js

Statements: 95.93% (519 / 541)      Branches: 92.24% (226 / 245)      Functions: 95.33% (102 / 107)      Lines: 95.93% (519 / 541)      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 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933  1 1 1 1 1 1 1   1     257             55     1565 1565 1565       1565 445 1120 602   518         1 111 111 111 111 111 111 111     1 1 75 75 147 17   130     75     1 85 85 122 122 122 122 118 118 118   39 1   38 38       121       1 28 28 31   28 33 5 2   3   5     33 47 14     47 33 18     33 33 33 20 20 3         14 14 14 12   2     14 14 14 14 14 2               1 75   1 75 85     74 82 115       74 28 28       75 75 75 75 23 23 23   75 10 10 10   75     1 42     1 3239   3239 3239   2 2 1   1     3238 1147       1 15601 15601 183663 188378         1 3327 3327 3327 5191 5191 18     5173 5173 7     5166 1864 1864 1864 1775   1864       3327 3327     1 1 1 682 264   418 418 54   364 364 364 364 364 386 386 11 11 10 10 4   6     1       375         418 418 418 418 18   418               1 128     128 77 77 77   51   51 60 60 60                 128 128 128 137 137 137     137 137 150 132 298 5 2     293 293                   107     1           1 53 53 53 1     52 52   52 31 561     31       21     52 52 52       52 1             52 5     52 52   52 5489     5489     52 3 27   3   49     52     1 4     1 3     1 13 4     13 2     11       1               10 5 5 8 2       5 1 4 2           7 7   7     1 1268 1268 1268 1268     1 537 126   55   5       1 1268 1268   24 24     24 24 5     24 24 24 24   1177   67                                 1 111 111 111 111 111 111 111 111 111 111 111 111 111 111 111 111 111 111     1 111 111 111     1 493 493 493   493 492 140   492   492       492 492 492       1 1 5342 5342 2   5340 1   5339 5339 5339 5339   5142 5142   5339 5309   5309 4400 1867 1867       4400 4400 4400   1270 1268 1268 1268 448   1267   2   4400       5309 3787 3787 2840     3787 3787 1634   3787 3787         5309 5309 5309 5309 5309 5309 5309 5309 613 613 613     5309 5309   5309 5309 5309   5309 5309 5309   1005 1005 994   1005     30 30 826   30 21     21 13   8     8 16 8   16       9 9 9 259 259 27 27   259 2000             9 10195   9     30 30 30 30 30 27   30       1 1214 1214   1214 1214   4 4 1   3     1213 1087   1233   1374       1 6 6 6 162 162 1322         6 6 162 162 72 72   72 1322     72       6     1 110 110 3016   110               110     1 603 603             1 1 1     1 1 248   1 177   1 132 332     1 380 132     248 248 248 71 71 108 108 108           108 108 108           177 29       88 94               148 234               1 132 132 132 132 132 132 100 100 100   132 132 132 132 303 303   1     131         1 145           145 3415 3415 230   3415 76 2     74 2     72 1   3339 33 2     31 2         136 2     134 2       1 150 2   148 3     145     1  
/*global setTimeout*/
var Assertion = require('./Assertion');
var utils = require('./utils');
var magicpen = require('magicpen');
var truncateStack = utils.truncateStack;
var extend = utils.extend;
var leven = require('leven');
var cloneError = utils.cloneError;
 
var anyType = {
    name: 'any',
    identify: function () {
        return true;
    },
    equal: utils.objectIs,
    inspect: function (value, depth, output) {
        return output.text(value);
    },
    diff: function (actual, expected, output, diff, inspect) {
        return null;
    },
    is: function (typeOrTypeName) {
        var typeName;
        Eif (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) {
    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 || [];
}
 
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) {
    var failedGroup = false;
    return orGroup.map(function (expectation) {
        var args = Array.prototype.slice.call(expectation);
        args.unshift(subject);
        var evaluation = { expectation: args };
        if (!failedGroup) {
            evaluation.evaluated = true;
            try {
                expect.apply(expect, args);
            } catch (e) {
                if (!e._isUnexpected) {
                    throw e;
                }
                failedGroup = true;
                evaluation.failure = e;
            }
        }
 
        return evaluation;
    });
}
 
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();
        }
 
        groupEvaluation.forEach(function (evaluation, j) {
            if (j > 0) {
                output.jsComment(' and').nl();
            }
 
            if (evaluation.failure) {
                if (hasAndClauses || hasOrClauses) {
                    output.error('⨯ ');
                }
 
                output.block(function (output) {
                    output.append(evaluation.failure.output);
                    if (!evaluation.failure._hasSerializedErrorMessage) {
                        var comparison = buildDiff(expect, evaluation.failure);
                        if (comparison) {
                            output.nl(2).append(comparison.diff);
                        }
                    }
                });
            } else {
                var style = evaluation.evaluated ? 'success' : 'text';
                var expectation = evaluation.expectation;
                if (evaluation.evaluated) {
                    output.success('✓ ');
                } else {
                    output.sp(2);
                }
 
                output.block(function (output) {
                    output[style]('expected ');
                    output.text(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 = orGroups.map(function (orGroup) {
            return evaluateGroup(expect, subject, orGroup);
        });
 
        var failed = groupEvaluations.every(function (groupEvaluation) {
            return groupEvaluation.some(function (evaluation) {
                return evaluation.failure;
            });
        });
 
        if (failed) {
            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 : 500;
    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.findTypeOf(actual, expected).equal(actual, expected, function (a, b) {
        return that.equal(a, b, depth - 1, seen);
    });
};
 
Unexpected.prototype.findTypeOf = function () { // ...
    var objs = Array.prototype.slice.call(arguments);
    return utils.findFirst(this.types || [], function (type) {
        return objs.every(function (obj) {
            return type.identify(obj);
        });
    });
};
 
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 (utils.isError(arg)) {
        throw arg;
    }
    var output = this.output.clone();
    if (typeof arg === 'function') {
        arg.call(this, output);
    } else {
        var that = this;
        var message = arg ? String(arg) : 'Explicit failure';
        var args = 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 args) {
                    var placeholderArg = args[index];
                    if (placeholderArg.isMagicPen) {
                        output.append(placeholderArg);
                    } else {
                        output.append(that.inspect(placeholderArg));
                    }
                } else {
                    output.text(match[0]);
                }
 
            } else {
                output.error(token);
            }
        });
    }
 
    var error = new Error();
    error._isUnexpected = true;
    error.output = output;
    if (nestingLevel === 0) {
        this.setErrorMessage(error);
    }
    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) {
    Iif (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) {
            Eif (typeof type === 'string') {
                Eif (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];
        Iif (!assertionsForType) {
            throw new Error('No such type: ' + typeName);
        }
        var isSeenByExpandedPattern = {};
        patterns.forEach(function (pattern) {
            ensureValidPattern(pattern);
            expandPattern(pattern).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: expandedPattern.flags,
                        alternations: expandedPattern.alternations
                    };
                }
            });
        });
    });
 
    return this.expect; // for chaining
};
 
Unexpected.prototype.getType = function (typeName) {
    return utils.findFirst(this.typeNames, function (type) {
        return type.name === typeName;
    });
};
 
Unexpected.prototype.addType = function (type) {
    var that = this;
    var baseType;
    if (typeof type.name !== 'string' || type.name.trim() === '') {
        throw new Error('A type must be given a non-empty name');
    }
 
    this.assertions[type.name] = {};
    this.typeByName[type.name] = type;
 
    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;
    }
 
    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 () {
        Iif (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.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 errorWithMessage(e, message) {
    delete e._hasSerializedErrorMessage;
    var newError = cloneError(e);
    newError.output = message;
    return newError;
}
 
function buildDiff(expect, err) {
    return err.createDiff && err.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);
    });
}
 
function handleNestedExpects(expect, e, assertion) {
    var errorMode = e.errorMode || assertion.errorMode;
    switch (errorMode) {
    case 'nested':
        var comparison = buildDiff(expect, e);
        var message = assertion.standardErrorMessage().nl()
            .indentLines()
            .i().block(function (output) {
                output.append(e.output);
                if (comparison) {
                    output.nl(2).append(comparison.diff);
                }
            });
        var newError = errorWithMessage(e, message);
        delete newError.createDiff;
        delete newError.label;
        return newError;
    case 'default':
        return errorWithMessage(e, assertion.standardErrorMessage());
    case 'bubble':
        return errorWithMessage(e, e.output);
    case 'diff':
        return errorWithMessage(e, e.output.clone().append(function (output) {
            var comparison = buildDiff(expect, e);
            delete e.createDiff;
 
            if (comparison && comparison.diff) {
                output.append(comparison.diff);
            } else {
                output.append(e.output);
            }
        }));
    default:
        throw new Error("Unknown error mode: '" + assertion.errorMode + "'");
    }
}
 
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.bind(unexpected);
    expect.fail = unexpected.fail.bind(unexpected);
    expect.diff = unexpected.diff.bind(unexpected);
    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.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) {
    Eif (!err._hasSerializedErrorMessage) {
        var outputFormat = this.outputFormat();
        var message = err.output.clone().append(err.output);
 
        var comparison = buildDiff(this.expect, err);
        if (comparison) {
            message.nl(2).append(comparison.diff);
        }
        delete err.createDiff;
 
        Iif (outputFormat === 'html') {
            outputFormat = 'text';
            err.htmlMessage = message.toString('html');
        }
        err.output = message;
        err.message = '\n' + message.toString(outputFormat);
        err._hasSerializedErrorMessage = true;
    }
};
 
var nestingLevel = 0;
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.');
    }
    if (typeof testDescriptionString !== 'string') {
        throw new Error('The expect function requires the second parameter to be a string.');
    }
    var matchingType = this.findTypeOf(subject);
    var typeWithAssertion = matchingType;
    var assertionRule = this.assertions[typeWithAssertion.name][testDescriptionString];
    while (!assertionRule && typeWithAssertion.name !== anyType.name) {
        // FIXME: Detect cycles?
        typeWithAssertion = typeWithAssertion.baseType;
        assertionRule = this.assertions[typeWithAssertion.name][testDescriptionString];
    }
    if (assertionRule) {
        var flags = extend({}, assertionRule.flags);
 
        var callInNestedContext = function (callback) {
            if (nestingLevel === 0) {
                setTimeout(function () {
                    nestingLevel = 0;
                }, 0);
            }
 
            nestingLevel += 1;
            try {
                callback();
            } catch (e) {
                if (e._isUnexpected) {
                    truncateStack(e, wrappedExpect);
                    var wrappedError = handleNestedExpects(wrappedExpect, e, assertion);
                    if (nestingLevel === 1) {
                        that.setErrorMessage(wrappedError);
                    }
                    throw wrappedError;
                }
                throw e;
            } finally {
                nestingLevel -= 1;
            }
        };
 
        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];
            }
            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.findTypeOf = this.findTypeOf;
        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;
        wrappedExpect.it = this.it.bind(this);
 
        var args = Array.prototype.slice.call(arguments, 2);
        args.unshift(wrappedExpect, subject);
        var assertion = new Assertion(wrappedExpect, subject, testDescriptionString,
                                      flags, assertionRule.alternations, args.slice(2));
        var handler = assertionRule.handler;
        try {
            handler.apply(assertion, args);
        } catch (e) {
            var err = e;
            if (err._isUnexpected) {
                truncateStack(err, this.expect);
            }
            throw err;
        }
    } else {
        var errorMessage = this.output.clone();
        var definedForIncompatibleTypes = this.types.filter(function (type) {
            return this.assertions[type.name][testDescriptionString];
        }, this);
        if (definedForIncompatibleTypes.length > 0) {
            errorMessage.error('The assertion "').jsString(testDescriptionString)
                .error('" is not defined for the type "').jsString(matchingType.name).error('",').nl()
                .error('but it is defined for ');
            if (definedForIncompatibleTypes.length === 1) {
                errorMessage.error('the type "').jsString(definedForIncompatibleTypes[0].name).error('"');
            } else {
                errorMessage.error('these types: ');
 
 
                definedForIncompatibleTypes.forEach(function (incompatibleType, index) {
                    if (index > 0) {
                        errorMessage.error(', ');
                    }
                    errorMessage.error('"').jsString(incompatibleType.name).error('"');
                });
            }
        } else {
            var assertionsWithScore = [];
            var bonusForNextMatchingType = 0;
            [].concat(this.types).reverse().forEach(function (type) {
                var typeMatchBonus = 0;
                if (type.identify(subject)) {
                    typeMatchBonus = bonusForNextMatchingType;
                    bonusForNextMatchingType += 0.9;
                }
                Object.keys(this.assertions[type.name]).forEach(function (assertion) {
                    assertionsWithScore.push({
                        type: type,
                        assertion: assertion,
                        score: typeMatchBonus - leven(testDescriptionString, assertion)
                    });
                });
            }, this);
            assertionsWithScore.sort(function (a, b) {
                return b.score - a.score;
            });
            errorMessage.error('Unknown assertion "').jsString(testDescriptionString)
                .error('", did you mean: "').jsString(assertionsWithScore[0].assertion).error('"');
        }
        var missingAssertionError = new Error();
        missingAssertionError.output = errorMessage;
        missingAssertionError._isUnexpected = true;
        missingAssertionError.errorMode = 'bubble';
        if (nestingLevel === 0) {
            this.setErrorMessage(missingAssertionError);
        }
        this.fail(missingAssertionError);
    }
};
 
Unexpected.prototype.diff = function (a, b, depth, seen) {
    var output = this.output.clone();
    var that = this;
 
    depth = typeof depth === 'number' ? depth : 500;
    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.findTypeOf(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) {
    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 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 (pattern.match(/^\s|\s$/)) {
        throw new Error("Assertion patterns can't start or end with whitespace");
    }
 
    ensureValidUseOfParenthesesOrBrackets(pattern);
}
 
module.exports = Unexpected;