react / wstein / node_modules / jest-cli / node_modules / node-haste / node_modules / esprima-fb / test / runner.js
80682 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 needLoc(syntax) {74var need = true;75if (typeof syntax.tokens !== 'undefined' && syntax.tokens.length > 0) {76need = (typeof syntax.tokens[0].loc !== 'undefined');77}78if (typeof syntax.comments !== 'undefined' && syntax.comments.length > 0) {79need = (typeof syntax.comments[0].loc !== 'undefined');80}81return need;82}8384function needRange(syntax) {85var need = true;86if (typeof syntax.tokens !== 'undefined' && syntax.tokens.length > 0) {87need = (typeof syntax.tokens[0].range !== 'undefined');88}89if (typeof syntax.comments !== 'undefined' && syntax.comments.length > 0) {90need = (typeof syntax.comments[0].range !== 'undefined');91}92return need;93}9495function testParse(esprima, code, syntax) {96'use strict';97var expected, tree, actual, options, StringObject, i, len, err;9899// alias, so that JSLint does not complain.100StringObject = String;101102options = {103comment: (typeof syntax.comments !== 'undefined'),104range: needRange(syntax),105loc: needLoc(syntax),106tokens: (typeof syntax.tokens !== 'undefined'),107raw: true,108tolerant: (typeof syntax.errors !== 'undefined'),109source: null110};111112if (options.loc) {113options.source = syntax.loc.source;114}115116expected = JSON.stringify(syntax, null, 4);117try {118tree = esprima.parse(code, options);119tree = (options.comment || options.tokens || options.tolerant) ? tree : tree.body[0];120121if (options.tolerant) {122for (i = 0, len = tree.errors.length; i < len; i += 1) {123tree.errors[i] = errorToObject(tree.errors[i]);124}125}126127actual = JSON.stringify(tree, adjustRegexLiteral, 4);128129// Only to ensure that there is no error when using string object.130esprima.parse(new StringObject(code), options);131132} catch (e) {133throw new NotMatchingError(expected, e.toString());134}135if (expected !== actual) {136throw new NotMatchingError(expected, actual);137}138139function filter(key, value) {140if (key === 'value' && value instanceof RegExp) {141value = value.toString();142}143return (key === 'loc' || key === 'range') ? undefined : value;144}145146if (options.tolerant) {147return;148}149150151// Check again without any location info.152options.range = false;153options.loc = false;154expected = JSON.stringify(syntax, filter, 4);155try {156tree = esprima.parse(code, options);157tree = (options.comment || options.tokens) ? tree : tree.body[0];158159if (options.tolerant) {160for (i = 0, len = tree.errors.length; i < len; i += 1) {161tree.errors[i] = errorToObject(tree.errors[i]);162}163}164165actual = JSON.stringify(tree, filter, 4);166} catch (e) {167throw new NotMatchingError(expected, e.toString());168}169if (expected !== actual) {170throw new NotMatchingError(expected, actual);171}172}173174function mustHaveLocRange(testName, node, needLoc, needRange, stack) {175var error;176if (node.hasOwnProperty('type')) {177if (needLoc && !node.loc) {178error = "doesn't have 'loc' property";179}180if (needRange && !node.range) {181error = "doesn't have 'range' property";182}183if (error) {184stack = stack.length ? ' at [' + stack.join('][') + ']' : '';185throw new Error("Test '" + testName + "'" + stack + " (type = " + node.type + ") " + error);186}187}188for (i in node) {189if (node.hasOwnProperty(i) && node[i] !== null && typeof node[i] === 'object') {190stack.push(i);191mustHaveLocRange(testName, node[i], needLoc, needRange, stack);192stack.pop();193}194}195}196197function testTokenize(esprima, code, tokens) {198'use strict';199var options, expected, actual, tree;200201options = {202comment: true,203tolerant: true,204loc: true,205range: true206};207208expected = JSON.stringify(tokens, null, 4);209210try {211tree = esprima.tokenize(code, options);212actual = JSON.stringify(tree, null, 4);213} catch (e) {214throw new NotMatchingError(expected, e.toString());215}216if (expected !== actual) {217throw new NotMatchingError(expected, actual);218}219}220221function testError(esprima, code, exception) {222'use strict';223var i, options, expected, actual, err, handleInvalidRegexFlag, tokenize;224225// Different parsing options should give the same error.226options = [227{},228{ comment: true },229{ raw: true },230{ raw: true, comment: true }231];232233// If handleInvalidRegexFlag is true, an invalid flag in a regular expression234// will throw an exception. In some old version V8, this is not the case235// and hence handleInvalidRegexFlag is false.236handleInvalidRegexFlag = false;237try {238'test'.match(new RegExp('[a-z]', 'x'));239} catch (e) {240handleInvalidRegexFlag = true;241}242243exception.description = exception.message.replace(/Error: Line [0-9]+: /, '');244245if (exception.tokenize) {246tokenize = true;247exception.tokenize = undefined;248}249expected = JSON.stringify(exception);250251for (i = 0; i < options.length; i += 1) {252253try {254if (tokenize) {255esprima.tokenize(code, options[i])256} else {257esprima.parse(code, options[i]);258}259} catch (e) {260err = errorToObject(e);261err.description = e.description;262actual = JSON.stringify(err);263}264265if (expected !== actual) {266267// Compensate for old V8 which does not handle invalid flag.268if (exception.message.indexOf('Invalid regular expression') > 0) {269if (typeof actual === 'undefined' && !handleInvalidRegexFlag) {270return;271}272}273274throw new NotMatchingError(expected, actual);275}276277}278}279280function testAPI(esprima, code, result) {281'use strict';282var expected, res, actual;283284expected = JSON.stringify(result.result, null, 4);285try {286if (typeof result.property !== 'undefined') {287res = esprima[result.property];288} else {289res = esprima[result.call].apply(esprima, result.args);290}291actual = JSON.stringify(res, adjustRegexLiteral, 4);292} catch (e) {293throw new NotMatchingError(expected, e.toString());294}295if (expected !== actual) {296throw new NotMatchingError(expected, actual);297}298}299300function runTest(esprima, code, result) {301'use strict';302if (result.hasOwnProperty('lineNumber')) {303testError(esprima, code, result);304} else if (result.hasOwnProperty('result')) {305testAPI(esprima, code, result);306} else if (result instanceof Array) {307testTokenize(esprima, code, result);308} else {309testParse(esprima, code, result);310}311}312313if (typeof window !== 'undefined') {314// Run all tests in a browser environment.315runTests = function () {316'use strict';317var total = 0,318failures = 0,319category,320fixture,321source,322tick,323expected,324index,325len;326327function setText(el, str) {328if (typeof el.innerText === 'string') {329el.innerText = str;330} else {331el.textContent = str;332}333}334335function startCategory(category) {336var report, e;337report = document.getElementById('report');338e = document.createElement('h4');339setText(e, category);340report.appendChild(e);341}342343function reportSuccess(code) {344var report, e;345report = document.getElementById('report');346e = document.createElement('pre');347e.setAttribute('class', 'code');348setText(e, code);349report.appendChild(e);350}351352function reportFailure(code, expected, actual) {353var report, e;354355report = document.getElementById('report');356357e = document.createElement('p');358setText(e, 'Code:');359report.appendChild(e);360361e = document.createElement('pre');362e.setAttribute('class', 'code');363setText(e, code);364report.appendChild(e);365366e = document.createElement('p');367setText(e, 'Expected');368report.appendChild(e);369370e = document.createElement('pre');371e.setAttribute('class', 'expected');372setText(e, expected);373report.appendChild(e);374375e = document.createElement('p');376setText(e, 'Actual');377report.appendChild(e);378379e = document.createElement('pre');380e.setAttribute('class', 'actual');381setText(e, actual);382report.appendChild(e);383}384385setText(document.getElementById('version'), esprima.version);386387tick = new Date();388for (category in testFixture) {389if (testFixture.hasOwnProperty(category)) {390startCategory(category);391fixture = testFixture[category];392for (source in fixture) {393if (fixture.hasOwnProperty(source)) {394expected = fixture[source];395total += 1;396try {397runTest(esprima, source, expected);398reportSuccess(source, JSON.stringify(expected, null, 4));399} catch (e) {400failures += 1;401reportFailure(source, e.expected, e.actual);402}403}404}405}406}407tick = (new Date()) - tick;408409if (failures > 0) {410document.getElementById('status').className = 'alert-box alert';411setText(document.getElementById('status'), total + ' tests. ' +412'Failures: ' + failures + '. ' + tick + ' ms.');413} else {414document.getElementById('status').className = 'alert-box success';415setText(document.getElementById('status'), total + ' tests. ' +416'No failure. ' + tick + ' ms.');417}418};419} else {420(function () {421'use strict';422423var esprima = require('../esprima'),424vm = require('vm'),425fs = require('fs'),426diff = require('json-diff').diffString,427total = 0,428failures = [],429tick = new Date(),430expected,431header;432433vm.runInThisContext(fs.readFileSync(__dirname + '/test.js', 'utf-8'));434vm.runInThisContext(fs.readFileSync(__dirname + '/harmonytest.js', 'utf-8'));435vm.runInThisContext(fs.readFileSync(__dirname + '/fbtest.js', 'utf-8'));436437Object.keys(testFixture).forEach(function (category) {438Object.keys(testFixture[category]).forEach(function (source) {439total += 1;440expected = testFixture[category][source];441if (!expected.hasOwnProperty('lineNumber') && !expected.hasOwnProperty('result')) {442mustHaveLocRange(source, expected, needLoc(expected), needRange(expected), []);443}444try {445runTest(esprima, source, expected);446} catch (e) {447e.source = source;448failures.push(e);449}450});451});452tick = (new Date()) - tick;453454header = total + ' tests. ' + failures.length + ' failures. ' +455tick + ' ms';456if (failures.length) {457console.error(header);458failures.forEach(function (failure) {459try {460var expectedObject = JSON.parse(failure.expected);461var actualObject = JSON.parse(failure.actual);462463console.error(failure.source + ': Expected\n ' +464failure.expected.split('\n').join('\n ') +465'\nto match\n ' + failure.actual + '\nDiff:\n' +466diff(expectedObject, actualObject));467} catch (ex) {468console.error(failure.source + ': Expected\n ' +469failure.expected.split('\n').join('\n ') +470'\nto match\n ' + failure.actual);471}472});473} else {474console.log(header);475}476process.exit(failures.length === 0 ? 0 : 1);477}());478}479480481