react / wstein / node_modules / react / node_modules / envify / node_modules / jstransform / node_modules / esprima-fb / test / runner.js
80556 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 literals: remove their `value`36// property since it may be `null` if it represents a regular expression37// that is not supported in the current environment. The `regex` property38// will be compared instead.39function adjustRegexLiteral(key, value) {40'use strict';41if (key === 'value' && value instanceof RegExp) {42value = value.toString();43}44return value;45}4647function NotMatchingError(expected, actual) {48'use strict';49Error.call(this, 'Expected ');50this.expected = expected;51this.actual = actual;52}53NotMatchingError.prototype = new Error();5455function errorToObject(e) {56'use strict';57var msg = e.toString();5859// Opera 9.64 produces an non-standard string in toString().60if (msg.substr(0, 6) !== 'Error:') {61if (typeof e.message === 'string') {62msg = 'Error: ' + e.message;63}64}6566return {67index: e.index,68lineNumber: e.lineNumber,69column: e.column,70message: msg71};72}7374function needLoc(syntax) {75var need = true;76if (typeof syntax.tokens !== 'undefined' && syntax.tokens.length > 0) {77need = (typeof syntax.tokens[0].loc !== 'undefined');78}79if (typeof syntax.comments !== 'undefined' && syntax.comments.length > 0) {80need = (typeof syntax.comments[0].loc !== 'undefined');81}82return need;83}8485function needRange(syntax) {86var need = true;87if (typeof syntax.tokens !== 'undefined' && syntax.tokens.length > 0) {88need = (typeof syntax.tokens[0].range !== 'undefined');89}90if (typeof syntax.comments !== 'undefined' && syntax.comments.length > 0) {91need = (typeof syntax.comments[0].range !== 'undefined');92}93return need;94}9596function hasAttachedComment(syntax) {97var key;98for (key in syntax) {99if (key === 'leadingComments' || key === 'trailingComments') {100return true;101}102if (syntax[key] && typeof syntax[key] === 'object') {103if (hasAttachedComment(syntax[key])) {104return true;105}106}107}108return false;109}110111function testParse(esprima, code, syntax, testOptions) {112'use strict';113var expected, tree, actual, options, StringObject, i, len, err;114115// alias, so that JSLint does not complain.116StringObject = String;117118options = {119comment: (typeof syntax.comments !== 'undefined'),120range: needRange(syntax),121loc: needLoc(syntax),122tokens: (typeof syntax.tokens !== 'undefined'),123raw: true,124tolerant: (typeof syntax.errors !== 'undefined'),125source: null,126sourceType: testOptions.sourceType127};128129if (options.comment) {130options.attachComment = hasAttachedComment(syntax);131}132133if (options.loc) {134options.source = syntax.loc.source;135}136137expected = JSON.stringify(syntax, adjustRegexLiteral, 4);138try {139tree = esprima.parse(code, options);140tree = (options.comment || options.tokens || options.tolerant) ? tree : tree.body[0];141142if (options.tolerant) {143for (i = 0, len = tree.errors.length; i < len; i += 1) {144tree.errors[i] = errorToObject(tree.errors[i]);145}146}147148actual = JSON.stringify(tree, adjustRegexLiteral, 4);149150// Only to ensure that there is no error when using string object.151esprima.parse(new StringObject(code), options);152153} catch (e) {154throw new NotMatchingError(expected, e.toString());155}156if (expected !== actual) {157throw new NotMatchingError(expected, actual);158}159160function filter(key, value) {161if (key === 'value' && value instanceof RegExp) {162value = value.toString();163}164return (key === 'loc' || key === 'range') ? undefined : value;165}166167if (options.tolerant) {168return;169}170171172// Check again without any location info.173options.range = false;174options.loc = false;175expected = JSON.stringify(syntax, filter, 4);176try {177tree = esprima.parse(code, options);178tree = (options.comment || options.tokens) ? tree : tree.body[0];179180if (options.tolerant) {181for (i = 0, len = tree.errors.length; i < len; i += 1) {182tree.errors[i] = errorToObject(tree.errors[i]);183}184}185186actual = JSON.stringify(tree, filter, 4);187} catch (e) {188throw new NotMatchingError(expected, e.toString());189}190if (expected !== actual) {191throw new NotMatchingError(expected, actual);192}193}194195function mustHaveLocRange(testName, node, needLoc, needRange, stack) {196var error;197if (node.hasOwnProperty('type')) {198if (needLoc && !node.loc) {199error = "doesn't have 'loc' property";200}201if (needRange && !node.range) {202error = "doesn't have 'range' property";203}204if (error) {205stack = stack.length ? ' at [' + stack.join('][') + ']' : '';206throw new Error("Test '" + testName + "'" + stack + " (type = " + node.type + ") " + error);207}208}209for (i in node) {210if (node.hasOwnProperty(i) && node[i] !== null && typeof node[i] === 'object') {211stack.push(i);212mustHaveLocRange(testName, node[i], needLoc, needRange, stack);213stack.pop();214}215}216}217218function testTokenize(esprima, code, tokens, testOptions) {219'use strict';220var options, expected, actual, tree;221222options = {223comment: true,224tolerant: true,225loc: true,226range: true,227sourceType: testOptions.sourceType228};229230expected = JSON.stringify(tokens, null, 4);231232try {233tree = esprima.tokenize(code, options);234actual = JSON.stringify(tree, null, 4);235} catch (e) {236throw new NotMatchingError(expected, e.toString());237}238if (expected !== actual) {239throw new NotMatchingError(expected, actual);240}241}242243function testError(esprima, code, exception, testOptions) {244'use strict';245var i, options, expected, actual, err, handleInvalidRegexFlag, tokenize,246sourceType;247248// Different parsing options should give the same error.249options = [250{ sourceType: testOptions.sourceType },251{ sourceType: testOptions.sourceType, comment: true },252{ sourceType: testOptions.sourceType, raw: true },253{ sourceType: testOptions.sourceType, raw: true, comment: true }254];255256// If handleInvalidRegexFlag is true, an invalid flag in a regular expression257// will throw an exception. In some old version of V8, this is not the case258// and hence handleInvalidRegexFlag is false.259handleInvalidRegexFlag = false;260try {261'test'.match(new RegExp('[a-z]', 'x'));262} catch (e) {263handleInvalidRegexFlag = true;264}265266exception.description = exception.message.replace(/Error: Line [0-9]+: /, '');267268if (exception.tokenize) {269tokenize = true;270exception.tokenize = undefined;271}272expected = JSON.stringify(exception);273274for (i = 0; i < options.length; i += 1) {275276try {277if (tokenize) {278esprima.tokenize(code, options[i])279} else {280esprima.parse(code, options[i]);281}282} catch (e) {283err = errorToObject(e);284err.description = e.description;285actual = JSON.stringify(err);286}287288if (expected !== actual) {289290// Compensate for old V8 which does not handle invalid flag.291if (exception.message.indexOf('Invalid regular expression') > 0) {292if (typeof actual === 'undefined' && !handleInvalidRegexFlag) {293return;294}295}296297throw new NotMatchingError(expected, actual);298}299300}301}302303function testAPI(esprima, code, result) {304'use strict';305var expected, res, actual;306307expected = JSON.stringify(result.result, null, 4);308try {309if (typeof result.property !== 'undefined') {310res = esprima[result.property];311} else {312res = esprima[result.call].apply(esprima, result.args);313}314actual = JSON.stringify(res, adjustRegexLiteral, 4);315} catch (e) {316throw new NotMatchingError(expected, e.toString());317}318if (expected !== actual) {319throw new NotMatchingError(expected, actual);320}321}322323function runTest(esprima, code, result, options) {324'use strict';325if (result.hasOwnProperty('lineNumber')) {326testError(esprima, code, result, options);327} else if (result.hasOwnProperty('result')) {328testAPI(esprima, code, result);329} else if (result instanceof Array) {330testTokenize(esprima, code, result, options);331} else {332testParse(esprima, code, result, options);333}334}335336if (typeof window !== 'undefined') {337// Run all tests in a browser environment.338runTests = function () {339'use strict';340var total = 0,341failures = 0,342category,343fixture,344source,345tick,346expected,347index,348len;349350function setText(el, str) {351if (typeof el.innerText === 'string') {352el.innerText = str;353} else {354el.textContent = str;355}356}357358function startCategory(category) {359var report, e;360report = document.getElementById('report');361e = document.createElement('h4');362setText(e, category);363report.appendChild(e);364}365366function reportSuccess(code) {367var report, e;368report = document.getElementById('report');369e = document.createElement('pre');370e.setAttribute('class', 'code');371setText(e, code);372report.appendChild(e);373}374375function reportFailure(code, expected, actual) {376var report, e;377378report = document.getElementById('report');379380e = document.createElement('p');381setText(e, 'Code:');382report.appendChild(e);383384e = document.createElement('pre');385e.setAttribute('class', 'code');386setText(e, code);387report.appendChild(e);388389e = document.createElement('p');390setText(e, 'Expected');391report.appendChild(e);392393e = document.createElement('pre');394e.setAttribute('class', 'expected');395setText(e, expected);396report.appendChild(e);397398e = document.createElement('p');399setText(e, 'Actual');400report.appendChild(e);401402e = document.createElement('pre');403e.setAttribute('class', 'actual');404setText(e, actual);405report.appendChild(e);406}407408setText(document.getElementById('version'), esprima.version);409410tick = new Date();411for (category in testFixture) {412if (testFixture.hasOwnProperty(category)) {413var categoryOptions = testFixtureOptions[category] || {};414startCategory(category);415fixture = testFixture[category];416for (source in fixture) {417if (fixture.hasOwnProperty(source)) {418var sourceOptions =419categoryOptions.hasOwnProperty(source)420? categoryOptions[source]421: categoryOptions;422423expected = fixture[source];424total += 1;425try {426427runTest(esprima, source, expected, sourceOptions);428reportSuccess(source, JSON.stringify(expected, null, 4));429} catch (e) {430failures += 1;431reportFailure(source, e.expected, e.actual);432}433}434}435}436}437tick = (new Date()) - tick;438439if (failures > 0) {440document.getElementById('status').className = 'alert-box alert';441setText(document.getElementById('status'), total + ' tests. ' +442'Failures: ' + failures + '. ' + tick + ' ms.');443} else {444document.getElementById('status').className = 'alert-box success';445setText(document.getElementById('status'), total + ' tests. ' +446'No failure. ' + tick + ' ms.');447}448};449} else {450(function () {451'use strict';452453var esprima = require('../esprima'),454vm = require('vm'),455fs = require('fs'),456diff = require('json-diff').diffString,457total = 0,458failures = [],459tick = new Date(),460expected,461header;462463vm.runInThisContext(fs.readFileSync(__dirname + '/test.js', 'utf-8'));464vm.runInThisContext(fs.readFileSync(__dirname + '/harmonytest.js', 'utf-8'));465vm.runInThisContext(fs.readFileSync(__dirname + '/fbtest.rec.js', 'utf-8'));466vm.runInThisContext(fs.readFileSync(__dirname + '/harmonymodulestest.js', 'utf-8'));467468Object.keys(testFixture).forEach(function (category) {469var categoryOptions = testFixtureOptions[category] || {};470Object.keys(testFixture[category]).forEach(function (source) {471var sourceOptions =472categoryOptions.hasOwnProperty(source)473? categoryOptions[source]474: categoryOptions;475total += 1;476expected = testFixture[category][source];477if (!expected.hasOwnProperty('lineNumber') && !expected.hasOwnProperty('result')) {478mustHaveLocRange(source, expected, needLoc(expected), needRange(expected), []);479}480try {481runTest(esprima, source, expected, sourceOptions);482} catch (e) {483e.source = source;484failures.push(e);485}486});487});488tick = (new Date()) - tick;489490header = total + ' tests. ' + failures.length + ' failures. ' +491tick + ' ms';492if (failures.length) {493console.error(header);494failures.forEach(function (failure) {495try {496var expectedObject = JSON.parse(failure.expected);497var actualObject = JSON.parse(failure.actual);498499console.error(failure.source + ': Expected\n ' +500failure.expected.split('\n').join('\n ') +501'\nto match\n ' + failure.actual + '\nDiff:\n' +502diff(expectedObject, actualObject));503} catch (ex) {504console.error(failure.source + ': Expected\n ' +505failure.expected.split('\n').join('\n ') +506'\nto match\n ' + failure.actual);507}508});509} else {510console.log(header);511}512process.exit(failures.length === 0 ? 0 : 1);513}());514}515516517