base: Change DCHECK_IS_ON to a macro DCHECK_IS_ON().
[chromium-blink-merge.git] / content / public / test / test_launcher.cc
blobc5de324eff1f32da09ba94136199cdb86ee0b43f
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 ShouldRunTest(const std::string& test_case_name,
123 const std::string& test_name) override;
124 size_t RunTests(base::TestLauncher* test_launcher,
125 const std::vector<std::string>& test_names) override;
126 size_t RetryTests(base::TestLauncher* test_launcher,
127 const std::vector<std::string>& test_names) override;
129 private:
130 void DoRunTest(base::TestLauncher* test_launcher,
131 const std::string& test_name);
133 // Launches test named |test_name| using parallel launcher,
134 // given result of PRE_ test |pre_test_result|.
135 void RunDependentTest(base::TestLauncher* test_launcher,
136 const std::string test_name,
137 const base::TestResult& pre_test_result);
139 // Callback to receive result of a test.
140 void GTestCallback(
141 base::TestLauncher* test_launcher,
142 const std::string& test_name,
143 int exit_code,
144 const base::TimeDelta& elapsed_time,
145 bool was_timeout,
146 const std::string& output);
148 content::TestLauncherDelegate* launcher_delegate_;
150 // Store dependent test name (map is indexed by full test name).
151 typedef std::map<std::string, std::string> DependentTestMap;
152 DependentTestMap dependent_test_map_;
153 DependentTestMap reverse_dependent_test_map_;
155 // Store unique data directory prefix for test names (without PRE_ prefixes).
156 // PRE_ tests and tests that depend on them must share the same
157 // data directory. Using test name as directory name leads to too long
158 // names (exceeding UNIX_PATH_MAX, which creates a problem with
159 // process_singleton_linux). Create a randomly-named temporary directory
160 // and keep track of the names so that PRE_ tests can still re-use them.
161 typedef std::map<std::string, base::FilePath> UserDataDirMap;
162 UserDataDirMap user_data_dir_map_;
164 // Store names of all seen tests to properly handle PRE_ tests.
165 std::set<std::string> all_test_names_;
167 // Temporary directory for user data directories.
168 base::ScopedTempDir temp_dir_;
170 DISALLOW_COPY_AND_ASSIGN(WrapperTestLauncherDelegate);
173 bool WrapperTestLauncherDelegate::ShouldRunTest(
174 const std::string& test_case_name,
175 const std::string& test_name) {
176 all_test_names_.insert(test_case_name + "." + test_name);
178 if (StartsWithASCII(test_name, kManualTestPrefix, true) &&
179 !base::CommandLine::ForCurrentProcess()->HasSwitch(kRunManualTestsFlag)) {
180 return false;
183 if (StartsWithASCII(test_name, kPreTestPrefix, true)) {
184 // We will actually run PRE_ tests, but to ensure they run on the same shard
185 // as dependent tests, handle all these details internally.
186 return false;
189 return true;
192 std::string GetPreTestName(const std::string& full_name) {
193 size_t dot_pos = full_name.find('.');
194 CHECK_NE(dot_pos, std::string::npos);
195 std::string test_case_name = full_name.substr(0, dot_pos);
196 std::string test_name = full_name.substr(dot_pos + 1);
197 return test_case_name + "." + kPreTestPrefix + test_name;
200 size_t WrapperTestLauncherDelegate::RunTests(
201 base::TestLauncher* test_launcher,
202 const std::vector<std::string>& test_names) {
203 dependent_test_map_.clear();
204 reverse_dependent_test_map_.clear();
205 user_data_dir_map_.clear();
207 // Number of additional tests to run because of dependencies.
208 size_t additional_tests_to_run_count = 0;
210 // Compute dependencies of tests to be run.
211 for (size_t i = 0; i < test_names.size(); i++) {
212 std::string full_name(test_names[i]);
213 std::string pre_test_name(GetPreTestName(full_name));
215 while (ContainsKey(all_test_names_, pre_test_name)) {
216 additional_tests_to_run_count++;
218 DCHECK(!ContainsKey(dependent_test_map_, pre_test_name));
219 dependent_test_map_[pre_test_name] = full_name;
221 DCHECK(!ContainsKey(reverse_dependent_test_map_, full_name));
222 reverse_dependent_test_map_[full_name] = pre_test_name;
224 full_name = pre_test_name;
225 pre_test_name = GetPreTestName(pre_test_name);
229 for (size_t i = 0; i < test_names.size(); i++) {
230 std::string full_name(test_names[i]);
232 // Make sure no PRE_ tests were requested explicitly.
233 DCHECK_EQ(full_name, RemoveAnyPrePrefixes(full_name));
235 if (!ContainsKey(user_data_dir_map_, full_name)) {
236 base::FilePath temp_dir;
237 CHECK(base::CreateTemporaryDirInDir(temp_dir_.path(),
238 FILE_PATH_LITERAL("d"), &temp_dir));
239 user_data_dir_map_[full_name] = temp_dir;
242 // If the test has any dependencies, get to the root and start with that.
243 while (ContainsKey(reverse_dependent_test_map_, full_name))
244 full_name = GetPreTestName(full_name);
246 DoRunTest(test_launcher, full_name);
249 return test_names.size() + additional_tests_to_run_count;
252 size_t WrapperTestLauncherDelegate::RetryTests(
253 base::TestLauncher* test_launcher,
254 const std::vector<std::string>& test_names) {
255 // List of tests we can kick off right now, depending on no other tests.
256 std::vector<std::string> tests_to_run_now;
258 // We retry at least the tests requested to retry.
259 std::set<std::string> test_names_set(test_names.begin(), test_names.end());
261 // In the face of PRE_ tests, we need to retry the entire chain of tests,
262 // from the very first one.
263 for (size_t i = 0; i < test_names.size(); i++) {
264 std::string test_name(test_names[i]);
265 while (ContainsKey(reverse_dependent_test_map_, test_name)) {
266 test_name = reverse_dependent_test_map_[test_name];
267 test_names_set.insert(test_name);
271 // Discard user data directories from any previous runs. Start with
272 // fresh state.
273 for (UserDataDirMap::const_iterator i = user_data_dir_map_.begin();
274 i != user_data_dir_map_.end();
275 ++i) {
276 // Delete temporary directories now to avoid using too much space in /tmp.
277 if (!base::DeleteFile(i->second, true)) {
278 LOG(WARNING) << "Failed to delete " << i->second.value();
281 user_data_dir_map_.clear();
283 for (std::set<std::string>::const_iterator i = test_names_set.begin();
284 i != test_names_set.end();
285 ++i) {
286 std::string full_name(*i);
288 // Make sure PRE_ tests and tests that depend on them share the same
289 // data directory - based it on the test name without prefixes.
290 std::string test_name_no_pre(RemoveAnyPrePrefixes(full_name));
291 if (!ContainsKey(user_data_dir_map_, test_name_no_pre)) {
292 base::FilePath temp_dir;
293 CHECK(base::CreateTemporaryDirInDir(temp_dir_.path(),
294 FILE_PATH_LITERAL("d"), &temp_dir));
295 user_data_dir_map_[test_name_no_pre] = temp_dir;
298 size_t dot_pos = full_name.find('.');
299 CHECK_NE(dot_pos, std::string::npos);
300 std::string test_case_name = full_name.substr(0, dot_pos);
301 std::string test_name = full_name.substr(dot_pos + 1);
302 std::string pre_test_name(
303 test_case_name + "." + kPreTestPrefix + test_name);
304 if (!ContainsKey(test_names_set, pre_test_name))
305 tests_to_run_now.push_back(full_name);
308 for (size_t i = 0; i < tests_to_run_now.size(); i++)
309 DoRunTest(test_launcher, tests_to_run_now[i]);
311 return test_names_set.size();
314 void WrapperTestLauncherDelegate::DoRunTest(base::TestLauncher* test_launcher,
315 const std::string& test_name) {
316 std::string test_name_no_pre(RemoveAnyPrePrefixes(test_name));
318 base::CommandLine cmd_line(*base::CommandLine::ForCurrentProcess());
319 CHECK(launcher_delegate_->AdjustChildProcessCommandLine(
320 &cmd_line, user_data_dir_map_[test_name_no_pre]));
322 base::CommandLine new_cmd_line(cmd_line.GetProgram());
323 base::CommandLine::SwitchMap switches = cmd_line.GetSwitches();
325 // Strip out gtest_output flag because otherwise we would overwrite results
326 // of the other tests.
327 switches.erase(base::kGTestOutputFlag);
329 for (base::CommandLine::SwitchMap::const_iterator iter = switches.begin();
330 iter != switches.end(); ++iter) {
331 new_cmd_line.AppendSwitchNative(iter->first, iter->second);
334 // Always enable disabled tests. This method is not called with disabled
335 // tests unless this flag was specified to the browser test executable.
336 new_cmd_line.AppendSwitch("gtest_also_run_disabled_tests");
337 new_cmd_line.AppendSwitchASCII("gtest_filter", test_name);
338 new_cmd_line.AppendSwitch(kSingleProcessTestsFlag);
340 char* browser_wrapper = getenv("BROWSER_WRAPPER");
342 test_launcher->LaunchChildGTestProcess(
343 new_cmd_line,
344 browser_wrapper ? browser_wrapper : std::string(),
345 TestTimeouts::action_max_timeout(),
346 base::TestLauncher::USE_JOB_OBJECTS |
347 base::TestLauncher::ALLOW_BREAKAWAY_FROM_JOB,
348 base::Bind(&WrapperTestLauncherDelegate::GTestCallback,
349 base::Unretained(this),
350 test_launcher,
351 test_name));
354 void WrapperTestLauncherDelegate::RunDependentTest(
355 base::TestLauncher* test_launcher,
356 const std::string test_name,
357 const base::TestResult& pre_test_result) {
358 if (pre_test_result.status == base::TestResult::TEST_SUCCESS) {
359 // Only run the dependent test if PRE_ test succeeded.
360 DoRunTest(test_launcher, test_name);
361 } else {
362 // Otherwise skip the test.
363 base::TestResult test_result;
364 test_result.full_name = test_name;
365 test_result.status = base::TestResult::TEST_SKIPPED;
366 test_launcher->OnTestFinished(test_result);
368 if (ContainsKey(dependent_test_map_, test_name)) {
369 RunDependentTest(test_launcher,
370 dependent_test_map_[test_name],
371 test_result);
376 void WrapperTestLauncherDelegate::GTestCallback(
377 base::TestLauncher* test_launcher,
378 const std::string& test_name,
379 int exit_code,
380 const base::TimeDelta& elapsed_time,
381 bool was_timeout,
382 const std::string& output) {
383 base::TestResult result;
384 result.full_name = test_name;
386 // TODO(phajdan.jr): Recognize crashes.
387 if (exit_code == 0)
388 result.status = base::TestResult::TEST_SUCCESS;
389 else if (was_timeout)
390 result.status = base::TestResult::TEST_TIMEOUT;
391 else
392 result.status = base::TestResult::TEST_FAILURE;
394 result.elapsed_time = elapsed_time;
396 result.output_snippet = GetTestOutputSnippet(result, output);
398 if (ContainsKey(dependent_test_map_, test_name)) {
399 RunDependentTest(test_launcher, dependent_test_map_[test_name], result);
400 } else {
401 // No other tests depend on this, we can delete the temporary directory now.
402 // Do so to avoid too many temporary files using lots of disk space.
403 std::string test_name_no_pre(RemoveAnyPrePrefixes(test_name));
404 if (ContainsKey(user_data_dir_map_, test_name_no_pre)) {
405 if (!base::DeleteFile(user_data_dir_map_[test_name_no_pre], true)) {
406 LOG(WARNING) << "Failed to delete "
407 << user_data_dir_map_[test_name_no_pre].value();
409 user_data_dir_map_.erase(test_name_no_pre);
413 test_launcher->OnTestFinished(result);
416 } // namespace
418 const char kHelpFlag[] = "help";
420 const char kLaunchAsBrowser[] = "as-browser";
422 // See kManualTestPrefix above.
423 const char kRunManualTestsFlag[] = "run-manual";
425 const char kSingleProcessTestsFlag[] = "single_process";
428 TestLauncherDelegate::~TestLauncherDelegate() {
431 int LaunchTests(TestLauncherDelegate* launcher_delegate,
432 int default_jobs,
433 int argc,
434 char** argv) {
435 DCHECK(!g_launcher_delegate);
436 g_launcher_delegate = launcher_delegate;
438 base::CommandLine::Init(argc, argv);
439 const base::CommandLine* command_line =
440 base::CommandLine::ForCurrentProcess();
442 if (command_line->HasSwitch(kHelpFlag)) {
443 PrintUsage();
444 return 0;
447 scoped_ptr<ContentMainDelegate> chrome_main_delegate(
448 launcher_delegate->CreateContentMainDelegate());
449 ContentMainParams params(chrome_main_delegate.get());
451 #if defined(OS_WIN)
452 sandbox::SandboxInterfaceInfo sandbox_info = {0};
453 InitializeSandboxInfo(&sandbox_info);
455 params.instance = GetModuleHandle(NULL);
456 params.sandbox_info = &sandbox_info;
457 #elif !defined(OS_ANDROID)
458 params.argc = argc;
459 params.argv = const_cast<const char**>(argv);
460 #endif // defined(OS_WIN)
462 if (command_line->HasSwitch(kSingleProcessTestsFlag) ||
463 (command_line->HasSwitch(switches::kSingleProcess) &&
464 command_line->HasSwitch(base::kGTestFilterFlag)) ||
465 command_line->HasSwitch(base::kGTestListTestsFlag) ||
466 command_line->HasSwitch(base::kGTestHelpFlag)) {
467 g_params = &params;
468 return launcher_delegate->RunTestSuite(argc, argv);
471 #if !defined(OS_ANDROID)
472 if (command_line->HasSwitch(switches::kProcessType) ||
473 command_line->HasSwitch(kLaunchAsBrowser)) {
474 return ContentMain(params);
476 #endif
478 base::AtExitManager at_exit;
479 testing::InitGoogleTest(&argc, argv);
480 TestTimeouts::Initialize();
482 fprintf(stdout,
483 "IMPORTANT DEBUGGING NOTE: each test is run inside its own process.\n"
484 "For debugging a test inside a debugger, use the\n"
485 "--gtest_filter=<your_test_name> flag along with either\n"
486 "--single_process (to run the test in one launcher/browser process) or\n"
487 "--single-process (to do the above, and also run Chrome in single-"
488 "process mode).\n");
490 base::MessageLoopForIO message_loop;
492 // Allow the |launcher_delegate| to modify |default_jobs|.
493 launcher_delegate->AdjustDefaultParallelJobs(&default_jobs);
495 WrapperTestLauncherDelegate delegate(launcher_delegate);
496 base::TestLauncher launcher(&delegate, default_jobs);
497 return (launcher.Run() ? 0 : 1);
500 TestLauncherDelegate* GetCurrentTestLauncherDelegate() {
501 return g_launcher_delegate;
504 ContentMainParams* GetContentMainParams() {
505 return g_params;
508 } // namespace content