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.
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) {
22 ' path-to-testfile.js testfile.js path_to_deps.js output.cc test-type');
27 * Full path to the test input file.
30 var jsFile
= arguments
[1];
33 * Relative path to the test input file appropriate for use in the
34 * C++ TestFixture's addLibrary method.
37 var jsFileBase
= arguments
[2];
40 * Path to Closure library style deps.js file.
43 var depsFile
= arguments
[3];
46 * Path to C++ file generation is outputting to.
49 var outputFile
= arguments
[4];
53 * @type {string} ('extension' | 'unit' | 'webui')
55 var testType
= arguments
[5];
56 if (testType
!= 'extension' &&
58 testType
!= 'webui') {
59 print('Invalid test type: ' + testType
);
64 * C++ gtest macro to use for TEST_F depending on |testType|.
65 * @type {string} ('TEST_F'|'IN_PROC_BROWSER_TEST_F')
70 * Keeps track of whether a typedef has been generated for each test
72 * @type {Object<string>}
74 var typedeffedCppFixtures
= {};
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>}
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.
89 var addSetPreloadInfo
;
92 * Whether cc headers need to be generated.
95 var needGenHeader
= true;
98 * Helpful hint pointing back to the source js.
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
) {
128 needGenHeader
= false;
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
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';
152 addSetPreloadInfo
= false;
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;
160 #include "url/gurl.h"
161 #include "testing/gtest/include/gtest/gtest.h"`);
162 // Add includes specified by test fixture.
164 if (this[testFixture
].prototype.testGenCppIncludes
)
165 this[testFixture
].prototype.testGenCppIncludes();
166 if (this[testFixture
].prototype.commandLineSwitches
)
167 output('#include "base/command_line.h"');
174 * @type {Array<{path: string, base: string>}
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
187 function includeFileToPaths(includeFile
) {
188 paths
= pathStack
[pathStack
.length
- 1];
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.
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
= {};
221 var goog
= goog
|| {};
223 * Called by the javascript in the deps file to add modules and their
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
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
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.');
255 var resultPaths
= [];
258 function addPath(path
) {
259 addedPaths
[path
] = true;
260 resultPaths
.push(path
);
263 function resolveAndAppend(path
) {
264 if (addedPaths
[path
]) {
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
);
275 resolveAndAppend(providingPath
);
277 resultPaths
.push(path
);
280 // Always add closure library's base.js if provided by deps.
281 var basePath
= dependencyProvidesToPaths
['goog'];
286 deps
.forEach(function(dep
) {
287 var providingPath
= dependencyProvidesToPaths
[dep
];
289 resolveAndAppend(providingPath
);
291 print('Unknown dependency:', dep
);
300 * Output |code| verbatim.
301 * @param {string} code The code to output.
304 maybeGenHeader(null);
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$/, '').
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
);
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') {
371 typedef ${typedefCppFixture} ${testFixture};
374 // Make the testFixture a class inheriting from the base fixture.
376 class ${testFixture} : public ${typedefCppFixture} {
378 // Override SetUpCommandLine and add each switch.
380 void SetUpCommandLine(base::CommandLine* command_line) override {`);
381 for (var i
= 0; i
< switches
.length
; i
++) {
383 command_line->AppendSwitchASCII(
384 "${switches[i].switchName}",
385 "${(switches[i].switchValue || '')}");`);
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, '/');
399 AddLibrary(base::FilePath(FILE_PATH_LITERAL(
400 "${libraryName}")));`);
403 AddLibrary(base::FilePath(FILE_PATH_LITERAL(
404 "${jsFileBase.replace(/\\/g, '/')}")));`);
405 if (addSetPreloadInfo) {
407 set_preload_test_fixture("${testFixture}");
408 set_preload_test_name("${testFunction}");`);
411 testGenPreamble(testFixture, testFunction);
413 output(` BrowsePreload(GURL("${browsePreload}"));`);
414 if (browsePrintPreload) {
416 BrowsePrintPreload(GURL(WebUITestDataPathToURL(
417 FILE_PATH_LITERAL("${browsePrintPreload}"))));`);
422 ${isAsyncParam}"${testFixture}",
423 "${testFunction}"));`);
424 if (testGenPostamble)
425 testGenPostamble(testFixture, testFunction);
429 // Now that generation functions are defined, load in |jsFile|.
430 var js = readJsFile(jsFile);
431 pathStack.push({path: jsFile, base: jsFileBase});
434 print(pendingOutput);