OLD | NEW |
(Empty) | |
| 1 // Copyright 2013 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 "base/test/test_launcher.h" |
| 6 |
| 7 #include "base/at_exit.h" |
| 8 #include "base/command_line.h" |
| 9 #include "base/environment.h" |
| 10 #include "base/files/file_path.h" |
| 11 #include "base/file_util.h" |
| 12 #include "base/logging.h" |
| 13 #include "base/memory/scoped_ptr.h" |
| 14 #include "base/string_number_conversions.h" |
| 15 #include "base/test/test_timeouts.h" |
| 16 #include "base/time.h" |
| 17 #include "testing/gtest/include/gtest/gtest.h" |
| 18 |
| 19 #if defined(OS_MACOSX) |
| 20 #include "base/mac/scoped_nsautorelease_pool.h" |
| 21 #endif |
| 22 |
| 23 namespace base { |
| 24 |
| 25 // The environment variable name for the total number of test shards. |
| 26 const char kTestTotalShards[] = "GTEST_TOTAL_SHARDS"; |
| 27 // The environment variable name for the test shard index. |
| 28 const char kTestShardIndex[] = "GTEST_SHARD_INDEX"; |
| 29 |
| 30 // The default output file for XML output. |
| 31 const base::FilePath::CharType kDefaultOutputFile[] = FILE_PATH_LITERAL( |
| 32 "test_detail.xml"); |
| 33 |
| 34 namespace { |
| 35 |
| 36 // Parses the environment variable var as an Int32. If it is unset, returns |
| 37 // default_val. If it is set, unsets it then converts it to Int32 before |
| 38 // returning it. If unsetting or converting to an Int32 fails, print an |
| 39 // error and exit with failure. |
| 40 int32 Int32FromEnvOrDie(const char* const var, int32 default_val) { |
| 41 scoped_ptr<base::Environment> env(base::Environment::Create()); |
| 42 std::string str_val; |
| 43 int32 result; |
| 44 if (!env->GetVar(var, &str_val)) |
| 45 return default_val; |
| 46 if (!env->UnSetVar(var)) { |
| 47 LOG(ERROR) << "Invalid environment: we could not unset " << var << ".\n"; |
| 48 exit(EXIT_FAILURE); |
| 49 } |
| 50 if (!base::StringToInt(str_val, &result)) { |
| 51 LOG(ERROR) << "Invalid environment: " << var << " is not an integer.\n"; |
| 52 exit(EXIT_FAILURE); |
| 53 } |
| 54 return result; |
| 55 } |
| 56 |
| 57 // Checks whether sharding is enabled by examining the relevant |
| 58 // environment variable values. If the variables are present, |
| 59 // but inconsistent (i.e., shard_index >= total_shards), prints |
| 60 // an error and exits. |
| 61 void InitSharding(int32* total_shards, int32* shard_index) { |
| 62 *total_shards = Int32FromEnvOrDie(kTestTotalShards, 1); |
| 63 *shard_index = Int32FromEnvOrDie(kTestShardIndex, 0); |
| 64 |
| 65 if (*total_shards == -1 && *shard_index != -1) { |
| 66 LOG(ERROR) << "Invalid environment variables: you have " |
| 67 << kTestShardIndex << " = " << *shard_index |
| 68 << ", but have left " << kTestTotalShards << " unset.\n"; |
| 69 exit(EXIT_FAILURE); |
| 70 } else if (*total_shards != -1 && *shard_index == -1) { |
| 71 LOG(ERROR) << "Invalid environment variables: you have " |
| 72 << kTestTotalShards << " = " << *total_shards |
| 73 << ", but have left " << kTestShardIndex << " unset.\n"; |
| 74 exit(EXIT_FAILURE); |
| 75 } else if (*shard_index < 0 || *shard_index >= *total_shards) { |
| 76 LOG(ERROR) << "Invalid environment variables: we require 0 <= " |
| 77 << kTestShardIndex << " < " << kTestTotalShards |
| 78 << ", but you have " << kTestShardIndex << "=" << *shard_index |
| 79 << ", " << kTestTotalShards << "=" << *total_shards << ".\n"; |
| 80 exit(EXIT_FAILURE); |
| 81 } |
| 82 } |
| 83 |
| 84 // Given the total number of shards, the shard index, and the test id, returns |
| 85 // true iff the test should be run on this shard. The test id is some arbitrary |
| 86 // but unique non-negative integer assigned by this launcher to each test |
| 87 // method. Assumes that 0 <= shard_index < total_shards, which is first |
| 88 // verified in ShouldShard(). |
| 89 bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) { |
| 90 return (test_id % total_shards) == shard_index; |
| 91 } |
| 92 |
| 93 // A helper class to output results. |
| 94 // Note: as currently XML is the only supported format by gtest, we don't |
| 95 // check output format (e.g. "xml:" prefix) here and output an XML file |
| 96 // unconditionally. |
| 97 // Note: we don't output per-test-case or total summary info like |
| 98 // total failed_test_count, disabled_test_count, elapsed_time and so on. |
| 99 // Only each test (testcase element in the XML) will have the correct |
| 100 // failed/disabled/elapsed_time information. Each test won't include |
| 101 // detailed failure messages either. |
| 102 class ResultsPrinter { |
| 103 public: |
| 104 explicit ResultsPrinter(const CommandLine& command_line); |
| 105 ~ResultsPrinter(); |
| 106 void OnTestCaseStart(const char* name, int test_count) const; |
| 107 void OnTestCaseEnd() const; |
| 108 |
| 109 void OnTestEnd(const char* name, const char* case_name, |
| 110 bool success, double elapsed_time) const; |
| 111 private: |
| 112 FILE* out_; |
| 113 |
| 114 DISALLOW_COPY_AND_ASSIGN(ResultsPrinter); |
| 115 }; |
| 116 |
| 117 ResultsPrinter::ResultsPrinter(const CommandLine& command_line) : out_(NULL) { |
| 118 if (!command_line.HasSwitch(kGTestOutputFlag)) |
| 119 return; |
| 120 std::string flag = command_line.GetSwitchValueASCII(kGTestOutputFlag); |
| 121 size_t colon_pos = flag.find(':'); |
| 122 base::FilePath path; |
| 123 if (colon_pos != std::string::npos) { |
| 124 base::FilePath flag_path = |
| 125 command_line.GetSwitchValuePath(kGTestOutputFlag); |
| 126 base::FilePath::StringType path_string = flag_path.value(); |
| 127 path = base::FilePath(path_string.substr(colon_pos + 1)); |
| 128 // If the given path ends with '/', consider it is a directory. |
| 129 // Note: This does NOT check that a directory (or file) actually exists |
| 130 // (the behavior is same as what gtest does). |
| 131 if (path.EndsWithSeparator()) { |
| 132 base::FilePath executable = command_line.GetProgram().BaseName(); |
| 133 path = path.Append(executable.ReplaceExtension( |
| 134 base::FilePath::StringType(FILE_PATH_LITERAL("xml")))); |
| 135 } |
| 136 } |
| 137 if (path.value().empty()) |
| 138 path = base::FilePath(kDefaultOutputFile); |
| 139 base::FilePath dir_name = path.DirName(); |
| 140 if (!file_util::DirectoryExists(dir_name)) { |
| 141 LOG(WARNING) << "The output directory does not exist. " |
| 142 << "Creating the directory: " << dir_name.value(); |
| 143 // Create the directory if necessary (because the gtest does the same). |
| 144 file_util::CreateDirectory(dir_name); |
| 145 } |
| 146 out_ = file_util::OpenFile(path, "w"); |
| 147 if (!out_) { |
| 148 LOG(ERROR) << "Cannot open output file: " |
| 149 << path.value() << "."; |
| 150 return; |
| 151 } |
| 152 fprintf(out_, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); |
| 153 fprintf(out_, "<testsuites name=\"AllTests\" tests=\"\" failures=\"\"" |
| 154 " disabled=\"\" errors=\"\" time=\"\">\n"); |
| 155 } |
| 156 |
| 157 ResultsPrinter::~ResultsPrinter() { |
| 158 if (!out_) |
| 159 return; |
| 160 fprintf(out_, "</testsuites>\n"); |
| 161 fclose(out_); |
| 162 } |
| 163 |
| 164 void ResultsPrinter::OnTestCaseStart(const char* name, int test_count) const { |
| 165 if (!out_) |
| 166 return; |
| 167 fprintf(out_, " <testsuite name=\"%s\" tests=\"%d\" failures=\"\"" |
| 168 " disabled=\"\" errors=\"\" time=\"\">\n", name, test_count); |
| 169 } |
| 170 |
| 171 void ResultsPrinter::OnTestCaseEnd() const { |
| 172 if (!out_) |
| 173 return; |
| 174 fprintf(out_, " </testsuite>\n"); |
| 175 } |
| 176 |
| 177 void ResultsPrinter::OnTestEnd(const char* name, |
| 178 const char* case_name, |
| 179 bool success, |
| 180 double elapsed_time) const { |
| 181 if (!out_) |
| 182 return; |
| 183 fprintf(out_, " <testcase name=\"%s\" status=\"run\" time=\"%.3f\"" |
| 184 " classname=\"%s\">\n", |
| 185 name, elapsed_time / 1000.0, case_name); |
| 186 if (!success) |
| 187 fprintf(out_, " <failure message=\"\" type=\"\"></failure>\n"); |
| 188 fprintf(out_, "</testcase>\n"); |
| 189 } |
| 190 |
| 191 class TestCasePrinterHelper { |
| 192 public: |
| 193 TestCasePrinterHelper(const ResultsPrinter& printer, |
| 194 const char* name, |
| 195 int total_test_count) |
| 196 : printer_(printer) { |
| 197 printer_.OnTestCaseStart(name, total_test_count); |
| 198 } |
| 199 ~TestCasePrinterHelper() { |
| 200 printer_.OnTestCaseEnd(); |
| 201 } |
| 202 private: |
| 203 const ResultsPrinter& printer_; |
| 204 |
| 205 DISALLOW_COPY_AND_ASSIGN(TestCasePrinterHelper); |
| 206 }; |
| 207 |
| 208 // For a basic pattern matching for gtest_filter options. (Copied from |
| 209 // gtest.cc, see the comment below and http://crbug.com/44497) |
| 210 bool PatternMatchesString(const char* pattern, const char* str) { |
| 211 switch (*pattern) { |
| 212 case '\0': |
| 213 case ':': // Either ':' or '\0' marks the end of the pattern. |
| 214 return *str == '\0'; |
| 215 case '?': // Matches any single character. |
| 216 return *str != '\0' && PatternMatchesString(pattern + 1, str + 1); |
| 217 case '*': // Matches any string (possibly empty) of characters. |
| 218 return (*str != '\0' && PatternMatchesString(pattern, str + 1)) || |
| 219 PatternMatchesString(pattern + 1, str); |
| 220 default: // Non-special character. Matches itself. |
| 221 return *pattern == *str && |
| 222 PatternMatchesString(pattern + 1, str + 1); |
| 223 } |
| 224 } |
| 225 |
| 226 // TODO(phajdan.jr): Avoid duplicating gtest code. (http://crbug.com/44497) |
| 227 // For basic pattern matching for gtest_filter options. (Copied from |
| 228 // gtest.cc) |
| 229 bool MatchesFilter(const std::string& name, const std::string& filter) { |
| 230 const char *cur_pattern = filter.c_str(); |
| 231 for (;;) { |
| 232 if (PatternMatchesString(cur_pattern, name.c_str())) { |
| 233 return true; |
| 234 } |
| 235 |
| 236 // Finds the next pattern in the filter. |
| 237 cur_pattern = strchr(cur_pattern, ':'); |
| 238 |
| 239 // Returns if no more pattern can be found. |
| 240 if (cur_pattern == NULL) { |
| 241 return false; |
| 242 } |
| 243 |
| 244 // Skips the pattern separater (the ':' character). |
| 245 cur_pattern++; |
| 246 } |
| 247 } |
| 248 |
| 249 bool RunTests(TestLauncherDelegate* launcher_delegate, |
| 250 int total_shards, |
| 251 int shard_index) { |
| 252 const CommandLine* command_line = CommandLine::ForCurrentProcess(); |
| 253 |
| 254 DCHECK(!command_line->HasSwitch(kGTestListTestsFlag)); |
| 255 |
| 256 testing::UnitTest* const unit_test = testing::UnitTest::GetInstance(); |
| 257 |
| 258 std::string filter = command_line->GetSwitchValueASCII(kGTestFilterFlag); |
| 259 |
| 260 // Split --gtest_filter at '-', if there is one, to separate into |
| 261 // positive filter and negative filter portions. |
| 262 std::string positive_filter = filter; |
| 263 std::string negative_filter; |
| 264 size_t dash_pos = filter.find('-'); |
| 265 if (dash_pos != std::string::npos) { |
| 266 positive_filter = filter.substr(0, dash_pos); // Everything up to the dash. |
| 267 negative_filter = filter.substr(dash_pos + 1); // Everything after the dash. |
| 268 } |
| 269 |
| 270 int num_runnable_tests = 0; |
| 271 int test_run_count = 0; |
| 272 std::vector<std::string> failed_tests; |
| 273 |
| 274 ResultsPrinter printer(*command_line); |
| 275 for (int i = 0; i < unit_test->total_test_case_count(); ++i) { |
| 276 const testing::TestCase* test_case = unit_test->GetTestCase(i); |
| 277 TestCasePrinterHelper helper(printer, test_case->name(), |
| 278 test_case->total_test_count()); |
| 279 for (int j = 0; j < test_case->total_test_count(); ++j) { |
| 280 const testing::TestInfo* test_info = test_case->GetTestInfo(j); |
| 281 std::string test_name = test_info->test_case_name(); |
| 282 test_name.append("."); |
| 283 test_name.append(test_info->name()); |
| 284 |
| 285 // Skip disabled tests. |
| 286 if (test_name.find("DISABLED") != std::string::npos && |
| 287 !command_line->HasSwitch(kGTestRunDisabledTestsFlag)) { |
| 288 continue; |
| 289 } |
| 290 |
| 291 // Skip the test that doesn't match the filter string (if given). |
| 292 if ((!positive_filter.empty() && |
| 293 !MatchesFilter(test_name, positive_filter)) || |
| 294 MatchesFilter(test_name, negative_filter)) { |
| 295 continue; |
| 296 } |
| 297 |
| 298 if (!launcher_delegate->ShouldRunTest(test_case, test_info)) |
| 299 continue; |
| 300 |
| 301 bool should_run = ShouldRunTestOnShard(total_shards, shard_index, |
| 302 num_runnable_tests); |
| 303 num_runnable_tests += 1; |
| 304 if (!should_run) |
| 305 continue; |
| 306 |
| 307 base::TimeTicks start_time = base::TimeTicks::Now(); |
| 308 ++test_run_count; |
| 309 bool success = launcher_delegate->RunTest(test_case, test_info); |
| 310 if (!success) |
| 311 failed_tests.push_back(test_name); |
| 312 printer.OnTestEnd( |
| 313 test_info->name(), test_case->name(), success, |
| 314 (base::TimeTicks::Now() - start_time).InMillisecondsF()); |
| 315 } |
| 316 } |
| 317 |
| 318 printf("%d test%s run\n", test_run_count, test_run_count > 1 ? "s" : ""); |
| 319 printf("%d test%s failed\n", |
| 320 static_cast<int>(failed_tests.size()), |
| 321 failed_tests.size() != 1 ? "s" : ""); |
| 322 if (failed_tests.empty()) |
| 323 return true; |
| 324 |
| 325 printf("Failing tests:\n"); |
| 326 for (std::vector<std::string>::const_iterator iter = failed_tests.begin(); |
| 327 iter != failed_tests.end(); ++iter) { |
| 328 printf("%s\n", iter->c_str()); |
| 329 } |
| 330 |
| 331 return false; |
| 332 } |
| 333 |
| 334 } // namespace |
| 335 |
| 336 const char kGTestFilterFlag[] = "gtest_filter"; |
| 337 const char kGTestListTestsFlag[] = "gtest_list_tests"; |
| 338 const char kGTestRepeatFlag[] = "gtest_repeat"; |
| 339 const char kGTestRunDisabledTestsFlag[] = "gtest_also_run_disabled_tests"; |
| 340 const char kGTestOutputFlag[] = "gtest_output"; |
| 341 |
| 342 const char kHelpFlag[] = "help"; |
| 343 |
| 344 TestLauncherDelegate::~TestLauncherDelegate() { |
| 345 } |
| 346 |
| 347 int LaunchTests(TestLauncherDelegate* launcher_delegate, |
| 348 int argc, |
| 349 char** argv) { |
| 350 const CommandLine* command_line = CommandLine::ForCurrentProcess(); |
| 351 |
| 352 int32 total_shards; |
| 353 int32 shard_index; |
| 354 InitSharding(&total_shards, &shard_index); |
| 355 |
| 356 int cycles = 1; |
| 357 if (command_line->HasSwitch(kGTestRepeatFlag)) { |
| 358 base::StringToInt(command_line->GetSwitchValueASCII(kGTestRepeatFlag), |
| 359 &cycles); |
| 360 } |
| 361 |
| 362 int exit_code = 0; |
| 363 while (cycles != 0) { |
| 364 if (!RunTests(launcher_delegate, total_shards, shard_index)) { |
| 365 exit_code = 1; |
| 366 break; |
| 367 } |
| 368 |
| 369 // Special value "-1" means "repeat indefinitely". |
| 370 if (cycles != -1) |
| 371 cycles--; |
| 372 } |
| 373 |
| 374 return exit_code; |
| 375 } |
| 376 |
| 377 } // namespace base |
OLD | NEW |