Re-subimission of https://codereview.chromium.org/1041213003/
[chromium-blink-merge.git] / content / public / test / test_launcher.cc
blobfc65ebd8a94436bf4e01d23f4f080c18388d69d3
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 #include "content/public/test/test_launcher.h"
7 #include <map>
8 #include <string>
9 #include <vector>
11 #include "base/command_line.h"
12 #include "base/containers/hash_tables.h"
13 #include "base/environment.h"
14 #include "base/files/file_util.h"
15 #include "base/files/scoped_temp_dir.h"
16 #include "base/logging.h"
17 #include "base/memory/linked_ptr.h"
18 #include "base/memory/scoped_ptr.h"
19 #include "base/message_loop/message_loop.h"
20 #include "base/stl_util.h"
21 #include "base/strings/string_number_conversions.h"
22 #include "base/strings/string_util.h"
23 #include "base/strings/utf_string_conversions.h"
24 #include "base/test/launcher/test_launcher.h"
25 #include "base/test/test_suite.h"
26 #include "base/test/test_switches.h"
27 #include "base/test/test_timeouts.h"
28 #include "base/time/time.h"
29 #include "content/public/app/content_main.h"
30 #include "content/public/app/content_main_delegate.h"
31 #include "content/public/app/startup_helper_win.h"
32 #include "content/public/common/content_switches.h"
33 #include "content/public/common/sandbox_init.h"
34 #include "content/public/test/browser_test.h"
35 #include "net/base/escape.h"
36 #include "testing/gtest/include/gtest/gtest.h"
38 #if defined(OS_WIN)
39 #include "base/base_switches.h"
40 #include "content/common/sandbox_win.h"
41 #include "sandbox/win/src/sandbox_factory.h"
42 #include "sandbox/win/src/sandbox_types.h"
43 #elif defined(OS_MACOSX)
44 #include "base/mac/scoped_nsautorelease_pool.h"
45 #endif
47 namespace content {
49 namespace {
51 // Tests with this prefix run before the same test without it, and use the same
52 // profile. i.e. Foo.PRE_Test runs and then Foo.Test. This allows writing tests
53 // that span browser restarts.
54 const char kPreTestPrefix[] = "PRE_";
56 // Manual tests only run when --run-manual is specified. This allows writing
57 // tests that don't run automatically but are still in the same test binary.
58 // This is useful so that a team that wants to run a few tests doesn't have to
59 // add a new binary that must be compiled on all builds.
60 const char kManualTestPrefix[] = "MANUAL_";
62 TestLauncherDelegate* g_launcher_delegate;
63 ContentMainParams* g_params;
65 std::string RemoveAnyPrePrefixes(const std::string& test_name) {
66 std::string result(test_name);
67 ReplaceSubstringsAfterOffset(&result, 0, kPreTestPrefix, std::string());
68 return result;
71 void PrintUsage() {
72 fprintf(stdout,
73 "Runs tests using the gtest framework, each batch of tests being\n"
74 "run in their own process. Supported command-line flags:\n"
75 "\n"
76 " Common flags:\n"
77 " --gtest_filter=...\n"
78 " Runs a subset of tests (see --gtest_help for more info).\n"
79 "\n"
80 " --help\n"
81 " Shows this message.\n"
82 "\n"
83 " --gtest_help\n"
84 " Shows the gtest help message.\n"
85 "\n"
86 " --test-launcher-jobs=N\n"
87 " Sets the number of parallel test jobs to N.\n"
88 "\n"
89 " --single_process\n"
90 " Runs the tests and the launcher in the same process. Useful\n"
91 " for debugging a specific test in a debugger.\n"
92 "\n"
93 " Other flags:\n"
94 " --test-launcher-retry-limit=N\n"
95 " Sets the limit of test retries on failures to N.\n"
96 "\n"
97 " --test-launcher-summary-output=PATH\n"
98 " Saves a JSON machine-readable summary of the run.\n"
99 "\n"
100 " --test-launcher-print-test-stdio=auto|always|never\n"
101 " Controls when full test output is printed.\n"
102 " auto means to print it when the test failed.\n"
103 "\n"
104 " --test-launcher-total-shards=N\n"
105 " Sets the total number of shards to N.\n"
106 "\n"
107 " --test-launcher-shard-index=N\n"
108 " Sets the shard index to run to N (from 0 to TOTAL - 1).\n");
111 // Implementation of base::TestLauncherDelegate. This is also a test launcher,
112 // wrapping a lower-level test launcher with content-specific code.
113 class WrapperTestLauncherDelegate : public base::TestLauncherDelegate {
114 public:
115 explicit WrapperTestLauncherDelegate(
116 content::TestLauncherDelegate* launcher_delegate)
117 : launcher_delegate_(launcher_delegate) {
118 CHECK(temp_dir_.CreateUniqueTempDir());
121 // base::TestLauncherDelegate:
122 bool GetTests(std::vector<base::SplitTestName>* output) override;
123 bool ShouldRunTest(const std::string& test_case_name,
124 const std::string& test_name) override;
125 size_t RunTests(base::TestLauncher* test_launcher,
126 const std::vector<std::string>& test_names) override;
127 size_t RetryTests(base::TestLauncher* test_launcher,
128 const std::vector<std::string>& test_names) override;
130 private:
131 void DoRunTest(base::TestLauncher* test_launcher,
132 const std::string& test_name);
134 // Launches test named |test_name| using parallel launcher,
135 // given result of PRE_ test |pre_test_result|.
136 void RunDependentTest(base::TestLauncher* test_launcher,
137 const std::string test_name,
138 const base::TestResult& pre_test_result);
140 // Callback to receive result of a test.
141 void GTestCallback(
142 base::TestLauncher* test_launcher,
143 const std::string& test_name,
144 int exit_code,
145 const base::TimeDelta& elapsed_time,
146 bool was_timeout,
147 const std::string& output);
149 content::TestLauncherDelegate* launcher_delegate_;
151 // Store dependent test name (map is indexed by full test name).
152 typedef std::map<std::string, std::string> DependentTestMap;
153 DependentTestMap dependent_test_map_;
154 DependentTestMap reverse_dependent_test_map_;
156 // Store unique data directory prefix for test names (without PRE_ prefixes).
157 // PRE_ tests and tests that depend on them must share the same
158 // data directory. Using test name as directory name leads to too long
159 // names (exceeding UNIX_PATH_MAX, which creates a problem with
160 // process_singleton_linux). Create a randomly-named temporary directory
161 // and keep track of the names so that PRE_ tests can still re-use them.
162 typedef std::map<std::string, base::FilePath> UserDataDirMap;
163 UserDataDirMap user_data_dir_map_;
165 // Store names of all seen tests to properly handle PRE_ tests.
166 std::set<std::string> all_test_names_;
168 // Temporary directory for user data directories.
169 base::ScopedTempDir temp_dir_;
171 DISALLOW_COPY_AND_ASSIGN(WrapperTestLauncherDelegate);
174 bool WrapperTestLauncherDelegate::GetTests(
175 std::vector<base::SplitTestName>* output) {
176 *output = base::GetCompiledInTests();
177 return true;
180 bool WrapperTestLauncherDelegate::ShouldRunTest(
181 const std::string& test_case_name,
182 const std::string& test_name) {
183 all_test_names_.insert(test_case_name + "." + test_name);
185 if (StartsWithASCII(test_name, kManualTestPrefix, true) &&
186 !base::CommandLine::ForCurrentProcess()->HasSwitch(kRunManualTestsFlag)) {
187 return false;
190 if (StartsWithASCII(test_name, kPreTestPrefix, true)) {
191 // We will actually run PRE_ tests, but to ensure they run on the same shard
192 // as dependent tests, handle all these details internally.
193 return false;
196 return true;
199 std::string GetPreTestName(const std::string& full_name) {
200 size_t dot_pos = full_name.find('.');
201 CHECK_NE(dot_pos, std::string::npos);
202 std::string test_case_name = full_name.substr(0, dot_pos);
203 std::string test_name = full_name.substr(dot_pos + 1);
204 return test_case_name + "." + kPreTestPrefix + test_name;
207 size_t WrapperTestLauncherDelegate::RunTests(
208 base::TestLauncher* test_launcher,
209 const std::vector<std::string>& test_names) {
210 dependent_test_map_.clear();
211 reverse_dependent_test_map_.clear();
212 user_data_dir_map_.clear();
214 // Number of additional tests to run because of dependencies.
215 size_t additional_tests_to_run_count = 0;
217 // Compute dependencies of tests to be run.
218 for (size_t i = 0; i < test_names.size(); i++) {
219 std::string full_name(test_names[i]);
220 std::string pre_test_name(GetPreTestName(full_name));
222 while (ContainsKey(all_test_names_, pre_test_name)) {
223 additional_tests_to_run_count++;
225 DCHECK(!ContainsKey(dependent_test_map_, pre_test_name));
226 dependent_test_map_[pre_test_name] = full_name;
228 DCHECK(!ContainsKey(reverse_dependent_test_map_, full_name));
229 reverse_dependent_test_map_[full_name] = pre_test_name;
231 full_name = pre_test_name;
232 pre_test_name = GetPreTestName(pre_test_name);
236 for (size_t i = 0; i < test_names.size(); i++) {
237 std::string full_name(test_names[i]);
239 // Make sure no PRE_ tests were requested explicitly.
240 DCHECK_EQ(full_name, RemoveAnyPrePrefixes(full_name));
242 if (!ContainsKey(user_data_dir_map_, full_name)) {
243 base::FilePath temp_dir;
244 CHECK(base::CreateTemporaryDirInDir(temp_dir_.path(),
245 FILE_PATH_LITERAL("d"), &temp_dir));
246 user_data_dir_map_[full_name] = temp_dir;
249 // If the test has any dependencies, get to the root and start with that.
250 while (ContainsKey(reverse_dependent_test_map_, full_name))
251 full_name = GetPreTestName(full_name);
253 DoRunTest(test_launcher, full_name);
256 return test_names.size() + additional_tests_to_run_count;
259 size_t WrapperTestLauncherDelegate::RetryTests(
260 base::TestLauncher* test_launcher,
261 const std::vector<std::string>& test_names) {
262 // List of tests we can kick off right now, depending on no other tests.
263 std::vector<std::string> tests_to_run_now;
265 // We retry at least the tests requested to retry.
266 std::set<std::string> test_names_set(test_names.begin(), test_names.end());
268 // In the face of PRE_ tests, we need to retry the entire chain of tests,
269 // from the very first one.
270 for (size_t i = 0; i < test_names.size(); i++) {
271 std::string test_name(test_names[i]);
272 while (ContainsKey(reverse_dependent_test_map_, test_name)) {
273 test_name = reverse_dependent_test_map_[test_name];
274 test_names_set.insert(test_name);
278 // Discard user data directories from any previous runs. Start with
279 // fresh state.
280 for (UserDataDirMap::const_iterator i = user_data_dir_map_.begin();
281 i != user_data_dir_map_.end();
282 ++i) {
283 // Delete temporary directories now to avoid using too much space in /tmp.
284 if (!base::DeleteFile(i->second, true)) {
285 LOG(WARNING) << "Failed to delete " << i->second.value();
288 user_data_dir_map_.clear();
290 for (std::set<std::string>::const_iterator i = test_names_set.begin();
291 i != test_names_set.end();
292 ++i) {
293 std::string full_name(*i);
295 // Make sure PRE_ tests and tests that depend on them share the same
296 // data directory - based it on the test name without prefixes.
297 std::string test_name_no_pre(RemoveAnyPrePrefixes(full_name));
298 if (!ContainsKey(user_data_dir_map_, test_name_no_pre)) {
299 base::FilePath temp_dir;
300 CHECK(base::CreateTemporaryDirInDir(temp_dir_.path(),
301 FILE_PATH_LITERAL("d"), &temp_dir));
302 user_data_dir_map_[test_name_no_pre] = temp_dir;
305 size_t dot_pos = full_name.find('.');
306 CHECK_NE(dot_pos, std::string::npos);
307 std::string test_case_name = full_name.substr(0, dot_pos);
308 std::string test_name = full_name.substr(dot_pos + 1);
309 std::string pre_test_name(
310 test_case_name + "." + kPreTestPrefix + test_name);
311 if (!ContainsKey(test_names_set, pre_test_name))
312 tests_to_run_now.push_back(full_name);
315 for (size_t i = 0; i < tests_to_run_now.size(); i++)
316 DoRunTest(test_launcher, tests_to_run_now[i]);
318 return test_names_set.size();
321 void WrapperTestLauncherDelegate::DoRunTest(base::TestLauncher* test_launcher,
322 const std::string& test_name) {
323 std::string test_name_no_pre(RemoveAnyPrePrefixes(test_name));
325 base::CommandLine cmd_line(*base::CommandLine::ForCurrentProcess());
326 CHECK(launcher_delegate_->AdjustChildProcessCommandLine(
327 &cmd_line, user_data_dir_map_[test_name_no_pre]));
329 base::CommandLine new_cmd_line(cmd_line.GetProgram());
330 base::CommandLine::SwitchMap switches = cmd_line.GetSwitches();
332 // Strip out gtest_output flag because otherwise we would overwrite results
333 // of the other tests.
334 switches.erase(base::kGTestOutputFlag);
336 for (base::CommandLine::SwitchMap::const_iterator iter = switches.begin();
337 iter != switches.end(); ++iter) {
338 new_cmd_line.AppendSwitchNative(iter->first, iter->second);
341 // Always enable disabled tests. This method is not called with disabled
342 // tests unless this flag was specified to the browser test executable.
343 new_cmd_line.AppendSwitch("gtest_also_run_disabled_tests");
344 new_cmd_line.AppendSwitchASCII("gtest_filter", test_name);
345 new_cmd_line.AppendSwitch(kSingleProcessTestsFlag);
347 char* browser_wrapper = getenv("BROWSER_WRAPPER");
349 test_launcher->LaunchChildGTestProcess(
350 new_cmd_line,
351 browser_wrapper ? browser_wrapper : std::string(),
352 TestTimeouts::action_max_timeout(),
353 base::TestLauncher::USE_JOB_OBJECTS |
354 base::TestLauncher::ALLOW_BREAKAWAY_FROM_JOB,
355 base::Bind(&WrapperTestLauncherDelegate::GTestCallback,
356 base::Unretained(this),
357 test_launcher,
358 test_name));
361 void WrapperTestLauncherDelegate::RunDependentTest(
362 base::TestLauncher* test_launcher,
363 const std::string test_name,
364 const base::TestResult& pre_test_result) {
365 if (pre_test_result.status == base::TestResult::TEST_SUCCESS) {
366 // Only run the dependent test if PRE_ test succeeded.
367 DoRunTest(test_launcher, test_name);
368 } else {
369 // Otherwise skip the test.
370 base::TestResult test_result;
371 test_result.full_name = test_name;
372 test_result.status = base::TestResult::TEST_SKIPPED;
373 test_launcher->OnTestFinished(test_result);
375 if (ContainsKey(dependent_test_map_, test_name)) {
376 RunDependentTest(test_launcher,
377 dependent_test_map_[test_name],
378 test_result);
383 void WrapperTestLauncherDelegate::GTestCallback(
384 base::TestLauncher* test_launcher,
385 const std::string& test_name,
386 int exit_code,
387 const base::TimeDelta& elapsed_time,
388 bool was_timeout,
389 const std::string& output) {
390 base::TestResult result;
391 result.full_name = test_name;
393 // TODO(phajdan.jr): Recognize crashes.
394 if (exit_code == 0)
395 result.status = base::TestResult::TEST_SUCCESS;
396 else if (was_timeout)
397 result.status = base::TestResult::TEST_TIMEOUT;
398 else
399 result.status = base::TestResult::TEST_FAILURE;
401 result.elapsed_time = elapsed_time;
403 result.output_snippet = GetTestOutputSnippet(result, output);
405 if (ContainsKey(dependent_test_map_, test_name)) {
406 RunDependentTest(test_launcher, dependent_test_map_[test_name], result);
407 } else {
408 // No other tests depend on this, we can delete the temporary directory now.
409 // Do so to avoid too many temporary files using lots of disk space.
410 std::string test_name_no_pre(RemoveAnyPrePrefixes(test_name));
411 if (ContainsKey(user_data_dir_map_, test_name_no_pre)) {
412 if (!base::DeleteFile(user_data_dir_map_[test_name_no_pre], true)) {
413 LOG(WARNING) << "Failed to delete "
414 << user_data_dir_map_[test_name_no_pre].value();
416 user_data_dir_map_.erase(test_name_no_pre);
420 test_launcher->OnTestFinished(result);
423 } // namespace
425 const char kHelpFlag[] = "help";
427 const char kLaunchAsBrowser[] = "as-browser";
429 // See kManualTestPrefix above.
430 const char kRunManualTestsFlag[] = "run-manual";
432 const char kSingleProcessTestsFlag[] = "single_process";
435 TestLauncherDelegate::~TestLauncherDelegate() {
438 int LaunchTests(TestLauncherDelegate* launcher_delegate,
439 int default_jobs,
440 int argc,
441 char** argv) {
442 DCHECK(!g_launcher_delegate);
443 g_launcher_delegate = launcher_delegate;
445 base::CommandLine::Init(argc, argv);
446 const base::CommandLine* command_line =
447 base::CommandLine::ForCurrentProcess();
449 if (command_line->HasSwitch(kHelpFlag)) {
450 PrintUsage();
451 return 0;
454 scoped_ptr<ContentMainDelegate> chrome_main_delegate(
455 launcher_delegate->CreateContentMainDelegate());
456 ContentMainParams params(chrome_main_delegate.get());
458 #if defined(OS_WIN)
459 sandbox::SandboxInterfaceInfo sandbox_info = {0};
460 InitializeSandboxInfo(&sandbox_info);
462 params.instance = GetModuleHandle(NULL);
463 params.sandbox_info = &sandbox_info;
464 #elif !defined(OS_ANDROID)
465 params.argc = argc;
466 params.argv = const_cast<const char**>(argv);
467 #endif // defined(OS_WIN)
469 if (command_line->HasSwitch(kSingleProcessTestsFlag) ||
470 (command_line->HasSwitch(switches::kSingleProcess) &&
471 command_line->HasSwitch(base::kGTestFilterFlag)) ||
472 command_line->HasSwitch(base::kGTestListTestsFlag) ||
473 command_line->HasSwitch(base::kGTestHelpFlag)) {
474 g_params = &params;
475 return launcher_delegate->RunTestSuite(argc, argv);
478 #if !defined(OS_ANDROID)
479 if (command_line->HasSwitch(switches::kProcessType) ||
480 command_line->HasSwitch(kLaunchAsBrowser)) {
481 return ContentMain(params);
483 #endif
485 base::AtExitManager at_exit;
486 testing::InitGoogleTest(&argc, argv);
487 TestTimeouts::Initialize();
489 fprintf(stdout,
490 "IMPORTANT DEBUGGING NOTE: each test is run inside its own process.\n"
491 "For debugging a test inside a debugger, use the\n"
492 "--gtest_filter=<your_test_name> flag along with either\n"
493 "--single_process (to run the test in one launcher/browser process) or\n"
494 "--single-process (to do the above, and also run Chrome in single-"
495 "process mode).\n");
497 base::MessageLoopForIO message_loop;
499 // Allow the |launcher_delegate| to modify |default_jobs|.
500 launcher_delegate->AdjustDefaultParallelJobs(&default_jobs);
502 WrapperTestLauncherDelegate delegate(launcher_delegate);
503 base::TestLauncher launcher(&delegate, default_jobs);
504 return (launcher.Run() ? 0 : 1);
507 TestLauncherDelegate* GetCurrentTestLauncherDelegate() {
508 return g_launcher_delegate;
511 ContentMainParams* GetContentMainParams() {
512 return g_params;
515 } // namespace content