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 tools/gypv8sh.py
16 // Arguments from rules in chrome_tests.gypi are passed in through
17 // python script gypv8sh.py.
18 if (arguments
.length
!= 6) {
21 ' path-to-testfile.js testfile.js path_to_deps.js output.cc test-type');
26 * Full path to the test input file.
29 var jsFile
= arguments
[1];
32 * Relative path to the test input file appropriate for use in the
33 * C++ TestFixture's addLibrary method.
36 var jsFileBase
= arguments
[2];
39 * The cwd, as determined by the paths of |jsFile| and |jsFileBase|.
40 * This is usually relative to the root source directory and points to the
41 * directory where the GYP rule processing the js file lives.
43 var jsDirBase
= jsFileBase
.replace(jsFile
, '');
46 * Path to Closure library style deps.js file.
49 var depsFile
= arguments
[3];
52 * Path to C++ file generation is outputting to.
55 var outputFile
= arguments
[4];
59 * @type {string} ('extension' | 'unit' | 'webui')
61 var testType
= arguments
[5];
62 if (testType
!= 'extension' &&
64 testType
!= 'webui') {
65 print('Invalid test type: ' + testType
);
70 * C++ gtest macro to use for TEST_F depending on |testType|.
71 * @type {string} ('TEST_F'|'IN_PROC_BROWSER_TEST_F')
76 * Keeps track of whether a typedef has been generated for each test
78 * @type {Object<string>}
80 var typedeffedCppFixtures
= {};
83 * Maintains a list of relative file paths to add to each gtest body
84 * for inclusion at runtime before running each JavaScript test.
85 * @type {Array<string>}
90 * When true, add calls to set_preload_test_(fixture|name). This is needed when
91 * |testType| === 'webui' to send an injection message before the page loads,
92 * but is not required or supported by any other test type.
95 var addSetPreloadInfo
;
98 * Whether cc headers need to be generated.
101 var needGenHeader
= true;
104 * Helpful hint pointing back to the source js.
107 var argHint
= '// ' + this['arguments'].join(' ');
111 * Generates the header of the cc file to stdout.
112 * @param {string?} testFixture Name of test fixture.
114 function maybeGenHeader(testFixture
) {
117 needGenHeader
= false;
118 print('// GENERATED FILE');
120 print('// PLEASE DO NOT HAND EDIT!');
123 // Output some C++ headers based upon the |testType|.
125 // Currently supports:
126 // 'extension' - browser_tests harness, js2extension rule,
127 // ExtensionJSBrowserTest superclass.
128 // 'unit' - unit_tests harness, js2unit rule, V8UnitTest superclass.
129 // 'webui' - browser_tests harness, js2webui rule, WebUIBrowserTest
131 if (testType
=== 'extension') {
132 print('#include "chrome/test/base/extension_js_browser_test.h"');
133 testing
.Test
.prototype.typedefCppFixture
= 'ExtensionJSBrowserTest';
134 addSetPreloadInfo
= false;
135 testF
= 'IN_PROC_BROWSER_TEST_F';
136 } else if (testType
=== 'unit') {
137 print('#include "chrome/test/base/v8_unit_test.h"');
138 testing
.Test
.prototype.typedefCppFixture
= 'V8UnitTest';
140 addSetPreloadInfo
= false;
142 print('#include "chrome/test/base/web_ui_browser_test.h"');
143 testing
.Test
.prototype.typedefCppFixture
= 'WebUIBrowserTest';
144 testF
= 'IN_PROC_BROWSER_TEST_F';
145 addSetPreloadInfo
= true;
147 print('#include "url/gurl.h"');
148 print('#include "testing/gtest/include/gtest/gtest.h"');
149 // Add includes specified by test fixture.
151 if (this[testFixture
].prototype.testGenCppIncludes
)
152 this[testFixture
].prototype.testGenCppIncludes();
153 if (this[testFixture
].prototype.commandLineSwitches
)
154 print('#include "base/command_line.h"');
161 * Convert the |includeFile| to paths appropriate for immediate
162 * inclusion (path) and runtime inclusion (base).
163 * @param {string} includeFile The file to include.
164 * @return {{path: string, base: string}} Object describing the paths
165 * for |includeFile|. |path| is relative to cwd; |base| is relative to
168 function includeFileToPaths(includeFile
) {
169 if (includeFile
.indexOf(jsDirBase
) == 0) {
170 // The caller supplied a path relative to root source.
171 var relPath
= includeFile
.replace(jsDirBase
, '');
174 base
: jsDirBase
+ relPath
178 // The caller supplied a path relative to the input js file's directory (cwd).
180 path
: jsFile
.replace(/[^\/\\]+$/, includeFile
),
181 base
: jsFileBase
.replace(/[^\/\\]+$/, includeFile
),
187 * Maps object names to the path to the file that provides them.
188 * Populated from the |depsFile| if any.
189 * @type {Object<string>}
191 var dependencyProvidesToPaths
= {};
194 * Maps dependency path names to object names required by the file.
195 * Populated from the |depsFile| if any.
196 * @type {Object<Array<string>>}
198 var dependencyPathsToRequires
= {};
201 var goog
= goog
|| {};
203 * Called by the javascript in the deps file to add modules and their
205 * @param {string} path Relative path to the file.
206 * @param Array<string> provides Objects provided by this file.
207 * @param Array<string> requires Objects required by this file.
209 goog
.addDependency = function(path
, provides
, requires
) {
210 provides
.forEach(function(provide
) {
211 dependencyProvidesToPaths
[provide
] = path
;
213 dependencyPathsToRequires
[path
] = requires
;
216 // Read and eval the deps file. It should only contain goog.addDependency
218 eval(read(depsFile
));
222 * Resolves a list of libraries to an ordered list of paths to load by the
223 * generated C++. The input should contain object names provided
224 * by the deps file. Dependencies will be resolved and included in the
225 * correct order, meaning that the returned array may contain more entries
227 * @param {Array<string>} deps List of dependencies.
228 * @return {Array<string>} List of paths to load.
230 function resolveClosureModuleDeps(deps
) {
231 if (!depsFile
&& deps
.length
> 0) {
232 print('Can\'t have closure dependencies without a deps file.');
235 var resultPaths
= [];
238 function addPath(path
) {
239 addedPaths
[path
] = true;
240 resultPaths
.push(path
);
243 function resolveAndAppend(path
) {
244 if (addedPaths
[path
]) {
247 // Set before recursing to catch cycles.
248 addedPaths
[path
] = true;
249 dependencyPathsToRequires
[path
].forEach(function(require
) {
250 var providingPath
= dependencyProvidesToPaths
[require
];
251 if (!providingPath
) {
252 print('Unknown object', require
, 'required by', path
);
255 resolveAndAppend(providingPath
);
257 resultPaths
.push(path
);
260 // Always add closure library's base.js if provided by deps.
261 var basePath
= dependencyProvidesToPaths
['goog'];
266 deps
.forEach(function(dep
) {
267 var providingPath
= dependencyProvidesToPaths
[dep
];
269 resolveAndAppend(providingPath
);
271 print('Unknown dependency:', dep
);
280 * Output |code| verbatim.
281 * @param {string} code The code to output.
284 maybeGenHeader(null);
289 * Outputs |commentEncodedCode|, converting comment to enclosed C++ code.
290 * @param {function} commentEncodedCode A function in the following format (note
291 * the space in '/ *' and '* /' should be removed to form a comment delimiter):
292 * function() {/ *! my_cpp_code.DoSomething(); * /
293 * Code between / *! and * / will be extracted and written to stdout.
295 function GEN_BLOCK(commentEncodedCode
) {
296 var code
= commentEncodedCode
.toString().
297 replace(/^[^\/]+\/\*!?/, '').
298 replace(/\*\/[^\/]+$/, '').
299 replace(/^\n|\n$/, '').
305 * Generate includes for the current |jsFile| by including them
306 * immediately and at runtime.
307 * The paths are allowed to be:
308 * 1. relative to the root src directory (i.e. similar to #include's).
309 * 2. relative to the directory specified in the GYP rule for the file.
310 * @param {Array<string>} includes Paths to JavaScript files to
311 * include immediately and at runtime.
313 function GEN_INCLUDE(includes
) {
314 for (var i
= 0; i
< includes
.length
; i
++) {
315 var includePaths
= includeFileToPaths(includes
[i
]);
316 var js
= read(includePaths
.path
);
317 ('global', eval
)(js
);
318 genIncludes
.push(includePaths
.base
);
323 * Generate gtest-style TEST_F definitions for C++ with a body that
324 * will invoke the |testBody| for |testFixture|.|testFunction|.
325 * @param {string} testFixture The name of this test's fixture.
326 * @param {string} testFunction The name of this test's function.
327 * @param {Function} testBody The function body to execute for this test.
329 function TEST_F(testFixture
, testFunction
, testBody
) {
330 maybeGenHeader(testFixture
);
331 var browsePreload
= this[testFixture
].prototype.browsePreload
;
332 var browsePrintPreload
= this[testFixture
].prototype.browsePrintPreload
;
333 var testGenPreamble
= this[testFixture
].prototype.testGenPreamble
;
334 var testGenPostamble
= this[testFixture
].prototype.testGenPostamble
;
335 var typedefCppFixture
= this[testFixture
].prototype.typedefCppFixture
;
336 var isAsyncParam
= testType
=== 'unit' ? '' :
337 this[testFixture
].prototype.isAsync
+ ', ';
338 var testShouldFail
= this[testFixture
].prototype.testShouldFail
;
339 var testPredicate
= testShouldFail
? 'ASSERT_FALSE' : 'ASSERT_TRUE';
340 var extraLibraries
= genIncludes
.concat(
341 this[testFixture
].prototype.extraLibraries
.map(
342 function(includeFile
) {
343 return includeFileToPaths(includeFile
).base
;
345 resolveClosureModuleDeps(this[testFixture
].prototype.closureModuleDeps
));
347 if (typedefCppFixture
&& !(testFixture
in typedeffedCppFixtures
)) {
348 var switches
= this[testFixture
].prototype.commandLineSwitches
;
349 if (!switches
|| !switches
.length
|| typedefCppFixture
== 'V8UnitTest') {
350 print('typedef ' + typedefCppFixture
+ ' ' + testFixture
+ ';');
352 // Make the testFixture a class inheriting from the base fixture.
353 print('class ' + testFixture
+ ' : public ' + typedefCppFixture
+ ' {');
355 // Override SetUpCommandLine and add each switch.
357 print(' SetUpCommandLine(base::CommandLine* command_line) override {');
358 for (var i
= 0; i
< switches
.length
; i
++) {
359 print(' command_line->AppendSwitchASCII(');
360 print(' "' + switches
[i
].switchName
+ '",');
361 print(' "' + (switches
[i
].switchValue
|| '') + '");');
366 typedeffedCppFixtures
[testFixture
] = typedefCppFixture
;
369 print(testF
+ '(' + testFixture
+ ', ' + testFunction
+ ') {');
370 for (var i
= 0; i
< extraLibraries
.length
; i
++) {
371 print(' AddLibrary(base::FilePath(FILE_PATH_LITERAL("' +
372 extraLibraries
[i
].replace(/\\/g, '/') + '")));');
374 print(' AddLibrary(base::FilePath(FILE_PATH_LITERAL("' +
375 jsFileBase.replace(/\\/g, '/') + '")));');
376 if (addSetPreloadInfo) {
377 print(' set_preload_test_fixture("' + testFixture + '");');
378 print(' set_preload_test_name("' + testFunction + '");');
381 testGenPreamble(testFixture, testFunction);
383 print(' BrowsePreload(GURL("' + browsePreload + '"));');
384 if (browsePrintPreload) {
385 print(' BrowsePrintPreload(GURL(WebUITestDataPathToURL(\n' +
386 ' FILE_PATH_LITERAL("' + browsePrintPreload + '"))));');
388 print(' ' + testPredicate + '(RunJavascriptTestF(' + isAsyncParam +
389 '"' + testFixture + '", ' +
390 '"' + testFunction + '"));');
391 if (testGenPostamble)
392 testGenPostamble(testFixture, testFunction);
397 // Now that generation functions are defined, load in |jsFile|.
398 var js = read(jsFile);