Code coverage report for lib/types.js

Statements: 97.95% (430 / 439)      Branches: 92.97% (238 / 256)      Functions: 98.92% (92 / 93)      Lines: 97.94% (428 / 437)      Ignored: none     

All files » lib/ » types.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 9091 1 1 1 1 1   1 1       4     60 60 60     2 2 2 2 2 2 1         1         1 1 1                       1     2738       597 2     595 9     586           586 12     574 574   574 583 4           570 574 574 33     35     615 615 41   574 878 878 878 878 1   878 878     878 878 878 57   821   878 1 877 1     878     574 574 793 793 793     574 878   878 304       574 80   80 196     80   494 494 682 682 682 188     494   574     39 5               34         34 34       34 34 101 101       34   34   34 57 57 57 57 57 57 39 5 5   34 34 28     28 13     6 6       18     57 57 51     57 57 57 57 29   28   57 33         34   34       34       1 98 98   98 31     67 5     62 50     12 1     11 11 11 11 11 25 6     25       1         47 47 129   47     27   27 18 26 15     3   9       217     217     197 197 197 9     188 1     187 187 2610 552   2058       187 187 2587 2587 2587     187 2610 2610 2423       187 4   4 35     4   183 183 2575 2575 2575 2392     183         24         24 1 1     23       23 23 77           23 23     23 147     23 1 34     23 38     23 23 23 15 15 17   15 15     1 34 34 117 117       23   23 38     23 23 11 11 11 14   11 14   11 11 11 11     23 38     23 12 12 13         12     23 23 104 104 31 73 46       23 104     23 77 77   77         54       23 14 14 14 35             14               14 3           14     23 87 35       23   23 87 87 87   87 10 10   77 14 63 35   28 28 3 25 3 3       22 22             23   23       1       2890       1       3     3     2838       1       2925     9       25       25     4         4 4   4       1     2935     8       2       1       3459     1     23 23 23 23 23 23 21 21 21 21   21 14   21 13   21 1   20     2 2 2   23       1       3533     72 72 72 82 1 1     81 1 80 8     81 81 93 12   93   81     72       1       5               50       1     3636             1             15       15   14 153     5     18 18 18   18 43 25   43     43 568 425 425 425 143 131       43 31   12     18     45 45 484 439   484 484   45 31   45 45       10 10 1   9   721     10       1 1             1 3 6   6 6           22325             1     6937     1076             56       56 56       1     9123     1139       1     8731       1     11167     330       1     11348     77       1     11360     16        
var utils = require('./utils');
var isRegExp = utils.isRegExp;
var leftPad = utils.leftPad;
var extend = utils.extend;
var arrayDiff = require('arraydiff');
var leven = require('leven');
 
