react / wstein / node_modules / browserify / node_modules / module-deps / node_modules / detective / node_modules / escodegen / node_modules / esprima / test / runner.js
80621 views/*1Copyright (C) 2012 Ariya Hidayat <[email protected]>2Copyright (C) 2012 Joost-Wim Boekesteijn <[email protected]>3Copyright (C) 2012 Yusuke Suzuki <[email protected]>4Copyright (C) 2012 Arpad Borsos <[email protected]>5Copyright (C) 2011 Ariya Hidayat <[email protected]>6Copyright (C) 2011 Yusuke Suzuki <[email protected]>7Copyright (C) 2011 Arpad Borsos <[email protected]>89Redistribution and use in source and binary forms, with or without10modification, are permitted provided that the following conditions are met:1112* Redistributions of source code must retain the above copyright13notice, this list of conditions and the following disclaimer.14* Redistributions in binary form must reproduce the above copyright15notice, this list of conditions and the following disclaimer in the16documentation and/or other materials provided with the distribution.1718THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"19AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE20IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE21ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY22DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES23(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;24LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND25ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT26(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF27THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.28*/2930/*jslint browser:true node:true */31/*global esprima:true, testFixture:true */3233var runTests;3435// Special handling for regular expression literal since we need to36// convert it to a string literal, otherwise it will be decoded37// as object "{}" and the regular expression would be lost.38function adjustRegexLiteral(key, value) {39'use strict';40if (key === 'value' && value instanceof RegExp) {41value = value.toString();42}43return value;44}4546function NotMatchingError(expected, actual) {47'use strict';48Error.call(this, 'Expected ');49this.expected = expected;50this.actual = actual;51}52NotMatchingError.prototype = new Error();5354function errorToObject(e) {55'use strict';56var msg = e.toString();5758// Opera 9.64 produces an non-standard string in toString().59if (msg.substr(0, 6) !== 'Error:') {60if (typeof e.message === 'string') {61msg = 'Error: ' + e.message;62}63}6465return {66index: e.index,67lineNumber: e.lineNumber,68column: e.column,69message: msg70};71}7273function sortedObject(o) {74if (o === null) {75return o;76}77if (o instanceof Array) {78return o.map(sortedObject);79}80if (typeof o !== 'object') {81return o;82}83if (o instanceof RegExp) {84return o;85}86var keys = Object.keys(o);87var result = {88range: undefined,89loc: undefined90};91keys.forEach(function (key) {92if (o.hasOwnProperty(key)){93result[key] = sortedObject(o[key]);94}95});96return result;97}9899function hasAttachedComment(syntax) {100var key;101for (key in syntax) {102if (key === 'leadingComments' || key === 'trailingComments') {103return true;104}105if (typeof syntax[key] === 'object' && syntax[key] !== null) {106if (hasAttachedComment(syntax[key])) {107return true;108}109}110}111return false;112}113114function testParse(esprima, code, syntax) {115'use strict';116var expected, tree, actual, options, StringObject, i, len, err;117118// alias, so that JSLint does not complain.119StringObject = String;120121options = {122comment: (typeof syntax.comments !== 'undefined'),123range: true,124loc: true,125tokens: (typeof syntax.tokens !== 'undefined'),126raw: true,127tolerant: (typeof syntax.errors !== 'undefined'),128source: null129};130131if (options.comment) {132options.attachComment = hasAttachedComment(syntax);133}134135if (typeof syntax.tokens !== 'undefined') {136if (syntax.tokens.length > 0) {137options.range = (typeof syntax.tokens[0].range !== 'undefined');138options.loc = (typeof syntax.tokens[0].loc !== 'undefined');139}140}141142if (typeof syntax.comments !== 'undefined') {143if (syntax.comments.length > 0) {144options.range = (typeof syntax.comments[0].range !== 'undefined');145options.loc = (typeof syntax.comments[0].loc !== 'undefined');146}147}148149if (options.loc) {150options.source = syntax.loc.source;151}152153syntax = sortedObject(syntax);154expected = JSON.stringify(syntax, null, 4);155try {156// Some variations of the options.157tree = esprima.parse(code, { tolerant: options.tolerant });158tree = esprima.parse(code, { tolerant: options.tolerant, range: true });159tree = esprima.parse(code, { tolerant: options.tolerant, loc: true });160161tree = esprima.parse(code, options);162tree = (options.comment || options.tokens || options.tolerant) ? tree : tree.body[0];163164if (options.tolerant) {165for (i = 0, len = tree.errors.length; i < len; i += 1) {166tree.errors[i] = errorToObject(tree.errors[i]);167}168}169tree = sortedObject(tree);170actual = JSON.stringify(tree, adjustRegexLiteral, 4);171172// Only to ensure that there is no error when using string object.173esprima.parse(new StringObject(code), options);174175} catch (e) {176throw new NotMatchingError(expected, e.toString());177}178if (expected !== actual) {179throw new NotMatchingError(expected, actual);180}181182function filter(key, value) {183if (key === 'value' && value instanceof RegExp) {184value = value.toString();185}186return (key === 'loc' || key === 'range') ? undefined : value;187}188189if (options.tolerant) {190return;191}192193194// Check again without any location info.195options.range = false;196options.loc = false;197syntax = sortedObject(syntax);198expected = JSON.stringify(syntax, filter, 4);199try {200tree = esprima.parse(code, options);201tree = (options.comment || options.tokens) ? tree : tree.body[0];202203if (options.tolerant) {204for (i = 0, len = tree.errors.length; i < len; i += 1) {205tree.errors[i] = errorToObject(tree.errors[i]);206}207}208tree = sortedObject(tree);209actual = JSON.stringify(tree, filter, 4);210} catch (e) {211throw new NotMatchingError(expected, e.toString());212}213if (expected !== actual) {214throw new NotMatchingError(expected, actual);215}216}217218function testTokenize(esprima, code, tokens) {219'use strict';220var options, expected, actual, tree;221222options = {223comment: true,224tolerant: true,225loc: true,226range: true227};228229expected = JSON.stringify(tokens, null, 4);230231try {232tree = esprima.tokenize(code, options);233actual = JSON.stringify(tree, null, 4);234} catch (e) {235throw new NotMatchingError(expected, e.toString());236}237if (expected !== actual) {238throw new NotMatchingError(expected, actual);239}240}241242function testError(esprima, code, exception) {243'use strict';244var i, options, expected, actual, err, handleInvalidRegexFlag, tokenize;245246// Different parsing options should give the same error.247options = [248{},249{ comment: true },250{ raw: true },251{ raw: true, comment: true }252];253254// If handleInvalidRegexFlag is true, an invalid flag in a regular expression255// will throw an exception. In some old version V8, this is not the case256// and hence handleInvalidRegexFlag is false.257handleInvalidRegexFlag = false;258try {259'test'.match(new RegExp('[a-z]', 'x'));260} catch (e) {261handleInvalidRegexFlag = true;262}263264exception.description = exception.message.replace(/Error: Line [0-9]+: /, '');265266if (exception.tokenize) {267tokenize = true;268exception.tokenize = undefined;269}270expected = JSON.stringify(exception);271272for (i = 0; i < options.length; i += 1) {273274try {275if (tokenize) {276esprima.tokenize(code, options[i])277} else {278esprima.parse(code, options[i]);279}280} catch (e) {281err = errorToObject(e);282err.description = e.description;283actual = JSON.stringify(err);284}285286if (expected !== actual) {287288// Compensate for old V8 which does not handle invalid flag.289if (exception.message.indexOf('Invalid regular expression') > 0) {290if (typeof actual === 'undefined' && !handleInvalidRegexFlag) {291return;292}293}294295throw new NotMatchingError(expected, actual);296}297298}299}300301function testAPI(esprima, code, result) {302'use strict';303var expected, res, actual;304305expected = JSON.stringify(result.result, null, 4);306try {307if (typeof result.property !== 'undefined') {308res = esprima[result.property];309} else {310res = esprima[result.call].apply(esprima, result.args);311}312actual = JSON.stringify(res, adjustRegexLiteral, 4);313} catch (e) {314throw new NotMatchingError(expected, e.toString());315}316if (expected !== actual) {317throw new NotMatchingError(expected, actual);318}319}320321function runTest(esprima, code, result) {322'use strict';323if (result.hasOwnProperty('lineNumber')) {324testError(esprima, code, result);325} else if (result.hasOwnProperty('result')) {326testAPI(esprima, code, result);327} else if (result instanceof Array) {328testTokenize(esprima, code, result);329} else {330testParse(esprima, code, result);331}332}333334if (typeof window !== 'undefined') {335// Run all tests in a browser environment.336runTests = function () {337'use strict';338var total = 0,339failures = 0,340category,341fixture,342source,343tick,344expected,345index,346len;347348function setText(el, str) {349if (typeof el.innerText === 'string') {350el.innerText = str;351} else {352el.textContent = str;353}354}355356function startCategory(category) {357var report, e;358report = document.getElementById('report');359e = document.createElement('h4');360setText(e, category);361report.appendChild(e);362}363364function reportSuccess(code) {365var report, e;366report = document.getElementById('report');367e = document.createElement('pre');368e.setAttribute('class', 'code');369setText(e, code);370report.appendChild(e);371}372373function reportFailure(code, expected, actual) {374var report, e;375376report = document.getElementById('report');377378e = document.createElement('p');379setText(e, 'Code:');380report.appendChild(e);381382e = document.createElement('pre');383e.setAttribute('class', 'code');384setText(e, code);385report.appendChild(e);386387e = document.createElement('p');388setText(e, 'Expected');389report.appendChild(e);390391e = document.createElement('pre');392e.setAttribute('class', 'expected');393setText(e, expected);394report.appendChild(e);395396e = document.createElement('p');397setText(e, 'Actual');398report.appendChild(e);399400e = document.createElement('pre');401e.setAttribute('class', 'actual');402setText(e, actual);403report.appendChild(e);404}405406setText(document.getElementById('version'), esprima.version);407408tick = new Date();409for (category in testFixture) {410if (testFixture.hasOwnProperty(category)) {411startCategory(category);412fixture = testFixture[category];413for (source in fixture) {414if (fixture.hasOwnProperty(source)) {415expected = fixture[source];416total += 1;417try {418runTest(esprima, source, expected);419reportSuccess(source, JSON.stringify(expected, null, 4));420} catch (e) {421failures += 1;422reportFailure(source, e.expected, e.actual);423}424}425}426}427}428tick = (new Date()) - tick;429430if (failures > 0) {431document.getElementById('status').className = 'alert-box alert';432setText(document.getElementById('status'), total + ' tests. ' +433'Failures: ' + failures + '. ' + tick + ' ms.');434} else {435document.getElementById('status').className = 'alert-box success';436setText(document.getElementById('status'), total + ' tests. ' +437'No failure. ' + tick + ' ms.');438}439};440} else {441(function () {442'use strict';443444var esprima = require('../esprima'),445vm = require('vm'),446fs = require('fs'),447diff = require('json-diff').diffString,448total = 0,449failures = [],450tick = new Date(),451expected,452header;453454vm.runInThisContext(fs.readFileSync(__dirname + '/test.js', 'utf-8'));455456Object.keys(testFixture).forEach(function (category) {457Object.keys(testFixture[category]).forEach(function (source) {458total += 1;459expected = testFixture[category][source];460try {461runTest(esprima, source, expected);462} catch (e) {463e.source = source;464failures.push(e);465}466});467});468tick = (new Date()) - tick;469470header = total + ' tests. ' + failures.length + ' failures. ' +471tick + ' ms';472if (failures.length) {473console.error(header);474failures.forEach(function (failure) {475try {476var expectedObject = JSON.parse(failure.expected);477var actualObject = JSON.parse(failure.actual);478479console.error(failure.source + ': Expected\n ' +480failure.expected.split('\n').join('\n ') +481'\nto match\n ' + failure.actual + '\nDiff:\n' +482diff(expectedObject, actualObject));483} catch (ex) {484console.error(failure.source + ': Expected\n ' +485failure.expected.split('\n').join('\n ') +486'\nto match\n ' + failure.actual);487}488});489} else {490console.log(header);491}492process.exit(failures.length === 0 ? 0 : 1);493}());494}495496497