Roll src/third_party/WebKit d9c6159:8139f33 (svn 201974:201975)
[chromium-blink-merge.git] / chrome / test / base / js2gtest.js
blobde09918abbc0fb1e37734bfd41ecc13bbc209b9d
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 /**
6 * @fileoverview Generator script for creating gtest-style JavaScript
7 * tests for extensions, WebUI and unit tests. Generates C++ gtest wrappers
8 * which will invoke the appropriate JavaScript for each test.
9 * @author scr@chromium.org (Sheridan Rawlins)
10 * @see WebUI testing: http://goo.gl/ZWFXF
11 * @see gtest documentation: http://goo.gl/Ujj3H
12 * @see chrome/chrome_tests.gypi
13 * @see chrome/test/base/js2gtest.js
14 * @see tools/gypv8sh.py
17 // Arguments from rules in chrome_tests.gypi are passed in through
18 // python script gypv8sh.py.
19 if (arguments.length != 6) {
20 print('usage: ' +
21 arguments[0] +
22 ' path-to-testfile.js testfile.js path_to_deps.js output.cc test-type');
23 quit(-1);
26 /**
27 * Full path to the test input file.
28 * @type {string}
30 var jsFile = arguments[1];
32 /**
33 * Relative path to the test input file appropriate for use in the
34 * C++ TestFixture's addLibrary method.
35 * @type {string}
37 var jsFileBase = arguments[2];
39 /**
40 * Path to Closure library style deps.js file.
41 * @type {string?}
43 var depsFile = arguments[3];
45 /**
46 * Path to C++ file generation is outputting to.
47 * @type {string}
49 var outputFile = arguments[4];
51 /**
52 * Type of this test.
53 * @type {string} ('extension' | 'unit' | 'webui')
55 var testType = arguments[5];
56 if (testType != 'extension' &&
57 testType != 'unit' &&
58 testType != 'webui') {
59 print('Invalid test type: ' + testType);
60 quit(-1);
63 /**
64 * C++ gtest macro to use for TEST_F depending on |testType|.
65 * @type {string} ('TEST_F'|'IN_PROC_BROWSER_TEST_F')
67 var testF;
69 /**
70 * Keeps track of whether a typedef has been generated for each test
71 * fixture.
72 * @type {Object<string>}
74 var typedeffedCppFixtures = {};
76 /**
77 * Maintains a list of relative file paths to add to each gtest body
78 * for inclusion at runtime before running each JavaScript test.
79 * @type {Array<string>}
81 var genIncludes = [];
83 /**
84 * When true, add calls to set_preload_test_(fixture|name). This is needed when
85 * |testType| === 'webui' to send an injection message before the page loads,
86 * but is not required or supported by any other test type.
87 * @type {boolean}
89 var addSetPreloadInfo;
91 /**
92 * Whether cc headers need to be generated.
93 * @type {boolean}
95 var needGenHeader = true;
97 /**
98 * Helpful hint pointing back to the source js.
99 * @type {string}
101 var argHint = '// ' + this['arguments'].join(' ');
104 * @type {Array<string>}
106 var pendingOutput = '';
109 * Adds a string followed by a newline to the pending output.
110 * If present, an initial newline character is stripped from the string.
111 * @param {string=} opt_string
113 function output(opt_string) {
114 opt_string = opt_string || '';
115 if (opt_string[0] == '\n')
116 opt_string = opt_string.substring(1);
117 pendingOutput += opt_string;
118 pendingOutput += '\n';
122 * Generates the header of the cc file to stdout.
123 * @param {string?} testFixture Name of test fixture.
125 function maybeGenHeader(testFixture) {
126 if (!needGenHeader)
127 return;
128 needGenHeader = false;
129 output(`
130 // GENERATED FILE'
131 ${argHint}
132 // PLEASE DO NOT HAND EDIT!
135 // Output some C++ headers based upon the |testType|.
137 // Currently supports:
138 // 'extension' - browser_tests harness, js2extension rule,
139 // ExtensionJSBrowserTest superclass.
140 // 'unit' - unit_tests harness, js2unit rule, V8UnitTest superclass.
141 // 'webui' - browser_tests harness, js2webui rule, WebUIBrowserTest
142 // superclass.
143 if (testType === 'extension') {
144 output('#include "chrome/test/base/extension_js_browser_test.h"');
145 testing.Test.prototype.typedefCppFixture = 'ExtensionJSBrowserTest';
146 addSetPreloadInfo = false;
147 testF = 'IN_PROC_BROWSER_TEST_F';
148 } else if (testType === 'unit') {
149 output('#include "chrome/test/base/v8_unit_test.h"');
150 testing.Test.prototype.typedefCppFixture = 'V8UnitTest';
151 testF = 'TEST_F';
152 addSetPreloadInfo = false;
153 } else {
154 output('#include "chrome/test/base/web_ui_browser_test.h"');
155 testing.Test.prototype.typedefCppFixture = 'WebUIBrowserTest';
156 testF = 'IN_PROC_BROWSER_TEST_F';
157 addSetPreloadInfo = true;
159 output(`
160 #include "url/gurl.h"
161 #include "testing/gtest/include/gtest/gtest.h"`);
162 // Add includes specified by test fixture.
163 if (testFixture) {
164 if (this[testFixture].prototype.testGenCppIncludes)
165 this[testFixture].prototype.testGenCppIncludes();
166 if (this[testFixture].prototype.commandLineSwitches)
167 output('#include "base/command_line.h"');
169 output();
174 * @type {Array<{path: string, base: string>}
176 var pathStack = [];
180 * Convert the |includeFile| to paths appropriate for immediate
181 * inclusion (path) and runtime inclusion (base).
182 * @param {string} includeFile The file to include.
183 * @return {{path: string, base: string}} Object describing the paths
184 * for |includeFile|. |path| is relative to cwd; |base| is relative to
185 * source root.
187 function includeFileToPaths(includeFile) {
188 paths = pathStack[pathStack.length - 1];
189 return {
190 path: paths.path.replace(/[^\/\\]+$/, includeFile),
191 base: paths.base.replace(/[^\/\\]+$/, includeFile),
196 * Returns the content of a javascript file with a sourceURL comment
197 * appended to facilitate better stack traces.
198 * @param {string} path Relative path name.
199 * return {string}
201 function readJsFile(path) {
202 return read(path) + '\n//# sourceURL=' + path;
207 * Maps object names to the path to the file that provides them.
208 * Populated from the |depsFile| if any.
209 * @type {Object<string>}
211 var dependencyProvidesToPaths = {};
214 * Maps dependency path names to object names required by the file.
215 * Populated from the |depsFile| if any.
216 * @type {Object<Array<string>>}
218 var dependencyPathsToRequires = {};
220 if (depsFile) {
221 var goog = goog || {};
223 * Called by the javascript in the deps file to add modules and their
224 * dependencies.
225 * @param {string} path Relative path to the file.
226 * @param Array<string> provides Objects provided by this file.
227 * @param Array<string> requires Objects required by this file.
229 goog.addDependency = function(path, provides, requires) {
230 provides.forEach(function(provide) {
231 dependencyProvidesToPaths[provide] = path;
233 dependencyPathsToRequires[path] = requires;
236 // Read and eval the deps file. It should only contain goog.addDependency
237 // calls.
238 eval(readJsFile(depsFile));
242 * Resolves a list of libraries to an ordered list of paths to load by the
243 * generated C++. The input should contain object names provided
244 * by the deps file. Dependencies will be resolved and included in the
245 * correct order, meaning that the returned array may contain more entries
246 * than the input.
247 * @param {Array<string>} deps List of dependencies.
248 * @return {Array<string>} List of paths to load.
250 function resolveClosureModuleDeps(deps) {
251 if (!depsFile && deps.length > 0) {
252 print('Can\'t have closure dependencies without a deps file.');
253 quit(-1);
255 var resultPaths = [];
256 var addedPaths = {};
258 function addPath(path) {
259 addedPaths[path] = true;
260 resultPaths.push(path);
263 function resolveAndAppend(path) {
264 if (addedPaths[path]) {
265 return;
267 // Set before recursing to catch cycles.
268 addedPaths[path] = true;
269 dependencyPathsToRequires[path].forEach(function(require) {
270 var providingPath = dependencyProvidesToPaths[require];
271 if (!providingPath) {
272 print('Unknown object', require, 'required by', path);
273 quit(-1);
275 resolveAndAppend(providingPath);
277 resultPaths.push(path);
280 // Always add closure library's base.js if provided by deps.
281 var basePath = dependencyProvidesToPaths['goog'];
282 if (basePath) {
283 addPath(basePath);
286 deps.forEach(function(dep) {
287 var providingPath = dependencyProvidesToPaths[dep];
288 if (providingPath) {
289 resolveAndAppend(providingPath);
290 } else {
291 print('Unknown dependency:', dep);
292 quit(-1);
296 return resultPaths;
300 * Output |code| verbatim.
301 * @param {string} code The code to output.
303 function GEN(code) {
304 maybeGenHeader(null);
305 output(code);
309 * Outputs |commentEncodedCode|, converting comment to enclosed C++ code.
310 * @param {function} commentEncodedCode A function in the following format (note
311 * the space in '/ *' and '* /' should be removed to form a comment delimiter):
312 * function() {/ *! my_cpp_code.DoSomething(); * /
313 * Code between / *! and * / will be extracted and written to stdout.
315 function GEN_BLOCK(commentEncodedCode) {
316 var code = commentEncodedCode.toString().
317 replace(/^[^\/]+\/\*!?/, '').
318 replace(/\*\/[^\/]+$/, '').
319 replace(/^\n|\n$/, '').
320 replace(/\s+$/, '');
321 GEN(code);
325 * Generate includes for the current |jsFile| by including them
326 * immediately and at runtime.
327 * The paths must be relative to the directory of the current file.
328 * @param {Array<string>} includes Paths to JavaScript files to
329 * include immediately and at runtime.
331 function GEN_INCLUDE(includes) {
332 for (var i = 0; i < includes.length; i++) {
333 var includePaths = includeFileToPaths(includes[i]);
334 var js = readJsFile(includePaths.path);
335 pathStack.push(includePaths);
336 ('global', eval)(js);
337 pathStack.pop();
338 genIncludes.push(includePaths.base);
343 * Generate gtest-style TEST_F definitions for C++ with a body that
344 * will invoke the |testBody| for |testFixture|.|testFunction|.
345 * @param {string} testFixture The name of this test's fixture.
346 * @param {string} testFunction The name of this test's function.
347 * @param {Function} testBody The function body to execute for this test.
349 function TEST_F(testFixture, testFunction, testBody) {
350 maybeGenHeader(testFixture);
351 var browsePreload = this[testFixture].prototype.browsePreload;
352 var browsePrintPreload = this[testFixture].prototype.browsePrintPreload;
353 var testGenPreamble = this[testFixture].prototype.testGenPreamble;
354 var testGenPostamble = this[testFixture].prototype.testGenPostamble;
355 var typedefCppFixture = this[testFixture].prototype.typedefCppFixture;
356 var isAsyncParam = testType === 'unit' ? '' :
357 this[testFixture].prototype.isAsync + ',\n ';
358 var testShouldFail = this[testFixture].prototype.testShouldFail;
359 var testPredicate = testShouldFail ? 'ASSERT_FALSE' : 'ASSERT_TRUE';
360 var extraLibraries = genIncludes.concat(
361 this[testFixture].prototype.extraLibraries.map(
362 function(includeFile) {
363 return includeFileToPaths(includeFile).base;
365 resolveClosureModuleDeps(this[testFixture].prototype.closureModuleDeps));
367 if (typedefCppFixture && !(testFixture in typedeffedCppFixtures)) {
368 var switches = this[testFixture].prototype.commandLineSwitches;
369 if (!switches || !switches.length || typedefCppFixture == 'V8UnitTest') {
370 output(`
371 typedef ${typedefCppFixture} ${testFixture};
373 } else {
374 // Make the testFixture a class inheriting from the base fixture.
375 output(`
376 class ${testFixture} : public ${typedefCppFixture} {
377 private:`);
378 // Override SetUpCommandLine and add each switch.
379 output(`
380 void SetUpCommandLine(base::CommandLine* command_line) override {`);
381 for (var i = 0; i < switches.length; i++) {
382 output(`
383 command_line->AppendSwitchASCII(
384 "${switches[i].switchName}",
385 "${(switches[i].switchValue || '')}");`);
387 output(`
392 typedeffedCppFixtures[testFixture] = typedefCppFixture;
395 output(`${testF}(${testFixture}, ${testFunction}) {`);
396 for (var i = 0; i < extraLibraries.length; i++) {
397 var libraryName = extraLibraries[i].replace(/\\/g, '/');
398 output(`
399 AddLibrary(base::FilePath(FILE_PATH_LITERAL(
400 "${libraryName}")));`);
402 output(`
403 AddLibrary(base::FilePath(FILE_PATH_LITERAL(
404 "${jsFileBase.replace(/\\/g, '/')}")));`);
405 if (addSetPreloadInfo) {
406 output(`
407 set_preload_test_fixture("${testFixture}");
408 set_preload_test_name("${testFunction}");`);
410 if (testGenPreamble)
411 testGenPreamble(testFixture, testFunction);
412 if (browsePreload)
413 output(` BrowsePreload(GURL("${browsePreload}"));`);
414 if (browsePrintPreload) {
415 output(`
416 BrowsePrintPreload(GURL(WebUITestDataPathToURL(
417 FILE_PATH_LITERAL("${browsePrintPreload}"))));`);
419 output(`
420 ${testPredicate}(
421 RunJavascriptTestF(
422 ${isAsyncParam}"${testFixture}",
423 "${testFunction}"));`);
424 if (testGenPostamble)
425 testGenPostamble(testFixture, testFunction);
426 output('}\n');
429 // Now that generation functions are defined, load in |jsFile|.
430 var js = readJsFile(jsFile);
431 pathStack.push({path: jsFile, base: jsFileBase});
432 eval(js);
433 pathStack.pop();
434 print(pendingOutput);