Debian Codegraph @

third_party/gtest/src/gtest.cc

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