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 | 1 1 1 1 1 1 1 1 252 930 3 47 1265 1265 1265 1265 419 846 475 371 1 55 55 55 55 55 55 55 1 1 57 57 109 13 96 57 1 74 74 102 102 102 102 100 100 100 34 1 33 33 101 1 25 25 28 25 30 5 2 3 5 30 42 12 42 30 16 30 30 30 17 17 2 12 12 12 10 2 12 12 12 12 12 2 1 57 1 66 74 65 71 97 65 25 25 57 57 57 57 15 15 15 57 8 8 8 57 1 34 1 1599 1599 1599 2 2 1 1 1598 610 1 11489 11489 123615 125642 1 2147 2147 2147 3767 3767 18 3749 3749 3 3746 1620 1620 1620 1594 1620 2147 2147 1 1 1 637 245 392 392 50 342 342 342 342 360 360 9 9 9 4 5 351 392 392 392 392 14 392 1 118 118 74 74 74 44 44 54 54 54 118 118 118 128 128 128 128 128 139 121 349 5 2 344 344 97 1 1 47 47 47 1 46 46 46 25 414 25 21 46 46 46 46 46 6 46 46 46 4048 4048 46 3 24 3 43 46 1 1 12 4 12 2 10 1 9 5 5 8 2 5 1 4 2 6 6 6 1 1194 1194 1194 1194 1 506 115 51 5 1 1194 1194 23 23 23 23 4 23 23 23 23 1105 66 1 55 55 55 55 55 55 55 55 55 55 55 55 55 55 55 55 55 1 55 55 55 1 466 466 466 466 466 130 466 466 466 466 466 1 1 5357 5357 2 5355 1 5354 5354 5354 5354 4946 4946 5354 5325 5325 4364 1980 1980 4364 4364 4364 1196 1194 1194 1194 426 1194 2 4364 5325 3787 3787 2884 3787 3787 1534 3787 3787 5325 5325 5325 5325 5325 5325 5325 5325 577 577 577 5325 5325 5325 5325 5325 5325 5325 5325 948 948 938 948 29 29 795 29 21 21 13 8 8 16 8 16 8 8 8 228 228 25 25 228 2255 8 11147 8 29 29 29 29 29 26 29 1 185 185 185 70 190 315 1 21 21 21 567 567 5839 21 21 567 567 252 252 252 5839 252 21 1 54 54 1458 54 54 1 520 520 1 1 1 1 1 241 1 169 1 121 323 1 362 121 241 241 241 72 72 133 133 133 133 133 133 169 29 81 174 140 333 1 121 121 121 121 121 121 101 101 101 121 121 121 121 354 354 1 120 1 134 134 3087 3087 232 3087 77 2 75 2 73 1 3010 33 2 31 2 125 2 123 2 1 139 2 137 3 134 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: function (a, b) { return a === b; }, 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.comment('or').nl(); } groupEvaluation.forEach(function (evaluation, j) { if (j > 0) { output.comment(' 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 = 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); } 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 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]; 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; 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.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.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 "').strings(testDescriptionString) .error('" is not defined for the type "').strings(matchingType.name).error('",').nl() .error('but it is defined for '); if (definedForIncompatibleTypes.length === 1) { errorMessage.error('the type "').strings(definedForIncompatibleTypes[0].name).error('"'); } else { errorMessage.error('these types: '); definedForIncompatibleTypes.forEach(function (incompatibleType, index) { if (index > 0) { errorMessage.error(', '); } errorMessage.error('"').strings(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 "').strings(testDescriptionString) .error('", did you mean: "').strings(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) { var output = this.output.clone(); var that = this; return this.findTypeOf(a, b).diff(a, b, output, function (actual, expected) { return that.diff(actual, expected); }, 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; |