Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(58)

Side by Side Diff: content/test/test_launcher.cc

Issue 8036044: Add (not yet working) content_browsertests target. (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src/
Patch Set: '' Created 9 years, 2 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
« no previous file with comments | « content/test/test_launcher.h ('k') | no next file » | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
Property Changes:
Added: svn:eol-style
+ LF
OLDNEW
(Empty)
1 // Copyright (c) 2011 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.
4
5 #include "content/test/test_launcher.h"
6
7 #include <string>
8 #include <vector>
9
10 #include "base/command_line.h"
11 #include "base/environment.h"
12 #include "base/file_util.h"
13 #include "base/hash_tables.h"
14 #include "base/logging.h"
15 #include "base/mac/scoped_nsautorelease_pool.h"
16 #include "base/memory/linked_ptr.h"
17 #include "base/memory/scoped_ptr.h"
18 #include "base/process_util.h"
19 #include "base/scoped_temp_dir.h"
20 #include "base/string_number_conversions.h"
21 #include "base/string_util.h"
22 #include "base/test/test_suite.h"
23 #include "base/test/test_timeouts.h"
24 #include "base/time.h"
25 #include "base/utf_string_conversions.h"
26 #include "content/test/browser_test.h"
27 #include "net/base/escape.h"
28 #include "testing/gtest/include/gtest/gtest.h"
29
30 namespace test_launcher {
31
32 namespace {
33
34 // The environment variable name for the total number of test shards.
35 static const char kTestTotalShards[] = "GTEST_TOTAL_SHARDS";
36 // The environment variable name for the test shard index.
37 static const char kTestShardIndex[] = "GTEST_SHARD_INDEX";
38
39 // The default output file for XML output.
40 static const FilePath::CharType kDefaultOutputFile[] = FILE_PATH_LITERAL(
41 "test_detail.xml");
42
43 // Name of the empty test below.
44 static const char kEmptyTestName[] = "InProcessBrowserTest.Empty";
45
46 // An empty test (it starts up and shuts down the browser as part of its
47 // setup and teardown) used to prefetch all of the browser code into memory.
48 IN_PROC_BROWSER_TEST_F(InProcessBrowserTest, Empty) {
49 }
50
51 // Parses the environment variable var as an Int32. If it is unset, returns
52 // default_val. If it is set, unsets it then converts it to Int32 before
53 // returning it. If unsetting or converting to an Int32 fails, print an
54 // error and exit with failure.
55 int32 Int32FromEnvOrDie(const char* const var, int32 default_val) {
56 scoped_ptr<base::Environment> env(base::Environment::Create());
57 std::string str_val;
58 int32 result;
59 if (!env->GetVar(var, &str_val))
60 return default_val;
61 if (!env->UnSetVar(var)) {
62 LOG(ERROR) << "Invalid environment: we could not unset " << var << ".\n";
63 exit(EXIT_FAILURE);
64 }
65 if (!base::StringToInt(str_val, &result)) {
66 LOG(ERROR) << "Invalid environment: " << var << " is not an integer.\n";
67 exit(EXIT_FAILURE);
68 }
69 return result;
70 }
71
72 // Checks whether sharding is enabled by examining the relevant
73 // environment variable values. If the variables are present,
74 // but inconsistent (i.e., shard_index >= total_shards), prints
75 // an error and exits.
76 bool ShouldShard(int32* total_shards, int32* shard_index) {
77 *total_shards = Int32FromEnvOrDie(kTestTotalShards, -1);
78 *shard_index = Int32FromEnvOrDie(kTestShardIndex, -1);
79
80 if (*total_shards == -1 && *shard_index == -1) {
81 return false;
82 } else if (*total_shards == -1 && *shard_index != -1) {
83 LOG(ERROR) << "Invalid environment variables: you have "
84 << kTestShardIndex << " = " << *shard_index
85 << ", but have left " << kTestTotalShards << " unset.\n";
86 exit(EXIT_FAILURE);
87 } else if (*total_shards != -1 && *shard_index == -1) {
88 LOG(ERROR) << "Invalid environment variables: you have "
89 << kTestTotalShards << " = " << *total_shards
90 << ", but have left " << kTestShardIndex << " unset.\n";
91 exit(EXIT_FAILURE);
92 } else if (*shard_index < 0 || *shard_index >= *total_shards) {
93 LOG(ERROR) << "Invalid environment variables: we require 0 <= "
94 << kTestShardIndex << " < " << kTestTotalShards
95 << ", but you have " << kTestShardIndex << "=" << *shard_index
96 << ", " << kTestTotalShards << "=" << *total_shards << ".\n";
97 exit(EXIT_FAILURE);
98 }
99
100 return *total_shards > 1;
101 }
102
103 // Given the total number of shards, the shard index, and the test id, returns
104 // true iff the test should be run on this shard. The test id is some arbitrary
105 // but unique non-negative integer assigned by this launcher to each test
106 // method. Assumes that 0 <= shard_index < total_shards, which is first
107 // verified in ShouldShard().
108 bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) {
109 return (test_id % total_shards) == shard_index;
110 }
111
112 // A helper class to output results.
113 // Note: as currently XML is the only supported format by gtest, we don't
114 // check output format (e.g. "xml:" prefix) here and output an XML file
115 // unconditionally.
116 // Note: we don't output per-test-case or total summary info like
117 // total failed_test_count, disabled_test_count, elapsed_time and so on.
118 // Only each test (testcase element in the XML) will have the correct
119 // failed/disabled/elapsed_time information. Each test won't include
120 // detailed failure messages either.
121 class ResultsPrinter {
122 public:
123 explicit ResultsPrinter(const CommandLine& command_line);
124 ~ResultsPrinter();
125 void OnTestCaseStart(const char* name, int test_count) const;
126 void OnTestCaseEnd() const;
127
128 void OnTestEnd(const char* name, const char* case_name, bool run,
129 bool failed, bool failure_ignored, double elapsed_time) const;
130 private:
131 FILE* out_;
132
133 DISALLOW_COPY_AND_ASSIGN(ResultsPrinter);
134 };
135
136 ResultsPrinter::ResultsPrinter(const CommandLine& command_line) : out_(NULL) {
137 if (!command_line.HasSwitch(kGTestOutputFlag))
138 return;
139 std::string flag = command_line.GetSwitchValueASCII(kGTestOutputFlag);
140 size_t colon_pos = flag.find(':');
141 FilePath path;
142 if (colon_pos != std::string::npos) {
143 FilePath flag_path = command_line.GetSwitchValuePath(kGTestOutputFlag);
144 FilePath::StringType path_string = flag_path.value();
145 path = FilePath(path_string.substr(colon_pos + 1));
146 // If the given path ends with '/', consider it is a directory.
147 // Note: This does NOT check that a directory (or file) actually exists
148 // (the behavior is same as what gtest does).
149 if (file_util::EndsWithSeparator(path)) {
150 FilePath executable = command_line.GetProgram().BaseName();
151 path = path.Append(executable.ReplaceExtension(
152 FilePath::StringType(FILE_PATH_LITERAL("xml"))));
153 }
154 }
155 if (path.value().empty())
156 path = FilePath(kDefaultOutputFile);
157 FilePath dir_name = path.DirName();
158 if (!file_util::DirectoryExists(dir_name)) {
159 LOG(WARNING) << "The output directory does not exist. "
160 << "Creating the directory: " << dir_name.value();
161 // Create the directory if necessary (because the gtest does the same).
162 file_util::CreateDirectory(dir_name);
163 }
164 out_ = file_util::OpenFile(path, "w");
165 if (!out_) {
166 LOG(ERROR) << "Cannot open output file: "
167 << path.value() << ".";
168 return;
169 }
170 fprintf(out_, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
171 fprintf(out_, "<testsuites name=\"AllTests\" tests=\"\" failures=\"\""
172 " disabled=\"\" errors=\"\" time=\"\">\n");
173 }
174
175 ResultsPrinter::~ResultsPrinter() {
176 if (!out_)
177 return;
178 fprintf(out_, "</testsuites>\n");
179 fclose(out_);
180 }
181
182 void ResultsPrinter::OnTestCaseStart(const char* name, int test_count) const {
183 if (!out_)
184 return;
185 fprintf(out_, " <testsuite name=\"%s\" tests=\"%d\" failures=\"\""
186 " disabled=\"\" errors=\"\" time=\"\">\n", name, test_count);
187 }
188
189 void ResultsPrinter::OnTestCaseEnd() const {
190 if (!out_)
191 return;
192 fprintf(out_, " </testsuite>\n");
193 }
194
195 void ResultsPrinter::OnTestEnd(const char* name,
196 const char* case_name,
197 bool run,
198 bool failed,
199 bool failure_ignored,
200 double elapsed_time) const {
201 if (!out_)
202 return;
203 fprintf(out_, " <testcase name=\"%s\" status=\"%s\" time=\"%.3f\""
204 " classname=\"%s\"",
205 name, run ? "run" : "notrun", elapsed_time / 1000.0, case_name);
206 if (!failed) {
207 fprintf(out_, " />\n");
208 return;
209 }
210 fprintf(out_, ">\n");
211 fprintf(out_, " <failure message=\"\" type=\"\"%s></failure>\n",
212 failure_ignored ? " ignored=\"true\"" : "");
213 fprintf(out_, " </testcase>\n");
214 }
215
216 class TestCasePrinterHelper {
217 public:
218 TestCasePrinterHelper(const ResultsPrinter& printer,
219 const char* name,
220 int total_test_count)
221 : printer_(printer) {
222 printer_.OnTestCaseStart(name, total_test_count);
223 }
224 ~TestCasePrinterHelper() {
225 printer_.OnTestCaseEnd();
226 }
227 private:
228 const ResultsPrinter& printer_;
229
230 DISALLOW_COPY_AND_ASSIGN(TestCasePrinterHelper);
231 };
232
233 // For a basic pattern matching for gtest_filter options. (Copied from
234 // gtest.cc, see the comment below and http://crbug.com/44497)
235 bool PatternMatchesString(const char* pattern, const char* str) {
236 switch (*pattern) {
237 case '\0':
238 case ':': // Either ':' or '\0' marks the end of the pattern.
239 return *str == '\0';
240 case '?': // Matches any single character.
241 return *str != '\0' && PatternMatchesString(pattern + 1, str + 1);
242 case '*': // Matches any string (possibly empty) of characters.
243 return (*str != '\0' && PatternMatchesString(pattern, str + 1)) ||
244 PatternMatchesString(pattern + 1, str);
245 default: // Non-special character. Matches itself.
246 return *pattern == *str &&
247 PatternMatchesString(pattern + 1, str + 1);
248 }
249 }
250
251 // TODO(phajdan.jr): Avoid duplicating gtest code. (http://crbug.com/44497)
252 // For basic pattern matching for gtest_filter options. (Copied from
253 // gtest.cc)
254 bool MatchesFilter(const std::string& name, const std::string& filter) {
255 const char *cur_pattern = filter.c_str();
256 for (;;) {
257 if (PatternMatchesString(cur_pattern, name.c_str())) {
258 return true;
259 }
260
261 // Finds the next pattern in the filter.
262 cur_pattern = strchr(cur_pattern, ':');
263
264 // Returns if no more pattern can be found.
265 if (cur_pattern == NULL) {
266 return false;
267 }
268
269 // Skips the pattern separater (the ':' character).
270 cur_pattern++;
271 }
272 }
273
274 // A multiplier for slow tests. We generally avoid multiplying
275 // test timeouts by any constants. Here it is used as last resort
276 // to implement the SLOW_ test prefix.
277 static const int kSlowTestTimeoutMultiplier = 5;
278
279 int GetTestTerminationTimeout(const std::string& test_name,
280 int default_timeout_ms) {
281 int timeout_ms = default_timeout_ms;
282
283 // Make it possible for selected tests to request a longer timeout.
284 // Generally tests should really avoid doing too much, and splitting
285 // a test instead of using SLOW prefix is strongly preferred.
286 if (test_name.find("SLOW_") != std::string::npos)
287 timeout_ms *= kSlowTestTimeoutMultiplier;
288
289 return timeout_ms;
290 }
291
292 // Runs test specified by |test_name| in a child process,
293 // and returns the exit code.
294 int RunTest(TestLauncherDelegate* launcher_delegate,
295 const std::string& test_name,
296 int default_timeout_ms) {
297 // Some of the below method calls will leak objects if there is no
298 // autorelease pool in place.
299 base::mac::ScopedNSAutoreleasePool pool;
300
301 const CommandLine* cmd_line = CommandLine::ForCurrentProcess();
302 CommandLine new_cmd_line(cmd_line->GetProgram());
303 CommandLine::SwitchMap switches = cmd_line->GetSwitches();
304
305 // Strip out gtest_output flag because otherwise we would overwrite results
306 // of the previous test. We will generate the final output file later
307 // in RunTests().
308 switches.erase(kGTestOutputFlag);
309
310 // Strip out gtest_repeat flag because we can only run one test in the child
311 // process (restarting the browser in the same process is illegal after it
312 // has been shut down and will actually crash).
313 switches.erase(kGTestRepeatFlag);
314
315 for (CommandLine::SwitchMap::const_iterator iter = switches.begin();
316 iter != switches.end(); ++iter) {
317 new_cmd_line.AppendSwitchNative((*iter).first, (*iter).second);
318 }
319
320 // Always enable disabled tests. This method is not called with disabled
321 // tests unless this flag was specified to the browser test executable.
322 new_cmd_line.AppendSwitch("gtest_also_run_disabled_tests");
323 new_cmd_line.AppendSwitchASCII("gtest_filter", test_name);
324 new_cmd_line.AppendSwitch(kSingleProcessTestsFlag);
325
326 // Do not let the child ignore failures. We need to propagate the
327 // failure status back to the parent.
328 new_cmd_line.AppendSwitch(base::TestSuite::kStrictFailureHandling);
329
330 if (!launcher_delegate->AdjustChildProcessCommandLine(&new_cmd_line))
331 return -1;
332
333 const char* browser_wrapper = getenv("BROWSER_WRAPPER");
334 if (browser_wrapper) {
335 #if defined(OS_WIN)
336 new_cmd_line.PrependWrapper(ASCIIToWide(browser_wrapper));
337 #elif defined(OS_POSIX)
338 new_cmd_line.PrependWrapper(browser_wrapper);
339 #endif
340 VLOG(1) << "BROWSER_WRAPPER was set, prefixing command_line with "
341 << browser_wrapper;
342 }
343
344 base::ProcessHandle process_handle;
345 base::LaunchOptions options;
346
347 #if defined(OS_POSIX)
348 // On POSIX, we launch the test in a new process group with pgid equal to
349 // its pid. Any child processes that the test may create will inherit the
350 // same pgid. This way, if the test is abruptly terminated, we can clean up
351 // any orphaned child processes it may have left behind.
352 options.new_process_group = true;
353 #endif
354
355 if (!base::LaunchProcess(new_cmd_line, options, &process_handle))
356 return -1;
357
358 int timeout_ms = GetTestTerminationTimeout(test_name,
359 default_timeout_ms);
360
361 int exit_code = 0;
362 if (!base::WaitForExitCodeWithTimeout(process_handle, &exit_code,
363 timeout_ms)) {
364 LOG(ERROR) << "Test timeout (" << timeout_ms
365 << " ms) exceeded for " << test_name;
366
367 exit_code = -1; // Set a non-zero exit code to signal a failure.
368
369 // Ensure that the process terminates.
370 base::KillProcess(process_handle, -1, true);
371 }
372
373 #if defined(OS_POSIX)
374 if (exit_code != 0) {
375 // On POSIX, in case the test does not exit cleanly, either due to a crash
376 // or due to it timing out, we need to clean up any child processes that
377 // it might have created. On Windows, child processes are automatically
378 // cleaned up using JobObjects.
379 base::KillProcessGroup(process_handle);
380 }
381 #endif
382
383 base::CloseProcessHandle(process_handle);
384
385 return exit_code;
386 }
387
388 bool RunTests(TestLauncherDelegate* launcher_delegate,
389 bool should_shard,
390 int total_shards,
391 int shard_index) {
392 const CommandLine* command_line = CommandLine::ForCurrentProcess();
393
394 DCHECK(!command_line->HasSwitch(kGTestListTestsFlag));
395
396 testing::UnitTest* const unit_test = testing::UnitTest::GetInstance();
397
398 std::string filter = command_line->GetSwitchValueASCII(kGTestFilterFlag);
399
400 // Split --gtest_filter at '-', if there is one, to separate into
401 // positive filter and negative filter portions.
402 std::string positive_filter = filter;
403 std::string negative_filter = "";
404 size_t dash_pos = filter.find('-');
405 if (dash_pos != std::string::npos) {
406 positive_filter = filter.substr(0, dash_pos); // Everything up to the dash.
407 negative_filter = filter.substr(dash_pos + 1); // Everything after the dash.
408 }
409
410 int num_runnable_tests = 0;
411 int test_run_count = 0;
412 int ignored_failure_count = 0;
413 std::vector<std::string> failed_tests;
414
415 ResultsPrinter printer(*command_line);
416 for (int i = 0; i < unit_test->total_test_case_count(); ++i) {
417 const testing::TestCase* test_case = unit_test->GetTestCase(i);
418 TestCasePrinterHelper helper(printer, test_case->name(),
419 test_case->total_test_count());
420 for (int j = 0; j < test_case->total_test_count(); ++j) {
421 const testing::TestInfo* test_info = test_case->GetTestInfo(j);
422 std::string test_name = test_info->test_case_name();
423 test_name.append(".");
424 test_name.append(test_info->name());
425
426 // Skip our special test so it's not run twice. That confuses
427 // the log parser.
428 if (test_name == kEmptyTestName)
429 continue;
430
431 // Skip disabled tests.
432 if (test_name.find("DISABLED") != std::string::npos &&
433 !command_line->HasSwitch(kGTestRunDisabledTestsFlag)) {
434 printer.OnTestEnd(test_info->name(), test_case->name(),
435 false, false, false, 0);
436 continue;
437 }
438
439 // Skip the test that doesn't match the filter string (if given).
440 if ((!positive_filter.empty() &&
441 !MatchesFilter(test_name, positive_filter)) ||
442 MatchesFilter(test_name, negative_filter)) {
443 printer.OnTestEnd(test_info->name(), test_case->name(),
444 false, false, false, 0);
445 continue;
446 }
447
448 // Decide if this test should be run.
449 bool should_run = true;
450 if (should_shard) {
451 should_run = ShouldRunTestOnShard(total_shards, shard_index,
452 num_runnable_tests);
453 }
454 num_runnable_tests += 1;
455 // If sharding is enabled and the test should not be run, skip it.
456 if (!should_run) {
457 continue;
458 }
459
460 base::Time start_time = base::Time::Now();
461 ++test_run_count;
462 int exit_code = RunTest(launcher_delegate,
463 test_name,
464 TestTimeouts::action_max_timeout_ms());
465 if (exit_code == 0) {
466 // Test passed.
467 printer.OnTestEnd(test_info->name(), test_case->name(), true, false,
468 false,
469 (base::Time::Now() - start_time).InMillisecondsF());
470 } else {
471 failed_tests.push_back(test_name);
472
473 bool ignore_failure = false;
474
475 // -1 exit code means a crash or hang. Never ignore those failures,
476 // they are serious and should always be visible.
477 if (exit_code != -1)
478 ignore_failure = base::TestSuite::ShouldIgnoreFailure(*test_info);
479
480 printer.OnTestEnd(test_info->name(), test_case->name(), true, true,
481 ignore_failure,
482 (base::Time::Now() - start_time).InMillisecondsF());
483 if (ignore_failure)
484 ++ignored_failure_count;
485 }
486 }
487 }
488
489 printf("%d test%s run\n", test_run_count, test_run_count > 1 ? "s" : "");
490 printf("%d test%s failed (%d ignored)\n",
491 static_cast<int>(failed_tests.size()),
492 failed_tests.size() > 1 ? "s" : "", ignored_failure_count);
493 if (failed_tests.size() - ignored_failure_count == 0)
494 return true;
495
496 printf("Failing tests:\n");
497 for (std::vector<std::string>::const_iterator iter = failed_tests.begin();
498 iter != failed_tests.end(); ++iter) {
499 printf("%s\n", iter->c_str());
500 }
501
502 return false;
503 }
504
505 void PrintUsage() {
506 fprintf(stdout,
507 "Runs tests using the gtest framework, each test being run in its own\n"
508 "process. Any gtest flags can be specified.\n"
509 " --single_process\n"
510 " Runs the tests and the launcher in the same process. Useful for \n"
511 " debugging a specific test in a debugger.\n"
512 " --single-process\n"
513 " Same as above, and also runs Chrome in single-process mode.\n"
514 " --help\n"
515 " Shows this message.\n"
516 " --gtest_help\n"
517 " Shows the gtest help message.\n");
518 }
519
520 } // namespace
521
522 const char kGTestFilterFlag[] = "gtest_filter";
523 const char kGTestHelpFlag[] = "gtest_help";
524 const char kGTestListTestsFlag[] = "gtest_list_tests";
525 const char kGTestRepeatFlag[] = "gtest_repeat";
526 const char kGTestRunDisabledTestsFlag[] = "gtest_also_run_disabled_tests";
527 const char kGTestOutputFlag[] = "gtest_output";
528
529 const char kSingleProcessTestsFlag[] = "single_process";
530 const char kSingleProcessTestsAndChromeFlag[] = "single-process";
531 // The following is kept for historical reasons (so people that are used to
532 // using it don't get surprised).
533 const char kChildProcessFlag[] = "child";
534
535 const char kHelpFlag[] = "help";
536
537 TestLauncherDelegate::~TestLauncherDelegate() {
538 }
539
540 int LaunchTests(TestLauncherDelegate* launcher_delegate,
541 int argc,
542 char** argv) {
543 launcher_delegate->EarlyInitialize();
544
545 CommandLine::Init(argc, argv);
546 const CommandLine* command_line = CommandLine::ForCurrentProcess();
547
548 if (command_line->HasSwitch(kHelpFlag)) {
549 PrintUsage();
550 return 0;
551 }
552
553 int return_code = 0;
554 if (launcher_delegate->Run(argc, argv, &return_code))
555 return return_code;
556
557 int32 total_shards;
558 int32 shard_index;
559 bool should_shard = ShouldShard(&total_shards, &shard_index);
560
561 fprintf(stdout,
562 "Starting tests...\n"
563 "IMPORTANT DEBUGGING NOTE: each test is run inside its own process.\n"
564 "For debugging a test inside a debugger, use the\n"
565 "--gtest_filter=<your_test_name> flag along with either\n"
566 "--single_process (to run all tests in one launcher/browser process) or\n"
567 "--single-process (to do the above, and also run Chrome in single-\n"
568 "process mode).\n");
569
570 testing::InitGoogleTest(&argc, argv);
571 TestTimeouts::Initialize();
572
573 // Make sure the entire browser code is loaded into memory. Reading it
574 // from disk may be slow on a busy bot, and can easily exceed the default
575 // timeout causing flaky test failures. Use an empty test that only starts
576 // and closes a browser with a long timeout to avoid those problems.
577 RunTest(launcher_delegate,
578 kEmptyTestName,
579 TestTimeouts::large_test_timeout_ms());
580
581 int cycles = 1;
582 if (command_line->HasSwitch(kGTestRepeatFlag)) {
583 base::StringToInt(command_line->GetSwitchValueASCII(kGTestRepeatFlag),
584 &cycles);
585 }
586
587 int exit_code = 0;
588 while (cycles != 0) {
589 if (!RunTests(launcher_delegate,
590 should_shard,
591 total_shards,
592 shard_index)) {
593 exit_code = 1;
594 break;
595 }
596
597 // Special value "-1" means "repeat indefinitely".
598 if (cycles != -1)
599 cycles--;
600 }
601 return exit_code;
602 }
603
604 } // namespcae test_launcher
OLDNEW
« no previous file with comments | « content/test/test_launcher.h ('k') | no next file » | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698