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 | 1 1 1 1 1 1 1 1 456 604 1328 131 870 870 870 870 324 546 278 268 1 44 44 44 44 44 44 1 1 49 49 98 13 85 49 1 75 75 85 85 85 85 83 83 83 37 1 36 36 84 1 28 28 31 28 33 5 2 3 5 33 42 9 42 33 13 33 9 9 9 7 2 9 9 9 9 2 1 49 1 67 75 66 72 80 66 28 28 49 49 49 49 12 12 12 49 8 8 8 49 1 29 1 1225 1225 1225 2 2 1 1 1224 594 1 8745 8745 85301 87185 1 1872 1872 1872 3217 21 3196 3196 3 3193 1345 1345 1315 1345 1872 1 1 1 502 201 301 301 41 260 260 260 260 300 300 20 20 20 9 11 280 301 301 301 301 301 1 104 104 62 62 62 42 42 51 51 51 104 104 104 113 113 113 113 113 124 106 330 5 2 325 325 83 1 1 45 45 1 44 44 44 25 396 25 19 44 44 44 3405 3405 44 2 16 2 42 44 1 5 1 4 4 1 951 951 951 951 1 1252 252 96 3 1 985 6 6 6 945 34 1 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 44 1 44 44 44 1 1286 1252 1252 1252 1252 221 1252 1252 1252 1252 1 3529 3529 2 3527 1 3526 3526 3526 3526 3400 3400 3526 3503 3503 3045 3045 988 985 985 985 985 3 3503 2577 1953 2577 2577 2577 3503 3503 3503 3503 3503 3503 3503 3503 468 468 468 3503 3503 3503 3503 3503 3503 3503 3503 743 743 732 743 23 23 587 23 15 15 9 6 12 8 8 8 212 212 25 25 212 2191 8 11267 8 23 1 298 298 298 46 134 158 1 12 12 12 300 3250 12 1 43 43 1075 43 43 1 1295 1295 1 1 1 1 1 221 1 153 1 106 300 1 327 106 221 221 221 68 68 129 129 129 129 129 129 153 29 81 174 124 316 1 106 106 106 106 106 106 97 97 97 106 106 106 106 335 335 1 105 1 119 119 2762 2762 224 2762 73 2 71 2 69 1 2689 33 2 31 2 110 2 108 2 1 124 2 122 3 119 1 | /*global window*/ 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; } 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.append(evaluation.failure.output); } else { var style = evaluation.evaluated ? 'success' : 'text'; var expectation = evaluation.expectation; if (evaluation.evaluated) { output.success('✓ '); } else { output.sp(2); } 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) { if (currentDepth === 0 && typeof obj === 'object') { return output.text('...'); } seen = seen || []; if (seen.indexOf(obj) !== -1) { return output.text('[Circular]'); } return that.findTypeOf(obj).inspect(obj, currentDepth, output, function (v, childDepth) { seen.push(obj); if (typeof childDepth === 'undefined') { childDepth = currentDepth - 1; } return printOutput(v, childDepth, output.clone()); }); }; return printOutput(obj, depth || 3, this.output.clone()); }; 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); 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; 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 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 extendedType = extend({}, baseType, type, { baseType: baseType }); 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.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) { 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) { switch (assertion.errorMode) { case 'nested': var newError = errorWithMessage(e, assertion.standardErrorMessage().nl() .indentLines() .i().block(e.output)); delete newError.createDiff; return newError; case 'default': return errorWithMessage(e, assertion.standardErrorMessage()); case 'bubble': return e; 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.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) { if (!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); } Iif (outputFormat === 'html') { outputFormat = typeof window !== 'undefined' && window.mochaPhantomJS ? 'ansi' : 'text'; err.htmlMessage = message.toString('html'); } err.output = message; err.message = '\n' + message.toString(outputFormat); err._hasSerializedErrorMessage = true; } }; 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 !== anyType) { // FIXME: Detect cycles? typeWithAssertion = typeWithAssertion.baseType; assertionRule = this.assertions[typeWithAssertion.name][testDescriptionString]; } if (assertionRule) { var flags = extend({}, assertionRule.flags); var callInNestedContext = function (callback) { try { callback(); } catch (e) { if (e._isUnexpected) { truncateStack(e, wrappedExpect); var wrappedError = handleNestedExpects(wrappedExpect, e, assertion); that.setErrorMessage(wrappedError); throw wrappedError; } throw e; } }; var wrappedExpect = function wrappedExpect(subject, testDescriptionString) { testDescriptionString = testDescriptionString.replace(/\[(!?)([^\]]+)\] ?/g, function (match, negate, flag) { return Boolean(flags[flag]) !== Boolean(negate) ? flag + ' ' : ''; }).trim(); 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.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; var definedForIncompatibleTypes = this.types.filter(function (type) { return this.assertions[type.name][testDescriptionString]; }, this); if (definedForIncompatibleTypes.length > 0) { errorMessage = 'The assertion "' + testDescriptionString + '" is not defined for the type "' + matchingType.name + '", but it is defined for '; if (definedForIncompatibleTypes.length === 1) { errorMessage += 'the type "' + definedForIncompatibleTypes[0].name + '"'; } else { errorMessage += 'these types: ' + definedForIncompatibleTypes.map(function (incompatibleType) { return '"' + incompatibleType.name + '"'; }).join(', '); } } 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 = 'Unknown assertion "' + testDescriptionString + '", ' + 'did you mean: "' + assertionsWithScore[0].assertion + '"'; } throw truncateStack(new Error(errorMessage), this.expect); } }; 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 isSeenByExpandedPattern = {}; Object.keys(assertions).forEach(function (typeName) { Object.keys(assertions[typeName]).forEach(function (expandedPattern) { isSeenByExpandedPattern[expandedPattern] = true; }); }, this); return Object.keys(isSeenByExpandedPattern).sort().join('\n'); }; 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() }); 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; |