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

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

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

Powered by Google App Engine
This is Rietveld 408576698