module.exports = function (expect) {
    expect.addType({
        name: 'wrapperObject',
        identify: false,
        equal: function (a, b, equal) {
            return a === b || equal(this.unwrap(a), this.unwrap(b));
        },
        inspect: function (value, depth, output, inspect) {
            output.append(this.prefix(output.clone()));
            output.append(inspect(this.unwrap(value)));
            output.append(this.suffix(output.clone()));
        },
        diff: function (actual, expected, output, diff, inspect) {
            actual = this.unwrap(actual);
            expected = this.unwrap(expected);
            var comparison = diff(actual, expected);
            var prefixOutput = this.prefix(output.clone());
            var suffixOutput = this.suffix(output.clone());
            if (comparison && comparison.inline) {
                return {
                    inline: true,
                    diff: output.append(prefixOutput).append(comparison.diff).append(suffixOutput)
                };
            } else {
                return {
                    inline: true,
                    diff: output.append(prefixOutput).nl()
                        .indentLines()
                        .i().block(function () {
                            this.append(inspect(actual)).sp().annotationBlock(function () {
                                this.error('should be ').block(inspect(expected));
                                Iif (comparison) {
                                    this.nl().append(comparison.diff);
                                }
                            });
                        }).nl()
                        .outdentLines()
                        .append(suffixOutput)
                };
            }
        }
    });
 
    expect.addType({
        name: 'object',
        identify: function (obj) {
            return obj && (typeof obj === 'object' || typeof obj === 'function');
        },
        getKeys: Object.keys,
        equal: function (a, b, equal) {
            if (a === b) {
                return true;
            }
 
            if (b.constructor !== a.constructor) {
                return false;
            }
 
            var actualKeys = utils.getKeysOfDefinedProperties(a),
                expectedKeys = utils.getKeysOfDefinedProperties(b),
                key,
                i;
 
            // having the same number of owned properties (keys incorporates hasOwnProperty)
            if (actualKeys.length !== expectedKeys.length) {
                return false;
            }
            //the same set of keys (although not necessarily the same order),
            actualKeys.sort();
            expectedKeys.sort();
            //~~~cheap key test
            for (i = actualKeys.length - 1; i >= 0; i -= 1) {
                if (actualKeys[i] !== expectedKeys[i]) {
                    return false;
                }
            }
 
            //equivalent values for every corresponding key, and
            //~~~possibly expensive deep test
            for (i = actualKeys.length - 1; i >= 0; i -= 1) {
                key = actualKeys[i];
                if (!equal(a[key], b[key])) {
                    return false;
                }
            }
            return true;
        },
        inspect: function (obj, depth, output, inspect) {
            var keys = Object.keys(obj);
            if (keys.length === 0) {
                return utils.wrapConstructorNameAroundOutput(output.text('{}'), obj);
            }
            var inspectedItems = keys.map(function (key) {
                var hasGetter = obj.__lookupGetter__ && obj.__lookupGetter__(key);
                var hasSetter = obj.__lookupGetter__ && obj.__lookupSetter__(key);
                var propertyOutput = output.clone();
                if (hasSetter && !hasGetter) {
                    propertyOutput.text('set').sp();
                }
                propertyOutput.key(key);
                propertyOutput.text(':');
 
                // Inspect the setter function if there's no getter:
                var value = (hasSetter && !hasGetter) ? hasSetter : obj[key];
                var inspectedValue = inspect(value);
                if (value && value._expectIt) {
                    propertyOutput.sp().block(inspectedValue);
                } else {
                    propertyOutput.sp().append(inspectedValue);
                }
                if (hasGetter && hasSetter) {
                    propertyOutput.sp().comment('/* getter/setter */');
                } else if (hasGetter) {
                    propertyOutput.sp().comment('/* getter */');
                }
 
                return propertyOutput;
            });
 
            var width = 0;
            var multipleLines = inspectedItems.some(function (o) {
                var size = o.size();
                width += size.width;
                return width > 50 || size.height > 1;
            });
 
            inspectedItems.forEach(function (inspectedItem, index) {
                var lastIndex = index === inspectedItems.length - 1;
 
                if (!lastIndex) {
                    inspectedItem.text(',');
                }
            });
 
            if (multipleLines) {
                output.text('{').nl().indentLines();
 
                inspectedItems.forEach(function (inspectedItem, index) {
                    output.i().block(inspectedItem).nl();
                });
 
                output.outdentLines().text('}');
            } else {
                output.text('{ ');
                inspectedItems.forEach(function (inspectedItem, index) {
                    output.append(inspectedItem);
                    var lastIndex = index === inspectedItems.length - 1;
                    if (!lastIndex) {
                        output.sp();
                    }
                });
                output.text(' }');
            }
            return utils.wrapConstructorNameAroundOutput(output, obj);
        },
        diff: function (actual, expected, output, diff, inspect, equal) {
            if (actual.constructor !== expected.constructor) {
                return {
                    diff: output.text('Mismatching constructors ')
                        .text(actual.constructor && actual.constructor.name || actual.constructor)
                        .text(' should be ').text(expected.constructor && expected.constructor.name || expected.constructor),
                    inline: false
                };
            }
 
            var result = {
                diff: output,
                inline: true
            };
 
            var constructorName = actual.constructor && actual.constructor !== Object && actual.constructor.name;
            Iif (constructorName) {
                output.text(constructorName + '(');
            }
 
            var keyIndex = {};
            Object.keys(actual).concat(Object.keys(expected)).forEach(function (key) {
                Eif (!(key in result)) {
                    keyIndex[key] = key;
                }
            });
 
            var keys = Object.keys(keyIndex);
 
            output.text('{').nl().indentLines();
 
            keys.forEach(function (key, index) {
                output.i().block(function () {
                    var valueOutput;
                    var annotation = output.clone();
                    var conflicting = !equal(actual[key], expected[key]);
                    var isInlineDiff = false;
                    if (conflicting) {
                        if (!(key in expected)) {
                            annotation.error('should be removed');
                            isInlineDiff = true;
                        } else {
                            var keyDiff = diff(actual[key], expected[key]);
                            if (!keyDiff || (keyDiff && !keyDiff.inline)) {
                                annotation.error('should be ')
                                    .block(inspect(expected[key]));
 
                                if (keyDiff) {
                                    annotation.nl().append(keyDiff.diff);
                                }
                            } else {
                                isInlineDiff = true;
                                valueOutput = keyDiff.diff;
                            }
                        }
                    } else {
                        isInlineDiff = true;
                    }
 
                    var last = index === keys.length - 1;
                    if (!valueOutput) {
                        valueOutput = inspect(actual[key], conflicting ? Infinity : 1);
                    }
 
                    this.key(key);
                    this.text(':').sp();
                    valueOutput.text(last ? '' : ',');
                    if (isInlineDiff) {
                        this.append(valueOutput);
                    } else {
                        this.block(valueOutput);
                    }
                    if (!annotation.isEmpty()) {
                        this.sp().annotationBlock(annotation);
                    }
                }).nl();
            });
 
            output.outdentLines().text('}');
 
            Iif (constructorName) {
                output.text(')');
            }
 
            return result;
        }
    });
 
    function structurallySimilar(a, b) {
        var typeA = typeof a;
        var typeB = typeof b;
 
        if (typeA !== typeB) {
            return false;
        }
 
        if (typeA === 'string') {
            return leven(a, b) < a.length / 2;
        }
 
        if (typeA !== 'object' || !a) {
            return false;
        }
 
        if (utils.isArray(a) && utils.isArray(b)) {
            return true;
        }
 
        var aKeys = Object.keys(a);
        var bKeys = Object.keys(b);
        var numberOfSimilarKeys = 0;
        var requiredSimilarKeys = Math.round(Math.max(aKeys.length, bKeys.length) / 2);
        return aKeys.concat(bKeys).some(function (key) {
            if (key in a && key in b) {
                numberOfSimilarKeys += 1;
            }
 
            return numberOfSimilarKeys >= requiredSimilarKeys;
        });
    }
 
    expect.addType({
        name: 'arrayLike',
        base: 'object',
        identify: false,
        getKeys: function (obj) {
            var keys = new Array(obj.length);
            for (var i = 0 ; i < obj.length ; i += 1) {
                keys[i] = i;
            }
            return keys;
        },
        equal: function (a, b, equal) {
            Iif (a === b) {
                return true;
            } else if (a.constructor === b.constructor && a.length === b.length) {
                for (var i = 0; i < a.length; i += 1) {
                    if (!equal(a[i], b[i])) {
                        return false;
                    }
                }
                return true;
            } else {
                return false;
            }
        },
        prefix: function (output) {
            return output.text('[');
        },
        suffix: function (output) {
            return output.text(']');
        },
        inspect: function (arr, depth, output, inspect) {
            var prefixOutput = this.prefix(output.clone(), arr);
            var suffixOutput = this.suffix(output.clone(), arr);
            if (arr.length === 0) {
                return output.append(prefixOutput).append(suffixOutput);
            }
 
            if (depth === 1) {
                return output.append(prefixOutput).text('...').append(suffixOutput);
            }
 
            var inspectedItems = new Array(arr.length);
            for (var i = 0; i < arr.length; i += 1) {
                if (i in arr) {
                    inspectedItems[i] = inspect(arr[i]);
                } else {
                    inspectedItems[i] = output.clone();
                }
            }
 
            var width = 0;
            var multipleLines = inspectedItems.some(function (o) {
                var size = o.size();
                width += size.width;
                return width > 50 || o.height > 1;
            });
 
            inspectedItems.forEach(function (inspectedItem, index) {
                var lastIndex = index === inspectedItems.length - 1;
                if (!lastIndex) {
                    inspectedItem.text(',');
                }
            });
 
            if (multipleLines) {
                output.append(prefixOutput).nl().indentLines();
 
                inspectedItems.forEach(function (inspectedItem, index) {
                    output.i().block(inspectedItem).nl();
                });
 
                output.outdentLines().append(suffixOutput);
            } else {
                output.append(prefixOutput).sp();
                inspectedItems.forEach(function (inspectedItem, index) {
                    output.append(inspectedItem);
                    var lastIndex = index === inspectedItems.length - 1;
                    if (!lastIndex) {
                        output.sp();
                    }
                });
                output.sp().append(suffixOutput);
            }
        },
        diffLimit: 512,
        diff: function (actual, expected, output, diff, inspect, equal) {
            var result = {
                diff: output,
                inline: true
            };
 
            if (Math.max(actual.length, expected.length) > this.diffLimit) {
                result.diff.comment('Diff suppressed due to size > ' + this.diffLimit);
                return result;
            }
 
            Iif (actual.constructor !== expected.constructor) {
                return this.baseType.diff(actual, expected);
            }
 
            var mutatedArray = new Array(actual.length);
            for (var k = 0; k < actual.length; k += 1) {
                mutatedArray[k] = {
                    type: 'similar',
                    value: actual[k]
                };
            }
 
            Eif (mutatedArray.length > 0) {
                mutatedArray[mutatedArray.length - 1].last = true;
            }
 
            var itemsDiff = arrayDiff(actual, expected, function (a, b) {
                return equal(a, b) || structurallySimilar(a, b);
            });
 
            var removeTable = [];
            function offsetIndex(index) {
                return index + (removeTable[index - 1] || 0);
            }
 
            var removes = itemsDiff.filter(function (diffItem) {
                return diffItem.type === 'remove';
            });
 
            var removesByIndex = {};
            var removedItems = 0;
            removes.forEach(function (diffItem) {
                var removeIndex = removedItems + diffItem.index;
                mutatedArray.slice(removeIndex, diffItem.howMany + removeIndex).forEach(function (v) {
                    v.type = 'remove';
                });
                removedItems += diffItem.howMany;
                removesByIndex[diffItem.index] = removedItems;
            });
 
            function updateRemoveTable() {
                removedItems = 0;
                actual.forEach(function (_, index) {
                    removedItems += removesByIndex[index] || 0;
                    removeTable[index] = removedItems;
                });
            }
 
            updateRemoveTable();
 
            var moves = itemsDiff.filter(function (diffItem) {
                return diffItem.type === 'move';
            });
 
            var movedItems = 0;
            moves.forEach(function (diffItem) {
                var moveFromIndex = offsetIndex(diffItem.from);
                var removed = mutatedArray.slice(moveFromIndex, diffItem.howMany + moveFromIndex);
                var added = removed.map(function (v) {
                    return utils.extend({}, v, { type: 'insert' });
                });
                removed.forEach(function (v) {
                    v.type = 'remove';
                });
                Array.prototype.splice.apply(mutatedArray, [offsetIndex(diffItem.to), 0].concat(added));
                movedItems += diffItem.howMany;
                removesByIndex[diffItem.from] = movedItems;
                updateRemoveTable();
            });
 
            var inserts = itemsDiff.filter(function (diffItem) {
                return diffItem.type === 'insert';
            });
 
            inserts.forEach(function (diffItem) {
                var added = new Array(diffItem.values.length);
                for (var i = 0 ; i < diffItem.values.length ; i += 1) {
                    added[i] = {
                        type: 'insert',
                        value: diffItem.values[i]
                    };
                }
                Array.prototype.splice.apply(mutatedArray, [offsetIndex(diffItem.index), 0].concat(added));
            });
 
            var offset = 0;
            mutatedArray.forEach(function (diffItem, index) {
                var type = diffItem.type;
                if (type === 'remove') {
                    offset -= 1;
                } else if (type === 'similar') {
                    diffItem.expected = expected[offset + index];
                }
            });
 
            var conflicts = mutatedArray.reduce(function (conflicts, item) {
                return item.type === 'similar' ? conflicts : conflicts + 1;
            }, 0);
 
            for (var i = 0, c = 0; i < Math.max(actual.length, expected.length) &&  c <= conflicts; i += 1) {
                var expectedType = typeof expected[i];
                var actualType = typeof actual[i];
 
                if (
                    actualType !== expectedType ||
                    ((actualType === 'object' || actualType === 'string') && !structurallySimilar(actual[i], expected[i])) ||
                    (actualType !== 'object' && actualType !== 'string' && !equal(actual[i], expected[i]))
                ) {
                    c += 1;
                }
            }
 
            if (c <= conflicts) {
                mutatedArray = [];
                var j;
                for (j = 0; j < Math.min(actual.length, expected.length); j += 1) {
                    mutatedArray.push({
                        type: 'similar',
                        value: actual[j],
                        expected: expected[j]
                    });
                }
 
                Iif (actual.length < expected.length) {
                    for (; j < Math.max(actual.length, expected.length); j += 1) {
                        mutatedArray.push({
                            type: 'insert',
                            value: expected[j]
                        });
                    }
                } else {
                    for (; j < Math.max(actual.length, expected.length); j += 1) {
                        mutatedArray.push({
                            type: 'remove',
                            value: actual[j]
                        });
                    }
                }
                mutatedArray[mutatedArray.length - 1].last = true;
            }
 
            mutatedArray.forEach(function (diffItem) {
                if (diffItem.type === 'similar' && equal(diffItem.value, diffItem.expected)) {
                    diffItem.type = 'equal';
                }
            });
 
            output.append(this.prefix(output.clone())).nl().indentLines();
 
            mutatedArray.forEach(function (diffItem, index) {
                output.i().block(function () {
                    var type = diffItem.type;
                    var last = !!diffItem.last;
 
                    if (type === 'insert') {
                        this.annotationBlock(function () {
                            this.error('missing ').block(inspect(diffItem.value));
                        });
                    } else if (type === 'remove') {
                        this.block(inspect(diffItem.value).text(last ? ' ' : ', ').error('// should be removed'));
                    } else if (type === 'equal') {
                        this.block(inspect(diffItem.value).text(last ? '' : ','));
                    } else {
                        var valueDiff = diff(diffItem.value, diffItem.expected);
                        if (valueDiff && valueDiff.inline) {
                            this.block(valueDiff.diff.text(last ? '' : ','));
                        } else if (valueDiff) {
                            this.block(inspect(diffItem.value).text(last ? ' ' : ', ')).annotationBlock(function () {
                                this.error('should be ').block(inspect(diffItem.expected)).nl()
                                    .append(valueDiff.diff);
                            });
                        } else {
                            this.block(inspect(diffItem.value).text(last ? ' ' : ', ')).annotationBlock(function () {
                                this.error('should be ').block(inspect(diffItem.expected));
                            });
                        }
                    }
                }).nl();
            });
 
            output.outdentLines().append(this.suffix(output.clone()));
 
            return result;
        }
    });
 
    expect.addType({
        name: 'array',
        base: 'arrayLike',
        identify: function (arr) {
            return utils.isArray(arr);
        }
    });
 
    expect.addType({
        name: 'arguments',
        base: 'arrayLike',
        prefix: function (output) {
            return output.text('arguments(', 'cyan');
        },
        suffix: function (output) {
            return output.text(')', 'cyan');
        },
        identify: function (obj) {
            return Object.prototype.toString.call(obj) === '[object Arguments]';
        }
    });
 
    expect.addType({
        base: 'object',
        name: 'Error',
        identify: function (value) {
            return utils.isError(value);
        },
        equal: function (a, b, equal) {
            return a === b ||
                (equal(a.message, b.message) && this.baseType.equal(a, b));
        },
        inspect: function (value, depth, output, inspect) {
            var errorObject = extend({
                message: value.message
            }, value);
            // TODO: Inspect Error as a built-in once we have the styles defined:
            output.text('Error(').append(inspect(errorObject, depth)).text(')');
        },
        diff: function (actual, expected, output, diff) {
            var result = diff(extend({
                message: actual.message
            }, actual), extend({
                message: expected.message
            }, expected));
            Eif (result.diff) {
                result.diff = utils.wrapConstructorNameAroundOutput(result.diff, actual);
            }
            return result;
        }
    });
 
    expect.addType({
        name: 'date',
        identify: function (obj) {
            return Object.prototype.toString.call(obj) === '[object Date]';
        },
        equal: function (a, b) {
            return a.getTime() === b.getTime();
        },
        inspect: function (date, depth, output, inspect) {
            // TODO: Inspect "new" as an operator and Date as a built-in once we have the styles defined:
            output.text('new Date(').append(inspect(date.toUTCString()).text(')'));
        }
    });
 
    expect.addType({
        base: 'object',
        name: 'function',
        identify: function (f) {
            return typeof f === 'function';
        },
        equal: function (a, b) {
            return a === b || a.toString() === b.toString();
        },
        inspect: function (f, depth, output, inspect) {
            var source = f.toString();
            var name;
            var args;
            var body;
            var matchSource = source.match(/^function (\w*)?\s*\(([^\)]*)\)\s*\{([\s\S]*?( *)?)\}$/);
            if (matchSource) {
                name = matchSource[1];
                args = matchSource[2];
                body = matchSource[3];
                var bodyIndent = matchSource[4] || '';
                // Remove leading indentation unless the function is a one-liner or it uses multiline string literals
                if (/\n/.test(body) && !/\\\n/.test(body)) {
                    body = body.replace(new RegExp('^ {' + bodyIndent.length + '}', 'mg'), '');
                }
                if (!name || name === 'anonymous') {
                    name = '';
                }
                if (/^\s*\[native code\]\s*$/.test(body)) {
                    body = ' /* native code */ ';
                } else {
                    body = body.replace(/^((?:.*\n){3}( *).*\n)[\s\S]*?\n((?:.*\n){3})$/, '$1$2// ... lines removed ...\n$3');
                }
            } else {
                name = f.name || '';
                args = ' /*...*/ ';
                body = ' /*...*/ ';
            }
            output.code('function ' + name + '(' + args + ') {' + body + '}', 'javascript');
        }
    });
 
    expect.addType({
        base: 'function',
        name: 'expect.it',
        identify: function (f) {
            return typeof f === 'function' && f._expectIt;
        },
        inspect: function (f, depth, output, inspect) {
            output.text('expect.it(');
            var orBranch = false;
            f._expectations.forEach(function (expectation, index) {
                if (expectation === f._OR) {
                    orBranch = true;
                    return;
                }
 
                if (orBranch) {
                    output.text(')\n      .or(');
                } else if (0 < index) {
                    output.text(')\n        .and(');
                }
 
                var args = Array.prototype.slice.call(expectation);
                args.forEach(function (arg, i) {
                    if (0 < i) {
                        output.text(', ');
                    }
                    output.append(inspect(arg));
                });
                orBranch = false;
            });
 
            output.text(')');
        }
    });
 
    expect.addType({
        name: 'regexp',
        identify: isRegExp,
        equal: function (a, b) {
            return a === b || (
                a.source === b.source &&
                    a.global === b.global &&
                    a.ignoreCase === b.ignoreCase &&
                    a.multiline === b.multiline
            );
        },
        inspect: function (regExp, depth, output) {
            output.regexp(regExp);
        }
    });
 
    expect.addType({
        name: 'DomElement',
        identify: function (value) {
            return utils.isDOMElement(value);
        },
        inspect: function (value, depth, output) {
            output.code(utils.getOuterHTML(value), 'html');
        }
    });
 
    expect.addType({
        name: 'binaryArray',
        base: 'arrayLike',
        digitWidth: 2,
        hexDumpWidth: 16,
        identify: false,
        equal: function (a, b) {
            Iif (a === b) {
                return true;
            }
 
            if (a.length !== b.length) return false;
 
            for (var i = 0; i < a.length; i += 1) {
                if (a[i] !== b[i]) return false;
            }
 
            return true;
        },
        hexDump: function (obj, maxLength) {
            var hexDump = '';
            Eif (typeof maxLength !== 'number' || maxLength === 0) {
                maxLength = obj.length;
            }
            for (var i = 0 ; i < maxLength ; i += this.hexDumpWidth) {
                if (hexDump.length > 0) {
                    hexDump += '\n';
                }
                var hexChars = '',
                    asciiChars = ' │';
 
                for (var j = 0 ; j < this.hexDumpWidth ; j += 1) {
                    if (i + j < maxLength) {
                        var octet = obj[i + j];
                        hexChars += leftPad(octet.toString(16).toUpperCase(), this.digitWidth, '0') + ' ';
                        asciiChars += String.fromCharCode(octet).replace(/\n/g, '␊').replace(/\r/g, '␍');
                    } else if (this.digitWidth === 2) {
                        hexChars += '   ';
                    }
                }
 
                if (this.digitWidth === 2) {
                    hexDump += hexChars + asciiChars + '│';
                } else {
                    hexDump += hexChars.replace(/\s+$/, '');
                }
            }
            return hexDump;
        },
        inspect: function (obj, depth, output) {
            var codeStr = this.name + '([';
            for (var i = 0 ; i < Math.min(this.hexDumpWidth, obj.length) ; i += 1) {
                if (i > 0) {
                    codeStr += ', ';
                }
                var octet = obj[i];
                codeStr += '0x' + leftPad(octet.toString(16).toUpperCase(), this.digitWidth, '0');
            }
            if (obj.length > this.hexDumpWidth) {
                codeStr += ' /* ' + (obj.length - this.hexDumpWidth) + ' more */ ';
            }
            codeStr += '])';
            output.code(codeStr, 'javascript');
        },
        diffLimit: 512,
        diff: function (actual, expected, output, diff, inspect) {
            var result = {diff: output};
            if (Math.max(actual.length, expected.length) > this.diffLimit) {
                result.diff.comment('Diff suppressed due to size > ' + this.diffLimit);
            } else {
                result.diff = utils.diffStrings(this.hexDump(actual), this.hexDump(expected), output, {type: 'Chars', markUpSpecialCharacters: false})
                    .replaceText(/[\x00-\x1f\x7f-\xff␊␍]/g, '.').replaceText(/[│ ]/g, function (styles, content) {
                        this.text(content);
                    });
            }
            return result;
        }
    });
 
    Eif (typeof Buffer !== 'undefined') {
        expect.addType({
            name: 'Buffer',
            base: 'binaryArray',
            identify: Buffer.isBuffer
        });
    }
 
    [8, 16, 32].forEach(function (numBits) {
        ['Int', 'Uint'].forEach(function (intOrUint) {
            var constructorName = intOrUint + numBits + 'Array',
                Constructor = this[constructorName];
            Eif (typeof Constructor !== 'undefined') {
                expect.addType({
                    name: constructorName,
                    base: 'binaryArray',
                    hexDumpWidth: 128 / numBits,
                    digitWidth: numBits / 4,
                    identify: function (obj) {
                        return obj instanceof Constructor;
                    }
                });
            }
        }, this);
    }, this);
 
    expect.addType({
        name: 'string',
        identify: function (value) {
            return typeof value === 'string';
        },
        inspect: function (value, depth, output) {
            output.strings('\'')
                .strings(JSON.stringify(value).replace(/^"|"$/g, '')
                         .replace(/'/g, "\\'")
                         .replace(/\\"/g, '"'))
                .strings('\'');
        },
        diff: function (actual, expected, output, diff, inspect) {
            var result = {
                diff: output,
                inline: false
            };
            utils.diffStrings(actual, expected, output, {type: 'WordsWithSpace', markUpSpecialCharacters: true});
            return result;
        }
    });
 
    expect.addType({
        name: 'number',
        identify: function (value) {
            return typeof value === 'number';
        },
        inspect: function (value, depth, output) {
            output.number(value);
        }
    });
 
    expect.addType({
        name: 'NaN',
        identify: function (value) {
            return typeof value === 'number' && isNaN(value);
        }
    });
 
    expect.addType({
        name: 'boolean',
        identify: function (value) {
            return typeof value === 'boolean';
        },
        inspect: function (value, depth, output) {
            output.keyword(value);
        }
    });
 
    expect.addType({
        name: 'undefined',
        identify: function (value) {
            return typeof value === 'undefined';
        },
        inspect: function (value, depth, output) {
            output.keyword(value);
        }
    });
 
    expect.addType({
        name: 'null',
        identify: function (value) {
            return value === null;
        },
        inspect: function (value, depth, output) {
            output.keyword(value);
        }
    });
};