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

Side by Side Diff: third_party/gtest/src/gtest.cc

Issue 624713003: Keep only base/extractor.[cc|h]. (Closed) Base URL: https://chromium.googlesource.com/external/omaha.git@master
Patch Set: Created 6 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
OLDNEW
(Empty)
1 // Copyright 2005, Google Inc.
2 // All rights reserved.
3 //
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
6 // met:
7 //
8 // * Redistributions of source code must retain the above copyright
9 // notice, this list of conditions and the following disclaimer.
10 // * Redistributions in binary form must reproduce the above
11 // copyright notice, this list of conditions and the following disclaimer
12 // in the documentation and/or other materials provided with the
13 // distribution.
14 // * Neither the name of Google Inc. nor the names of its
15 // contributors may be used to endorse or promote products derived from
16 // this software without specific prior written permission.
17 //
18 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 //
30 // Author: wan@google.com (Zhanyong Wan)
31 //
32 // The Google C++ Testing Framework (Google Test)
33
34 #include <gtest/gtest.h>
35 #include <gtest/gtest-spi.h>
36
37 #include <ctype.h>
38 #include <math.h>
39 #include <stdarg.h>
40 #include <stdio.h>
41 #include <stdlib.h>
42 #include <wchar.h>
43 #include <wctype.h>
44
45 #include <ostream>
46
47 #if GTEST_OS_LINUX
48
49 // TODO(kenton@google.com): Use autoconf to detect availability of
50 // gettimeofday().
51 #define GTEST_HAS_GETTIMEOFDAY_ 1
52
53 #include <fcntl.h>
54 #include <limits.h>
55 #include <sched.h>
56 // Declares vsnprintf(). This header is not available on Windows.
57 #include <strings.h>
58 #include <sys/mman.h>
59 #include <sys/time.h>
60 #include <unistd.h>
61 #include <string>
62 #include <vector>
63
64 #elif GTEST_OS_SYMBIAN
65 #define GTEST_HAS_GETTIMEOFDAY_ 1
66 #include <sys/time.h> // NOLINT
67
68 #elif GTEST_OS_ZOS
69 #define GTEST_HAS_GETTIMEOFDAY_ 1
70 #include <sys/time.h> // NOLINT
71
72 // On z/OS we additionally need strings.h for strcasecmp.
73 #include <strings.h> // NOLINT
74
75 #elif GTEST_OS_WINDOWS_MOBILE // We are on Windows CE.
76
77 #include <windows.h> // NOLINT
78
79 #elif GTEST_OS_WINDOWS // We are on Windows proper.
80
81 #include <io.h> // NOLINT
82 #include <sys/timeb.h> // NOLINT
83 #include <sys/types.h> // NOLINT
84 #include <sys/stat.h> // NOLINT
85
86 #if GTEST_OS_WINDOWS_MINGW
87 // MinGW has gettimeofday() but not _ftime64().
88 // TODO(kenton@google.com): Use autoconf to detect availability of
89 // gettimeofday().
90 // TODO(kenton@google.com): There are other ways to get the time on
91 // Windows, like GetTickCount() or GetSystemTimeAsFileTime(). MinGW
92 // supports these. consider using them instead.
93 #define GTEST_HAS_GETTIMEOFDAY_ 1
94 #include <sys/time.h> // NOLINT
95 #endif // GTEST_OS_WINDOWS_MINGW
96
97 // cpplint thinks that the header is already included, so we want to
98 // silence it.
99 #include <windows.h> // NOLINT
100
101 #else
102
103 // Assume other platforms have gettimeofday().
104 // TODO(kenton@google.com): Use autoconf to detect availability of
105 // gettimeofday().
106 #define GTEST_HAS_GETTIMEOFDAY_ 1
107
108 // cpplint thinks that the header is already included, so we want to
109 // silence it.
110 #include <sys/time.h> // NOLINT
111 #include <unistd.h> // NOLINT
112
113 #endif // GTEST_OS_LINUX
114
115 #if GTEST_HAS_EXCEPTIONS
116 #include <stdexcept>
117 #endif
118
119 // Indicates that this translation unit is part of Google Test's
120 // implementation. It must come before gtest-internal-inl.h is
121 // included, or there will be a compiler error. This trick is to
122 // prevent a user from accidentally including gtest-internal-inl.h in
123 // his code.
124 #define GTEST_IMPLEMENTATION_ 1
125 #include "src/gtest-internal-inl.h"
126 #undef GTEST_IMPLEMENTATION_
127
128 #if GTEST_OS_WINDOWS
129 #define vsnprintf _vsnprintf
130 #endif // GTEST_OS_WINDOWS
131
132 namespace testing {
133
134 // Constants.
135
136 // A test whose test case name or test name matches this filter is
137 // disabled and not run.
138 static const char kDisableTestFilter[] = "DISABLED_*:*/DISABLED_*";
139
140 // A test case whose name matches this filter is considered a death
141 // test case and will be run before test cases whose name doesn't
142 // match this filter.
143 static const char kDeathTestCaseFilter[] = "*DeathTest:*DeathTest/*";
144
145 // A test filter that matches everything.
146 static const char kUniversalFilter[] = "*";
147
148 // The default output file for XML output.
149 static const char kDefaultOutputFile[] = "test_detail.xml";
150
151 // The environment variable name for the test shard index.
152 static const char kTestShardIndex[] = "GTEST_SHARD_INDEX";
153 // The environment variable name for the total number of test shards.
154 static const char kTestTotalShards[] = "GTEST_TOTAL_SHARDS";
155 // The environment variable name for the test shard status file.
156 static const char kTestShardStatusFile[] = "GTEST_SHARD_STATUS_FILE";
157
158 namespace internal {
159
160 // The text used in failure messages to indicate the start of the
161 // stack trace.
162 const char kStackTraceMarker[] = "\nStack trace:\n";
163
164 // g_help_flag is true iff the --help flag or an equivalent form is
165 // specified on the command line.
166 bool g_help_flag = false;
167
168 } // namespace internal
169
170 GTEST_DEFINE_bool_(
171 also_run_disabled_tests,
172 internal::BoolFromGTestEnv("also_run_disabled_tests", false),
173 "Run disabled tests too, in addition to the tests normally being run.");
174
175 GTEST_DEFINE_bool_(
176 break_on_failure,
177 internal::BoolFromGTestEnv("break_on_failure", false),
178 "True iff a failed assertion should be a debugger break-point.");
179
180 GTEST_DEFINE_bool_(
181 catch_exceptions,
182 internal::BoolFromGTestEnv("catch_exceptions", false),
183 "True iff " GTEST_NAME_
184 " should catch exceptions and treat them as test failures.");
185
186 GTEST_DEFINE_string_(
187 color,
188 internal::StringFromGTestEnv("color", "auto"),
189 "Whether to use colors in the output. Valid values: yes, no, "
190 "and auto. 'auto' means to use colors if the output is "
191 "being sent to a terminal and the TERM environment variable "
192 "is set to xterm, xterm-color, xterm-256color, linux or cygwin.");
193
194 GTEST_DEFINE_string_(
195 filter,
196 internal::StringFromGTestEnv("filter", kUniversalFilter),
197 "A colon-separated list of glob (not regex) patterns "
198 "for filtering the tests to run, optionally followed by a "
199 "'-' and a : separated list of negative patterns (tests to "
200 "exclude). A test is run if it matches one of the positive "
201 "patterns and does not match any of the negative patterns.");
202
203 GTEST_DEFINE_bool_(list_tests, false,
204 "List all tests without running them.");
205
206 GTEST_DEFINE_string_(
207 output,
208 internal::StringFromGTestEnv("output", ""),
209 "A format (currently must be \"xml\"), optionally followed "
210 "by a colon and an output file name or directory. A directory "
211 "is indicated by a trailing pathname separator. "
212 "Examples: \"xml:filename.xml\", \"xml::directoryname/\". "
213 "If a directory is specified, output files will be created "
214 "within that directory, with file-names based on the test "
215 "executable's name and, if necessary, made unique by adding "
216 "digits.");
217
218 GTEST_DEFINE_bool_(
219 print_time,
220 internal::BoolFromGTestEnv("print_time", true),
221 "True iff " GTEST_NAME_
222 " should display elapsed time in text output.");
223
224 GTEST_DEFINE_int32_(
225 random_seed,
226 internal::Int32FromGTestEnv("random_seed", 0),
227 "Random number seed to use when shuffling test orders. Must be in range "
228 "[1, 99999], or 0 to use a seed based on the current time.");
229
230 GTEST_DEFINE_int32_(
231 repeat,
232 internal::Int32FromGTestEnv("repeat", 1),
233 "How many times to repeat each test. Specify a negative number "
234 "for repeating forever. Useful for shaking out flaky tests.");
235
236 GTEST_DEFINE_bool_(
237 show_internal_stack_frames, false,
238 "True iff " GTEST_NAME_ " should include internal stack frames when "
239 "printing test failure stack traces.");
240
241 GTEST_DEFINE_bool_(
242 shuffle,
243 internal::BoolFromGTestEnv("shuffle", false),
244 "True iff " GTEST_NAME_
245 " should randomize tests' order on every run.");
246
247 GTEST_DEFINE_int32_(
248 stack_trace_depth,
249 internal::Int32FromGTestEnv("stack_trace_depth", kMaxStackTraceDepth),
250 "The maximum number of stack frames to print when an "
251 "assertion fails. The valid range is 0 through 100, inclusive.");
252
253 GTEST_DEFINE_bool_(
254 throw_on_failure,
255 internal::BoolFromGTestEnv("throw_on_failure", false),
256 "When this flag is specified, a failed assertion will throw an exception "
257 "if exceptions are enabled or exit the program with a non-zero code "
258 "otherwise.");
259
260 namespace internal {
261
262 // Generates a random number from [0, range), using a Linear
263 // Congruential Generator (LCG). Crashes if 'range' is 0 or greater
264 // than kMaxRange.
265 UInt32 Random::Generate(UInt32 range) {
266 // These constants are the same as are used in glibc's rand(3).
267 state_ = (1103515245U*state_ + 12345U) % kMaxRange;
268
269 GTEST_CHECK_(range > 0)
270 << "Cannot generate a number in the range [0, 0).";
271 GTEST_CHECK_(range <= kMaxRange)
272 << "Generation of a number in [0, " << range << ") was requested, "
273 << "but this can only generate numbers in [0, " << kMaxRange << ").";
274
275 // Converting via modulus introduces a bit of downward bias, but
276 // it's simple, and a linear congruential generator isn't too good
277 // to begin with.
278 return state_ % range;
279 }
280
281 // GTestIsInitialized() returns true iff the user has initialized
282 // Google Test. Useful for catching the user mistake of not initializing
283 // Google Test before calling RUN_ALL_TESTS().
284 //
285 // A user must call testing::InitGoogleTest() to initialize Google
286 // Test. g_init_gtest_count is set to the number of times
287 // InitGoogleTest() has been called. We don't protect this variable
288 // under a mutex as it is only accessed in the main thread.
289 int g_init_gtest_count = 0;
290 static bool GTestIsInitialized() { return g_init_gtest_count != 0; }
291
292 // Iterates over a vector of TestCases, keeping a running sum of the
293 // results of calling a given int-returning method on each.
294 // Returns the sum.
295 static int SumOverTestCaseList(const internal::Vector<TestCase*>& case_list,
296 int (TestCase::*method)() const) {
297 int sum = 0;
298 for (int i = 0; i < case_list.size(); i++) {
299 sum += (case_list.GetElement(i)->*method)();
300 }
301 return sum;
302 }
303
304 // Returns true iff the test case passed.
305 static bool TestCasePassed(const TestCase* test_case) {
306 return test_case->should_run() && test_case->Passed();
307 }
308
309 // Returns true iff the test case failed.
310 static bool TestCaseFailed(const TestCase* test_case) {
311 return test_case->should_run() && test_case->Failed();
312 }
313
314 // Returns true iff test_case contains at least one test that should
315 // run.
316 static bool ShouldRunTestCase(const TestCase* test_case) {
317 return test_case->should_run();
318 }
319
320 // AssertHelper constructor.
321 AssertHelper::AssertHelper(TestPartResult::Type type,
322 const char* file,
323 int line,
324 const char* message)
325 : data_(new AssertHelperData(type, file, line, message)) {
326 }
327
328 AssertHelper::~AssertHelper() {
329 delete data_;
330 }
331
332 // Message assignment, for assertion streaming support.
333 void AssertHelper::operator=(const Message& message) const {
334 UnitTest::GetInstance()->
335 AddTestPartResult(data_->type, data_->file, data_->line,
336 AppendUserMessage(data_->message, message),
337 UnitTest::GetInstance()->impl()
338 ->CurrentOsStackTraceExceptTop(1)
339 // Skips the stack frame for this function itself.
340 ); // NOLINT
341 }
342
343 // Mutex for linked pointers.
344 Mutex g_linked_ptr_mutex(Mutex::NO_CONSTRUCTOR_NEEDED_FOR_STATIC_MUTEX);
345
346 // Application pathname gotten in InitGoogleTest.
347 String g_executable_path;
348
349 // Returns the current application's name, removing directory path if that
350 // is present.
351 FilePath GetCurrentExecutableName() {
352 FilePath result;
353
354 #if GTEST_OS_WINDOWS
355 result.Set(FilePath(g_executable_path).RemoveExtension("exe"));
356 #else
357 result.Set(FilePath(g_executable_path));
358 #endif // GTEST_OS_WINDOWS
359
360 return result.RemoveDirectoryName();
361 }
362
363 // Functions for processing the gtest_output flag.
364
365 // Returns the output format, or "" for normal printed output.
366 String UnitTestOptions::GetOutputFormat() {
367 const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
368 if (gtest_output_flag == NULL) return String("");
369
370 const char* const colon = strchr(gtest_output_flag, ':');
371 return (colon == NULL) ?
372 String(gtest_output_flag) :
373 String(gtest_output_flag, colon - gtest_output_flag);
374 }
375
376 // Returns the name of the requested output file, or the default if none
377 // was explicitly specified.
378 String UnitTestOptions::GetAbsolutePathToOutputFile() {
379 const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
380 if (gtest_output_flag == NULL)
381 return String("");
382
383 const char* const colon = strchr(gtest_output_flag, ':');
384 if (colon == NULL)
385 return String(internal::FilePath::ConcatPaths(
386 internal::FilePath(
387 UnitTest::GetInstance()->original_working_dir()),
388 internal::FilePath(kDefaultOutputFile)).ToString() );
389
390 internal::FilePath output_name(colon + 1);
391 if (!output_name.IsAbsolutePath())
392 // TODO(wan@google.com): on Windows \some\path is not an absolute
393 // path (as its meaning depends on the current drive), yet the
394 // following logic for turning it into an absolute path is wrong.
395 // Fix it.
396 output_name = internal::FilePath::ConcatPaths(
397 internal::FilePath(UnitTest::GetInstance()->original_working_dir()),
398 internal::FilePath(colon + 1));
399
400 if (!output_name.IsDirectory())
401 return output_name.ToString();
402
403 internal::FilePath result(internal::FilePath::GenerateUniqueFileName(
404 output_name, internal::GetCurrentExecutableName(),
405 GetOutputFormat().c_str()));
406 return result.ToString();
407 }
408
409 // Returns true iff the wildcard pattern matches the string. The
410 // first ':' or '\0' character in pattern marks the end of it.
411 //
412 // This recursive algorithm isn't very efficient, but is clear and
413 // works well enough for matching test names, which are short.
414 bool UnitTestOptions::PatternMatchesString(const char *pattern,
415 const char *str) {
416 switch (*pattern) {
417 case '\0':
418 case ':': // Either ':' or '\0' marks the end of the pattern.
419 return *str == '\0';
420 case '?': // Matches any single character.
421 return *str != '\0' && PatternMatchesString(pattern + 1, str + 1);
422 case '*': // Matches any string (possibly empty) of characters.
423 return (*str != '\0' && PatternMatchesString(pattern, str + 1)) ||
424 PatternMatchesString(pattern + 1, str);
425 default: // Non-special character. Matches itself.
426 return *pattern == *str &&
427 PatternMatchesString(pattern + 1, str + 1);
428 }
429 }
430
431 bool UnitTestOptions::MatchesFilter(const String& name, const char* filter) {
432 const char *cur_pattern = filter;
433 for (;;) {
434 if (PatternMatchesString(cur_pattern, name.c_str())) {
435 return true;
436 }
437
438 // Finds the next pattern in the filter.
439 cur_pattern = strchr(cur_pattern, ':');
440
441 // Returns if no more pattern can be found.
442 if (cur_pattern == NULL) {
443 return false;
444 }
445
446 // Skips the pattern separater (the ':' character).
447 cur_pattern++;
448 }
449 }
450
451 // TODO(keithray): move String function implementations to gtest-string.cc.
452
453 // Returns true iff the user-specified filter matches the test case
454 // name and the test name.
455 bool UnitTestOptions::FilterMatchesTest(const String &test_case_name,
456 const String &test_name) {
457 const String& full_name = String::Format("%s.%s",
458 test_case_name.c_str(),
459 test_name.c_str());
460
461 // Split --gtest_filter at '-', if there is one, to separate into
462 // positive filter and negative filter portions
463 const char* const p = GTEST_FLAG(filter).c_str();
464 const char* const dash = strchr(p, '-');
465 String positive;
466 String negative;
467 if (dash == NULL) {
468 positive = GTEST_FLAG(filter).c_str(); // Whole string is a positive filter
469 negative = String("");
470 } else {
471 positive = String(p, dash - p); // Everything up to the dash
472 negative = String(dash+1); // Everything after the dash
473 if (positive.empty()) {
474 // Treat '-test1' as the same as '*-test1'
475 positive = kUniversalFilter;
476 }
477 }
478
479 // A filter is a colon-separated list of patterns. It matches a
480 // test if any pattern in it matches the test.
481 return (MatchesFilter(full_name, positive.c_str()) &&
482 !MatchesFilter(full_name, negative.c_str()));
483 }
484
485 #if GTEST_OS_WINDOWS
486 // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
487 // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
488 // This function is useful as an __except condition.
489 int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) {
490 // Google Test should handle an exception if:
491 // 1. the user wants it to, AND
492 // 2. this is not a breakpoint exception.
493 return (GTEST_FLAG(catch_exceptions) &&
494 exception_code != EXCEPTION_BREAKPOINT) ?
495 EXCEPTION_EXECUTE_HANDLER :
496 EXCEPTION_CONTINUE_SEARCH;
497 }
498 #endif // GTEST_OS_WINDOWS
499
500 } // namespace internal
501
502 // The c'tor sets this object as the test part result reporter used by
503 // Google Test. The 'result' parameter specifies where to report the
504 // results. Intercepts only failures from the current thread.
505 ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
506 TestPartResultArray* result)
507 : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD),
508 result_(result) {
509 Init();
510 }
511
512 // The c'tor sets this object as the test part result reporter used by
513 // Google Test. The 'result' parameter specifies where to report the
514 // results.
515 ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
516 InterceptMode intercept_mode, TestPartResultArray* result)
517 : intercept_mode_(intercept_mode),
518 result_(result) {
519 Init();
520 }
521
522 void ScopedFakeTestPartResultReporter::Init() {
523 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
524 if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
525 old_reporter_ = impl->GetGlobalTestPartResultReporter();
526 impl->SetGlobalTestPartResultReporter(this);
527 } else {
528 old_reporter_ = impl->GetTestPartResultReporterForCurrentThread();
529 impl->SetTestPartResultReporterForCurrentThread(this);
530 }
531 }
532
533 // The d'tor restores the test part result reporter used by Google Test
534 // before.
535 ScopedFakeTestPartResultReporter::~ScopedFakeTestPartResultReporter() {
536 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
537 if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
538 impl->SetGlobalTestPartResultReporter(old_reporter_);
539 } else {
540 impl->SetTestPartResultReporterForCurrentThread(old_reporter_);
541 }
542 }
543
544 // Increments the test part result count and remembers the result.
545 // This method is from the TestPartResultReporterInterface interface.
546 void ScopedFakeTestPartResultReporter::ReportTestPartResult(
547 const TestPartResult& result) {
548 result_->Append(result);
549 }
550
551 namespace internal {
552
553 // Returns the type ID of ::testing::Test. We should always call this
554 // instead of GetTypeId< ::testing::Test>() to get the type ID of
555 // testing::Test. This is to work around a suspected linker bug when
556 // using Google Test as a framework on Mac OS X. The bug causes
557 // GetTypeId< ::testing::Test>() to return different values depending
558 // on whether the call is from the Google Test framework itself or
559 // from user test code. GetTestTypeId() is guaranteed to always
560 // return the same value, as it always calls GetTypeId<>() from the
561 // gtest.cc, which is within the Google Test framework.
562 TypeId GetTestTypeId() {
563 return GetTypeId<Test>();
564 }
565
566 // The value of GetTestTypeId() as seen from within the Google Test
567 // library. This is solely for testing GetTestTypeId().
568 extern const TypeId kTestTypeIdInGoogleTest = GetTestTypeId();
569
570 // This predicate-formatter checks that 'results' contains a test part
571 // failure of the given type and that the failure message contains the
572 // given substring.
573 AssertionResult HasOneFailure(const char* /* results_expr */,
574 const char* /* type_expr */,
575 const char* /* substr_expr */,
576 const TestPartResultArray& results,
577 TestPartResult::Type type,
578 const char* substr) {
579 const String expected(type == TestPartResult::kFatalFailure ?
580 "1 fatal failure" :
581 "1 non-fatal failure");
582 Message msg;
583 if (results.size() != 1) {
584 msg << "Expected: " << expected << "\n"
585 << " Actual: " << results.size() << " failures";
586 for (int i = 0; i < results.size(); i++) {
587 msg << "\n" << results.GetTestPartResult(i);
588 }
589 return AssertionFailure(msg);
590 }
591
592 const TestPartResult& r = results.GetTestPartResult(0);
593 if (r.type() != type) {
594 msg << "Expected: " << expected << "\n"
595 << " Actual:\n"
596 << r;
597 return AssertionFailure(msg);
598 }
599
600 if (strstr(r.message(), substr) == NULL) {
601 msg << "Expected: " << expected << " containing \""
602 << substr << "\"\n"
603 << " Actual:\n"
604 << r;
605 return AssertionFailure(msg);
606 }
607
608 return AssertionSuccess();
609 }
610
611 // The constructor of SingleFailureChecker remembers where to look up
612 // test part results, what type of failure we expect, and what
613 // substring the failure message should contain.
614 SingleFailureChecker:: SingleFailureChecker(
615 const TestPartResultArray* results,
616 TestPartResult::Type type,
617 const char* substr)
618 : results_(results),
619 type_(type),
620 substr_(substr) {}
621
622 // The destructor of SingleFailureChecker verifies that the given
623 // TestPartResultArray contains exactly one failure that has the given
624 // type and contains the given substring. If that's not the case, a
625 // non-fatal failure will be generated.
626 SingleFailureChecker::~SingleFailureChecker() {
627 EXPECT_PRED_FORMAT3(HasOneFailure, *results_, type_, substr_.c_str());
628 }
629
630 DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter(
631 UnitTestImpl* unit_test) : unit_test_(unit_test) {}
632
633 void DefaultGlobalTestPartResultReporter::ReportTestPartResult(
634 const TestPartResult& result) {
635 unit_test_->current_test_result()->AddTestPartResult(result);
636 unit_test_->listeners()->repeater()->OnTestPartResult(result);
637 }
638
639 DefaultPerThreadTestPartResultReporter::DefaultPerThreadTestPartResultReporter(
640 UnitTestImpl* unit_test) : unit_test_(unit_test) {}
641
642 void DefaultPerThreadTestPartResultReporter::ReportTestPartResult(
643 const TestPartResult& result) {
644 unit_test_->GetGlobalTestPartResultReporter()->ReportTestPartResult(result);
645 }
646
647 // Returns the global test part result reporter.
648 TestPartResultReporterInterface*
649 UnitTestImpl::GetGlobalTestPartResultReporter() {
650 internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
651 return global_test_part_result_repoter_;
652 }
653
654 // Sets the global test part result reporter.
655 void UnitTestImpl::SetGlobalTestPartResultReporter(
656 TestPartResultReporterInterface* reporter) {
657 internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
658 global_test_part_result_repoter_ = reporter;
659 }
660
661 // Returns the test part result reporter for the current thread.
662 TestPartResultReporterInterface*
663 UnitTestImpl::GetTestPartResultReporterForCurrentThread() {
664 return per_thread_test_part_result_reporter_.get();
665 }
666
667 // Sets the test part result reporter for the current thread.
668 void UnitTestImpl::SetTestPartResultReporterForCurrentThread(
669 TestPartResultReporterInterface* reporter) {
670 per_thread_test_part_result_reporter_.set(reporter);
671 }
672
673 // Gets the number of successful test cases.
674 int UnitTestImpl::successful_test_case_count() const {
675 return test_cases_.CountIf(TestCasePassed);
676 }
677
678 // Gets the number of failed test cases.
679 int UnitTestImpl::failed_test_case_count() const {
680 return test_cases_.CountIf(TestCaseFailed);
681 }
682
683 // Gets the number of all test cases.
684 int UnitTestImpl::total_test_case_count() const {
685 return test_cases_.size();
686 }
687
688 // Gets the number of all test cases that contain at least one test
689 // that should run.
690 int UnitTestImpl::test_case_to_run_count() const {
691 return test_cases_.CountIf(ShouldRunTestCase);
692 }
693
694 // Gets the number of successful tests.
695 int UnitTestImpl::successful_test_count() const {
696 return SumOverTestCaseList(test_cases_, &TestCase::successful_test_count);
697 }
698
699 // Gets the number of failed tests.
700 int UnitTestImpl::failed_test_count() const {
701 return SumOverTestCaseList(test_cases_, &TestCase::failed_test_count);
702 }
703
704 // Gets the number of disabled tests.
705 int UnitTestImpl::disabled_test_count() const {
706 return SumOverTestCaseList(test_cases_, &TestCase::disabled_test_count);
707 }
708
709 // Gets the number of all tests.
710 int UnitTestImpl::total_test_count() const {
711 return SumOverTestCaseList(test_cases_, &TestCase::total_test_count);
712 }
713
714 // Gets the number of tests that should run.
715 int UnitTestImpl::test_to_run_count() const {
716 return SumOverTestCaseList(test_cases_, &TestCase::test_to_run_count);
717 }
718
719 // Returns the current OS stack trace as a String.
720 //
721 // The maximum number of stack frames to be included is specified by
722 // the gtest_stack_trace_depth flag. The skip_count parameter
723 // specifies the number of top frames to be skipped, which doesn't
724 // count against the number of frames to be included.
725 //
726 // For example, if Foo() calls Bar(), which in turn calls
727 // CurrentOsStackTraceExceptTop(1), Foo() will be included in the
728 // trace but Bar() and CurrentOsStackTraceExceptTop() won't.
729 String UnitTestImpl::CurrentOsStackTraceExceptTop(int skip_count) {
730 (void)skip_count;
731 return String("");
732 }
733
734 // Returns the current time in milliseconds.
735 TimeInMillis GetTimeInMillis() {
736 #if GTEST_OS_WINDOWS_MOBILE || defined(__BORLANDC__)
737 // Difference between 1970-01-01 and 1601-01-01 in milliseconds.
738 // http://analogous.blogspot.com/2005/04/epoch.html
739 const TimeInMillis kJavaEpochToWinFileTimeDelta =
740 static_cast<TimeInMillis>(116444736UL) * 100000UL;
741 const DWORD kTenthMicrosInMilliSecond = 10000;
742
743 SYSTEMTIME now_systime;
744 FILETIME now_filetime;
745 ULARGE_INTEGER now_int64;
746 // TODO(kenton@google.com): Shouldn't this just use
747 // GetSystemTimeAsFileTime()?
748 GetSystemTime(&now_systime);
749 if (SystemTimeToFileTime(&now_systime, &now_filetime)) {
750 now_int64.LowPart = now_filetime.dwLowDateTime;
751 now_int64.HighPart = now_filetime.dwHighDateTime;
752 now_int64.QuadPart = (now_int64.QuadPart / kTenthMicrosInMilliSecond) -
753 kJavaEpochToWinFileTimeDelta;
754 return now_int64.QuadPart;
755 }
756 return 0;
757 #elif GTEST_OS_WINDOWS && !GTEST_HAS_GETTIMEOFDAY_
758 __timeb64 now;
759 #ifdef _MSC_VER
760 // MSVC 8 deprecates _ftime64(), so we want to suppress warning 4996
761 // (deprecated function) there.
762 // TODO(kenton@google.com): Use GetTickCount()? Or use
763 // SystemTimeToFileTime()
764 #pragma warning(push) // Saves the current warning state.
765 #pragma warning(disable:4996) // Temporarily disables warning 4996.
766 _ftime64(&now);
767 #pragma warning(pop) // Restores the warning state.
768 #else
769 _ftime64(&now);
770 #endif // _MSC_VER
771 return static_cast<TimeInMillis>(now.time) * 1000 + now.millitm;
772 #elif GTEST_HAS_GETTIMEOFDAY_
773 struct timeval now;
774 gettimeofday(&now, NULL);
775 return static_cast<TimeInMillis>(now.tv_sec) * 1000 + now.tv_usec / 1000;
776 #else
777 #error "Don't know how to get the current time on your system."
778 #endif
779 }
780
781 // Utilities
782
783 // class String
784
785 // Returns the input enclosed in double quotes if it's not NULL;
786 // otherwise returns "(null)". For example, "\"Hello\"" is returned
787 // for input "Hello".
788 //
789 // This is useful for printing a C string in the syntax of a literal.
790 //
791 // Known issue: escape sequences are not handled yet.
792 String String::ShowCStringQuoted(const char* c_str) {
793 return c_str ? String::Format("\"%s\"", c_str) : String("(null)");
794 }
795
796 // Copies at most length characters from str into a newly-allocated
797 // piece of memory of size length+1. The memory is allocated with new[].
798 // A terminating null byte is written to the memory, and a pointer to it
799 // is returned. If str is NULL, NULL is returned.
800 static char* CloneString(const char* str, size_t length) {
801 if (str == NULL) {
802 return NULL;
803 } else {
804 char* const clone = new char[length + 1];
805 posix::StrNCpy(clone, str, length);
806 clone[length] = '\0';
807 return clone;
808 }
809 }
810
811 // Clones a 0-terminated C string, allocating memory using new. The
812 // caller is responsible for deleting[] the return value. Returns the
813 // cloned string, or NULL if the input is NULL.
814 const char * String::CloneCString(const char* c_str) {
815 return (c_str == NULL) ?
816 NULL : CloneString(c_str, strlen(c_str));
817 }
818
819 #if GTEST_OS_WINDOWS_MOBILE
820 // Creates a UTF-16 wide string from the given ANSI string, allocating
821 // memory using new. The caller is responsible for deleting the return
822 // value using delete[]. Returns the wide string, or NULL if the
823 // input is NULL.
824 LPCWSTR String::AnsiToUtf16(const char* ansi) {
825 if (!ansi) return NULL;
826 const int length = strlen(ansi);
827 const int unicode_length =
828 MultiByteToWideChar(CP_ACP, 0, ansi, length,
829 NULL, 0);
830 WCHAR* unicode = new WCHAR[unicode_length + 1];
831 MultiByteToWideChar(CP_ACP, 0, ansi, length,
832 unicode, unicode_length);
833 unicode[unicode_length] = 0;
834 return unicode;
835 }
836
837 // Creates an ANSI string from the given wide string, allocating
838 // memory using new. The caller is responsible for deleting the return
839 // value using delete[]. Returns the ANSI string, or NULL if the
840 // input is NULL.
841 const char* String::Utf16ToAnsi(LPCWSTR utf16_str) {
842 if (!utf16_str) return NULL;
843 const int ansi_length =
844 WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
845 NULL, 0, NULL, NULL);
846 char* ansi = new char[ansi_length + 1];
847 WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
848 ansi, ansi_length, NULL, NULL);
849 ansi[ansi_length] = 0;
850 return ansi;
851 }
852
853 #endif // GTEST_OS_WINDOWS_MOBILE
854
855 // Compares two C strings. Returns true iff they have the same content.
856 //
857 // Unlike strcmp(), this function can handle NULL argument(s). A NULL
858 // C string is considered different to any non-NULL C string,
859 // including the empty string.
860 bool String::CStringEquals(const char * lhs, const char * rhs) {
861 if ( lhs == NULL ) return rhs == NULL;
862
863 if ( rhs == NULL ) return false;
864
865 return strcmp(lhs, rhs) == 0;
866 }
867
868 #if GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
869
870 // Converts an array of wide chars to a narrow string using the UTF-8
871 // encoding, and streams the result to the given Message object.
872 static void StreamWideCharsToMessage(const wchar_t* wstr, size_t length,
873 Message* msg) {
874 // TODO(wan): consider allowing a testing::String object to
875 // contain '\0'. This will make it behave more like std::string,
876 // and will allow ToUtf8String() to return the correct encoding
877 // for '\0' s.t. we can get rid of the conditional here (and in
878 // several other places).
879 for (size_t i = 0; i != length; ) { // NOLINT
880 if (wstr[i] != L'\0') {
881 *msg << WideStringToUtf8(wstr + i, static_cast<int>(length - i));
882 while (i != length && wstr[i] != L'\0')
883 i++;
884 } else {
885 *msg << '\0';
886 i++;
887 }
888 }
889 }
890
891 #endif // GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
892
893 } // namespace internal
894
895 #if GTEST_HAS_STD_WSTRING
896 // Converts the given wide string to a narrow string using the UTF-8
897 // encoding, and streams the result to this Message object.
898 Message& Message::operator <<(const ::std::wstring& wstr) {
899 internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
900 return *this;
901 }
902 #endif // GTEST_HAS_STD_WSTRING
903
904 #if GTEST_HAS_GLOBAL_WSTRING
905 // Converts the given wide string to a narrow string using the UTF-8
906 // encoding, and streams the result to this Message object.
907 Message& Message::operator <<(const ::wstring& wstr) {
908 internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
909 return *this;
910 }
911 #endif // GTEST_HAS_GLOBAL_WSTRING
912
913 namespace internal {
914
915 // Formats a value to be used in a failure message.
916
917 // For a char value, we print it as a C++ char literal and as an
918 // unsigned integer (both in decimal and in hexadecimal).
919 String FormatForFailureMessage(char ch) {
920 const unsigned int ch_as_uint = ch;
921 // A String object cannot contain '\0', so we print "\\0" when ch is
922 // '\0'.
923 return String::Format("'%s' (%u, 0x%X)",
924 ch ? String::Format("%c", ch).c_str() : "\\0",
925 ch_as_uint, ch_as_uint);
926 }
927
928 // For a wchar_t value, we print it as a C++ wchar_t literal and as an
929 // unsigned integer (both in decimal and in hexidecimal).
930 String FormatForFailureMessage(wchar_t wchar) {
931 // The C++ standard doesn't specify the exact size of the wchar_t
932 // type. It just says that it shall have the same size as another
933 // integral type, called its underlying type.
934 //
935 // Therefore, in order to print a wchar_t value in the numeric form,
936 // we first convert it to the largest integral type (UInt64) and
937 // then print the converted value.
938 //
939 // We use streaming to print the value as "%llu" doesn't work
940 // correctly with MSVC 7.1.
941 const UInt64 wchar_as_uint64 = wchar;
942 Message msg;
943 // A String object cannot contain '\0', so we print "\\0" when wchar is
944 // L'\0'.
945 char buffer[32]; // CodePointToUtf8 requires a buffer that big.
946 msg << "L'"
947 << (wchar ? CodePointToUtf8(static_cast<UInt32>(wchar), buffer) : "\\0")
948 << "' (" << wchar_as_uint64 << ", 0x" << ::std::setbase(16)
949 << wchar_as_uint64 << ")";
950 return msg.GetString();
951 }
952
953 } // namespace internal
954
955 // AssertionResult constructors.
956 // Used in EXPECT_TRUE/FALSE(assertion_result).
957 AssertionResult::AssertionResult(const AssertionResult& other)
958 : success_(other.success_),
959 message_(other.message_.get() != NULL ?
960 new internal::String(*other.message_) :
961 static_cast<internal::String*>(NULL)) {
962 }
963
964 // Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE.
965 AssertionResult AssertionResult::operator!() const {
966 AssertionResult negation(!success_);
967 if (message_.get() != NULL)
968 negation << *message_;
969 return negation;
970 }
971
972 // Makes a successful assertion result.
973 AssertionResult AssertionSuccess() {
974 return AssertionResult(true);
975 }
976
977 // Makes a failed assertion result.
978 AssertionResult AssertionFailure() {
979 return AssertionResult(false);
980 }
981
982 // Makes a failed assertion result with the given failure message.
983 // Deprecated; use AssertionFailure() << message.
984 AssertionResult AssertionFailure(const Message& message) {
985 return AssertionFailure() << message;
986 }
987
988 namespace internal {
989
990 // Constructs and returns the message for an equality assertion
991 // (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure.
992 //
993 // The first four parameters are the expressions used in the assertion
994 // and their values, as strings. For example, for ASSERT_EQ(foo, bar)
995 // where foo is 5 and bar is 6, we have:
996 //
997 // expected_expression: "foo"
998 // actual_expression: "bar"
999 // expected_value: "5"
1000 // actual_value: "6"
1001 //
1002 // The ignoring_case parameter is true iff the assertion is a
1003 // *_STRCASEEQ*. When it's true, the string " (ignoring case)" will
1004 // be inserted into the message.
1005 AssertionResult EqFailure(const char* expected_expression,
1006 const char* actual_expression,
1007 const String& expected_value,
1008 const String& actual_value,
1009 bool ignoring_case) {
1010 Message msg;
1011 msg << "Value of: " << actual_expression;
1012 if (actual_value != actual_expression) {
1013 msg << "\n Actual: " << actual_value;
1014 }
1015
1016 msg << "\nExpected: " << expected_expression;
1017 if (ignoring_case) {
1018 msg << " (ignoring case)";
1019 }
1020 if (expected_value != expected_expression) {
1021 msg << "\nWhich is: " << expected_value;
1022 }
1023
1024 return AssertionFailure(msg);
1025 }
1026
1027 // Constructs a failure message for Boolean assertions such as EXPECT_TRUE.
1028 String GetBoolAssertionFailureMessage(const AssertionResult& assertion_result,
1029 const char* expression_text,
1030 const char* actual_predicate_value,
1031 const char* expected_predicate_value) {
1032 const char* actual_message = assertion_result.message();
1033 Message msg;
1034 msg << "Value of: " << expression_text
1035 << "\n Actual: " << actual_predicate_value;
1036 if (actual_message[0] != '\0')
1037 msg << " (" << actual_message << ")";
1038 msg << "\nExpected: " << expected_predicate_value;
1039 return msg.GetString();
1040 }
1041
1042 // Helper function for implementing ASSERT_NEAR.
1043 AssertionResult DoubleNearPredFormat(const char* expr1,
1044 const char* expr2,
1045 const char* abs_error_expr,
1046 double val1,
1047 double val2,
1048 double abs_error) {
1049 const double diff = fabs(val1 - val2);
1050 if (diff <= abs_error) return AssertionSuccess();
1051
1052 // TODO(wan): do not print the value of an expression if it's
1053 // already a literal.
1054 Message msg;
1055 msg << "The difference between " << expr1 << " and " << expr2
1056 << " is " << diff << ", which exceeds " << abs_error_expr << ", where\n"
1057 << expr1 << " evaluates to " << val1 << ",\n"
1058 << expr2 << " evaluates to " << val2 << ", and\n"
1059 << abs_error_expr << " evaluates to " << abs_error << ".";
1060 return AssertionFailure(msg);
1061 }
1062
1063
1064 // Helper template for implementing FloatLE() and DoubleLE().
1065 template <typename RawType>
1066 AssertionResult FloatingPointLE(const char* expr1,
1067 const char* expr2,
1068 RawType val1,
1069 RawType val2) {
1070 // Returns success if val1 is less than val2,
1071 if (val1 < val2) {
1072 return AssertionSuccess();
1073 }
1074
1075 // or if val1 is almost equal to val2.
1076 const FloatingPoint<RawType> lhs(val1), rhs(val2);
1077 if (lhs.AlmostEquals(rhs)) {
1078 return AssertionSuccess();
1079 }
1080
1081 // Note that the above two checks will both fail if either val1 or
1082 // val2 is NaN, as the IEEE floating-point standard requires that
1083 // any predicate involving a NaN must return false.
1084
1085 StrStream val1_ss;
1086 val1_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
1087 << val1;
1088
1089 StrStream val2_ss;
1090 val2_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
1091 << val2;
1092
1093 Message msg;
1094 msg << "Expected: (" << expr1 << ") <= (" << expr2 << ")\n"
1095 << " Actual: " << StrStreamToString(&val1_ss) << " vs "
1096 << StrStreamToString(&val2_ss);
1097
1098 return AssertionFailure(msg);
1099 }
1100
1101 } // namespace internal
1102
1103 // Asserts that val1 is less than, or almost equal to, val2. Fails
1104 // otherwise. In particular, it fails if either val1 or val2 is NaN.
1105 AssertionResult FloatLE(const char* expr1, const char* expr2,
1106 float val1, float val2) {
1107 return internal::FloatingPointLE<float>(expr1, expr2, val1, val2);
1108 }
1109
1110 // Asserts that val1 is less than, or almost equal to, val2. Fails
1111 // otherwise. In particular, it fails if either val1 or val2 is NaN.
1112 AssertionResult DoubleLE(const char* expr1, const char* expr2,
1113 double val1, double val2) {
1114 return internal::FloatingPointLE<double>(expr1, expr2, val1, val2);
1115 }
1116
1117 namespace internal {
1118
1119 // The helper function for {ASSERT|EXPECT}_EQ with int or enum
1120 // arguments.
1121 AssertionResult CmpHelperEQ(const char* expected_expression,
1122 const char* actual_expression,
1123 BiggestInt expected,
1124 BiggestInt actual) {
1125 if (expected == actual) {
1126 return AssertionSuccess();
1127 }
1128
1129 return EqFailure(expected_expression,
1130 actual_expression,
1131 FormatForComparisonFailureMessage(expected, actual),
1132 FormatForComparisonFailureMessage(actual, expected),
1133 false);
1134 }
1135
1136 // A macro for implementing the helper functions needed to implement
1137 // ASSERT_?? and EXPECT_?? with integer or enum arguments. It is here
1138 // just to avoid copy-and-paste of similar code.
1139 #define GTEST_IMPL_CMP_HELPER_(op_name, op)\
1140 AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \
1141 BiggestInt val1, BiggestInt val2) {\
1142 if (val1 op val2) {\
1143 return AssertionSuccess();\
1144 } else {\
1145 Message msg;\
1146 msg << "Expected: (" << expr1 << ") " #op " (" << expr2\
1147 << "), actual: " << FormatForComparisonFailureMessage(val1, val2)\
1148 << " vs " << FormatForComparisonFailureMessage(val2, val1);\
1149 return AssertionFailure(msg);\
1150 }\
1151 }
1152
1153 // Implements the helper function for {ASSERT|EXPECT}_NE with int or
1154 // enum arguments.
1155 GTEST_IMPL_CMP_HELPER_(NE, !=)
1156 // Implements the helper function for {ASSERT|EXPECT}_LE with int or
1157 // enum arguments.
1158 GTEST_IMPL_CMP_HELPER_(LE, <=)
1159 // Implements the helper function for {ASSERT|EXPECT}_LT with int or
1160 // enum arguments.
1161 GTEST_IMPL_CMP_HELPER_(LT, < )
1162 // Implements the helper function for {ASSERT|EXPECT}_GE with int or
1163 // enum arguments.
1164 GTEST_IMPL_CMP_HELPER_(GE, >=)
1165 // Implements the helper function for {ASSERT|EXPECT}_GT with int or
1166 // enum arguments.
1167 GTEST_IMPL_CMP_HELPER_(GT, > )
1168
1169 #undef GTEST_IMPL_CMP_HELPER_
1170
1171 // The helper function for {ASSERT|EXPECT}_STREQ.
1172 AssertionResult CmpHelperSTREQ(const char* expected_expression,
1173 const char* actual_expression,
1174 const char* expected,
1175 const char* actual) {
1176 if (String::CStringEquals(expected, actual)) {
1177 return AssertionSuccess();
1178 }
1179
1180 return EqFailure(expected_expression,
1181 actual_expression,
1182 String::ShowCStringQuoted(expected),
1183 String::ShowCStringQuoted(actual),
1184 false);
1185 }
1186
1187 // The helper function for {ASSERT|EXPECT}_STRCASEEQ.
1188 AssertionResult CmpHelperSTRCASEEQ(const char* expected_expression,
1189 const char* actual_expression,
1190 const char* expected,
1191 const char* actual) {
1192 if (String::CaseInsensitiveCStringEquals(expected, actual)) {
1193 return AssertionSuccess();
1194 }
1195
1196 return EqFailure(expected_expression,
1197 actual_expression,
1198 String::ShowCStringQuoted(expected),
1199 String::ShowCStringQuoted(actual),
1200 true);
1201 }
1202
1203 // The helper function for {ASSERT|EXPECT}_STRNE.
1204 AssertionResult CmpHelperSTRNE(const char* s1_expression,
1205 const char* s2_expression,
1206 const char* s1,
1207 const char* s2) {
1208 if (!String::CStringEquals(s1, s2)) {
1209 return AssertionSuccess();
1210 } else {
1211 Message msg;
1212 msg << "Expected: (" << s1_expression << ") != ("
1213 << s2_expression << "), actual: \""
1214 << s1 << "\" vs \"" << s2 << "\"";
1215 return AssertionFailure(msg);
1216 }
1217 }
1218
1219 // The helper function for {ASSERT|EXPECT}_STRCASENE.
1220 AssertionResult CmpHelperSTRCASENE(const char* s1_expression,
1221 const char* s2_expression,
1222 const char* s1,
1223 const char* s2) {
1224 if (!String::CaseInsensitiveCStringEquals(s1, s2)) {
1225 return AssertionSuccess();
1226 } else {
1227 Message msg;
1228 msg << "Expected: (" << s1_expression << ") != ("
1229 << s2_expression << ") (ignoring case), actual: \""
1230 << s1 << "\" vs \"" << s2 << "\"";
1231 return AssertionFailure(msg);
1232 }
1233 }
1234
1235 } // namespace internal
1236
1237 namespace {
1238
1239 // Helper functions for implementing IsSubString() and IsNotSubstring().
1240
1241 // This group of overloaded functions return true iff needle is a
1242 // substring of haystack. NULL is considered a substring of itself
1243 // only.
1244
1245 bool IsSubstringPred(const char* needle, const char* haystack) {
1246 if (needle == NULL || haystack == NULL)
1247 return needle == haystack;
1248
1249 return strstr(haystack, needle) != NULL;
1250 }
1251
1252 bool IsSubstringPred(const wchar_t* needle, const wchar_t* haystack) {
1253 if (needle == NULL || haystack == NULL)
1254 return needle == haystack;
1255
1256 return wcsstr(haystack, needle) != NULL;
1257 }
1258
1259 // StringType here can be either ::std::string or ::std::wstring.
1260 template <typename StringType>
1261 bool IsSubstringPred(const StringType& needle,
1262 const StringType& haystack) {
1263 return haystack.find(needle) != StringType::npos;
1264 }
1265
1266 // This function implements either IsSubstring() or IsNotSubstring(),
1267 // depending on the value of the expected_to_be_substring parameter.
1268 // StringType here can be const char*, const wchar_t*, ::std::string,
1269 // or ::std::wstring.
1270 template <typename StringType>
1271 AssertionResult IsSubstringImpl(
1272 bool expected_to_be_substring,
1273 const char* needle_expr, const char* haystack_expr,
1274 const StringType& needle, const StringType& haystack) {
1275 if (IsSubstringPred(needle, haystack) == expected_to_be_substring)
1276 return AssertionSuccess();
1277
1278 const bool is_wide_string = sizeof(needle[0]) > 1;
1279 const char* const begin_string_quote = is_wide_string ? "L\"" : "\"";
1280 return AssertionFailure(
1281 Message()
1282 << "Value of: " << needle_expr << "\n"
1283 << " Actual: " << begin_string_quote << needle << "\"\n"
1284 << "Expected: " << (expected_to_be_substring ? "" : "not ")
1285 << "a substring of " << haystack_expr << "\n"
1286 << "Which is: " << begin_string_quote << haystack << "\"");
1287 }
1288
1289 } // namespace
1290
1291 // IsSubstring() and IsNotSubstring() check whether needle is a
1292 // substring of haystack (NULL is considered a substring of itself
1293 // only), and return an appropriate error message when they fail.
1294
1295 AssertionResult IsSubstring(
1296 const char* needle_expr, const char* haystack_expr,
1297 const char* needle, const char* haystack) {
1298 return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
1299 }
1300
1301 AssertionResult IsSubstring(
1302 const char* needle_expr, const char* haystack_expr,
1303 const wchar_t* needle, const wchar_t* haystack) {
1304 return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
1305 }
1306
1307 AssertionResult IsNotSubstring(
1308 const char* needle_expr, const char* haystack_expr,
1309 const char* needle, const char* haystack) {
1310 return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
1311 }
1312
1313 AssertionResult IsNotSubstring(
1314 const char* needle_expr, const char* haystack_expr,
1315 const wchar_t* needle, const wchar_t* haystack) {
1316 return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
1317 }
1318
1319 #if GTEST_HAS_STD_STRING
1320 AssertionResult IsSubstring(
1321 const char* needle_expr, const char* haystack_expr,
1322 const ::std::string& needle, const ::std::string& haystack) {
1323 return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
1324 }
1325
1326 AssertionResult IsNotSubstring(
1327 const char* needle_expr, const char* haystack_expr,
1328 const ::std::string& needle, const ::std::string& haystack) {
1329 return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
1330 }
1331 #endif // GTEST_HAS_STD_STRING
1332
1333 #if GTEST_HAS_STD_WSTRING
1334 AssertionResult IsSubstring(
1335 const char* needle_expr, const char* haystack_expr,
1336 const ::std::wstring& needle, const ::std::wstring& haystack) {
1337 return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
1338 }
1339
1340 AssertionResult IsNotSubstring(
1341 const char* needle_expr, const char* haystack_expr,
1342 const ::std::wstring& needle, const ::std::wstring& haystack) {
1343 return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
1344 }
1345 #endif // GTEST_HAS_STD_WSTRING
1346
1347 namespace internal {
1348
1349 #if GTEST_OS_WINDOWS
1350
1351 namespace {
1352
1353 // Helper function for IsHRESULT{SuccessFailure} predicates
1354 AssertionResult HRESULTFailureHelper(const char* expr,
1355 const char* expected,
1356 long hr) { // NOLINT
1357 #if GTEST_OS_WINDOWS_MOBILE
1358 // Windows CE doesn't support FormatMessage.
1359 const char error_text[] = "";
1360 #else
1361 // Looks up the human-readable system message for the HRESULT code
1362 // and since we're not passing any params to FormatMessage, we don't
1363 // want inserts expanded.
1364 const DWORD kFlags = FORMAT_MESSAGE_FROM_SYSTEM |
1365 FORMAT_MESSAGE_IGNORE_INSERTS;
1366 const DWORD kBufSize = 4096; // String::Format can't exceed this length.
1367 // Gets the system's human readable message string for this HRESULT.
1368 char error_text[kBufSize] = { '\0' };
1369 DWORD message_length = ::FormatMessageA(kFlags,
1370 0, // no source, we're asking system
1371 hr, // the error
1372 0, // no line width restrictions
1373 error_text, // output buffer
1374 kBufSize, // buf size
1375 NULL); // no arguments for inserts
1376 // Trims tailing white space (FormatMessage leaves a trailing cr-lf)
1377 for (; message_length && isspace(error_text[message_length - 1]);
1378 --message_length) {
1379 error_text[message_length - 1] = '\0';
1380 }
1381 #endif // GTEST_OS_WINDOWS_MOBILE
1382
1383 const String error_hex(String::Format("0x%08X ", hr));
1384 Message msg;
1385 msg << "Expected: " << expr << " " << expected << ".\n"
1386 << " Actual: " << error_hex << error_text << "\n";
1387
1388 return ::testing::AssertionFailure(msg);
1389 }
1390
1391 } // namespace
1392
1393 AssertionResult IsHRESULTSuccess(const char* expr, long hr) { // NOLINT
1394 if (SUCCEEDED(hr)) {
1395 return AssertionSuccess();
1396 }
1397 return HRESULTFailureHelper(expr, "succeeds", hr);
1398 }
1399
1400 AssertionResult IsHRESULTFailure(const char* expr, long hr) { // NOLINT
1401 if (FAILED(hr)) {
1402 return AssertionSuccess();
1403 }
1404 return HRESULTFailureHelper(expr, "fails", hr);
1405 }
1406
1407 #endif // GTEST_OS_WINDOWS
1408
1409 // Utility functions for encoding Unicode text (wide strings) in
1410 // UTF-8.
1411
1412 // A Unicode code-point can have upto 21 bits, and is encoded in UTF-8
1413 // like this:
1414 //
1415 // Code-point length Encoding
1416 // 0 - 7 bits 0xxxxxxx
1417 // 8 - 11 bits 110xxxxx 10xxxxxx
1418 // 12 - 16 bits 1110xxxx 10xxxxxx 10xxxxxx
1419 // 17 - 21 bits 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
1420
1421 // The maximum code-point a one-byte UTF-8 sequence can represent.
1422 const UInt32 kMaxCodePoint1 = (static_cast<UInt32>(1) << 7) - 1;
1423
1424 // The maximum code-point a two-byte UTF-8 sequence can represent.
1425 const UInt32 kMaxCodePoint2 = (static_cast<UInt32>(1) << (5 + 6)) - 1;
1426
1427 // The maximum code-point a three-byte UTF-8 sequence can represent.
1428 const UInt32 kMaxCodePoint3 = (static_cast<UInt32>(1) << (4 + 2*6)) - 1;
1429
1430 // The maximum code-point a four-byte UTF-8 sequence can represent.
1431 const UInt32 kMaxCodePoint4 = (static_cast<UInt32>(1) << (3 + 3*6)) - 1;
1432
1433 // Chops off the n lowest bits from a bit pattern. Returns the n
1434 // lowest bits. As a side effect, the original bit pattern will be
1435 // shifted to the right by n bits.
1436 inline UInt32 ChopLowBits(UInt32* bits, int n) {
1437 const UInt32 low_bits = *bits & ((static_cast<UInt32>(1) << n) - 1);
1438 *bits >>= n;
1439 return low_bits;
1440 }
1441
1442 // Converts a Unicode code point to a narrow string in UTF-8 encoding.
1443 // code_point parameter is of type UInt32 because wchar_t may not be
1444 // wide enough to contain a code point.
1445 // The output buffer str must containt at least 32 characters.
1446 // The function returns the address of the output buffer.
1447 // If the code_point is not a valid Unicode code point
1448 // (i.e. outside of Unicode range U+0 to U+10FFFF) it will be output
1449 // as '(Invalid Unicode 0xXXXXXXXX)'.
1450 char* CodePointToUtf8(UInt32 code_point, char* str) {
1451 if (code_point <= kMaxCodePoint1) {
1452 str[1] = '\0';
1453 str[0] = static_cast<char>(code_point); // 0xxxxxxx
1454 } else if (code_point <= kMaxCodePoint2) {
1455 str[2] = '\0';
1456 str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
1457 str[0] = static_cast<char>(0xC0 | code_point); // 110xxxxx
1458 } else if (code_point <= kMaxCodePoint3) {
1459 str[3] = '\0';
1460 str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
1461 str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
1462 str[0] = static_cast<char>(0xE0 | code_point); // 1110xxxx
1463 } else if (code_point <= kMaxCodePoint4) {
1464 str[4] = '\0';
1465 str[3] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
1466 str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
1467 str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
1468 str[0] = static_cast<char>(0xF0 | code_point); // 11110xxx
1469 } else {
1470 // The longest string String::Format can produce when invoked
1471 // with these parameters is 28 character long (not including
1472 // the terminating nul character). We are asking for 32 character
1473 // buffer just in case. This is also enough for strncpy to
1474 // null-terminate the destination string.
1475 posix::StrNCpy(
1476 str, String::Format("(Invalid Unicode 0x%X)", code_point).c_str(), 32);
1477 str[31] = '\0'; // Makes sure no change in the format to strncpy leaves
1478 // the result unterminated.
1479 }
1480 return str;
1481 }
1482
1483 // The following two functions only make sense if the the system
1484 // uses UTF-16 for wide string encoding. All supported systems
1485 // with 16 bit wchar_t (Windows, Cygwin, Symbian OS) do use UTF-16.
1486
1487 // Determines if the arguments constitute UTF-16 surrogate pair
1488 // and thus should be combined into a single Unicode code point
1489 // using CreateCodePointFromUtf16SurrogatePair.
1490 inline bool IsUtf16SurrogatePair(wchar_t first, wchar_t second) {
1491 return sizeof(wchar_t) == 2 &&
1492 (first & 0xFC00) == 0xD800 && (second & 0xFC00) == 0xDC00;
1493 }
1494
1495 // Creates a Unicode code point from UTF16 surrogate pair.
1496 inline UInt32 CreateCodePointFromUtf16SurrogatePair(wchar_t first,
1497 wchar_t second) {
1498 const UInt32 mask = (1 << 10) - 1;
1499 return (sizeof(wchar_t) == 2) ?
1500 (((first & mask) << 10) | (second & mask)) + 0x10000 :
1501 // This function should not be called when the condition is
1502 // false, but we provide a sensible default in case it is.
1503 static_cast<UInt32>(first);
1504 }
1505
1506 // Converts a wide string to a narrow string in UTF-8 encoding.
1507 // The wide string is assumed to have the following encoding:
1508 // UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS)
1509 // UTF-32 if sizeof(wchar_t) == 4 (on Linux)
1510 // Parameter str points to a null-terminated wide string.
1511 // Parameter num_chars may additionally limit the number
1512 // of wchar_t characters processed. -1 is used when the entire string
1513 // should be processed.
1514 // If the string contains code points that are not valid Unicode code points
1515 // (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
1516 // as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
1517 // and contains invalid UTF-16 surrogate pairs, values in those pairs
1518 // will be encoded as individual Unicode characters from Basic Normal Plane.
1519 String WideStringToUtf8(const wchar_t* str, int num_chars) {
1520 if (num_chars == -1)
1521 num_chars = static_cast<int>(wcslen(str));
1522
1523 StrStream stream;
1524 for (int i = 0; i < num_chars; ++i) {
1525 UInt32 unicode_code_point;
1526
1527 if (str[i] == L'\0') {
1528 break;
1529 } else if (i + 1 < num_chars && IsUtf16SurrogatePair(str[i], str[i + 1])) {
1530 unicode_code_point = CreateCodePointFromUtf16SurrogatePair(str[i],
1531 str[i + 1]);
1532 i++;
1533 } else {
1534 unicode_code_point = static_cast<UInt32>(str[i]);
1535 }
1536
1537 char buffer[32]; // CodePointToUtf8 requires a buffer this big.
1538 stream << CodePointToUtf8(unicode_code_point, buffer);
1539 }
1540 return StrStreamToString(&stream);
1541 }
1542
1543 // Converts a wide C string to a String using the UTF-8 encoding.
1544 // NULL will be converted to "(null)".
1545 String String::ShowWideCString(const wchar_t * wide_c_str) {
1546 if (wide_c_str == NULL) return String("(null)");
1547
1548 return String(internal::WideStringToUtf8(wide_c_str, -1).c_str());
1549 }
1550
1551 // Similar to ShowWideCString(), except that this function encloses
1552 // the converted string in double quotes.
1553 String String::ShowWideCStringQuoted(const wchar_t* wide_c_str) {
1554 if (wide_c_str == NULL) return String("(null)");
1555
1556 return String::Format("L\"%s\"",
1557 String::ShowWideCString(wide_c_str).c_str());
1558 }
1559
1560 // Compares two wide C strings. Returns true iff they have the same
1561 // content.
1562 //
1563 // Unlike wcscmp(), this function can handle NULL argument(s). A NULL
1564 // C string is considered different to any non-NULL C string,
1565 // including the empty string.
1566 bool String::WideCStringEquals(const wchar_t * lhs, const wchar_t * rhs) {
1567 if (lhs == NULL) return rhs == NULL;
1568
1569 if (rhs == NULL) return false;
1570
1571 return wcscmp(lhs, rhs) == 0;
1572 }
1573
1574 // Helper function for *_STREQ on wide strings.
1575 AssertionResult CmpHelperSTREQ(const char* expected_expression,
1576 const char* actual_expression,
1577 const wchar_t* expected,
1578 const wchar_t* actual) {
1579 if (String::WideCStringEquals(expected, actual)) {
1580 return AssertionSuccess();
1581 }
1582
1583 return EqFailure(expected_expression,
1584 actual_expression,
1585 String::ShowWideCStringQuoted(expected),
1586 String::ShowWideCStringQuoted(actual),
1587 false);
1588 }
1589
1590 // Helper function for *_STRNE on wide strings.
1591 AssertionResult CmpHelperSTRNE(const char* s1_expression,
1592 const char* s2_expression,
1593 const wchar_t* s1,
1594 const wchar_t* s2) {
1595 if (!String::WideCStringEquals(s1, s2)) {
1596 return AssertionSuccess();
1597 }
1598
1599 Message msg;
1600 msg << "Expected: (" << s1_expression << ") != ("
1601 << s2_expression << "), actual: "
1602 << String::ShowWideCStringQuoted(s1)
1603 << " vs " << String::ShowWideCStringQuoted(s2);
1604 return AssertionFailure(msg);
1605 }
1606
1607 // Compares two C strings, ignoring case. Returns true iff they have
1608 // the same content.
1609 //
1610 // Unlike strcasecmp(), this function can handle NULL argument(s). A
1611 // NULL C string is considered different to any non-NULL C string,
1612 // including the empty string.
1613 bool String::CaseInsensitiveCStringEquals(const char * lhs, const char * rhs) {
1614 if (lhs == NULL)
1615 return rhs == NULL;
1616 if (rhs == NULL)
1617 return false;
1618 return posix::StrCaseCmp(lhs, rhs) == 0;
1619 }
1620
1621 // Compares two wide C strings, ignoring case. Returns true iff they
1622 // have the same content.
1623 //
1624 // Unlike wcscasecmp(), this function can handle NULL argument(s).
1625 // A NULL C string is considered different to any non-NULL wide C string,
1626 // including the empty string.
1627 // NB: The implementations on different platforms slightly differ.
1628 // On windows, this method uses _wcsicmp which compares according to LC_CTYPE
1629 // environment variable. On GNU platform this method uses wcscasecmp
1630 // which compares according to LC_CTYPE category of the current locale.
1631 // On MacOS X, it uses towlower, which also uses LC_CTYPE category of the
1632 // current locale.
1633 bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs,
1634 const wchar_t* rhs) {
1635 if ( lhs == NULL ) return rhs == NULL;
1636
1637 if ( rhs == NULL ) return false;
1638
1639 #if GTEST_OS_WINDOWS
1640 return _wcsicmp(lhs, rhs) == 0;
1641 #elif GTEST_OS_LINUX
1642 return wcscasecmp(lhs, rhs) == 0;
1643 #else
1644 // Mac OS X and Cygwin don't define wcscasecmp. Other unknown OSes
1645 // may not define it either.
1646 wint_t left, right;
1647 do {
1648 left = towlower(*lhs++);
1649 right = towlower(*rhs++);
1650 } while (left && left == right);
1651 return left == right;
1652 #endif // OS selector
1653 }
1654
1655 // Compares this with another String.
1656 // Returns < 0 if this is less than rhs, 0 if this is equal to rhs, or > 0
1657 // if this is greater than rhs.
1658 int String::Compare(const String & rhs) const {
1659 const char* const lhs_c_str = c_str();
1660 const char* const rhs_c_str = rhs.c_str();
1661
1662 if (lhs_c_str == NULL) {
1663 return rhs_c_str == NULL ? 0 : -1; // NULL < anything except NULL
1664 } else if (rhs_c_str == NULL) {
1665 return 1;
1666 }
1667
1668 const size_t shorter_str_len =
1669 length() <= rhs.length() ? length() : rhs.length();
1670 for (size_t i = 0; i != shorter_str_len; i++) {
1671 if (lhs_c_str[i] < rhs_c_str[i]) {
1672 return -1;
1673 } else if (lhs_c_str[i] > rhs_c_str[i]) {
1674 return 1;
1675 }
1676 }
1677 return (length() < rhs.length()) ? -1 :
1678 (length() > rhs.length()) ? 1 : 0;
1679 }
1680
1681 // Returns true iff this String ends with the given suffix. *Any*
1682 // String is considered to end with a NULL or empty suffix.
1683 bool String::EndsWith(const char* suffix) const {
1684 if (suffix == NULL || CStringEquals(suffix, "")) return true;
1685
1686 if (c_str() == NULL) return false;
1687
1688 const size_t this_len = strlen(c_str());
1689 const size_t suffix_len = strlen(suffix);
1690 return (this_len >= suffix_len) &&
1691 CStringEquals(c_str() + this_len - suffix_len, suffix);
1692 }
1693
1694 // Returns true iff this String ends with the given suffix, ignoring case.
1695 // Any String is considered to end with a NULL or empty suffix.
1696 bool String::EndsWithCaseInsensitive(const char* suffix) const {
1697 if (suffix == NULL || CStringEquals(suffix, "")) return true;
1698
1699 if (c_str() == NULL) return false;
1700
1701 const size_t this_len = strlen(c_str());
1702 const size_t suffix_len = strlen(suffix);
1703 return (this_len >= suffix_len) &&
1704 CaseInsensitiveCStringEquals(c_str() + this_len - suffix_len, suffix);
1705 }
1706
1707 // Formats a list of arguments to a String, using the same format
1708 // spec string as for printf.
1709 //
1710 // We do not use the StringPrintf class as it is not universally
1711 // available.
1712 //
1713 // The result is limited to 4096 characters (including the tailing 0).
1714 // If 4096 characters are not enough to format the input, or if
1715 // there's an error, "<formatting error or buffer exceeded>" is
1716 // returned.
1717 String String::Format(const char * format, ...) {
1718 va_list args;
1719 va_start(args, format);
1720
1721 char buffer[4096];
1722 const int kBufferSize = sizeof(buffer)/sizeof(buffer[0]);
1723
1724 // MSVC 8 deprecates vsnprintf(), so we want to suppress warning
1725 // 4996 (deprecated function) there.
1726 #ifdef _MSC_VER // We are using MSVC.
1727 #pragma warning(push) // Saves the current warning state.
1728 #pragma warning(disable:4996) // Temporarily disables warning 4996.
1729 const int size = vsnprintf(buffer, kBufferSize, format, args);
1730 #pragma warning(pop) // Restores the warning state.
1731 #else // We are not using MSVC.
1732 const int size = vsnprintf(buffer, kBufferSize, format, args);
1733 #endif // _MSC_VER
1734 va_end(args);
1735
1736 // vsnprintf()'s behavior is not portable. When the buffer is not
1737 // big enough, it returns a negative value in MSVC, and returns the
1738 // needed buffer size on Linux. When there is an output error, it
1739 // always returns a negative value. For simplicity, we lump the two
1740 // error cases together.
1741 if (size < 0 || size >= kBufferSize) {
1742 return String("<formatting error or buffer exceeded>");
1743 } else {
1744 return String(buffer, size);
1745 }
1746 }
1747
1748 // Converts the buffer in a StrStream to a String, converting NUL
1749 // bytes to "\\0" along the way.
1750 String StrStreamToString(StrStream* ss) {
1751 #if GTEST_HAS_STD_STRING
1752 const ::std::string& str = ss->str();
1753 const char* const start = str.c_str();
1754 const char* const end = start + str.length();
1755 #else
1756 const char* const start = ss->str();
1757 const char* const end = start + ss->pcount();
1758 #endif // GTEST_HAS_STD_STRING
1759
1760 // We need to use a helper StrStream to do this transformation
1761 // because String doesn't support push_back().
1762 StrStream helper;
1763 for (const char* ch = start; ch != end; ++ch) {
1764 if (*ch == '\0') {
1765 helper << "\\0"; // Replaces NUL with "\\0";
1766 } else {
1767 helper.put(*ch);
1768 }
1769 }
1770
1771 #if GTEST_HAS_STD_STRING
1772 return String(helper.str().c_str());
1773 #else
1774 const String str(helper.str(), helper.pcount());
1775 helper.freeze(false);
1776 ss->freeze(false);
1777 return str;
1778 #endif // GTEST_HAS_STD_STRING
1779 }
1780
1781 // Appends the user-supplied message to the Google-Test-generated message.
1782 String AppendUserMessage(const String& gtest_msg,
1783 const Message& user_msg) {
1784 // Appends the user message if it's non-empty.
1785 const String user_msg_string = user_msg.GetString();
1786 if (user_msg_string.empty()) {
1787 return gtest_msg;
1788 }
1789
1790 Message msg;
1791 msg << gtest_msg << "\n" << user_msg_string;
1792
1793 return msg.GetString();
1794 }
1795
1796 } // namespace internal
1797
1798 // class TestResult
1799
1800 // Creates an empty TestResult.
1801 TestResult::TestResult()
1802 : test_part_results_(new internal::Vector<TestPartResult>),
1803 test_properties_(new internal::Vector<TestProperty>),
1804 death_test_count_(0),
1805 elapsed_time_(0) {
1806 }
1807
1808 // D'tor.
1809 TestResult::~TestResult() {
1810 }
1811
1812 // Returns the i-th test part result among all the results. i can
1813 // range from 0 to total_part_count() - 1. If i is not in that range,
1814 // aborts the program.
1815 const TestPartResult& TestResult::GetTestPartResult(int i) const {
1816 return test_part_results_->GetElement(i);
1817 }
1818
1819 // Returns the i-th test property. i can range from 0 to
1820 // test_property_count() - 1. If i is not in that range, aborts the
1821 // program.
1822 const TestProperty& TestResult::GetTestProperty(int i) const {
1823 return test_properties_->GetElement(i);
1824 }
1825
1826 // Clears the test part results.
1827 void TestResult::ClearTestPartResults() {
1828 test_part_results_->Clear();
1829 }
1830
1831 // Adds a test part result to the list.
1832 void TestResult::AddTestPartResult(const TestPartResult& test_part_result) {
1833 test_part_results_->PushBack(test_part_result);
1834 }
1835
1836 // Adds a test property to the list. If a property with the same key as the
1837 // supplied property is already represented, the value of this test_property
1838 // replaces the old value for that key.
1839 void TestResult::RecordProperty(const TestProperty& test_property) {
1840 if (!ValidateTestProperty(test_property)) {
1841 return;
1842 }
1843 internal::MutexLock lock(&test_properites_mutex_);
1844 TestProperty* const property_with_matching_key =
1845 test_properties_->FindIf(
1846 internal::TestPropertyKeyIs(test_property.key()));
1847 if (property_with_matching_key == NULL) {
1848 test_properties_->PushBack(test_property);
1849 return;
1850 }
1851 property_with_matching_key->SetValue(test_property.value());
1852 }
1853
1854 // Adds a failure if the key is a reserved attribute of Google Test
1855 // testcase tags. Returns true if the property is valid.
1856 bool TestResult::ValidateTestProperty(const TestProperty& test_property) {
1857 internal::String key(test_property.key());
1858 if (key == "name" || key == "status" || key == "time" || key == "classname") {
1859 ADD_FAILURE()
1860 << "Reserved key used in RecordProperty(): "
1861 << key
1862 << " ('name', 'status', 'time', and 'classname' are reserved by "
1863 << GTEST_NAME_ << ")";
1864 return false;
1865 }
1866 return true;
1867 }
1868
1869 // Clears the object.
1870 void TestResult::Clear() {
1871 test_part_results_->Clear();
1872 test_properties_->Clear();
1873 death_test_count_ = 0;
1874 elapsed_time_ = 0;
1875 }
1876
1877 // Returns true iff the test failed.
1878 bool TestResult::Failed() const {
1879 for (int i = 0; i < total_part_count(); ++i) {
1880 if (GetTestPartResult(i).failed())
1881 return true;
1882 }
1883 return false;
1884 }
1885
1886 // Returns true iff the test part fatally failed.
1887 static bool TestPartFatallyFailed(const TestPartResult& result) {
1888 return result.fatally_failed();
1889 }
1890
1891 // Returns true iff the test fatally failed.
1892 bool TestResult::HasFatalFailure() const {
1893 return test_part_results_->CountIf(TestPartFatallyFailed) > 0;
1894 }
1895
1896 // Returns true iff the test part non-fatally failed.
1897 static bool TestPartNonfatallyFailed(const TestPartResult& result) {
1898 return result.nonfatally_failed();
1899 }
1900
1901 // Returns true iff the test has a non-fatal failure.
1902 bool TestResult::HasNonfatalFailure() const {
1903 return test_part_results_->CountIf(TestPartNonfatallyFailed) > 0;
1904 }
1905
1906 // Gets the number of all test parts. This is the sum of the number
1907 // of successful test parts and the number of failed test parts.
1908 int TestResult::total_part_count() const {
1909 return test_part_results_->size();
1910 }
1911
1912 // Returns the number of the test properties.
1913 int TestResult::test_property_count() const {
1914 return test_properties_->size();
1915 }
1916
1917 // class Test
1918
1919 // Creates a Test object.
1920
1921 // The c'tor saves the values of all Google Test flags.
1922 Test::Test()
1923 : gtest_flag_saver_(new internal::GTestFlagSaver) {
1924 }
1925
1926 // The d'tor restores the values of all Google Test flags.
1927 Test::~Test() {
1928 delete gtest_flag_saver_;
1929 }
1930
1931 // Sets up the test fixture.
1932 //
1933 // A sub-class may override this.
1934 void Test::SetUp() {
1935 }
1936
1937 // Tears down the test fixture.
1938 //
1939 // A sub-class may override this.
1940 void Test::TearDown() {
1941 }
1942
1943 // Allows user supplied key value pairs to be recorded for later output.
1944 void Test::RecordProperty(const char* key, const char* value) {
1945 UnitTest::GetInstance()->RecordPropertyForCurrentTest(key, value);
1946 }
1947
1948 // Allows user supplied key value pairs to be recorded for later output.
1949 void Test::RecordProperty(const char* key, int value) {
1950 Message value_message;
1951 value_message << value;
1952 RecordProperty(key, value_message.GetString().c_str());
1953 }
1954
1955 namespace internal {
1956
1957 void ReportFailureInUnknownLocation(TestPartResult::Type result_type,
1958 const String& message) {
1959 // This function is a friend of UnitTest and as such has access to
1960 // AddTestPartResult.
1961 UnitTest::GetInstance()->AddTestPartResult(
1962 result_type,
1963 NULL, // No info about the source file where the exception occurred.
1964 -1, // We have no info on which line caused the exception.
1965 message,
1966 String()); // No stack trace, either.
1967 }
1968
1969 } // namespace internal
1970
1971 #if GTEST_OS_WINDOWS
1972 // We are on Windows.
1973
1974 // Adds an "exception thrown" fatal failure to the current test.
1975 static void AddExceptionThrownFailure(DWORD exception_code,
1976 const char* location) {
1977 Message message;
1978 message << "Exception thrown with code 0x" << std::setbase(16) <<
1979 exception_code << std::setbase(10) << " in " << location << ".";
1980
1981 internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure,
1982 message.GetString());
1983 }
1984
1985 #endif // GTEST_OS_WINDOWS
1986
1987 // Google Test requires all tests in the same test case to use the same test
1988 // fixture class. This function checks if the current test has the
1989 // same fixture class as the first test in the current test case. If
1990 // yes, it returns true; otherwise it generates a Google Test failure and
1991 // returns false.
1992 bool Test::HasSameFixtureClass() {
1993 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
1994 const TestCase* const test_case = impl->current_test_case();
1995
1996 // Info about the first test in the current test case.
1997 const internal::TestInfoImpl* const first_test_info =
1998 test_case->test_info_list().GetElement(0)->impl();
1999 const internal::TypeId first_fixture_id = first_test_info->fixture_class_id();
2000 const char* const first_test_name = first_test_info->name();
2001
2002 // Info about the current test.
2003 const internal::TestInfoImpl* const this_test_info =
2004 impl->current_test_info()->impl();
2005 const internal::TypeId this_fixture_id = this_test_info->fixture_class_id();
2006 const char* const this_test_name = this_test_info->name();
2007
2008 if (this_fixture_id != first_fixture_id) {
2009 // Is the first test defined using TEST?
2010 const bool first_is_TEST = first_fixture_id == internal::GetTestTypeId();
2011 // Is this test defined using TEST?
2012 const bool this_is_TEST = this_fixture_id == internal::GetTestTypeId();
2013
2014 if (first_is_TEST || this_is_TEST) {
2015 // The user mixed TEST and TEST_F in this test case - we'll tell
2016 // him/her how to fix it.
2017
2018 // Gets the name of the TEST and the name of the TEST_F. Note
2019 // that first_is_TEST and this_is_TEST cannot both be true, as
2020 // the fixture IDs are different for the two tests.
2021 const char* const TEST_name =
2022 first_is_TEST ? first_test_name : this_test_name;
2023 const char* const TEST_F_name =
2024 first_is_TEST ? this_test_name : first_test_name;
2025
2026 ADD_FAILURE()
2027 << "All tests in the same test case must use the same test fixture\n"
2028 << "class, so mixing TEST_F and TEST in the same test case is\n"
2029 << "illegal. In test case " << this_test_info->test_case_name()
2030 << ",\n"
2031 << "test " << TEST_F_name << " is defined using TEST_F but\n"
2032 << "test " << TEST_name << " is defined using TEST. You probably\n"
2033 << "want to change the TEST to TEST_F or move it to another test\n"
2034 << "case.";
2035 } else {
2036 // The user defined two fixture classes with the same name in
2037 // two namespaces - we'll tell him/her how to fix it.
2038 ADD_FAILURE()
2039 << "All tests in the same test case must use the same test fixture\n"
2040 << "class. However, in test case "
2041 << this_test_info->test_case_name() << ",\n"
2042 << "you defined test " << first_test_name
2043 << " and test " << this_test_name << "\n"
2044 << "using two different test fixture classes. This can happen if\n"
2045 << "the two classes are from different namespaces or translation\n"
2046 << "units and have the same name. You should probably rename one\n"
2047 << "of the classes to put the tests into different test cases.";
2048 }
2049 return false;
2050 }
2051
2052 return true;
2053 }
2054
2055 // Runs the test and updates the test result.
2056 void Test::Run() {
2057 if (!HasSameFixtureClass()) return;
2058
2059 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
2060 #if GTEST_HAS_SEH
2061 // Catch SEH-style exceptions.
2062 impl->os_stack_trace_getter()->UponLeavingGTest();
2063 __try {
2064 SetUp();
2065 } __except(internal::UnitTestOptions::GTestShouldProcessSEH(
2066 GetExceptionCode())) {
2067 AddExceptionThrownFailure(GetExceptionCode(), "SetUp()");
2068 }
2069
2070 // We will run the test only if SetUp() had no fatal failure.
2071 if (!HasFatalFailure()) {
2072 impl->os_stack_trace_getter()->UponLeavingGTest();
2073 __try {
2074 TestBody();
2075 } __except(internal::UnitTestOptions::GTestShouldProcessSEH(
2076 GetExceptionCode())) {
2077 AddExceptionThrownFailure(GetExceptionCode(), "the test body");
2078 }
2079 }
2080
2081 // However, we want to clean up as much as possible. Hence we will
2082 // always call TearDown(), even if SetUp() or the test body has
2083 // failed.
2084 impl->os_stack_trace_getter()->UponLeavingGTest();
2085 __try {
2086 TearDown();
2087 } __except(internal::UnitTestOptions::GTestShouldProcessSEH(
2088 GetExceptionCode())) {
2089 AddExceptionThrownFailure(GetExceptionCode(), "TearDown()");
2090 }
2091
2092 #else // We are on a compiler or platform that doesn't support SEH.
2093 impl->os_stack_trace_getter()->UponLeavingGTest();
2094 SetUp();
2095
2096 // We will run the test only if SetUp() was successful.
2097 if (!HasFatalFailure()) {
2098 impl->os_stack_trace_getter()->UponLeavingGTest();
2099 TestBody();
2100 }
2101
2102 // However, we want to clean up as much as possible. Hence we will
2103 // always call TearDown(), even if SetUp() or the test body has
2104 // failed.
2105 impl->os_stack_trace_getter()->UponLeavingGTest();
2106 TearDown();
2107 #endif // GTEST_HAS_SEH
2108 }
2109
2110
2111 // Returns true iff the current test has a fatal failure.
2112 bool Test::HasFatalFailure() {
2113 return internal::GetUnitTestImpl()->current_test_result()->HasFatalFailure();
2114 }
2115
2116 // Returns true iff the current test has a non-fatal failure.
2117 bool Test::HasNonfatalFailure() {
2118 return internal::GetUnitTestImpl()->current_test_result()->
2119 HasNonfatalFailure();
2120 }
2121
2122 // class TestInfo
2123
2124 // Constructs a TestInfo object. It assumes ownership of the test factory
2125 // object via impl_.
2126 TestInfo::TestInfo(const char* test_case_name,
2127 const char* name,
2128 const char* test_case_comment,
2129 const char* comment,
2130 internal::TypeId fixture_class_id,
2131 internal::TestFactoryBase* factory) {
2132 impl_ = new internal::TestInfoImpl(this, test_case_name, name,
2133 test_case_comment, comment,
2134 fixture_class_id, factory);
2135 }
2136
2137 // Destructs a TestInfo object.
2138 TestInfo::~TestInfo() {
2139 delete impl_;
2140 }
2141
2142 namespace internal {
2143
2144 // Creates a new TestInfo object and registers it with Google Test;
2145 // returns the created object.
2146 //
2147 // Arguments:
2148 //
2149 // test_case_name: name of the test case
2150 // name: name of the test
2151 // test_case_comment: a comment on the test case that will be included in
2152 // the test output
2153 // comment: a comment on the test that will be included in the
2154 // test output
2155 // fixture_class_id: ID of the test fixture class
2156 // set_up_tc: pointer to the function that sets up the test case
2157 // tear_down_tc: pointer to the function that tears down the test case
2158 // factory: pointer to the factory that creates a test object.
2159 // The newly created TestInfo instance will assume
2160 // ownership of the factory object.
2161 TestInfo* MakeAndRegisterTestInfo(
2162 const char* test_case_name, const char* name,
2163 const char* test_case_comment, const char* comment,
2164 TypeId fixture_class_id,
2165 SetUpTestCaseFunc set_up_tc,
2166 TearDownTestCaseFunc tear_down_tc,
2167 TestFactoryBase* factory) {
2168 TestInfo* const test_info =
2169 new TestInfo(test_case_name, name, test_case_comment, comment,
2170 fixture_class_id, factory);
2171 GetUnitTestImpl()->AddTestInfo(set_up_tc, tear_down_tc, test_info);
2172 return test_info;
2173 }
2174
2175 #if GTEST_HAS_PARAM_TEST
2176 void ReportInvalidTestCaseType(const char* test_case_name,
2177 const char* file, int line) {
2178 Message errors;
2179 errors
2180 << "Attempted redefinition of test case " << test_case_name << ".\n"
2181 << "All tests in the same test case must use the same test fixture\n"
2182 << "class. However, in test case " << test_case_name << ", you tried\n"
2183 << "to define a test using a fixture class different from the one\n"
2184 << "used earlier. This can happen if the two fixture classes are\n"
2185 << "from different namespaces and have the same name. You should\n"
2186 << "probably rename one of the classes to put the tests into different\n"
2187 << "test cases.";
2188
2189 fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(),
2190 errors.GetString().c_str());
2191 }
2192 #endif // GTEST_HAS_PARAM_TEST
2193
2194 } // namespace internal
2195
2196 // Returns the test case name.
2197 const char* TestInfo::test_case_name() const {
2198 return impl_->test_case_name();
2199 }
2200
2201 // Returns the test name.
2202 const char* TestInfo::name() const {
2203 return impl_->name();
2204 }
2205
2206 // Returns the test case comment.
2207 const char* TestInfo::test_case_comment() const {
2208 return impl_->test_case_comment();
2209 }
2210
2211 // Returns the test comment.
2212 const char* TestInfo::comment() const {
2213 return impl_->comment();
2214 }
2215
2216 // Returns true if this test should run.
2217 bool TestInfo::should_run() const { return impl_->should_run(); }
2218
2219 // Returns true if this test matches the user-specified filter.
2220 bool TestInfo::matches_filter() const { return impl_->matches_filter(); }
2221
2222 // Returns the result of the test.
2223 const TestResult* TestInfo::result() const { return impl_->result(); }
2224
2225 // Increments the number of death tests encountered in this test so
2226 // far.
2227 int TestInfo::increment_death_test_count() {
2228 return impl_->result()->increment_death_test_count();
2229 }
2230
2231 namespace {
2232
2233 // A predicate that checks the test name of a TestInfo against a known
2234 // value.
2235 //
2236 // This is used for implementation of the TestCase class only. We put
2237 // it in the anonymous namespace to prevent polluting the outer
2238 // namespace.
2239 //
2240 // TestNameIs is copyable.
2241 class TestNameIs {
2242 public:
2243 // Constructor.
2244 //
2245 // TestNameIs has NO default constructor.
2246 explicit TestNameIs(const char* name)
2247 : name_(name) {}
2248
2249 // Returns true iff the test name of test_info matches name_.
2250 bool operator()(const TestInfo * test_info) const {
2251 return test_info && internal::String(test_info->name()).Compare(name_) == 0;
2252 }
2253
2254 private:
2255 internal::String name_;
2256 };
2257
2258 } // namespace
2259
2260 namespace internal {
2261
2262 // This method expands all parameterized tests registered with macros TEST_P
2263 // and INSTANTIATE_TEST_CASE_P into regular tests and registers those.
2264 // This will be done just once during the program runtime.
2265 void UnitTestImpl::RegisterParameterizedTests() {
2266 #if GTEST_HAS_PARAM_TEST
2267 if (!parameterized_tests_registered_) {
2268 parameterized_test_registry_.RegisterTests();
2269 parameterized_tests_registered_ = true;
2270 }
2271 #endif
2272 }
2273
2274 // Creates the test object, runs it, records its result, and then
2275 // deletes it.
2276 void TestInfoImpl::Run() {
2277 if (!should_run_) return;
2278
2279 // Tells UnitTest where to store test result.
2280 UnitTestImpl* const impl = internal::GetUnitTestImpl();
2281 impl->set_current_test_info(parent_);
2282
2283 TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
2284
2285 // Notifies the unit test event listeners that a test is about to start.
2286 repeater->OnTestStart(*parent_);
2287
2288 const TimeInMillis start = GetTimeInMillis();
2289
2290 impl->os_stack_trace_getter()->UponLeavingGTest();
2291 #if GTEST_HAS_SEH
2292 // Catch SEH-style exceptions.
2293 Test* test = NULL;
2294
2295 __try {
2296 // Creates the test object.
2297 test = factory_->CreateTest();
2298 } __except(internal::UnitTestOptions::GTestShouldProcessSEH(
2299 GetExceptionCode())) {
2300 AddExceptionThrownFailure(GetExceptionCode(),
2301 "the test fixture's constructor");
2302 return;
2303 }
2304 #else // We are on a compiler or platform that doesn't support SEH.
2305
2306 // TODO(wan): If test->Run() throws, test won't be deleted. This is
2307 // not a problem now as we don't use exceptions. If we were to
2308 // enable exceptions, we should revise the following to be
2309 // exception-safe.
2310
2311 // Creates the test object.
2312 Test* test = factory_->CreateTest();
2313 #endif // GTEST_HAS_SEH
2314
2315 // Runs the test only if the constructor of the test fixture didn't
2316 // generate a fatal failure.
2317 if (!Test::HasFatalFailure()) {
2318 test->Run();
2319 }
2320
2321 // Deletes the test object.
2322 impl->os_stack_trace_getter()->UponLeavingGTest();
2323 delete test;
2324 test = NULL;
2325
2326 result_.set_elapsed_time(GetTimeInMillis() - start);
2327
2328 // Notifies the unit test event listener that a test has just finished.
2329 repeater->OnTestEnd(*parent_);
2330
2331 // Tells UnitTest to stop associating assertion results to this
2332 // test.
2333 impl->set_current_test_info(NULL);
2334 }
2335
2336 } // namespace internal
2337
2338 // class TestCase
2339
2340 // Gets the number of successful tests in this test case.
2341 int TestCase::successful_test_count() const {
2342 return test_info_list_->CountIf(TestPassed);
2343 }
2344
2345 // Gets the number of failed tests in this test case.
2346 int TestCase::failed_test_count() const {
2347 return test_info_list_->CountIf(TestFailed);
2348 }
2349
2350 int TestCase::disabled_test_count() const {
2351 return test_info_list_->CountIf(TestDisabled);
2352 }
2353
2354 // Get the number of tests in this test case that should run.
2355 int TestCase::test_to_run_count() const {
2356 return test_info_list_->CountIf(ShouldRunTest);
2357 }
2358
2359 // Gets the number of all tests.
2360 int TestCase::total_test_count() const {
2361 return test_info_list_->size();
2362 }
2363
2364 // Creates a TestCase with the given name.
2365 //
2366 // Arguments:
2367 //
2368 // name: name of the test case
2369 // set_up_tc: pointer to the function that sets up the test case
2370 // tear_down_tc: pointer to the function that tears down the test case
2371 TestCase::TestCase(const char* name, const char* comment,
2372 Test::SetUpTestCaseFunc set_up_tc,
2373 Test::TearDownTestCaseFunc tear_down_tc)
2374 : name_(name),
2375 comment_(comment),
2376 test_info_list_(new internal::Vector<TestInfo*>),
2377 test_indices_(new internal::Vector<int>),
2378 set_up_tc_(set_up_tc),
2379 tear_down_tc_(tear_down_tc),
2380 should_run_(false),
2381 elapsed_time_(0) {
2382 }
2383
2384 // Destructor of TestCase.
2385 TestCase::~TestCase() {
2386 // Deletes every Test in the collection.
2387 test_info_list_->ForEach(internal::Delete<TestInfo>);
2388 }
2389
2390 // Returns the i-th test among all the tests. i can range from 0 to
2391 // total_test_count() - 1. If i is not in that range, returns NULL.
2392 const TestInfo* TestCase::GetTestInfo(int i) const {
2393 const int index = test_indices_->GetElementOr(i, -1);
2394 return index < 0 ? NULL : test_info_list_->GetElement(index);
2395 }
2396
2397 // Returns the i-th test among all the tests. i can range from 0 to
2398 // total_test_count() - 1. If i is not in that range, returns NULL.
2399 TestInfo* TestCase::GetMutableTestInfo(int i) {
2400 const int index = test_indices_->GetElementOr(i, -1);
2401 return index < 0 ? NULL : test_info_list_->GetElement(index);
2402 }
2403
2404 // Adds a test to this test case. Will delete the test upon
2405 // destruction of the TestCase object.
2406 void TestCase::AddTestInfo(TestInfo * test_info) {
2407 test_info_list_->PushBack(test_info);
2408 test_indices_->PushBack(test_indices_->size());
2409 }
2410
2411 // Runs every test in this TestCase.
2412 void TestCase::Run() {
2413 if (!should_run_) return;
2414
2415 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
2416 impl->set_current_test_case(this);
2417
2418 TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
2419
2420 repeater->OnTestCaseStart(*this);
2421 impl->os_stack_trace_getter()->UponLeavingGTest();
2422 set_up_tc_();
2423
2424 const internal::TimeInMillis start = internal::GetTimeInMillis();
2425 for (int i = 0; i < total_test_count(); i++) {
2426 GetMutableTestInfo(i)->impl()->Run();
2427 }
2428 elapsed_time_ = internal::GetTimeInMillis() - start;
2429
2430 impl->os_stack_trace_getter()->UponLeavingGTest();
2431 tear_down_tc_();
2432 repeater->OnTestCaseEnd(*this);
2433 impl->set_current_test_case(NULL);
2434 }
2435
2436 // Clears the results of all tests in this test case.
2437 void TestCase::ClearResult() {
2438 test_info_list_->ForEach(internal::TestInfoImpl::ClearTestResult);
2439 }
2440
2441 // Returns true iff test passed.
2442 bool TestCase::TestPassed(const TestInfo * test_info) {
2443 const internal::TestInfoImpl* const impl = test_info->impl();
2444 return impl->should_run() && impl->result()->Passed();
2445 }
2446
2447 // Returns true iff test failed.
2448 bool TestCase::TestFailed(const TestInfo * test_info) {
2449 const internal::TestInfoImpl* const impl = test_info->impl();
2450 return impl->should_run() && impl->result()->Failed();
2451 }
2452
2453 // Returns true iff test is disabled.
2454 bool TestCase::TestDisabled(const TestInfo * test_info) {
2455 return test_info->impl()->is_disabled();
2456 }
2457
2458 // Returns true if the given test should run.
2459 bool TestCase::ShouldRunTest(const TestInfo *test_info) {
2460 return test_info->impl()->should_run();
2461 }
2462
2463 // Shuffles the tests in this test case.
2464 void TestCase::ShuffleTests(internal::Random* random) {
2465 test_indices_->Shuffle(random);
2466 }
2467
2468 // Restores the test order to before the first shuffle.
2469 void TestCase::UnshuffleTests() {
2470 for (int i = 0; i < test_indices_->size(); i++) {
2471 test_indices_->GetMutableElement(i) = i;
2472 }
2473 }
2474
2475 // Formats a countable noun. Depending on its quantity, either the
2476 // singular form or the plural form is used. e.g.
2477 //
2478 // FormatCountableNoun(1, "formula", "formuli") returns "1 formula".
2479 // FormatCountableNoun(5, "book", "books") returns "5 books".
2480 static internal::String FormatCountableNoun(int count,
2481 const char * singular_form,
2482 const char * plural_form) {
2483 return internal::String::Format("%d %s", count,
2484 count == 1 ? singular_form : plural_form);
2485 }
2486
2487 // Formats the count of tests.
2488 static internal::String FormatTestCount(int test_count) {
2489 return FormatCountableNoun(test_count, "test", "tests");
2490 }
2491
2492 // Formats the count of test cases.
2493 static internal::String FormatTestCaseCount(int test_case_count) {
2494 return FormatCountableNoun(test_case_count, "test case", "test cases");
2495 }
2496
2497 // Converts a TestPartResult::Type enum to human-friendly string
2498 // representation. Both kNonFatalFailure and kFatalFailure are translated
2499 // to "Failure", as the user usually doesn't care about the difference
2500 // between the two when viewing the test result.
2501 static const char * TestPartResultTypeToString(TestPartResult::Type type) {
2502 switch (type) {
2503 case TestPartResult::kSuccess:
2504 return "Success";
2505
2506 case TestPartResult::kNonFatalFailure:
2507 case TestPartResult::kFatalFailure:
2508 #ifdef _MSC_VER
2509 return "error: ";
2510 #else
2511 return "Failure\n";
2512 #endif
2513 }
2514
2515 return "Unknown result type";
2516 }
2517
2518 // Prints a TestPartResult to a String.
2519 static internal::String PrintTestPartResultToString(
2520 const TestPartResult& test_part_result) {
2521 return (Message()
2522 << internal::FormatFileLocation(test_part_result.file_name(),
2523 test_part_result.line_number())
2524 << " " << TestPartResultTypeToString(test_part_result.type())
2525 << test_part_result.message()).GetString();
2526 }
2527
2528 // Prints a TestPartResult.
2529 static void PrintTestPartResult(const TestPartResult& test_part_result) {
2530 const internal::String& result =
2531 PrintTestPartResultToString(test_part_result);
2532 printf("%s\n", result.c_str());
2533 fflush(stdout);
2534 // If the test program runs in Visual Studio or a debugger, the
2535 // following statements add the test part result message to the Output
2536 // window such that the user can double-click on it to jump to the
2537 // corresponding source code location; otherwise they do nothing.
2538 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
2539 // We don't call OutputDebugString*() on Windows Mobile, as printing
2540 // to stdout is done by OutputDebugString() there already - we don't
2541 // want the same message printed twice.
2542 ::OutputDebugStringA(result.c_str());
2543 ::OutputDebugStringA("\n");
2544 #endif
2545 }
2546
2547 // class PrettyUnitTestResultPrinter
2548
2549 namespace internal {
2550
2551 enum GTestColor {
2552 COLOR_DEFAULT,
2553 COLOR_RED,
2554 COLOR_GREEN,
2555 COLOR_YELLOW
2556 };
2557
2558 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
2559
2560 // Returns the character attribute for the given color.
2561 WORD GetColorAttribute(GTestColor color) {
2562 switch (color) {
2563 case COLOR_RED: return FOREGROUND_RED;
2564 case COLOR_GREEN: return FOREGROUND_GREEN;
2565 case COLOR_YELLOW: return FOREGROUND_RED | FOREGROUND_GREEN;
2566 default: return 0;
2567 }
2568 }
2569
2570 #else
2571
2572 // Returns the ANSI color code for the given color. COLOR_DEFAULT is
2573 // an invalid input.
2574 const char* GetAnsiColorCode(GTestColor color) {
2575 switch (color) {
2576 case COLOR_RED: return "1";
2577 case COLOR_GREEN: return "2";
2578 case COLOR_YELLOW: return "3";
2579 default: return NULL;
2580 };
2581 }
2582
2583 #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
2584
2585 // Returns true iff Google Test should use colors in the output.
2586 bool ShouldUseColor(bool stdout_is_tty) {
2587 const char* const gtest_color = GTEST_FLAG(color).c_str();
2588
2589 if (String::CaseInsensitiveCStringEquals(gtest_color, "auto")) {
2590 #if GTEST_OS_WINDOWS
2591 // On Windows the TERM variable is usually not set, but the
2592 // console there does support colors.
2593 return stdout_is_tty;
2594 #else
2595 // On non-Windows platforms, we rely on the TERM variable.
2596 const char* const term = posix::GetEnv("TERM");
2597 const bool term_supports_color =
2598 String::CStringEquals(term, "xterm") ||
2599 String::CStringEquals(term, "xterm-color") ||
2600 String::CStringEquals(term, "xterm-256color") ||
2601 String::CStringEquals(term, "linux") ||
2602 String::CStringEquals(term, "cygwin");
2603 return stdout_is_tty && term_supports_color;
2604 #endif // GTEST_OS_WINDOWS
2605 }
2606
2607 return String::CaseInsensitiveCStringEquals(gtest_color, "yes") ||
2608 String::CaseInsensitiveCStringEquals(gtest_color, "true") ||
2609 String::CaseInsensitiveCStringEquals(gtest_color, "t") ||
2610 String::CStringEquals(gtest_color, "1");
2611 // We take "yes", "true", "t", and "1" as meaning "yes". If the
2612 // value is neither one of these nor "auto", we treat it as "no" to
2613 // be conservative.
2614 }
2615
2616 // Helpers for printing colored strings to stdout. Note that on Windows, we
2617 // cannot simply emit special characters and have the terminal change colors.
2618 // This routine must actually emit the characters rather than return a string
2619 // that would be colored when printed, as can be done on Linux.
2620 void ColoredPrintf(GTestColor color, const char* fmt, ...) {
2621 va_list args;
2622 va_start(args, fmt);
2623
2624 #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS
2625 const bool use_color = false;
2626 #else
2627 static const bool in_color_mode =
2628 ShouldUseColor(posix::IsATTY(posix::FileNo(stdout)) != 0);
2629 const bool use_color = in_color_mode && (color != COLOR_DEFAULT);
2630 #endif // GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS
2631 // The '!= 0' comparison is necessary to satisfy MSVC 7.1.
2632
2633 if (!use_color) {
2634 vprintf(fmt, args);
2635 va_end(args);
2636 return;
2637 }
2638
2639 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
2640 const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
2641
2642 // Gets the current text color.
2643 CONSOLE_SCREEN_BUFFER_INFO buffer_info;
2644 GetConsoleScreenBufferInfo(stdout_handle, &buffer_info);
2645 const WORD old_color_attrs = buffer_info.wAttributes;
2646
2647 SetConsoleTextAttribute(stdout_handle,
2648 GetColorAttribute(color) | FOREGROUND_INTENSITY);
2649 vprintf(fmt, args);
2650
2651 // Restores the text color.
2652 SetConsoleTextAttribute(stdout_handle, old_color_attrs);
2653 #else
2654 printf("\033[0;3%sm", GetAnsiColorCode(color));
2655 vprintf(fmt, args);
2656 printf("\033[m"); // Resets the terminal to default.
2657 #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
2658 va_end(args);
2659 }
2660
2661 // This class implements the TestEventListener interface.
2662 //
2663 // Class PrettyUnitTestResultPrinter is copyable.
2664 class PrettyUnitTestResultPrinter : public TestEventListener {
2665 public:
2666 PrettyUnitTestResultPrinter() {}
2667 static void PrintTestName(const char * test_case, const char * test) {
2668 printf("%s.%s", test_case, test);
2669 }
2670
2671 // The following methods override what's in the TestEventListener class.
2672 virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {}
2673 virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration);
2674 virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test);
2675 virtual void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) {}
2676 virtual void OnTestCaseStart(const TestCase& test_case);
2677 virtual void OnTestStart(const TestInfo& test_info);
2678 virtual void OnTestPartResult(const TestPartResult& result);
2679 virtual void OnTestEnd(const TestInfo& test_info);
2680 virtual void OnTestCaseEnd(const TestCase& test_case);
2681 virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test);
2682 virtual void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) {}
2683 virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
2684 virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) {}
2685
2686 private:
2687 static void PrintFailedTests(const UnitTest& unit_test);
2688
2689 internal::String test_case_name_;
2690 };
2691
2692 // Fired before each iteration of tests starts.
2693 void PrettyUnitTestResultPrinter::OnTestIterationStart(
2694 const UnitTest& unit_test, int iteration) {
2695 if (GTEST_FLAG(repeat) != 1)
2696 printf("\nRepeating all tests (iteration %d) . . .\n\n", iteration + 1);
2697
2698 const char* const filter = GTEST_FLAG(filter).c_str();
2699
2700 // Prints the filter if it's not *. This reminds the user that some
2701 // tests may be skipped.
2702 if (!internal::String::CStringEquals(filter, kUniversalFilter)) {
2703 ColoredPrintf(COLOR_YELLOW,
2704 "Note: %s filter = %s\n", GTEST_NAME_, filter);
2705 }
2706
2707 if (internal::ShouldShard(kTestTotalShards, kTestShardIndex, false)) {
2708 ColoredPrintf(COLOR_YELLOW,
2709 "Note: This is test shard %s of %s.\n",
2710 internal::posix::GetEnv(kTestShardIndex),
2711 internal::posix::GetEnv(kTestTotalShards));
2712 }
2713
2714 if (GTEST_FLAG(shuffle)) {
2715 ColoredPrintf(COLOR_YELLOW,
2716 "Note: Randomizing tests' orders with a seed of %d .\n",
2717 unit_test.random_seed());
2718 }
2719
2720 ColoredPrintf(COLOR_GREEN, "[==========] ");
2721 printf("Running %s from %s.\n",
2722 FormatTestCount(unit_test.test_to_run_count()).c_str(),
2723 FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str());
2724 fflush(stdout);
2725 }
2726
2727 void PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart(
2728 const UnitTest& /*unit_test*/) {
2729 ColoredPrintf(COLOR_GREEN, "[----------] ");
2730 printf("Global test environment set-up.\n");
2731 fflush(stdout);
2732 }
2733
2734 void PrettyUnitTestResultPrinter::OnTestCaseStart(const TestCase& test_case) {
2735 test_case_name_ = test_case.name();
2736 const internal::String counts =
2737 FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
2738 ColoredPrintf(COLOR_GREEN, "[----------] ");
2739 printf("%s from %s", counts.c_str(), test_case_name_.c_str());
2740 if (test_case.comment()[0] == '\0') {
2741 printf("\n");
2742 } else {
2743 printf(", where %s\n", test_case.comment());
2744 }
2745 fflush(stdout);
2746 }
2747
2748 void PrettyUnitTestResultPrinter::OnTestStart(const TestInfo& test_info) {
2749 ColoredPrintf(COLOR_GREEN, "[ RUN ] ");
2750 PrintTestName(test_case_name_.c_str(), test_info.name());
2751 if (test_info.comment()[0] == '\0') {
2752 printf("\n");
2753 } else {
2754 printf(", where %s\n", test_info.comment());
2755 }
2756 fflush(stdout);
2757 }
2758
2759 // Called after an assertion failure.
2760 void PrettyUnitTestResultPrinter::OnTestPartResult(
2761 const TestPartResult& result) {
2762 // If the test part succeeded, we don't need to do anything.
2763 if (result.type() == TestPartResult::kSuccess)
2764 return;
2765
2766 // Print failure message from the assertion (e.g. expected this and got that).
2767 PrintTestPartResult(result);
2768 fflush(stdout);
2769 }
2770
2771 void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) {
2772 if (test_info.result()->Passed()) {
2773 ColoredPrintf(COLOR_GREEN, "[ OK ] ");
2774 } else {
2775 ColoredPrintf(COLOR_RED, "[ FAILED ] ");
2776 }
2777 PrintTestName(test_case_name_.c_str(), test_info.name());
2778 if (GTEST_FLAG(print_time)) {
2779 printf(" (%s ms)\n", internal::StreamableToString(
2780 test_info.result()->elapsed_time()).c_str());
2781 } else {
2782 printf("\n");
2783 }
2784 fflush(stdout);
2785 }
2786
2787 void PrettyUnitTestResultPrinter::OnTestCaseEnd(const TestCase& test_case) {
2788 if (!GTEST_FLAG(print_time)) return;
2789
2790 test_case_name_ = test_case.name();
2791 const internal::String counts =
2792 FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
2793 ColoredPrintf(COLOR_GREEN, "[----------] ");
2794 printf("%s from %s (%s ms total)\n\n",
2795 counts.c_str(), test_case_name_.c_str(),
2796 internal::StreamableToString(test_case.elapsed_time()).c_str());
2797 fflush(stdout);
2798 }
2799
2800 void PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart(
2801 const UnitTest& /*unit_test*/) {
2802 ColoredPrintf(COLOR_GREEN, "[----------] ");
2803 printf("Global test environment tear-down\n");
2804 fflush(stdout);
2805 }
2806
2807 // Internal helper for printing the list of failed tests.
2808 void PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest& unit_test) {
2809 const int failed_test_count = unit_test.failed_test_count();
2810 if (failed_test_count == 0) {
2811 return;
2812 }
2813
2814 for (int i = 0; i < unit_test.total_test_case_count(); ++i) {
2815 const TestCase& test_case = *unit_test.GetTestCase(i);
2816 if (!test_case.should_run() || (test_case.failed_test_count() == 0)) {
2817 continue;
2818 }
2819 for (int j = 0; j < test_case.total_test_count(); ++j) {
2820 const TestInfo& test_info = *test_case.GetTestInfo(j);
2821 if (!test_info.should_run() || test_info.result()->Passed()) {
2822 continue;
2823 }
2824 ColoredPrintf(COLOR_RED, "[ FAILED ] ");
2825 printf("%s.%s", test_case.name(), test_info.name());
2826 if (test_case.comment()[0] != '\0' ||
2827 test_info.comment()[0] != '\0') {
2828 printf(", where %s", test_case.comment());
2829 if (test_case.comment()[0] != '\0' &&
2830 test_info.comment()[0] != '\0') {
2831 printf(" and ");
2832 }
2833 }
2834 printf("%s\n", test_info.comment());
2835 }
2836 }
2837 }
2838
2839 void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
2840 int /*iteration*/) {
2841 ColoredPrintf(COLOR_GREEN, "[==========] ");
2842 printf("%s from %s ran.",
2843 FormatTestCount(unit_test.test_to_run_count()).c_str(),
2844 FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str());
2845 if (GTEST_FLAG(print_time)) {
2846 printf(" (%s ms total)",
2847 internal::StreamableToString(unit_test.elapsed_time()).c_str());
2848 }
2849 printf("\n");
2850 ColoredPrintf(COLOR_GREEN, "[ PASSED ] ");
2851 printf("%s.\n", FormatTestCount(unit_test.successful_test_count()).c_str());
2852
2853 int num_failures = unit_test.failed_test_count();
2854 if (!unit_test.Passed()) {
2855 const int failed_test_count = unit_test.failed_test_count();
2856 ColoredPrintf(COLOR_RED, "[ FAILED ] ");
2857 printf("%s, listed below:\n", FormatTestCount(failed_test_count).c_str());
2858 PrintFailedTests(unit_test);
2859 printf("\n%2d FAILED %s\n", num_failures,
2860 num_failures == 1 ? "TEST" : "TESTS");
2861 }
2862
2863 int num_disabled = unit_test.disabled_test_count();
2864 if (num_disabled && !GTEST_FLAG(also_run_disabled_tests)) {
2865 if (!num_failures) {
2866 printf("\n"); // Add a spacer if no FAILURE banner is displayed.
2867 }
2868 ColoredPrintf(COLOR_YELLOW,
2869 " YOU HAVE %d DISABLED %s\n\n",
2870 num_disabled,
2871 num_disabled == 1 ? "TEST" : "TESTS");
2872 }
2873 // Ensure that Google Test output is printed before, e.g., heapchecker output.
2874 fflush(stdout);
2875 }
2876
2877 // End PrettyUnitTestResultPrinter
2878
2879 // class TestEventRepeater
2880 //
2881 // This class forwards events to other event listeners.
2882 class TestEventRepeater : public TestEventListener {
2883 public:
2884 TestEventRepeater() : forwarding_enabled_(true) {}
2885 virtual ~TestEventRepeater();
2886 void Append(TestEventListener *listener);
2887 TestEventListener* Release(TestEventListener* listener);
2888
2889 // Controls whether events will be forwarded to listeners_. Set to false
2890 // in death test child processes.
2891 bool forwarding_enabled() const { return forwarding_enabled_; }
2892 void set_forwarding_enabled(bool enable) { forwarding_enabled_ = enable; }
2893
2894 virtual void OnTestProgramStart(const UnitTest& unit_test);
2895 virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration);
2896 virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test);
2897 virtual void OnEnvironmentsSetUpEnd(const UnitTest& unit_test);
2898 virtual void OnTestCaseStart(const TestCase& test_case);
2899 virtual void OnTestStart(const TestInfo& test_info);
2900 virtual void OnTestPartResult(const TestPartResult& result);
2901 virtual void OnTestEnd(const TestInfo& test_info);
2902 virtual void OnTestCaseEnd(const TestCase& test_case);
2903 virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test);
2904 virtual void OnEnvironmentsTearDownEnd(const UnitTest& unit_test);
2905 virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
2906 virtual void OnTestProgramEnd(const UnitTest& unit_test);
2907
2908 private:
2909 // Controls whether events will be forwarded to listeners_. Set to false
2910 // in death test child processes.
2911 bool forwarding_enabled_;
2912 // The list of listeners that receive events.
2913 Vector<TestEventListener*> listeners_;
2914
2915 GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventRepeater);
2916 };
2917
2918 TestEventRepeater::~TestEventRepeater() {
2919 for (int i = 0; i < listeners_.size(); i++) {
2920 delete listeners_.GetElement(i);
2921 }
2922 }
2923
2924 void TestEventRepeater::Append(TestEventListener *listener) {
2925 listeners_.PushBack(listener);
2926 }
2927
2928 // TODO(vladl@google.com): Factor the search functionality into Vector::Find.
2929 TestEventListener* TestEventRepeater::Release(TestEventListener *listener) {
2930 for (int i = 0; i < listeners_.size(); ++i) {
2931 if (listeners_.GetElement(i) == listener) {
2932 listeners_.Erase(i);
2933 return listener;
2934 }
2935 }
2936
2937 return NULL;
2938 }
2939
2940 // Since most methods are very similar, use macros to reduce boilerplate.
2941 // This defines a member that forwards the call to all listeners.
2942 #define GTEST_REPEATER_METHOD_(Name, Type) \
2943 void TestEventRepeater::Name(const Type& parameter) { \
2944 if (forwarding_enabled_) { \
2945 for (int i = 0; i < listeners_.size(); i++) { \
2946 listeners_.GetElement(i)->Name(parameter); \
2947 } \
2948 } \
2949 }
2950 // This defines a member that forwards the call to all listeners in reverse
2951 // order.
2952 #define GTEST_REVERSE_REPEATER_METHOD_(Name, Type) \
2953 void TestEventRepeater::Name(const Type& parameter) { \
2954 if (forwarding_enabled_) { \
2955 for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) { \
2956 listeners_.GetElement(i)->Name(parameter); \
2957 } \
2958 } \
2959 }
2960
2961 GTEST_REPEATER_METHOD_(OnTestProgramStart, UnitTest)
2962 GTEST_REPEATER_METHOD_(OnEnvironmentsSetUpStart, UnitTest)
2963 GTEST_REPEATER_METHOD_(OnTestCaseStart, TestCase)
2964 GTEST_REPEATER_METHOD_(OnTestStart, TestInfo)
2965 GTEST_REPEATER_METHOD_(OnTestPartResult, TestPartResult)
2966 GTEST_REPEATER_METHOD_(OnEnvironmentsTearDownStart, UnitTest)
2967 GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsSetUpEnd, UnitTest)
2968 GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsTearDownEnd, UnitTest)
2969 GTEST_REVERSE_REPEATER_METHOD_(OnTestEnd, TestInfo)
2970 GTEST_REVERSE_REPEATER_METHOD_(OnTestCaseEnd, TestCase)
2971 GTEST_REVERSE_REPEATER_METHOD_(OnTestProgramEnd, UnitTest)
2972
2973 #undef GTEST_REPEATER_METHOD_
2974 #undef GTEST_REVERSE_REPEATER_METHOD_
2975
2976 void TestEventRepeater::OnTestIterationStart(const UnitTest& unit_test,
2977 int iteration) {
2978 if (forwarding_enabled_) {
2979 for (int i = 0; i < listeners_.size(); i++) {
2980 listeners_.GetElement(i)->OnTestIterationStart(unit_test, iteration);
2981 }
2982 }
2983 }
2984
2985 void TestEventRepeater::OnTestIterationEnd(const UnitTest& unit_test,
2986 int iteration) {
2987 if (forwarding_enabled_) {
2988 for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) {
2989 listeners_.GetElement(i)->OnTestIterationEnd(unit_test, iteration);
2990 }
2991 }
2992 }
2993
2994 // End TestEventRepeater
2995
2996 // This class generates an XML output file.
2997 class XmlUnitTestResultPrinter : public EmptyTestEventListener {
2998 public:
2999 explicit XmlUnitTestResultPrinter(const char* output_file);
3000
3001 virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
3002
3003 private:
3004 // Is c a whitespace character that is normalized to a space character
3005 // when it appears in an XML attribute value?
3006 static bool IsNormalizableWhitespace(char c) {
3007 return c == 0x9 || c == 0xA || c == 0xD;
3008 }
3009
3010 // May c appear in a well-formed XML document?
3011 static bool IsValidXmlCharacter(char c) {
3012 return IsNormalizableWhitespace(c) || c >= 0x20;
3013 }
3014
3015 // Returns an XML-escaped copy of the input string str. If
3016 // is_attribute is true, the text is meant to appear as an attribute
3017 // value, and normalizable whitespace is preserved by replacing it
3018 // with character references.
3019 static String EscapeXml(const char* str, bool is_attribute);
3020
3021 // Returns the given string with all characters invalid in XML removed.
3022 static String RemoveInvalidXmlCharacters(const char* str);
3023
3024 // Convenience wrapper around EscapeXml when str is an attribute value.
3025 static String EscapeXmlAttribute(const char* str) {
3026 return EscapeXml(str, true);
3027 }
3028
3029 // Convenience wrapper around EscapeXml when str is not an attribute value.
3030 static String EscapeXmlText(const char* str) { return EscapeXml(str, false); }
3031
3032 // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
3033 static void OutputXmlCDataSection(::std::ostream* stream, const char* data);
3034
3035 // Streams an XML representation of a TestInfo object.
3036 static void OutputXmlTestInfo(::std::ostream* stream,
3037 const char* test_case_name,
3038 const TestInfo& test_info);
3039
3040 // Prints an XML representation of a TestCase object
3041 static void PrintXmlTestCase(FILE* out, const TestCase& test_case);
3042
3043 // Prints an XML summary of unit_test to output stream out.
3044 static void PrintXmlUnitTest(FILE* out, const UnitTest& unit_test);
3045
3046 // Produces a string representing the test properties in a result as space
3047 // delimited XML attributes based on the property key="value" pairs.
3048 // When the String is not empty, it includes a space at the beginning,
3049 // to delimit this attribute from prior attributes.
3050 static String TestPropertiesAsXmlAttributes(const TestResult& result);
3051
3052 // The output file.
3053 const String output_file_;
3054
3055 GTEST_DISALLOW_COPY_AND_ASSIGN_(XmlUnitTestResultPrinter);
3056 };
3057
3058 // Creates a new XmlUnitTestResultPrinter.
3059 XmlUnitTestResultPrinter::XmlUnitTestResultPrinter(const char* output_file)
3060 : output_file_(output_file) {
3061 if (output_file_.c_str() == NULL || output_file_.empty()) {
3062 fprintf(stderr, "XML output file may not be null\n");
3063 fflush(stderr);
3064 exit(EXIT_FAILURE);
3065 }
3066 }
3067
3068 // Called after the unit test ends.
3069 void XmlUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
3070 int /*iteration*/) {
3071 FILE* xmlout = NULL;
3072 FilePath output_file(output_file_);
3073 FilePath output_dir(output_file.RemoveFileName());
3074
3075 if (output_dir.CreateDirectoriesRecursively()) {
3076 xmlout = posix::FOpen(output_file_.c_str(), "w");
3077 }
3078 if (xmlout == NULL) {
3079 // TODO(wan): report the reason of the failure.
3080 //
3081 // We don't do it for now as:
3082 //
3083 // 1. There is no urgent need for it.
3084 // 2. It's a bit involved to make the errno variable thread-safe on
3085 // all three operating systems (Linux, Windows, and Mac OS).
3086 // 3. To interpret the meaning of errno in a thread-safe way,
3087 // we need the strerror_r() function, which is not available on
3088 // Windows.
3089 fprintf(stderr,
3090 "Unable to open file \"%s\"\n",
3091 output_file_.c_str());
3092 fflush(stderr);
3093 exit(EXIT_FAILURE);
3094 }
3095 PrintXmlUnitTest(xmlout, unit_test);
3096 fclose(xmlout);
3097 }
3098
3099 // Returns an XML-escaped copy of the input string str. If is_attribute
3100 // is true, the text is meant to appear as an attribute value, and
3101 // normalizable whitespace is preserved by replacing it with character
3102 // references.
3103 //
3104 // Invalid XML characters in str, if any, are stripped from the output.
3105 // It is expected that most, if not all, of the text processed by this
3106 // module will consist of ordinary English text.
3107 // If this module is ever modified to produce version 1.1 XML output,
3108 // most invalid characters can be retained using character references.
3109 // TODO(wan): It might be nice to have a minimally invasive, human-readable
3110 // escaping scheme for invalid characters, rather than dropping them.
3111 String XmlUnitTestResultPrinter::EscapeXml(const char* str, bool is_attribute) {
3112 Message m;
3113
3114 if (str != NULL) {
3115 for (const char* src = str; *src; ++src) {
3116 switch (*src) {
3117 case '<':
3118 m << "&lt;";
3119 break;
3120 case '>':
3121 m << "&gt;";
3122 break;
3123 case '&':
3124 m << "&amp;";
3125 break;
3126 case '\'':
3127 if (is_attribute)
3128 m << "&apos;";
3129 else
3130 m << '\'';
3131 break;
3132 case '"':
3133 if (is_attribute)
3134 m << "&quot;";
3135 else
3136 m << '"';
3137 break;
3138 default:
3139 if (IsValidXmlCharacter(*src)) {
3140 if (is_attribute && IsNormalizableWhitespace(*src))
3141 m << String::Format("&#x%02X;", unsigned(*src));
3142 else
3143 m << *src;
3144 }
3145 break;
3146 }
3147 }
3148 }
3149
3150 return m.GetString();
3151 }
3152
3153 // Returns the given string with all characters invalid in XML removed.
3154 // Currently invalid characters are dropped from the string. An
3155 // alternative is to replace them with certain characters such as . or ?.
3156 String XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters(const char* str) {
3157 char* const output = new char[strlen(str) + 1];
3158 char* appender = output;
3159 for (char ch = *str; ch != '\0'; ch = *++str)
3160 if (IsValidXmlCharacter(ch))
3161 *appender++ = ch;
3162 *appender = '\0';
3163
3164 String ret_value(output);
3165 delete[] output;
3166 return ret_value;
3167 }
3168
3169 // The following routines generate an XML representation of a UnitTest
3170 // object.
3171 //
3172 // This is how Google Test concepts map to the DTD:
3173 //
3174 // <testsuites name="AllTests"> <-- corresponds to a UnitTest object
3175 // <testsuite name="testcase-name"> <-- corresponds to a TestCase object
3176 // <testcase name="test-name"> <-- corresponds to a TestInfo object
3177 // <failure message="...">...</failure>
3178 // <failure message="...">...</failure>
3179 // <failure message="...">...</failure>
3180 // <-- individual assertion failures
3181 // </testcase>
3182 // </testsuite>
3183 // </testsuites>
3184
3185 // Formats the given time in milliseconds as seconds. The returned
3186 // C-string is owned by this function and cannot be released by the
3187 // caller. Calling the function again invalidates the previous
3188 // result.
3189 const char* FormatTimeInMillisAsSeconds(TimeInMillis ms) {
3190 static String str;
3191 str = (Message() << (ms/1000.0)).GetString();
3192 return str.c_str();
3193 }
3194
3195 // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
3196 void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream,
3197 const char* data) {
3198 const char* segment = data;
3199 *stream << "<![CDATA[";
3200 for (;;) {
3201 const char* const next_segment = strstr(segment, "]]>");
3202 if (next_segment != NULL) {
3203 stream->write(
3204 segment, static_cast<std::streamsize>(next_segment - segment));
3205 *stream << "]]>]]&gt;<![CDATA[";
3206 segment = next_segment + strlen("]]>");
3207 } else {
3208 *stream << segment;
3209 break;
3210 }
3211 }
3212 *stream << "]]>";
3213 }
3214
3215 // Prints an XML representation of a TestInfo object.
3216 // TODO(wan): There is also value in printing properties with the plain printer.
3217 void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream,
3218 const char* test_case_name,
3219 const TestInfo& test_info) {
3220 const TestResult& result = *test_info.result();
3221 *stream << " <testcase name=\""
3222 << EscapeXmlAttribute(test_info.name()).c_str()
3223 << "\" status=\""
3224 << (test_info.should_run() ? "run" : "notrun")
3225 << "\" time=\""
3226 << FormatTimeInMillisAsSeconds(result.elapsed_time())
3227 << "\" classname=\"" << EscapeXmlAttribute(test_case_name).c_str()
3228 << "\"" << TestPropertiesAsXmlAttributes(result).c_str();
3229
3230 int failures = 0;
3231 for (int i = 0; i < result.total_part_count(); ++i) {
3232 const TestPartResult& part = result.GetTestPartResult(i);
3233 if (part.failed()) {
3234 if (++failures == 1)
3235 *stream << ">\n";
3236 *stream << " <failure message=\""
3237 << EscapeXmlAttribute(part.summary()).c_str()
3238 << "\" type=\"\">";
3239 const String message = RemoveInvalidXmlCharacters(String::Format(
3240 "%s:%d\n%s",
3241 part.file_name(), part.line_number(),
3242 part.message()).c_str());
3243 OutputXmlCDataSection(stream, message.c_str());
3244 *stream << "</failure>\n";
3245 }
3246 }
3247
3248 if (failures == 0)
3249 *stream << " />\n";
3250 else
3251 *stream << " </testcase>\n";
3252 }
3253
3254 // Prints an XML representation of a TestCase object
3255 void XmlUnitTestResultPrinter::PrintXmlTestCase(FILE* out,
3256 const TestCase& test_case) {
3257 fprintf(out,
3258 " <testsuite name=\"%s\" tests=\"%d\" failures=\"%d\" "
3259 "disabled=\"%d\" ",
3260 EscapeXmlAttribute(test_case.name()).c_str(),
3261 test_case.total_test_count(),
3262 test_case.failed_test_count(),
3263 test_case.disabled_test_count());
3264 fprintf(out,
3265 "errors=\"0\" time=\"%s\">\n",
3266 FormatTimeInMillisAsSeconds(test_case.elapsed_time()));
3267 for (int i = 0; i < test_case.total_test_count(); ++i) {
3268 StrStream stream;
3269 OutputXmlTestInfo(&stream, test_case.name(), *test_case.GetTestInfo(i));
3270 fprintf(out, "%s", StrStreamToString(&stream).c_str());
3271 }
3272 fprintf(out, " </testsuite>\n");
3273 }
3274
3275 // Prints an XML summary of unit_test to output stream out.
3276 void XmlUnitTestResultPrinter::PrintXmlUnitTest(FILE* out,
3277 const UnitTest& unit_test) {
3278 fprintf(out, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
3279 fprintf(out,
3280 "<testsuites tests=\"%d\" failures=\"%d\" disabled=\"%d\" "
3281 "errors=\"0\" time=\"%s\" ",
3282 unit_test.total_test_count(),
3283 unit_test.failed_test_count(),
3284 unit_test.disabled_test_count(),
3285 FormatTimeInMillisAsSeconds(unit_test.elapsed_time()));
3286 if (GTEST_FLAG(shuffle)) {
3287 fprintf(out, "random_seed=\"%d\" ", unit_test.random_seed());
3288 }
3289 fprintf(out, "name=\"AllTests\">\n");
3290 for (int i = 0; i < unit_test.total_test_case_count(); ++i)
3291 PrintXmlTestCase(out, *unit_test.GetTestCase(i));
3292 fprintf(out, "</testsuites>\n");
3293 }
3294
3295 // Produces a string representing the test properties in a result as space
3296 // delimited XML attributes based on the property key="value" pairs.
3297 String XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes(
3298 const TestResult& result) {
3299 Message attributes;
3300 for (int i = 0; i < result.test_property_count(); ++i) {
3301 const TestProperty& property = result.GetTestProperty(i);
3302 attributes << " " << property.key() << "="
3303 << "\"" << EscapeXmlAttribute(property.value()) << "\"";
3304 }
3305 return attributes.GetString();
3306 }
3307
3308 // End XmlUnitTestResultPrinter
3309
3310 // Class ScopedTrace
3311
3312 // Pushes the given source file location and message onto a per-thread
3313 // trace stack maintained by Google Test.
3314 // L < UnitTest::mutex_
3315 ScopedTrace::ScopedTrace(const char* file, int line, const Message& message) {
3316 TraceInfo trace;
3317 trace.file = file;
3318 trace.line = line;
3319 trace.message = message.GetString();
3320
3321 UnitTest::GetInstance()->PushGTestTrace(trace);
3322 }
3323
3324 // Pops the info pushed by the c'tor.
3325 // L < UnitTest::mutex_
3326 ScopedTrace::~ScopedTrace() {
3327 UnitTest::GetInstance()->PopGTestTrace();
3328 }
3329
3330
3331 // class OsStackTraceGetter
3332
3333 // Returns the current OS stack trace as a String. Parameters:
3334 //
3335 // max_depth - the maximum number of stack frames to be included
3336 // in the trace.
3337 // skip_count - the number of top frames to be skipped; doesn't count
3338 // against max_depth.
3339 //
3340 // L < mutex_
3341 // We use "L < mutex_" to denote that the function may acquire mutex_.
3342 String OsStackTraceGetter::CurrentStackTrace(int, int) {
3343 return String("");
3344 }
3345
3346 // L < mutex_
3347 void OsStackTraceGetter::UponLeavingGTest() {
3348 }
3349
3350 const char* const
3351 OsStackTraceGetter::kElidedFramesMarker =
3352 "... " GTEST_NAME_ " internal frames ...";
3353
3354 } // namespace internal
3355
3356 // class TestEventListeners
3357
3358 TestEventListeners::TestEventListeners()
3359 : repeater_(new internal::TestEventRepeater()),
3360 default_result_printer_(NULL),
3361 default_xml_generator_(NULL) {
3362 }
3363
3364 TestEventListeners::~TestEventListeners() { delete repeater_; }
3365
3366 // Returns the standard listener responsible for the default console
3367 // output. Can be removed from the listeners list to shut down default
3368 // console output. Note that removing this object from the listener list
3369 // with Release transfers its ownership to the user.
3370 void TestEventListeners::Append(TestEventListener* listener) {
3371 repeater_->Append(listener);
3372 }
3373
3374 // Removes the given event listener from the list and returns it. It then
3375 // becomes the caller's responsibility to delete the listener. Returns
3376 // NULL if the listener is not found in the list.
3377 TestEventListener* TestEventListeners::Release(TestEventListener* listener) {
3378 if (listener == default_result_printer_)
3379 default_result_printer_ = NULL;
3380 else if (listener == default_xml_generator_)
3381 default_xml_generator_ = NULL;
3382 return repeater_->Release(listener);
3383 }
3384
3385 // Returns repeater that broadcasts the TestEventListener events to all
3386 // subscribers.
3387 TestEventListener* TestEventListeners::repeater() { return repeater_; }
3388
3389 // Sets the default_result_printer attribute to the provided listener.
3390 // The listener is also added to the listener list and previous
3391 // default_result_printer is removed from it and deleted. The listener can
3392 // also be NULL in which case it will not be added to the list. Does
3393 // nothing if the previous and the current listener objects are the same.
3394 void TestEventListeners::SetDefaultResultPrinter(TestEventListener* listener) {
3395 if (default_result_printer_ != listener) {
3396 // It is an error to pass this method a listener that is already in the
3397 // list.
3398 delete Release(default_result_printer_);
3399 default_result_printer_ = listener;
3400 if (listener != NULL)
3401 Append(listener);
3402 }
3403 }
3404
3405 // Sets the default_xml_generator attribute to the provided listener. The
3406 // listener is also added to the listener list and previous
3407 // default_xml_generator is removed from it and deleted. The listener can
3408 // also be NULL in which case it will not be added to the list. Does
3409 // nothing if the previous and the current listener objects are the same.
3410 void TestEventListeners::SetDefaultXmlGenerator(TestEventListener* listener) {
3411 if (default_xml_generator_ != listener) {
3412 // It is an error to pass this method a listener that is already in the
3413 // list.
3414 delete Release(default_xml_generator_);
3415 default_xml_generator_ = listener;
3416 if (listener != NULL)
3417 Append(listener);
3418 }
3419 }
3420
3421 // Controls whether events will be forwarded by the repeater to the
3422 // listeners in the list.
3423 bool TestEventListeners::EventForwardingEnabled() const {
3424 return repeater_->forwarding_enabled();
3425 }
3426
3427 void TestEventListeners::SuppressEventForwarding() {
3428 repeater_->set_forwarding_enabled(false);
3429 }
3430
3431 // class UnitTest
3432
3433 // Gets the singleton UnitTest object. The first time this method is
3434 // called, a UnitTest object is constructed and returned. Consecutive
3435 // calls will return the same object.
3436 //
3437 // We don't protect this under mutex_ as a user is not supposed to
3438 // call this before main() starts, from which point on the return
3439 // value will never change.
3440 UnitTest * UnitTest::GetInstance() {
3441 // When compiled with MSVC 7.1 in optimized mode, destroying the
3442 // UnitTest object upon exiting the program messes up the exit code,
3443 // causing successful tests to appear failed. We have to use a
3444 // different implementation in this case to bypass the compiler bug.
3445 // This implementation makes the compiler happy, at the cost of
3446 // leaking the UnitTest object.
3447
3448 // CodeGear C++Builder insists on a public destructor for the
3449 // default implementation. Use this implementation to keep good OO
3450 // design with private destructor.
3451
3452 #if (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)
3453 static UnitTest* const instance = new UnitTest;
3454 return instance;
3455 #else
3456 static UnitTest instance;
3457 return &instance;
3458 #endif // (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)
3459 }
3460
3461 // Gets the number of successful test cases.
3462 int UnitTest::successful_test_case_count() const {
3463 return impl()->successful_test_case_count();
3464 }
3465
3466 // Gets the number of failed test cases.
3467 int UnitTest::failed_test_case_count() const {
3468 return impl()->failed_test_case_count();
3469 }
3470
3471 // Gets the number of all test cases.
3472 int UnitTest::total_test_case_count() const {
3473 return impl()->total_test_case_count();
3474 }
3475
3476 // Gets the number of all test cases that contain at least one test
3477 // that should run.
3478 int UnitTest::test_case_to_run_count() const {
3479 return impl()->test_case_to_run_count();
3480 }
3481
3482 // Gets the number of successful tests.
3483 int UnitTest::successful_test_count() const {
3484 return impl()->successful_test_count();
3485 }
3486
3487 // Gets the number of failed tests.
3488 int UnitTest::failed_test_count() const { return impl()->failed_test_count(); }
3489
3490 // Gets the number of disabled tests.
3491 int UnitTest::disabled_test_count() const {
3492 return impl()->disabled_test_count();
3493 }
3494
3495 // Gets the number of all tests.
3496 int UnitTest::total_test_count() const { return impl()->total_test_count(); }
3497
3498 // Gets the number of tests that should run.
3499 int UnitTest::test_to_run_count() const { return impl()->test_to_run_count(); }
3500
3501 // Gets the elapsed time, in milliseconds.
3502 internal::TimeInMillis UnitTest::elapsed_time() const {
3503 return impl()->elapsed_time();
3504 }
3505
3506 // Returns true iff the unit test passed (i.e. all test cases passed).
3507 bool UnitTest::Passed() const { return impl()->Passed(); }
3508
3509 // Returns true iff the unit test failed (i.e. some test case failed
3510 // or something outside of all tests failed).
3511 bool UnitTest::Failed() const { return impl()->Failed(); }
3512
3513 // Gets the i-th test case among all the test cases. i can range from 0 to
3514 // total_test_case_count() - 1. If i is not in that range, returns NULL.
3515 const TestCase* UnitTest::GetTestCase(int i) const {
3516 return impl()->GetTestCase(i);
3517 }
3518
3519 // Gets the i-th test case among all the test cases. i can range from 0 to
3520 // total_test_case_count() - 1. If i is not in that range, returns NULL.
3521 TestCase* UnitTest::GetMutableTestCase(int i) {
3522 return impl()->GetMutableTestCase(i);
3523 }
3524
3525 // Returns the list of event listeners that can be used to track events
3526 // inside Google Test.
3527 TestEventListeners& UnitTest::listeners() {
3528 return *impl()->listeners();
3529 }
3530
3531 // Registers and returns a global test environment. When a test
3532 // program is run, all global test environments will be set-up in the
3533 // order they were registered. After all tests in the program have
3534 // finished, all global test environments will be torn-down in the
3535 // *reverse* order they were registered.
3536 //
3537 // The UnitTest object takes ownership of the given environment.
3538 //
3539 // We don't protect this under mutex_, as we only support calling it
3540 // from the main thread.
3541 Environment* UnitTest::AddEnvironment(Environment* env) {
3542 if (env == NULL) {
3543 return NULL;
3544 }
3545
3546 impl_->environments()->PushBack(env);
3547 impl_->environments_in_reverse_order()->PushFront(env);
3548 return env;
3549 }
3550
3551 #if GTEST_HAS_EXCEPTIONS
3552 // A failed Google Test assertion will throw an exception of this type
3553 // when exceptions are enabled. We derive it from std::runtime_error,
3554 // which is for errors presumably detectable only at run time. Since
3555 // std::runtime_error inherits from std::exception, many testing
3556 // frameworks know how to extract and print the message inside it.
3557 class GoogleTestFailureException : public ::std::runtime_error {
3558 public:
3559 explicit GoogleTestFailureException(const TestPartResult& failure)
3560 : ::std::runtime_error(PrintTestPartResultToString(failure).c_str()) {}
3561 };
3562 #endif
3563
3564 // Adds a TestPartResult to the current TestResult object. All Google Test
3565 // assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) eventually call
3566 // this to report their results. The user code should use the
3567 // assertion macros instead of calling this directly.
3568 // L < mutex_
3569 void UnitTest::AddTestPartResult(TestPartResult::Type result_type,
3570 const char* file_name,
3571 int line_number,
3572 const internal::String& message,
3573 const internal::String& os_stack_trace) {
3574 Message msg;
3575 msg << message;
3576
3577 internal::MutexLock lock(&mutex_);
3578 if (impl_->gtest_trace_stack()->size() > 0) {
3579 msg << "\n" << GTEST_NAME_ << " trace:";
3580
3581 for (int i = 0; i < impl_->gtest_trace_stack()->size(); i++) {
3582 const internal::TraceInfo& trace =
3583 impl_->gtest_trace_stack()->GetElement(i);
3584 msg << "\n" << internal::FormatFileLocation(trace.file, trace.line)
3585 << " " << trace.message;
3586 }
3587 }
3588
3589 if (os_stack_trace.c_str() != NULL && !os_stack_trace.empty()) {
3590 msg << internal::kStackTraceMarker << os_stack_trace;
3591 }
3592
3593 const TestPartResult result =
3594 TestPartResult(result_type, file_name, line_number,
3595 msg.GetString().c_str());
3596 impl_->GetTestPartResultReporterForCurrentThread()->
3597 ReportTestPartResult(result);
3598
3599 if (result_type != TestPartResult::kSuccess) {
3600 // gtest_break_on_failure takes precedence over
3601 // gtest_throw_on_failure. This allows a user to set the latter
3602 // in the code (perhaps in order to use Google Test assertions
3603 // with another testing framework) and specify the former on the
3604 // command line for debugging.
3605 if (GTEST_FLAG(break_on_failure)) {
3606 #if GTEST_OS_WINDOWS
3607 // Using DebugBreak on Windows allows gtest to still break into a debugger
3608 // when a failure happens and both the --gtest_break_on_failure and
3609 // the --gtest_catch_exceptions flags are specified.
3610 DebugBreak();
3611 #else
3612 *static_cast<int*>(NULL) = 1;
3613 #endif // GTEST_OS_WINDOWS
3614 } else if (GTEST_FLAG(throw_on_failure)) {
3615 #if GTEST_HAS_EXCEPTIONS
3616 throw GoogleTestFailureException(result);
3617 #else
3618 // We cannot call abort() as it generates a pop-up in debug mode
3619 // that cannot be suppressed in VC 7.1 or below.
3620 exit(1);
3621 #endif
3622 }
3623 }
3624 }
3625
3626 // Creates and adds a property to the current TestResult. If a property matching
3627 // the supplied value already exists, updates its value instead.
3628 void UnitTest::RecordPropertyForCurrentTest(const char* key,
3629 const char* value) {
3630 const TestProperty test_property(key, value);
3631 impl_->current_test_result()->RecordProperty(test_property);
3632 }
3633
3634 // Runs all tests in this UnitTest object and prints the result.
3635 // Returns 0 if successful, or 1 otherwise.
3636 //
3637 // We don't protect this under mutex_, as we only support calling it
3638 // from the main thread.
3639 int UnitTest::Run() {
3640 #if GTEST_HAS_SEH
3641 // Catch SEH-style exceptions.
3642
3643 const bool in_death_test_child_process =
3644 internal::GTEST_FLAG(internal_run_death_test).length() > 0;
3645
3646 // Either the user wants Google Test to catch exceptions thrown by the
3647 // tests or this is executing in the context of death test child
3648 // process. In either case the user does not want to see pop-up dialogs
3649 // about crashes - they are expected..
3650 if (GTEST_FLAG(catch_exceptions) || in_death_test_child_process) {
3651 #if !GTEST_OS_WINDOWS_MOBILE
3652 // SetErrorMode doesn't exist on CE.
3653 SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT |
3654 SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);
3655 #endif // !GTEST_OS_WINDOWS_MOBILE
3656
3657 #if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE
3658 // Death test children can be terminated with _abort(). On Windows,
3659 // _abort() can show a dialog with a warning message. This forces the
3660 // abort message to go to stderr instead.
3661 _set_error_mode(_OUT_TO_STDERR);
3662 #endif
3663
3664 #if _MSC_VER >= 1400 && !GTEST_OS_WINDOWS_MOBILE
3665 // In the debug version, Visual Studio pops up a separate dialog
3666 // offering a choice to debug the aborted program. We need to suppress
3667 // this dialog or it will pop up for every EXPECT/ASSERT_DEATH statement
3668 // executed. Google Test will notify the user of any unexpected
3669 // failure via stderr.
3670 //
3671 // VC++ doesn't define _set_abort_behavior() prior to the version 8.0.
3672 // Users of prior VC versions shall suffer the agony and pain of
3673 // clicking through the countless debug dialogs.
3674 // TODO(vladl@google.com): find a way to suppress the abort dialog() in the
3675 // debug mode when compiled with VC 7.1 or lower.
3676 if (!GTEST_FLAG(break_on_failure))
3677 _set_abort_behavior(
3678 0x0, // Clear the following flags:
3679 _WRITE_ABORT_MSG | _CALL_REPORTFAULT); // pop-up window, core dump.
3680 #endif
3681 }
3682
3683 __try {
3684 return impl_->RunAllTests();
3685 } __except(internal::UnitTestOptions::GTestShouldProcessSEH(
3686 GetExceptionCode())) {
3687 printf("Exception thrown with code 0x%x.\nFAIL\n", GetExceptionCode());
3688 fflush(stdout);
3689 return 1;
3690 }
3691
3692 #else // We are on a compiler or platform that doesn't support SEH.
3693
3694 return impl_->RunAllTests();
3695 #endif // GTEST_HAS_SEH
3696 }
3697
3698 // Returns the working directory when the first TEST() or TEST_F() was
3699 // executed.
3700 const char* UnitTest::original_working_dir() const {
3701 return impl_->original_working_dir_.c_str();
3702 }
3703
3704 // Returns the TestCase object for the test that's currently running,
3705 // or NULL if no test is running.
3706 // L < mutex_
3707 const TestCase* UnitTest::current_test_case() const {
3708 internal::MutexLock lock(&mutex_);
3709 return impl_->current_test_case();
3710 }
3711
3712 // Returns the TestInfo object for the test that's currently running,
3713 // or NULL if no test is running.
3714 // L < mutex_
3715 const TestInfo* UnitTest::current_test_info() const {
3716 internal::MutexLock lock(&mutex_);
3717 return impl_->current_test_info();
3718 }
3719
3720 // Returns the random seed used at the start of the current test run.
3721 int UnitTest::random_seed() const { return impl_->random_seed(); }
3722
3723 #if GTEST_HAS_PARAM_TEST
3724 // Returns ParameterizedTestCaseRegistry object used to keep track of
3725 // value-parameterized tests and instantiate and register them.
3726 // L < mutex_
3727 internal::ParameterizedTestCaseRegistry&
3728 UnitTest::parameterized_test_registry() {
3729 return impl_->parameterized_test_registry();
3730 }
3731 #endif // GTEST_HAS_PARAM_TEST
3732
3733 // Creates an empty UnitTest.
3734 UnitTest::UnitTest() {
3735 impl_ = new internal::UnitTestImpl(this);
3736 }
3737
3738 // Destructor of UnitTest.
3739 UnitTest::~UnitTest() {
3740 delete impl_;
3741 }
3742
3743 // Pushes a trace defined by SCOPED_TRACE() on to the per-thread
3744 // Google Test trace stack.
3745 // L < mutex_
3746 void UnitTest::PushGTestTrace(const internal::TraceInfo& trace) {
3747 internal::MutexLock lock(&mutex_);
3748 impl_->gtest_trace_stack()->PushFront(trace);
3749 }
3750
3751 // Pops a trace from the per-thread Google Test trace stack.
3752 // L < mutex_
3753 void UnitTest::PopGTestTrace() {
3754 internal::MutexLock lock(&mutex_);
3755 impl_->gtest_trace_stack()->PopFront(NULL);
3756 }
3757
3758 namespace internal {
3759
3760 UnitTestImpl::UnitTestImpl(UnitTest* parent)
3761 : parent_(parent),
3762 #ifdef _MSC_VER
3763 #pragma warning(push) // Saves the current warning state.
3764 #pragma warning(disable:4355) // Temporarily disables warning 4355
3765 // (using this in initializer).
3766 default_global_test_part_result_reporter_(this),
3767 default_per_thread_test_part_result_reporter_(this),
3768 #pragma warning(pop) // Restores the warning state again.
3769 #else
3770 default_global_test_part_result_reporter_(this),
3771 default_per_thread_test_part_result_reporter_(this),
3772 #endif // _MSC_VER
3773 global_test_part_result_repoter_(
3774 &default_global_test_part_result_reporter_),
3775 per_thread_test_part_result_reporter_(
3776 &default_per_thread_test_part_result_reporter_),
3777 #if GTEST_HAS_PARAM_TEST
3778 parameterized_test_registry_(),
3779 parameterized_tests_registered_(false),
3780 #endif // GTEST_HAS_PARAM_TEST
3781 last_death_test_case_(-1),
3782 current_test_case_(NULL),
3783 current_test_info_(NULL),
3784 ad_hoc_test_result_(),
3785 os_stack_trace_getter_(NULL),
3786 post_flag_parse_init_performed_(false),
3787 random_seed_(0), // Will be overridden by the flag before first use.
3788 random_(0), // Will be reseeded before first use.
3789 #if GTEST_HAS_DEATH_TEST
3790 elapsed_time_(0),
3791 internal_run_death_test_flag_(NULL),
3792 death_test_factory_(new DefaultDeathTestFactory) {
3793 #else
3794 elapsed_time_(0) {
3795 #endif // GTEST_HAS_DEATH_TEST
3796 listeners()->SetDefaultResultPrinter(new PrettyUnitTestResultPrinter);
3797 }
3798
3799 UnitTestImpl::~UnitTestImpl() {
3800 // Deletes every TestCase.
3801 test_cases_.ForEach(internal::Delete<TestCase>);
3802
3803 // Deletes every Environment.
3804 environments_.ForEach(internal::Delete<Environment>);
3805
3806 delete os_stack_trace_getter_;
3807 }
3808
3809 #if GTEST_HAS_DEATH_TEST
3810 // Disables event forwarding if the control is currently in a death test
3811 // subprocess. Must not be called before InitGoogleTest.
3812 void UnitTestImpl::SuppressTestEventsIfInSubprocess() {
3813 if (internal_run_death_test_flag_.get() != NULL)
3814 listeners()->SuppressEventForwarding();
3815 }
3816 #endif // GTEST_HAS_DEATH_TEST
3817
3818 // Initializes event listeners performing XML output as specified by
3819 // UnitTestOptions. Must not be called before InitGoogleTest.
3820 void UnitTestImpl::ConfigureXmlOutput() {
3821 const String& output_format = UnitTestOptions::GetOutputFormat();
3822 if (output_format == "xml") {
3823 listeners()->SetDefaultXmlGenerator(new XmlUnitTestResultPrinter(
3824 UnitTestOptions::GetAbsolutePathToOutputFile().c_str()));
3825 } else if (output_format != "") {
3826 printf("WARNING: unrecognized output format \"%s\" ignored.\n",
3827 output_format.c_str());
3828 fflush(stdout);
3829 }
3830 }
3831
3832 // Performs initialization dependent upon flag values obtained in
3833 // ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to
3834 // ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest
3835 // this function is also called from RunAllTests. Since this function can be
3836 // called more than once, it has to be idempotent.
3837 void UnitTestImpl::PostFlagParsingInit() {
3838 // Ensures that this function does not execute more than once.
3839 if (!post_flag_parse_init_performed_) {
3840 post_flag_parse_init_performed_ = true;
3841
3842 #if GTEST_HAS_DEATH_TEST
3843 InitDeathTestSubprocessControlInfo();
3844 SuppressTestEventsIfInSubprocess();
3845 #endif // GTEST_HAS_DEATH_TEST
3846
3847 // Registers parameterized tests. This makes parameterized tests
3848 // available to the UnitTest reflection API without running
3849 // RUN_ALL_TESTS.
3850 RegisterParameterizedTests();
3851
3852 // Configures listeners for XML output. This makes it possible for users
3853 // to shut down the default XML output before invoking RUN_ALL_TESTS.
3854 ConfigureXmlOutput();
3855 }
3856 }
3857
3858 // A predicate that checks the name of a TestCase against a known
3859 // value.
3860 //
3861 // This is used for implementation of the UnitTest class only. We put
3862 // it in the anonymous namespace to prevent polluting the outer
3863 // namespace.
3864 //
3865 // TestCaseNameIs is copyable.
3866 class TestCaseNameIs {
3867 public:
3868 // Constructor.
3869 explicit TestCaseNameIs(const String& name)
3870 : name_(name) {}
3871
3872 // Returns true iff the name of test_case matches name_.
3873 bool operator()(const TestCase* test_case) const {
3874 return test_case != NULL && strcmp(test_case->name(), name_.c_str()) == 0;
3875 }
3876
3877 private:
3878 String name_;
3879 };
3880
3881 // Finds and returns a TestCase with the given name. If one doesn't
3882 // exist, creates one and returns it. It's the CALLER'S
3883 // RESPONSIBILITY to ensure that this function is only called WHEN THE
3884 // TESTS ARE NOT SHUFFLED.
3885 //
3886 // Arguments:
3887 //
3888 // test_case_name: name of the test case
3889 // set_up_tc: pointer to the function that sets up the test case
3890 // tear_down_tc: pointer to the function that tears down the test case
3891 TestCase* UnitTestImpl::GetTestCase(const char* test_case_name,
3892 const char* comment,
3893 Test::SetUpTestCaseFunc set_up_tc,
3894 Test::TearDownTestCaseFunc tear_down_tc) {
3895 // Can we find a TestCase with the given name?
3896 TestCase** test_case = test_cases_.FindIf(TestCaseNameIs(test_case_name));
3897
3898 if (test_case != NULL)
3899 return *test_case;
3900
3901 // No. Let's create one.
3902 TestCase* const new_test_case =
3903 new TestCase(test_case_name, comment, set_up_tc, tear_down_tc);
3904
3905 // Is this a death test case?
3906 if (internal::UnitTestOptions::MatchesFilter(String(test_case_name),
3907 kDeathTestCaseFilter)) {
3908 // Yes. Inserts the test case after the last death test case
3909 // defined so far. This only works when the test cases haven't
3910 // been shuffled. Otherwise we may end up running a death test
3911 // after a non-death test.
3912 test_cases_.Insert(new_test_case, ++last_death_test_case_);
3913 } else {
3914 // No. Appends to the end of the list.
3915 test_cases_.PushBack(new_test_case);
3916 }
3917
3918 test_case_indices_.PushBack(test_case_indices_.size());
3919 return new_test_case;
3920 }
3921
3922 // Helpers for setting up / tearing down the given environment. They
3923 // are for use in the Vector::ForEach() method.
3924 static void SetUpEnvironment(Environment* env) { env->SetUp(); }
3925 static void TearDownEnvironment(Environment* env) { env->TearDown(); }
3926
3927 // Runs all tests in this UnitTest object, prints the result, and
3928 // returns 0 if all tests are successful, or 1 otherwise. If any
3929 // exception is thrown during a test on Windows, this test is
3930 // considered to be failed, but the rest of the tests will still be
3931 // run. (We disable exceptions on Linux and Mac OS X, so the issue
3932 // doesn't apply there.)
3933 // When parameterized tests are enabled, it expands and registers
3934 // parameterized tests first in RegisterParameterizedTests().
3935 // All other functions called from RunAllTests() may safely assume that
3936 // parameterized tests are ready to be counted and run.
3937 int UnitTestImpl::RunAllTests() {
3938 // Makes sure InitGoogleTest() was called.
3939 if (!GTestIsInitialized()) {
3940 printf("%s",
3941 "\nThis test program did NOT call ::testing::InitGoogleTest "
3942 "before calling RUN_ALL_TESTS(). Please fix it.\n");
3943 return 1;
3944 }
3945
3946 // Do not run any test if the --help flag was specified.
3947 if (g_help_flag)
3948 return 0;
3949
3950 // Repeats the call to the post-flag parsing initialization in case the
3951 // user didn't call InitGoogleTest.
3952 PostFlagParsingInit();
3953
3954 // Even if sharding is not on, test runners may want to use the
3955 // GTEST_SHARD_STATUS_FILE to query whether the test supports the sharding
3956 // protocol.
3957 internal::WriteToShardStatusFileIfNeeded();
3958
3959 // True iff we are in a subprocess for running a thread-safe-style
3960 // death test.
3961 bool in_subprocess_for_death_test = false;
3962
3963 #if GTEST_HAS_DEATH_TEST
3964 in_subprocess_for_death_test = (internal_run_death_test_flag_.get() != NULL);
3965 #endif // GTEST_HAS_DEATH_TEST
3966
3967 const bool should_shard = ShouldShard(kTestTotalShards, kTestShardIndex,
3968 in_subprocess_for_death_test);
3969
3970 // Compares the full test names with the filter to decide which
3971 // tests to run.
3972 const bool has_tests_to_run = FilterTests(should_shard
3973 ? HONOR_SHARDING_PROTOCOL
3974 : IGNORE_SHARDING_PROTOCOL) > 0;
3975
3976 // Lists the tests and exits if the --gtest_list_tests flag was specified.
3977 if (GTEST_FLAG(list_tests)) {
3978 // This must be called *after* FilterTests() has been called.
3979 ListTestsMatchingFilter();
3980 return 0;
3981 }
3982
3983 random_seed_ = GTEST_FLAG(shuffle) ?
3984 GetRandomSeedFromFlag(GTEST_FLAG(random_seed)) : 0;
3985
3986 // True iff at least one test has failed.
3987 bool failed = false;
3988
3989 TestEventListener* repeater = listeners()->repeater();
3990
3991 repeater->OnTestProgramStart(*parent_);
3992
3993 // How many times to repeat the tests? We don't want to repeat them
3994 // when we are inside the subprocess of a death test.
3995 const int repeat = in_subprocess_for_death_test ? 1 : GTEST_FLAG(repeat);
3996 // Repeats forever if the repeat count is negative.
3997 const bool forever = repeat < 0;
3998 for (int i = 0; forever || i != repeat; i++) {
3999 ClearResult();
4000
4001 const TimeInMillis start = GetTimeInMillis();
4002
4003 // Shuffles test cases and tests if requested.
4004 if (has_tests_to_run && GTEST_FLAG(shuffle)) {
4005 random()->Reseed(random_seed_);
4006 // This should be done before calling OnTestIterationStart(),
4007 // such that a test event listener can see the actual test order
4008 // in the event.
4009 ShuffleTests();
4010 }
4011
4012 // Tells the unit test event listeners that the tests are about to start.
4013 repeater->OnTestIterationStart(*parent_, i);
4014
4015 // Runs each test case if there is at least one test to run.
4016 if (has_tests_to_run) {
4017 // Sets up all environments beforehand.
4018 repeater->OnEnvironmentsSetUpStart(*parent_);
4019 environments_.ForEach(SetUpEnvironment);
4020 repeater->OnEnvironmentsSetUpEnd(*parent_);
4021
4022 // Runs the tests only if there was no fatal failure during global
4023 // set-up.
4024 if (!Test::HasFatalFailure()) {
4025 for (int i = 0; i < total_test_case_count(); i++) {
4026 GetMutableTestCase(i)->Run();
4027 }
4028 }
4029
4030 // Tears down all environments in reverse order afterwards.
4031 repeater->OnEnvironmentsTearDownStart(*parent_);
4032 environments_in_reverse_order_.ForEach(TearDownEnvironment);
4033 repeater->OnEnvironmentsTearDownEnd(*parent_);
4034 }
4035
4036 elapsed_time_ = GetTimeInMillis() - start;
4037
4038 // Tells the unit test event listener that the tests have just finished.
4039 repeater->OnTestIterationEnd(*parent_, i);
4040
4041 // Gets the result and clears it.
4042 if (!Passed()) {
4043 failed = true;
4044 }
4045
4046 // Restores the original test order after the iteration. This
4047 // allows the user to quickly repro a failure that happens in the
4048 // N-th iteration without repeating the first (N - 1) iterations.
4049 // This is not enclosed in "if (GTEST_FLAG(shuffle)) { ... }", in
4050 // case the user somehow changes the value of the flag somewhere
4051 // (it's always safe to unshuffle the tests).
4052 UnshuffleTests();
4053
4054 if (GTEST_FLAG(shuffle)) {
4055 // Picks a new random seed for each iteration.
4056 random_seed_ = GetNextRandomSeed(random_seed_);
4057 }
4058 }
4059
4060 repeater->OnTestProgramEnd(*parent_);
4061
4062 // Returns 0 if all tests passed, or 1 other wise.
4063 return failed ? 1 : 0;
4064 }
4065
4066 // Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
4067 // if the variable is present. If a file already exists at this location, this
4068 // function will write over it. If the variable is present, but the file cannot
4069 // be created, prints an error and exits.
4070 void WriteToShardStatusFileIfNeeded() {
4071 const char* const test_shard_file = posix::GetEnv(kTestShardStatusFile);
4072 if (test_shard_file != NULL) {
4073 FILE* const file = posix::FOpen(test_shard_file, "w");
4074 if (file == NULL) {
4075 ColoredPrintf(COLOR_RED,
4076 "Could not write to the test shard status file \"%s\" "
4077 "specified by the %s environment variable.\n",
4078 test_shard_file, kTestShardStatusFile);
4079 fflush(stdout);
4080 exit(EXIT_FAILURE);
4081 }
4082 fclose(file);
4083 }
4084 }
4085
4086 // Checks whether sharding is enabled by examining the relevant
4087 // environment variable values. If the variables are present,
4088 // but inconsistent (i.e., shard_index >= total_shards), prints
4089 // an error and exits. If in_subprocess_for_death_test, sharding is
4090 // disabled because it must only be applied to the original test
4091 // process. Otherwise, we could filter out death tests we intended to execute.
4092 bool ShouldShard(const char* total_shards_env,
4093 const char* shard_index_env,
4094 bool in_subprocess_for_death_test) {
4095 if (in_subprocess_for_death_test) {
4096 return false;
4097 }
4098
4099 const Int32 total_shards = Int32FromEnvOrDie(total_shards_env, -1);
4100 const Int32 shard_index = Int32FromEnvOrDie(shard_index_env, -1);
4101
4102 if (total_shards == -1 && shard_index == -1) {
4103 return false;
4104 } else if (total_shards == -1 && shard_index != -1) {
4105 const Message msg = Message()
4106 << "Invalid environment variables: you have "
4107 << kTestShardIndex << " = " << shard_index
4108 << ", but have left " << kTestTotalShards << " unset.\n";
4109 ColoredPrintf(COLOR_RED, msg.GetString().c_str());
4110 fflush(stdout);
4111 exit(EXIT_FAILURE);
4112 } else if (total_shards != -1 && shard_index == -1) {
4113 const Message msg = Message()
4114 << "Invalid environment variables: you have "
4115 << kTestTotalShards << " = " << total_shards
4116 << ", but have left " << kTestShardIndex << " unset.\n";
4117 ColoredPrintf(COLOR_RED, msg.GetString().c_str());
4118 fflush(stdout);
4119 exit(EXIT_FAILURE);
4120 } else if (shard_index < 0 || shard_index >= total_shards) {
4121 const Message msg = Message()
4122 << "Invalid environment variables: we require 0 <= "
4123 << kTestShardIndex << " < " << kTestTotalShards
4124 << ", but you have " << kTestShardIndex << "=" << shard_index
4125 << ", " << kTestTotalShards << "=" << total_shards << ".\n";
4126 ColoredPrintf(COLOR_RED, msg.GetString().c_str());
4127 fflush(stdout);
4128 exit(EXIT_FAILURE);
4129 }
4130
4131 return total_shards > 1;
4132 }
4133
4134 // Parses the environment variable var as an Int32. If it is unset,
4135 // returns default_val. If it is not an Int32, prints an error
4136 // and aborts.
4137 Int32 Int32FromEnvOrDie(const char* const var, Int32 default_val) {
4138 const char* str_val = posix::GetEnv(var);
4139 if (str_val == NULL) {
4140 return default_val;
4141 }
4142
4143 Int32 result;
4144 if (!ParseInt32(Message() << "The value of environment variable " << var,
4145 str_val, &result)) {
4146 exit(EXIT_FAILURE);
4147 }
4148 return result;
4149 }
4150
4151 // Given the total number of shards, the shard index, and the test id,
4152 // returns true iff the test should be run on this shard. The test id is
4153 // some arbitrary but unique non-negative integer assigned to each test
4154 // method. Assumes that 0 <= shard_index < total_shards.
4155 bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) {
4156 return (test_id % total_shards) == shard_index;
4157 }
4158
4159 // Compares the name of each test with the user-specified filter to
4160 // decide whether the test should be run, then records the result in
4161 // each TestCase and TestInfo object.
4162 // If shard_tests == true, further filters tests based on sharding
4163 // variables in the environment - see
4164 // http://code.google.com/p/googletest/wiki/GoogleTestAdvancedGuide.
4165 // Returns the number of tests that should run.
4166 int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) {
4167 const Int32 total_shards = shard_tests == HONOR_SHARDING_PROTOCOL ?
4168 Int32FromEnvOrDie(kTestTotalShards, -1) : -1;
4169 const Int32 shard_index = shard_tests == HONOR_SHARDING_PROTOCOL ?
4170 Int32FromEnvOrDie(kTestShardIndex, -1) : -1;
4171
4172 // num_runnable_tests are the number of tests that will
4173 // run across all shards (i.e., match filter and are not disabled).
4174 // num_selected_tests are the number of tests to be run on
4175 // this shard.
4176 int num_runnable_tests = 0;
4177 int num_selected_tests = 0;
4178 for (int i = 0; i < test_cases_.size(); i++) {
4179 TestCase* const test_case = test_cases_.GetElement(i);
4180 const String &test_case_name = test_case->name();
4181 test_case->set_should_run(false);
4182
4183 for (int j = 0; j < test_case->test_info_list().size(); j++) {
4184 TestInfo* const test_info = test_case->test_info_list().GetElement(j);
4185 const String test_name(test_info->name());
4186 // A test is disabled if test case name or test name matches
4187 // kDisableTestFilter.
4188 const bool is_disabled =
4189 internal::UnitTestOptions::MatchesFilter(test_case_name,
4190 kDisableTestFilter) ||
4191 internal::UnitTestOptions::MatchesFilter(test_name,
4192 kDisableTestFilter);
4193 test_info->impl()->set_is_disabled(is_disabled);
4194
4195 const bool matches_filter =
4196 internal::UnitTestOptions::FilterMatchesTest(test_case_name,
4197 test_name);
4198 test_info->impl()->set_matches_filter(matches_filter);
4199
4200 const bool is_runnable =
4201 (GTEST_FLAG(also_run_disabled_tests) || !is_disabled) &&
4202 matches_filter;
4203
4204 const bool is_selected = is_runnable &&
4205 (shard_tests == IGNORE_SHARDING_PROTOCOL ||
4206 ShouldRunTestOnShard(total_shards, shard_index,
4207 num_runnable_tests));
4208
4209 num_runnable_tests += is_runnable;
4210 num_selected_tests += is_selected;
4211
4212 test_info->impl()->set_should_run(is_selected);
4213 test_case->set_should_run(test_case->should_run() || is_selected);
4214 }
4215 }
4216 return num_selected_tests;
4217 }
4218
4219 // Prints the names of the tests matching the user-specified filter flag.
4220 void UnitTestImpl::ListTestsMatchingFilter() {
4221 for (int i = 0; i < test_cases_.size(); i++) {
4222 const TestCase* const test_case = test_cases_.GetElement(i);
4223 bool printed_test_case_name = false;
4224
4225 for (int j = 0; j < test_case->test_info_list().size(); j++) {
4226 const TestInfo* const test_info =
4227 test_case->test_info_list().GetElement(j);
4228 if (test_info->matches_filter()) {
4229 if (!printed_test_case_name) {
4230 printed_test_case_name = true;
4231 printf("%s.\n", test_case->name());
4232 }
4233 printf(" %s\n", test_info->name());
4234 }
4235 }
4236 }
4237 fflush(stdout);
4238 }
4239
4240 // Sets the OS stack trace getter.
4241 //
4242 // Does nothing if the input and the current OS stack trace getter are
4243 // the same; otherwise, deletes the old getter and makes the input the
4244 // current getter.
4245 void UnitTestImpl::set_os_stack_trace_getter(
4246 OsStackTraceGetterInterface* getter) {
4247 if (os_stack_trace_getter_ != getter) {
4248 delete os_stack_trace_getter_;
4249 os_stack_trace_getter_ = getter;
4250 }
4251 }
4252
4253 // Returns the current OS stack trace getter if it is not NULL;
4254 // otherwise, creates an OsStackTraceGetter, makes it the current
4255 // getter, and returns it.
4256 OsStackTraceGetterInterface* UnitTestImpl::os_stack_trace_getter() {
4257 if (os_stack_trace_getter_ == NULL) {
4258 os_stack_trace_getter_ = new OsStackTraceGetter;
4259 }
4260
4261 return os_stack_trace_getter_;
4262 }
4263
4264 // Returns the TestResult for the test that's currently running, or
4265 // the TestResult for the ad hoc test if no test is running.
4266 TestResult* UnitTestImpl::current_test_result() {
4267 return current_test_info_ ?
4268 current_test_info_->impl()->result() : &ad_hoc_test_result_;
4269 }
4270
4271 // Shuffles all test cases, and the tests within each test case,
4272 // making sure that death tests are still run first.
4273 void UnitTestImpl::ShuffleTests() {
4274 // Shuffles the death test cases.
4275 test_case_indices_.ShuffleRange(random(), 0, last_death_test_case_ + 1);
4276
4277 // Shuffles the non-death test cases.
4278 test_case_indices_.ShuffleRange(random(), last_death_test_case_ + 1,
4279 test_cases_.size());
4280
4281 // Shuffles the tests inside each test case.
4282 for (int i = 0; i < test_cases_.size(); i++) {
4283 test_cases_.GetElement(i)->ShuffleTests(random());
4284 }
4285 }
4286
4287 // Restores the test cases and tests to their order before the first shuffle.
4288 void UnitTestImpl::UnshuffleTests() {
4289 for (int i = 0; i < test_cases_.size(); i++) {
4290 // Unshuffles the tests in each test case.
4291 test_cases_.GetElement(i)->UnshuffleTests();
4292 // Resets the index of each test case.
4293 test_case_indices_.GetMutableElement(i) = i;
4294 }
4295 }
4296
4297 // TestInfoImpl constructor. The new instance assumes ownership of the test
4298 // factory object.
4299 TestInfoImpl::TestInfoImpl(TestInfo* parent,
4300 const char* test_case_name,
4301 const char* name,
4302 const char* test_case_comment,
4303 const char* comment,
4304 TypeId fixture_class_id,
4305 internal::TestFactoryBase* factory) :
4306 parent_(parent),
4307 test_case_name_(String(test_case_name)),
4308 name_(String(name)),
4309 test_case_comment_(String(test_case_comment)),
4310 comment_(String(comment)),
4311 fixture_class_id_(fixture_class_id),
4312 should_run_(false),
4313 is_disabled_(false),
4314 matches_filter_(false),
4315 factory_(factory) {
4316 }
4317
4318 // TestInfoImpl destructor.
4319 TestInfoImpl::~TestInfoImpl() {
4320 delete factory_;
4321 }
4322
4323 // Returns the current OS stack trace as a String.
4324 //
4325 // The maximum number of stack frames to be included is specified by
4326 // the gtest_stack_trace_depth flag. The skip_count parameter
4327 // specifies the number of top frames to be skipped, which doesn't
4328 // count against the number of frames to be included.
4329 //
4330 // For example, if Foo() calls Bar(), which in turn calls
4331 // GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in
4332 // the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.
4333 String GetCurrentOsStackTraceExceptTop(UnitTest* /*unit_test*/,
4334 int skip_count) {
4335 // We pass skip_count + 1 to skip this wrapper function in addition
4336 // to what the user really wants to skip.
4337 return GetUnitTestImpl()->CurrentOsStackTraceExceptTop(skip_count + 1);
4338 }
4339
4340 // Used by the GTEST_HIDE_UNREACHABLE_CODE_ macro to suppress unreachable
4341 // code warnings.
4342 namespace {
4343 class ClassUniqueToAlwaysTrue {};
4344 }
4345
4346 bool IsTrue(bool condition) { return condition; }
4347
4348 bool AlwaysTrue() {
4349 #if GTEST_HAS_EXCEPTIONS
4350 // This condition is always false so AlwaysTrue() never actually throws,
4351 // but it makes the compiler think that it may throw.
4352 if (IsTrue(false))
4353 throw ClassUniqueToAlwaysTrue();
4354 #endif // GTEST_HAS_EXCEPTIONS
4355 return true;
4356 }
4357
4358 // If *pstr starts with the given prefix, modifies *pstr to be right
4359 // past the prefix and returns true; otherwise leaves *pstr unchanged
4360 // and returns false. None of pstr, *pstr, and prefix can be NULL.
4361 bool SkipPrefix(const char* prefix, const char** pstr) {
4362 const size_t prefix_len = strlen(prefix);
4363 if (strncmp(*pstr, prefix, prefix_len) == 0) {
4364 *pstr += prefix_len;
4365 return true;
4366 }
4367 return false;
4368 }
4369
4370 // Parses a string as a command line flag. The string should have
4371 // the format "--flag=value". When def_optional is true, the "=value"
4372 // part can be omitted.
4373 //
4374 // Returns the value of the flag, or NULL if the parsing failed.
4375 const char* ParseFlagValue(const char* str,
4376 const char* flag,
4377 bool def_optional) {
4378 // str and flag must not be NULL.
4379 if (str == NULL || flag == NULL) return NULL;
4380
4381 // The flag must start with "--" followed by GTEST_FLAG_PREFIX_.
4382 const String flag_str = String::Format("--%s%s", GTEST_FLAG_PREFIX_, flag);
4383 const size_t flag_len = flag_str.length();
4384 if (strncmp(str, flag_str.c_str(), flag_len) != 0) return NULL;
4385
4386 // Skips the flag name.
4387 const char* flag_end = str + flag_len;
4388
4389 // When def_optional is true, it's OK to not have a "=value" part.
4390 if (def_optional && (flag_end[0] == '\0')) {
4391 return flag_end;
4392 }
4393
4394 // If def_optional is true and there are more characters after the
4395 // flag name, or if def_optional is false, there must be a '=' after
4396 // the flag name.
4397 if (flag_end[0] != '=') return NULL;
4398
4399 // Returns the string after "=".
4400 return flag_end + 1;
4401 }
4402
4403 // Parses a string for a bool flag, in the form of either
4404 // "--flag=value" or "--flag".
4405 //
4406 // In the former case, the value is taken as true as long as it does
4407 // not start with '0', 'f', or 'F'.
4408 //
4409 // In the latter case, the value is taken as true.
4410 //
4411 // On success, stores the value of the flag in *value, and returns
4412 // true. On failure, returns false without changing *value.
4413 bool ParseBoolFlag(const char* str, const char* flag, bool* value) {
4414 // Gets the value of the flag as a string.
4415 const char* const value_str = ParseFlagValue(str, flag, true);
4416
4417 // Aborts if the parsing failed.
4418 if (value_str == NULL) return false;
4419
4420 // Converts the string value to a bool.
4421 *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F');
4422 return true;
4423 }
4424
4425 // Parses a string for an Int32 flag, in the form of
4426 // "--flag=value".
4427 //
4428 // On success, stores the value of the flag in *value, and returns
4429 // true. On failure, returns false without changing *value.
4430 bool ParseInt32Flag(const char* str, const char* flag, Int32* value) {
4431 // Gets the value of the flag as a string.
4432 const char* const value_str = ParseFlagValue(str, flag, false);
4433
4434 // Aborts if the parsing failed.
4435 if (value_str == NULL) return false;
4436
4437 // Sets *value to the value of the flag.
4438 return ParseInt32(Message() << "The value of flag --" << flag,
4439 value_str, value);
4440 }
4441
4442 // Parses a string for a string flag, in the form of
4443 // "--flag=value".
4444 //
4445 // On success, stores the value of the flag in *value, and returns
4446 // true. On failure, returns false without changing *value.
4447 bool ParseStringFlag(const char* str, const char* flag, String* value) {
4448 // Gets the value of the flag as a string.
4449 const char* const value_str = ParseFlagValue(str, flag, false);
4450
4451 // Aborts if the parsing failed.
4452 if (value_str == NULL) return false;
4453
4454 // Sets *value to the value of the flag.
4455 *value = value_str;
4456 return true;
4457 }
4458
4459 // Determines whether a string has a prefix that Google Test uses for its
4460 // flags, i.e., starts with GTEST_FLAG_PREFIX_ or GTEST_FLAG_PREFIX_DASH_.
4461 // If Google Test detects that a command line flag has its prefix but is not
4462 // recognized, it will print its help message. Flags starting with
4463 // GTEST_INTERNAL_PREFIX_ followed by "internal_" are considered Google Test
4464 // internal flags and do not trigger the help message.
4465 static bool HasGoogleTestFlagPrefix(const char* str) {
4466 return (SkipPrefix("--", &str) ||
4467 SkipPrefix("-", &str) ||
4468 SkipPrefix("/", &str)) &&
4469 !SkipPrefix(GTEST_FLAG_PREFIX_ "internal_", &str) &&
4470 (SkipPrefix(GTEST_FLAG_PREFIX_, &str) ||
4471 SkipPrefix(GTEST_FLAG_PREFIX_DASH_, &str));
4472 }
4473
4474 // Prints a string containing code-encoded text. The following escape
4475 // sequences can be used in the string to control the text color:
4476 //
4477 // @@ prints a single '@' character.
4478 // @R changes the color to red.
4479 // @G changes the color to green.
4480 // @Y changes the color to yellow.
4481 // @D changes to the default terminal text color.
4482 //
4483 // TODO(wan@google.com): Write tests for this once we add stdout
4484 // capturing to Google Test.
4485 static void PrintColorEncoded(const char* str) {
4486 GTestColor color = COLOR_DEFAULT; // The current color.
4487
4488 // Conceptually, we split the string into segments divided by escape
4489 // sequences. Then we print one segment at a time. At the end of
4490 // each iteration, the str pointer advances to the beginning of the
4491 // next segment.
4492 for (;;) {
4493 const char* p = strchr(str, '@');
4494 if (p == NULL) {
4495 ColoredPrintf(color, "%s", str);
4496 return;
4497 }
4498
4499 ColoredPrintf(color, "%s", String(str, p - str).c_str());
4500
4501 const char ch = p[1];
4502 str = p + 2;
4503 if (ch == '@') {
4504 ColoredPrintf(color, "@");
4505 } else if (ch == 'D') {
4506 color = COLOR_DEFAULT;
4507 } else if (ch == 'R') {
4508 color = COLOR_RED;
4509 } else if (ch == 'G') {
4510 color = COLOR_GREEN;
4511 } else if (ch == 'Y') {
4512 color = COLOR_YELLOW;
4513 } else {
4514 --str;
4515 }
4516 }
4517 }
4518
4519 static const char kColorEncodedHelpMessage[] =
4520 "This program contains tests written using " GTEST_NAME_ ". You can use the\n"
4521 "following command line flags to control its behavior:\n"
4522 "\n"
4523 "Test Selection:\n"
4524 " @G--" GTEST_FLAG_PREFIX_ "list_tests@D\n"
4525 " List the names of all tests instead of running them. The name of\n"
4526 " TEST(Foo, Bar) is \"Foo.Bar\".\n"
4527 " @G--" GTEST_FLAG_PREFIX_ "filter=@YPOSTIVE_PATTERNS"
4528 "[@G-@YNEGATIVE_PATTERNS]@D\n"
4529 " Run only the tests whose name matches one of the positive patterns but\n"
4530 " none of the negative patterns. '?' matches any single character; '*'\n"
4531 " matches any substring; ':' separates two patterns.\n"
4532 " @G--" GTEST_FLAG_PREFIX_ "also_run_disabled_tests@D\n"
4533 " Run all disabled tests too.\n"
4534 "\n"
4535 "Test Execution:\n"
4536 " @G--" GTEST_FLAG_PREFIX_ "repeat=@Y[COUNT]@D\n"
4537 " Run the tests repeatedly; use a negative count to repeat forever.\n"
4538 " @G--" GTEST_FLAG_PREFIX_ "shuffle@D\n"
4539 " Randomize tests' orders on every iteration.\n"
4540 " @G--" GTEST_FLAG_PREFIX_ "random_seed=@Y[NUMBER]@D\n"
4541 " Random number seed to use for shuffling test orders (between 1 and\n"
4542 " 99999, or 0 to use a seed based on the current time).\n"
4543 "\n"
4544 "Test Output:\n"
4545 " @G--" GTEST_FLAG_PREFIX_ "color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\n"
4546 " Enable/disable colored output. The default is @Gauto@D.\n"
4547 " -@G-" GTEST_FLAG_PREFIX_ "print_time=0@D\n"
4548 " Don't print the elapsed time of each test.\n"
4549 " @G--" GTEST_FLAG_PREFIX_ "output=xml@Y[@G:@YDIRECTORY_PATH@G"
4550 GTEST_PATH_SEP_ "@Y|@G:@YFILE_PATH]@D\n"
4551 " Generate an XML report in the given directory or with the given file\n"
4552 " name. @YFILE_PATH@D defaults to @Gtest_details.xml@D.\n"
4553 "\n"
4554 "Assertion Behavior:\n"
4555 #if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
4556 " @G--" GTEST_FLAG_PREFIX_ "death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n"
4557 " Set the default death test style.\n"
4558 #endif // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
4559 " @G--" GTEST_FLAG_PREFIX_ "break_on_failure@D\n"
4560 " Turn assertion failures into debugger break-points.\n"
4561 " @G--" GTEST_FLAG_PREFIX_ "throw_on_failure@D\n"
4562 " Turn assertion failures into C++ exceptions.\n"
4563 #if GTEST_OS_WINDOWS
4564 " @G--" GTEST_FLAG_PREFIX_ "catch_exceptions@D\n"
4565 " Suppress pop-ups caused by exceptions.\n"
4566 #endif // GTEST_OS_WINDOWS
4567 "\n"
4568 "Except for @G--" GTEST_FLAG_PREFIX_ "list_tests@D, you can alternatively set "
4569 "the corresponding\n"
4570 "environment variable of a flag (all letters in upper-case). For example, to\n"
4571 "disable colored text output, you can either specify @G--" GTEST_FLAG_PREFIX_
4572 "color=no@D or set\n"
4573 "the @G" GTEST_FLAG_PREFIX_UPPER_ "COLOR@D environment variable to @Gno@D.\n"
4574 "\n"
4575 "For more information, please read the " GTEST_NAME_ " documentation at\n"
4576 "@G" GTEST_PROJECT_URL_ "@D. If you find a bug in " GTEST_NAME_ "\n"
4577 "(not one in your own code or tests), please report it to\n"
4578 "@G<" GTEST_DEV_EMAIL_ ">@D.\n";
4579
4580 // Parses the command line for Google Test flags, without initializing
4581 // other parts of Google Test. The type parameter CharType can be
4582 // instantiated to either char or wchar_t.
4583 template <typename CharType>
4584 void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) {
4585 for (int i = 1; i < *argc; i++) {
4586 const String arg_string = StreamableToString(argv[i]);
4587 const char* const arg = arg_string.c_str();
4588
4589 using internal::ParseBoolFlag;
4590 using internal::ParseInt32Flag;
4591 using internal::ParseStringFlag;
4592
4593 // Do we see a Google Test flag?
4594 if (ParseBoolFlag(arg, kAlsoRunDisabledTestsFlag,
4595 &GTEST_FLAG(also_run_disabled_tests)) ||
4596 ParseBoolFlag(arg, kBreakOnFailureFlag,
4597 &GTEST_FLAG(break_on_failure)) ||
4598 ParseBoolFlag(arg, kCatchExceptionsFlag,
4599 &GTEST_FLAG(catch_exceptions)) ||
4600 ParseStringFlag(arg, kColorFlag, &GTEST_FLAG(color)) ||
4601 ParseStringFlag(arg, kDeathTestStyleFlag,
4602 &GTEST_FLAG(death_test_style)) ||
4603 ParseBoolFlag(arg, kDeathTestUseFork,
4604 &GTEST_FLAG(death_test_use_fork)) ||
4605 ParseStringFlag(arg, kFilterFlag, &GTEST_FLAG(filter)) ||
4606 ParseStringFlag(arg, kInternalRunDeathTestFlag,
4607 &GTEST_FLAG(internal_run_death_test)) ||
4608 ParseBoolFlag(arg, kListTestsFlag, &GTEST_FLAG(list_tests)) ||
4609 ParseStringFlag(arg, kOutputFlag, &GTEST_FLAG(output)) ||
4610 ParseBoolFlag(arg, kPrintTimeFlag, &GTEST_FLAG(print_time)) ||
4611 ParseInt32Flag(arg, kRandomSeedFlag, &GTEST_FLAG(random_seed)) ||
4612 ParseInt32Flag(arg, kRepeatFlag, &GTEST_FLAG(repeat)) ||
4613 ParseBoolFlag(arg, kShuffleFlag, &GTEST_FLAG(shuffle)) ||
4614 ParseInt32Flag(arg, kStackTraceDepthFlag,
4615 &GTEST_FLAG(stack_trace_depth)) ||
4616 ParseBoolFlag(arg, kThrowOnFailureFlag, &GTEST_FLAG(throw_on_failure))
4617 ) {
4618 // Yes. Shift the remainder of the argv list left by one. Note
4619 // that argv has (*argc + 1) elements, the last one always being
4620 // NULL. The following loop moves the trailing NULL element as
4621 // well.
4622 for (int j = i; j != *argc; j++) {
4623 argv[j] = argv[j + 1];
4624 }
4625
4626 // Decrements the argument count.
4627 (*argc)--;
4628
4629 // We also need to decrement the iterator as we just removed
4630 // an element.
4631 i--;
4632 } else if (arg_string == "--help" || arg_string == "-h" ||
4633 arg_string == "-?" || arg_string == "/?" ||
4634 HasGoogleTestFlagPrefix(arg)) {
4635 // Both help flag and unrecognized Google Test flags (excluding
4636 // internal ones) trigger help display.
4637 g_help_flag = true;
4638 }
4639 }
4640
4641 if (g_help_flag) {
4642 // We print the help here instead of in RUN_ALL_TESTS(), as the
4643 // latter may not be called at all if the user is using Google
4644 // Test with another testing framework.
4645 PrintColorEncoded(kColorEncodedHelpMessage);
4646 }
4647 }
4648
4649 // Parses the command line for Google Test flags, without initializing
4650 // other parts of Google Test.
4651 void ParseGoogleTestFlagsOnly(int* argc, char** argv) {
4652 ParseGoogleTestFlagsOnlyImpl(argc, argv);
4653 }
4654 void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv) {
4655 ParseGoogleTestFlagsOnlyImpl(argc, argv);
4656 }
4657
4658 // The internal implementation of InitGoogleTest().
4659 //
4660 // The type parameter CharType can be instantiated to either char or
4661 // wchar_t.
4662 template <typename CharType>
4663 void InitGoogleTestImpl(int* argc, CharType** argv) {
4664 g_init_gtest_count++;
4665
4666 // We don't want to run the initialization code twice.
4667 if (g_init_gtest_count != 1) return;
4668
4669 if (*argc <= 0) return;
4670
4671 internal::g_executable_path = internal::StreamableToString(argv[0]);
4672
4673 #if GTEST_HAS_DEATH_TEST
4674 g_argvs.clear();
4675 for (int i = 0; i != *argc; i++) {
4676 g_argvs.push_back(StreamableToString(argv[i]));
4677 }
4678 #endif // GTEST_HAS_DEATH_TEST
4679
4680 ParseGoogleTestFlagsOnly(argc, argv);
4681 GetUnitTestImpl()->PostFlagParsingInit();
4682 }
4683
4684 } // namespace internal
4685
4686 // Initializes Google Test. This must be called before calling
4687 // RUN_ALL_TESTS(). In particular, it parses a command line for the
4688 // flags that Google Test recognizes. Whenever a Google Test flag is
4689 // seen, it is removed from argv, and *argc is decremented.
4690 //
4691 // No value is returned. Instead, the Google Test flag variables are
4692 // updated.
4693 //
4694 // Calling the function for the second time has no user-visible effect.
4695 void InitGoogleTest(int* argc, char** argv) {
4696 internal::InitGoogleTestImpl(argc, argv);
4697 }
4698
4699 // This overloaded version can be used in Windows programs compiled in
4700 // UNICODE mode.
4701 void InitGoogleTest(int* argc, wchar_t** argv) {
4702 internal::InitGoogleTestImpl(argc, argv);
4703 }
4704
4705 } // namespace testing
OLDNEW
« no previous file with comments | « third_party/gtest/include/gtest/internal/gtest-type-util.h ('k') | third_party/gtest/src/gtest-all.cc » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698