1 // Copyright 2008, Google Inc.
2 // All rights reserved.
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
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
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.
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.
30 // Author: mheule@google.com (Markus Heule)
32 // Google C++ Testing Framework (Google Test)
34 // Sometimes it's desirable to build Google Test by compiling a single file.
35 // This file serves this purpose.
37 // This line ensures that gtest.h can be compiled on its own, even
39 #include "gtest/gtest.h"
41 // The following lines pull in the real gtest *.cc files.
42 // Copyright 2005, Google Inc.
43 // All rights reserved.
45 // Redistribution and use in source and binary forms, with or without
46 // modification, are permitted provided that the following conditions are
49 // * Redistributions of source code must retain the above copyright
50 // notice, this list of conditions and the following disclaimer.
51 // * Redistributions in binary form must reproduce the above
52 // copyright notice, this list of conditions and the following disclaimer
53 // in the documentation and/or other materials provided with the
55 // * Neither the name of Google Inc. nor the names of its
56 // contributors may be used to endorse or promote products derived from
57 // this software without specific prior written permission.
59 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
60 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
61 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
62 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
63 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
64 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
65 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
66 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
67 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
68 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
69 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
71 // Author: wan@google.com (Zhanyong Wan)
73 // The Google C++ Testing Framework (Google Test)
75 // Copyright 2007, Google Inc.
76 // All rights reserved.
78 // Redistribution and use in source and binary forms, with or without
79 // modification, are permitted provided that the following conditions are
82 // * Redistributions of source code must retain the above copyright
83 // notice, this list of conditions and the following disclaimer.
84 // * Redistributions in binary form must reproduce the above
85 // copyright notice, this list of conditions and the following disclaimer
86 // in the documentation and/or other materials provided with the
88 // * Neither the name of Google Inc. nor the names of its
89 // contributors may be used to endorse or promote products derived from
90 // this software without specific prior written permission.
92 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
93 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
94 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
95 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
96 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
97 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
98 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
99 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
100 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
101 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
102 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
104 // Author: wan@google.com (Zhanyong Wan)
106 // Utilities for testing Google Test itself and code that uses Google Test
107 // (e.g. frameworks built on top of Google Test).
109 #ifndef GTEST_INCLUDE_GTEST_GTEST_SPI_H_
110 #define GTEST_INCLUDE_GTEST_GTEST_SPI_H_
115 // This helper class can be used to mock out Google Test failure reporting
116 // so that we can test Google Test or code that builds on Google Test.
118 // An object of this class appends a TestPartResult object to the
119 // TestPartResultArray object given in the constructor whenever a Google Test
120 // failure is reported. It can either intercept only failures that are
121 // generated in the same thread that created this object or it can intercept
122 // all generated failures. The scope of this mock object can be controlled with
123 // the second argument to the two arguments constructor.
124 class GTEST_API_ ScopedFakeTestPartResultReporter
125 : public TestPartResultReporterInterface {
127 // The two possible mocking modes of this object.
129 INTERCEPT_ONLY_CURRENT_THREAD, // Intercepts only thread local failures.
130 INTERCEPT_ALL_THREADS // Intercepts all failures.
133 // The c'tor sets this object as the test part result reporter used
134 // by Google Test. The 'result' parameter specifies where to report the
135 // results. This reporter will only catch failures generated in the current
136 // thread. DEPRECATED
137 explicit ScopedFakeTestPartResultReporter(TestPartResultArray* result);
139 // Same as above, but you can choose the interception scope of this object.
140 ScopedFakeTestPartResultReporter(InterceptMode intercept_mode,
141 TestPartResultArray* result);
143 // The d'tor restores the previous test part result reporter.
144 virtual ~ScopedFakeTestPartResultReporter();
146 // Appends the TestPartResult object to the TestPartResultArray
147 // received in the constructor.
149 // This method is from the TestPartResultReporterInterface
151 virtual void ReportTestPartResult(const TestPartResult& result);
155 const InterceptMode intercept_mode_;
156 TestPartResultReporterInterface* old_reporter_;
157 TestPartResultArray* const result_;
159 GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedFakeTestPartResultReporter);
164 // A helper class for implementing EXPECT_FATAL_FAILURE() and
165 // EXPECT_NONFATAL_FAILURE(). Its destructor verifies that the given
166 // TestPartResultArray contains exactly one failure that has the given
167 // type and contains the given substring. If that's not the case, a
168 // non-fatal failure will be generated.
169 class GTEST_API_ SingleFailureChecker {
171 // The constructor remembers the arguments.
172 SingleFailureChecker(const TestPartResultArray* results,
173 TestPartResult::Type type,
174 const string& substr);
175 ~SingleFailureChecker();
177 const TestPartResultArray* const results_;
178 const TestPartResult::Type type_;
179 const string substr_;
181 GTEST_DISALLOW_COPY_AND_ASSIGN_(SingleFailureChecker);
184 } // namespace internal
186 } // namespace testing
188 // A set of macros for testing Google Test assertions or code that's expected
189 // to generate Google Test fatal failures. It verifies that the given
190 // statement will cause exactly one fatal Google Test failure with 'substr'
191 // being part of the failure message.
193 // There are two different versions of this macro. EXPECT_FATAL_FAILURE only
194 // affects and considers failures generated in the current thread and
195 // EXPECT_FATAL_FAILURE_ON_ALL_THREADS does the same but for all threads.
197 // The verification of the assertion is done correctly even when the statement
198 // throws an exception or aborts the current function.
200 // Known restrictions:
201 // - 'statement' cannot reference local non-static variables or
202 // non-static members of the current object.
203 // - 'statement' cannot return a value.
204 // - You cannot stream a failure message to this macro.
206 // Note that even though the implementations of the following two
207 // macros are much alike, we cannot refactor them to use a common
208 // helper macro, due to some peculiarity in how the preprocessor
209 // works. The AcceptsMacroThatExpandsToUnprotectedComma test in
210 // gtest_unittest.cc will fail to compile if we do that.
211 #define EXPECT_FATAL_FAILURE(statement, substr) \
213 class GTestExpectFatalFailureHelper {\
215 static void Execute() { statement; }\
217 ::testing::TestPartResultArray gtest_failures;\
218 ::testing::internal::SingleFailureChecker gtest_checker(\
219 >est_failures, ::testing::TestPartResult::kFatalFailure, (substr));\
221 ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
222 ::testing::ScopedFakeTestPartResultReporter:: \
223 INTERCEPT_ONLY_CURRENT_THREAD, >est_failures);\
224 GTestExpectFatalFailureHelper::Execute();\
226 } while (::testing::internal::AlwaysFalse())
228 #define EXPECT_FATAL_FAILURE_ON_ALL_THREADS(statement, substr) \
230 class GTestExpectFatalFailureHelper {\
232 static void Execute() { statement; }\
234 ::testing::TestPartResultArray gtest_failures;\
235 ::testing::internal::SingleFailureChecker gtest_checker(\
236 >est_failures, ::testing::TestPartResult::kFatalFailure, (substr));\
238 ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
239 ::testing::ScopedFakeTestPartResultReporter:: \
240 INTERCEPT_ALL_THREADS, >est_failures);\
241 GTestExpectFatalFailureHelper::Execute();\
243 } while (::testing::internal::AlwaysFalse())
245 // A macro for testing Google Test assertions or code that's expected to
246 // generate Google Test non-fatal failures. It asserts that the given
247 // statement will cause exactly one non-fatal Google Test failure with 'substr'
248 // being part of the failure message.
250 // There are two different versions of this macro. EXPECT_NONFATAL_FAILURE only
251 // affects and considers failures generated in the current thread and
252 // EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS does the same but for all threads.
254 // 'statement' is allowed to reference local variables and members of
255 // the current object.
257 // The verification of the assertion is done correctly even when the statement
258 // throws an exception or aborts the current function.
260 // Known restrictions:
261 // - You cannot stream a failure message to this macro.
263 // Note that even though the implementations of the following two
264 // macros are much alike, we cannot refactor them to use a common
265 // helper macro, due to some peculiarity in how the preprocessor
266 // works. If we do that, the code won't compile when the user gives
267 // EXPECT_NONFATAL_FAILURE() a statement that contains a macro that
268 // expands to code containing an unprotected comma. The
269 // AcceptsMacroThatExpandsToUnprotectedComma test in gtest_unittest.cc
272 // For the same reason, we have to write
273 // if (::testing::internal::AlwaysTrue()) { statement; }
275 // GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement)
276 // to avoid an MSVC warning on unreachable code.
277 #define EXPECT_NONFATAL_FAILURE(statement, substr) \
279 ::testing::TestPartResultArray gtest_failures;\
280 ::testing::internal::SingleFailureChecker gtest_checker(\
281 >est_failures, ::testing::TestPartResult::kNonFatalFailure, \
284 ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
285 ::testing::ScopedFakeTestPartResultReporter:: \
286 INTERCEPT_ONLY_CURRENT_THREAD, >est_failures);\
287 if (::testing::internal::AlwaysTrue()) { statement; }\
289 } while (::testing::internal::AlwaysFalse())
291 #define EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(statement, substr) \
293 ::testing::TestPartResultArray gtest_failures;\
294 ::testing::internal::SingleFailureChecker gtest_checker(\
295 >est_failures, ::testing::TestPartResult::kNonFatalFailure, \
298 ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
299 ::testing::ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS,\
301 if (::testing::internal::AlwaysTrue()) { statement; }\
303 } while (::testing::internal::AlwaysFalse())
305 #endif // GTEST_INCLUDE_GTEST_GTEST_SPI_H_
316 #include <ostream> // NOLINT
322 // TODO(kenton@google.com): Use autoconf to detect availability of
324 # define GTEST_HAS_GETTIMEOFDAY_ 1
326 # include <fcntl.h> // NOLINT
327 # include <limits.h> // NOLINT
328 # include <sched.h> // NOLINT
329 // Declares vsnprintf(). This header is not available on Windows.
330 # include <strings.h> // NOLINT
331 # include <sys/mman.h> // NOLINT
332 # include <sys/time.h> // NOLINT
333 # include <unistd.h> // NOLINT
336 #elif GTEST_OS_SYMBIAN
337 # define GTEST_HAS_GETTIMEOFDAY_ 1
338 # include <sys/time.h> // NOLINT
341 # define GTEST_HAS_GETTIMEOFDAY_ 1
342 # include <sys/time.h> // NOLINT
344 // On z/OS we additionally need strings.h for strcasecmp.
345 # include <strings.h> // NOLINT
347 #elif GTEST_OS_WINDOWS_MOBILE // We are on Windows CE.
349 # include <windows.h> // NOLINT
351 #elif GTEST_OS_WINDOWS // We are on Windows proper.
353 # include <io.h> // NOLINT
354 # include <sys/timeb.h> // NOLINT
355 # include <sys/types.h> // NOLINT
356 # include <sys/stat.h> // NOLINT
358 # if GTEST_OS_WINDOWS_MINGW
359 // MinGW has gettimeofday() but not _ftime64().
360 // TODO(kenton@google.com): Use autoconf to detect availability of
362 // TODO(kenton@google.com): There are other ways to get the time on
363 // Windows, like GetTickCount() or GetSystemTimeAsFileTime(). MinGW
364 // supports these. consider using them instead.
365 # define GTEST_HAS_GETTIMEOFDAY_ 1
366 # include <sys/time.h> // NOLINT
367 # endif // GTEST_OS_WINDOWS_MINGW
369 // cpplint thinks that the header is already included, so we want to
371 # include <windows.h> // NOLINT
375 // Assume other platforms have gettimeofday().
376 // TODO(kenton@google.com): Use autoconf to detect availability of
378 # define GTEST_HAS_GETTIMEOFDAY_ 1
380 // cpplint thinks that the header is already included, so we want to
382 # include <sys/time.h> // NOLINT
383 # include <unistd.h> // NOLINT
385 #endif // GTEST_OS_LINUX
387 #if GTEST_HAS_EXCEPTIONS
388 # include <stdexcept>
391 #if GTEST_CAN_STREAM_RESULTS_
392 # include <arpa/inet.h> // NOLINT
393 # include <netdb.h> // NOLINT
396 // Indicates that this translation unit is part of Google Test's
397 // implementation. It must come before gtest-internal-inl.h is
398 // included, or there will be a compiler error. This trick is to
399 // prevent a user from accidentally including gtest-internal-inl.h in
401 #define GTEST_IMPLEMENTATION_ 1
402 // Copyright 2005, Google Inc.
403 // All rights reserved.
405 // Redistribution and use in source and binary forms, with or without
406 // modification, are permitted provided that the following conditions are
409 // * Redistributions of source code must retain the above copyright
410 // notice, this list of conditions and the following disclaimer.
411 // * Redistributions in binary form must reproduce the above
412 // copyright notice, this list of conditions and the following disclaimer
413 // in the documentation and/or other materials provided with the
415 // * Neither the name of Google Inc. nor the names of its
416 // contributors may be used to endorse or promote products derived from
417 // this software without specific prior written permission.
419 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
420 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
421 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
422 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
423 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
424 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
425 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
426 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
427 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
428 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
429 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
431 // Utility functions and classes used by the Google C++ testing framework.
433 // Author: wan@google.com (Zhanyong Wan)
435 // This file contains purely Google Test's internal implementation. Please
436 // DO NOT #INCLUDE IT IN A USER PROGRAM.
438 #ifndef GTEST_SRC_GTEST_INTERNAL_INL_H_
439 #define GTEST_SRC_GTEST_INTERNAL_INL_H_
441 // GTEST_IMPLEMENTATION_ is defined to 1 iff the current translation unit is
442 // part of Google Test's implementation; otherwise it's undefined.
443 #if !GTEST_IMPLEMENTATION_
444 // A user is trying to include this from his code - just say no.
445 # error "gtest-internal-inl.h is part of Google Test's internal implementation."
446 # error "It must not be included except by Google Test itself."
447 #endif // GTEST_IMPLEMENTATION_
451 #endif // !_WIN32_WCE
453 #include <stdlib.h> // For strtoll/_strtoul64/malloc/free.
454 #include <string.h> // For memmove.
462 # include <windows.h> // NOLINT
463 #endif // GTEST_OS_WINDOWS
468 // Declares the flags.
470 // We don't want the users to modify this flag in the code, but want
471 // Google Test's own unit tests to be able to access it. Therefore we
472 // declare it here as opposed to in gtest.h.
473 GTEST_DECLARE_bool_(death_test_use_fork);
477 // The value of GetTestTypeId() as seen from within the Google Test
478 // library. This is solely for testing GetTestTypeId().
479 GTEST_API_ extern const TypeId kTestTypeIdInGoogleTest;
481 // Names of the flags (needed for parsing Google Test flags).
482 const char kAlsoRunDisabledTestsFlag[] = "also_run_disabled_tests";
483 const char kBreakOnFailureFlag[] = "break_on_failure";
484 const char kCatchExceptionsFlag[] = "catch_exceptions";
485 const char kColorFlag[] = "color";
486 const char kFilterFlag[] = "filter";
487 const char kListTestsFlag[] = "list_tests";
488 const char kOutputFlag[] = "output";
489 const char kPrintTimeFlag[] = "print_time";
490 const char kRandomSeedFlag[] = "random_seed";
491 const char kRepeatFlag[] = "repeat";
492 const char kShuffleFlag[] = "shuffle";
493 const char kStackTraceDepthFlag[] = "stack_trace_depth";
494 const char kStreamResultToFlag[] = "stream_result_to";
495 const char kThrowOnFailureFlag[] = "throw_on_failure";
497 // A valid random seed must be in [1, kMaxRandomSeed].
498 const int kMaxRandomSeed = 99999;
500 // g_help_flag is true iff the --help flag or an equivalent form is
501 // specified on the command line.
502 GTEST_API_ extern bool g_help_flag;
504 // Returns the current time in milliseconds.
505 GTEST_API_ TimeInMillis GetTimeInMillis();
507 // Returns true iff Google Test should use colors in the output.
508 GTEST_API_ bool ShouldUseColor(bool stdout_is_tty);
510 // Formats the given time in milliseconds as seconds.
511 GTEST_API_ std::string FormatTimeInMillisAsSeconds(TimeInMillis ms);
513 // Parses a string for an Int32 flag, in the form of "--flag=value".
515 // On success, stores the value of the flag in *value, and returns
516 // true. On failure, returns false without changing *value.
517 GTEST_API_ bool ParseInt32Flag(
518 const char* str, const char* flag, Int32* value);
520 // Returns a random seed in range [1, kMaxRandomSeed] based on the
521 // given --gtest_random_seed flag value.
522 inline int GetRandomSeedFromFlag(Int32 random_seed_flag) {
523 const unsigned int raw_seed = (random_seed_flag == 0) ?
524 static_cast<unsigned int>(GetTimeInMillis()) :
525 static_cast<unsigned int>(random_seed_flag);
527 // Normalizes the actual seed to range [1, kMaxRandomSeed] such that
528 // it's easy to type.
529 const int normalized_seed =
530 static_cast<int>((raw_seed - 1U) %
531 static_cast<unsigned int>(kMaxRandomSeed)) + 1;
532 return normalized_seed;
535 // Returns the first valid random seed after 'seed'. The behavior is
536 // undefined if 'seed' is invalid. The seed after kMaxRandomSeed is
537 // considered to be 1.
538 inline int GetNextRandomSeed(int seed) {
539 GTEST_CHECK_(1 <= seed && seed <= kMaxRandomSeed)
540 << "Invalid random seed " << seed << " - must be in [1, "
541 << kMaxRandomSeed << "].";
542 const int next_seed = seed + 1;
543 return (next_seed > kMaxRandomSeed) ? 1 : next_seed;
546 // This class saves the values of all Google Test flags in its c'tor, and
547 // restores them in its d'tor.
548 class GTestFlagSaver {
552 also_run_disabled_tests_ = GTEST_FLAG(also_run_disabled_tests);
553 break_on_failure_ = GTEST_FLAG(break_on_failure);
554 catch_exceptions_ = GTEST_FLAG(catch_exceptions);
555 color_ = GTEST_FLAG(color);
556 death_test_style_ = GTEST_FLAG(death_test_style);
557 death_test_use_fork_ = GTEST_FLAG(death_test_use_fork);
558 filter_ = GTEST_FLAG(filter);
559 internal_run_death_test_ = GTEST_FLAG(internal_run_death_test);
560 list_tests_ = GTEST_FLAG(list_tests);
561 output_ = GTEST_FLAG(output);
562 print_time_ = GTEST_FLAG(print_time);
563 random_seed_ = GTEST_FLAG(random_seed);
564 repeat_ = GTEST_FLAG(repeat);
565 shuffle_ = GTEST_FLAG(shuffle);
566 stack_trace_depth_ = GTEST_FLAG(stack_trace_depth);
567 stream_result_to_ = GTEST_FLAG(stream_result_to);
568 throw_on_failure_ = GTEST_FLAG(throw_on_failure);
571 // The d'tor is not virtual. DO NOT INHERIT FROM THIS CLASS.
573 GTEST_FLAG(also_run_disabled_tests) = also_run_disabled_tests_;
574 GTEST_FLAG(break_on_failure) = break_on_failure_;
575 GTEST_FLAG(catch_exceptions) = catch_exceptions_;
576 GTEST_FLAG(color) = color_;
577 GTEST_FLAG(death_test_style) = death_test_style_;
578 GTEST_FLAG(death_test_use_fork) = death_test_use_fork_;
579 GTEST_FLAG(filter) = filter_;
580 GTEST_FLAG(internal_run_death_test) = internal_run_death_test_;
581 GTEST_FLAG(list_tests) = list_tests_;
582 GTEST_FLAG(output) = output_;
583 GTEST_FLAG(print_time) = print_time_;
584 GTEST_FLAG(random_seed) = random_seed_;
585 GTEST_FLAG(repeat) = repeat_;
586 GTEST_FLAG(shuffle) = shuffle_;
587 GTEST_FLAG(stack_trace_depth) = stack_trace_depth_;
588 GTEST_FLAG(stream_result_to) = stream_result_to_;
589 GTEST_FLAG(throw_on_failure) = throw_on_failure_;
592 // Fields for saving the original values of flags.
593 bool also_run_disabled_tests_;
594 bool break_on_failure_;
595 bool catch_exceptions_;
597 String death_test_style_;
598 bool death_test_use_fork_;
600 String internal_run_death_test_;
605 internal::Int32 random_seed_;
606 internal::Int32 repeat_;
608 internal::Int32 stack_trace_depth_;
609 String stream_result_to_;
610 bool throw_on_failure_;
611 } GTEST_ATTRIBUTE_UNUSED_;
613 // Converts a Unicode code point to a narrow string in UTF-8 encoding.
614 // code_point parameter is of type UInt32 because wchar_t may not be
615 // wide enough to contain a code point.
616 // The output buffer str must containt at least 32 characters.
617 // The function returns the address of the output buffer.
618 // If the code_point is not a valid Unicode code point
619 // (i.e. outside of Unicode range U+0 to U+10FFFF) it will be output
620 // as '(Invalid Unicode 0xXXXXXXXX)'.
621 GTEST_API_ char* CodePointToUtf8(UInt32 code_point, char* str);
623 // Converts a wide string to a narrow string in UTF-8 encoding.
624 // The wide string is assumed to have the following encoding:
625 // UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS)
626 // UTF-32 if sizeof(wchar_t) == 4 (on Linux)
627 // Parameter str points to a null-terminated wide string.
628 // Parameter num_chars may additionally limit the number
629 // of wchar_t characters processed. -1 is used when the entire string
630 // should be processed.
631 // If the string contains code points that are not valid Unicode code points
632 // (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
633 // as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
634 // and contains invalid UTF-16 surrogate pairs, values in those pairs
635 // will be encoded as individual Unicode characters from Basic Normal Plane.
636 GTEST_API_ String WideStringToUtf8(const wchar_t* str, int num_chars);
638 // Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
639 // if the variable is present. If a file already exists at this location, this
640 // function will write over it. If the variable is present, but the file cannot
641 // be created, prints an error and exits.
642 void WriteToShardStatusFileIfNeeded();
644 // Checks whether sharding is enabled by examining the relevant
645 // environment variable values. If the variables are present,
646 // but inconsistent (e.g., shard_index >= total_shards), prints
647 // an error and exits. If in_subprocess_for_death_test, sharding is
648 // disabled because it must only be applied to the original test
649 // process. Otherwise, we could filter out death tests we intended to execute.
650 GTEST_API_ bool ShouldShard(const char* total_shards_str,
651 const char* shard_index_str,
652 bool in_subprocess_for_death_test);
654 // Parses the environment variable var as an Int32. If it is unset,
655 // returns default_val. If it is not an Int32, prints an error and
657 GTEST_API_ Int32 Int32FromEnvOrDie(const char* env_var, Int32 default_val);
659 // Given the total number of shards, the shard index, and the test id,
660 // returns true iff the test should be run on this shard. The test id is
661 // some arbitrary but unique non-negative integer assigned to each test
662 // method. Assumes that 0 <= shard_index < total_shards.
663 GTEST_API_ bool ShouldRunTestOnShard(
664 int total_shards, int shard_index, int test_id);
666 // STL container utilities.
668 // Returns the number of elements in the given container that satisfy
669 // the given predicate.
670 template <class Container, typename Predicate>
671 inline int CountIf(const Container& c, Predicate predicate) {
672 // Implemented as an explicit loop since std::count_if() in libCstd on
673 // Solaris has a non-standard signature.
675 for (typename Container::const_iterator it = c.begin(); it != c.end(); ++it) {
682 // Applies a function/functor to each element in the container.
683 template <class Container, typename Functor>
684 void ForEach(const Container& c, Functor functor) {
685 std::for_each(c.begin(), c.end(), functor);
688 // Returns the i-th element of the vector, or default_value if i is not
689 // in range [0, v.size()).
690 template <typename E>
691 inline E GetElementOr(const std::vector<E>& v, int i, E default_value) {
692 return (i < 0 || i >= static_cast<int>(v.size())) ? default_value : v[i];
695 // Performs an in-place shuffle of a range of the vector's elements.
696 // 'begin' and 'end' are element indices as an STL-style range;
697 // i.e. [begin, end) are shuffled, where 'end' == size() means to
698 // shuffle to the end of the vector.
699 template <typename E>
700 void ShuffleRange(internal::Random* random, int begin, int end,
702 const int size = static_cast<int>(v->size());
703 GTEST_CHECK_(0 <= begin && begin <= size)
704 << "Invalid shuffle range start " << begin << ": must be in range [0, "
706 GTEST_CHECK_(begin <= end && end <= size)
707 << "Invalid shuffle range finish " << end << ": must be in range ["
708 << begin << ", " << size << "].";
710 // Fisher-Yates shuffle, from
711 // http://en.wikipedia.org/wiki/Fisher-Yates_shuffle
712 for (int range_width = end - begin; range_width >= 2; range_width--) {
713 const int last_in_range = begin + range_width - 1;
714 const int selected = begin + random->Generate(range_width);
715 std::swap((*v)[selected], (*v)[last_in_range]);
719 // Performs an in-place shuffle of the vector's elements.
720 template <typename E>
721 inline void Shuffle(internal::Random* random, std::vector<E>* v) {
722 ShuffleRange(random, 0, static_cast<int>(v->size()), v);
725 // A function for deleting an object. Handy for being used as a
727 template <typename T>
728 static void Delete(T* x) {
732 // A predicate that checks the key of a TestProperty against a known key.
734 // TestPropertyKeyIs is copyable.
735 class TestPropertyKeyIs {
739 // TestPropertyKeyIs has NO default constructor.
740 explicit TestPropertyKeyIs(const char* key)
743 // Returns true iff the test name of test property matches on key_.
744 bool operator()(const TestProperty& test_property) const {
745 return String(test_property.key()).Compare(key_) == 0;
752 // Class UnitTestOptions.
754 // This class contains functions for processing options the user
755 // specifies when running the tests. It has only static members.
757 // In most cases, the user can specify an option using either an
758 // environment variable or a command line flag. E.g. you can set the
759 // test filter using either GTEST_FILTER or --gtest_filter. If both
760 // the variable and the flag are present, the latter overrides the
762 class GTEST_API_ UnitTestOptions {
764 // Functions for processing the gtest_output flag.
766 // Returns the output format, or "" for normal printed output.
767 static String GetOutputFormat();
769 // Returns the absolute path of the requested output file, or the
770 // default (test_detail.xml in the original working directory) if
771 // none was explicitly specified.
772 static String GetAbsolutePathToOutputFile();
774 // Functions for processing the gtest_filter flag.
776 // Returns true iff the wildcard pattern matches the string. The
777 // first ':' or '\0' character in pattern marks the end of it.
779 // This recursive algorithm isn't very efficient, but is clear and
780 // works well enough for matching test names, which are short.
781 static bool PatternMatchesString(const char *pattern, const char *str);
783 // Returns true iff the user-specified filter matches the test case
784 // name and the test name.
785 static bool FilterMatchesTest(const String &test_case_name,
786 const String &test_name);
789 // Function for supporting the gtest_catch_exception flag.
791 // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
792 // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
793 // This function is useful as an __except condition.
794 static int GTestShouldProcessSEH(DWORD exception_code);
795 #endif // GTEST_OS_WINDOWS
797 // Returns true if "name" matches the ':' separated list of glob-style
798 // filters in "filter".
799 static bool MatchesFilter(const String& name, const char* filter);
802 // Returns the current application's name, removing directory path if that
803 // is present. Used by UnitTestOptions::GetOutputFile.
804 GTEST_API_ FilePath GetCurrentExecutableName();
806 // The role interface for getting the OS stack trace as a string.
807 class OsStackTraceGetterInterface {
809 OsStackTraceGetterInterface() {}
810 virtual ~OsStackTraceGetterInterface() {}
812 // Returns the current OS stack trace as a String. Parameters:
814 // max_depth - the maximum number of stack frames to be included
816 // skip_count - the number of top frames to be skipped; doesn't count
817 // against max_depth.
818 virtual String CurrentStackTrace(int max_depth, int skip_count) = 0;
820 // UponLeavingGTest() should be called immediately before Google Test calls
821 // user code. It saves some information about the current stack that
822 // CurrentStackTrace() will use to find and hide Google Test stack frames.
823 virtual void UponLeavingGTest() = 0;
826 GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetterInterface);
829 // A working implementation of the OsStackTraceGetterInterface interface.
830 class OsStackTraceGetter : public OsStackTraceGetterInterface {
832 OsStackTraceGetter() : caller_frame_(NULL) {}
833 virtual String CurrentStackTrace(int max_depth, int skip_count);
834 virtual void UponLeavingGTest();
836 // This string is inserted in place of stack frames that are part of
837 // Google Test's implementation.
838 static const char* const kElidedFramesMarker;
841 Mutex mutex_; // protects all internal state
843 // We save the stack frame below the frame that calls user code.
844 // We do this because the address of the frame immediately below
845 // the user code changes between the call to UponLeavingGTest()
846 // and any calls to CurrentStackTrace() from within the user code.
849 GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetter);
852 // Information about a Google Test trace point.
859 // This is the default global test part result reporter used in UnitTestImpl.
860 // This class should only be used by UnitTestImpl.
861 class DefaultGlobalTestPartResultReporter
862 : public TestPartResultReporterInterface {
864 explicit DefaultGlobalTestPartResultReporter(UnitTestImpl* unit_test);
865 // Implements the TestPartResultReporterInterface. Reports the test part
866 // result in the current test.
867 virtual void ReportTestPartResult(const TestPartResult& result);
870 UnitTestImpl* const unit_test_;
872 GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultGlobalTestPartResultReporter);
875 // This is the default per thread test part result reporter used in
876 // UnitTestImpl. This class should only be used by UnitTestImpl.
877 class DefaultPerThreadTestPartResultReporter
878 : public TestPartResultReporterInterface {
880 explicit DefaultPerThreadTestPartResultReporter(UnitTestImpl* unit_test);
881 // Implements the TestPartResultReporterInterface. The implementation just
882 // delegates to the current global test part result reporter of *unit_test_.
883 virtual void ReportTestPartResult(const TestPartResult& result);
886 UnitTestImpl* const unit_test_;
888 GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultPerThreadTestPartResultReporter);
891 // The private implementation of the UnitTest class. We don't protect
892 // the methods under a mutex, as this class is not accessible by a
893 // user and the UnitTest class that delegates work to this class does
895 class GTEST_API_ UnitTestImpl {
897 explicit UnitTestImpl(UnitTest* parent);
898 virtual ~UnitTestImpl();
900 // There are two different ways to register your own TestPartResultReporter.
901 // You can register your own repoter to listen either only for test results
902 // from the current thread or for results from all threads.
903 // By default, each per-thread test result repoter just passes a new
904 // TestPartResult to the global test result reporter, which registers the
905 // test part result for the currently running test.
907 // Returns the global test part result reporter.
908 TestPartResultReporterInterface* GetGlobalTestPartResultReporter();
910 // Sets the global test part result reporter.
911 void SetGlobalTestPartResultReporter(
912 TestPartResultReporterInterface* reporter);
914 // Returns the test part result reporter for the current thread.
915 TestPartResultReporterInterface* GetTestPartResultReporterForCurrentThread();
917 // Sets the test part result reporter for the current thread.
918 void SetTestPartResultReporterForCurrentThread(
919 TestPartResultReporterInterface* reporter);
921 // Gets the number of successful test cases.
922 int successful_test_case_count() const;
924 // Gets the number of failed test cases.
925 int failed_test_case_count() const;
927 // Gets the number of all test cases.
928 int total_test_case_count() const;
930 // Gets the number of all test cases that contain at least one test
932 int test_case_to_run_count() const;
934 // Gets the number of successful tests.
935 int successful_test_count() const;
937 // Gets the number of failed tests.
938 int failed_test_count() const;
940 // Gets the number of disabled tests.
941 int disabled_test_count() const;
943 // Gets the number of all tests.
944 int total_test_count() const;
946 // Gets the number of tests that should run.
947 int test_to_run_count() const;
949 // Gets the elapsed time, in milliseconds.
950 TimeInMillis elapsed_time() const { return elapsed_time_; }
952 // Returns true iff the unit test passed (i.e. all test cases passed).
953 bool Passed() const { return !Failed(); }
955 // Returns true iff the unit test failed (i.e. some test case failed
956 // or something outside of all tests failed).
957 bool Failed() const {
958 return failed_test_case_count() > 0 || ad_hoc_test_result()->Failed();
961 // Gets the i-th test case among all the test cases. i can range from 0 to
962 // total_test_case_count() - 1. If i is not in that range, returns NULL.
963 const TestCase* GetTestCase(int i) const {
964 const int index = GetElementOr(test_case_indices_, i, -1);
965 return index < 0 ? NULL : test_cases_[i];
968 // Gets the i-th test case among all the test cases. i can range from 0 to
969 // total_test_case_count() - 1. If i is not in that range, returns NULL.
970 TestCase* GetMutableTestCase(int i) {
971 const int index = GetElementOr(test_case_indices_, i, -1);
972 return index < 0 ? NULL : test_cases_[index];
975 // Provides access to the event listener list.
976 TestEventListeners* listeners() { return &listeners_; }
978 // Returns the TestResult for the test that's currently running, or
979 // the TestResult for the ad hoc test if no test is running.
980 TestResult* current_test_result();
982 // Returns the TestResult for the ad hoc test.
983 const TestResult* ad_hoc_test_result() const { return &ad_hoc_test_result_; }
985 // Sets the OS stack trace getter.
987 // Does nothing if the input and the current OS stack trace getter
988 // are the same; otherwise, deletes the old getter and makes the
989 // input the current getter.
990 void set_os_stack_trace_getter(OsStackTraceGetterInterface* getter);
992 // Returns the current OS stack trace getter if it is not NULL;
993 // otherwise, creates an OsStackTraceGetter, makes it the current
994 // getter, and returns it.
995 OsStackTraceGetterInterface* os_stack_trace_getter();
997 // Returns the current OS stack trace as a String.
999 // The maximum number of stack frames to be included is specified by
1000 // the gtest_stack_trace_depth flag. The skip_count parameter
1001 // specifies the number of top frames to be skipped, which doesn't
1002 // count against the number of frames to be included.
1004 // For example, if Foo() calls Bar(), which in turn calls
1005 // CurrentOsStackTraceExceptTop(1), Foo() will be included in the
1006 // trace but Bar() and CurrentOsStackTraceExceptTop() won't.
1007 String CurrentOsStackTraceExceptTop(int skip_count);
1009 // Finds and returns a TestCase with the given name. If one doesn't
1010 // exist, creates one and returns it.
1014 // test_case_name: name of the test case
1015 // type_param: the name of the test's type parameter, or NULL if
1016 // this is not a typed or a type-parameterized test.
1017 // set_up_tc: pointer to the function that sets up the test case
1018 // tear_down_tc: pointer to the function that tears down the test case
1019 TestCase* GetTestCase(const char* test_case_name,
1020 const char* type_param,
1021 Test::SetUpTestCaseFunc set_up_tc,
1022 Test::TearDownTestCaseFunc tear_down_tc);
1024 // Adds a TestInfo to the unit test.
1028 // set_up_tc: pointer to the function that sets up the test case
1029 // tear_down_tc: pointer to the function that tears down the test case
1030 // test_info: the TestInfo object
1031 void AddTestInfo(Test::SetUpTestCaseFunc set_up_tc,
1032 Test::TearDownTestCaseFunc tear_down_tc,
1033 TestInfo* test_info) {
1034 // In order to support thread-safe death tests, we need to
1035 // remember the original working directory when the test program
1036 // was first invoked. We cannot do this in RUN_ALL_TESTS(), as
1037 // the user may have changed the current directory before calling
1038 // RUN_ALL_TESTS(). Therefore we capture the current directory in
1039 // AddTestInfo(), which is called to register a TEST or TEST_F
1040 // before main() is reached.
1041 if (original_working_dir_.IsEmpty()) {
1042 original_working_dir_.Set(FilePath::GetCurrentDir());
1043 GTEST_CHECK_(!original_working_dir_.IsEmpty())
1044 << "Failed to get the current working directory.";
1047 GetTestCase(test_info->test_case_name(),
1048 test_info->type_param(),
1050 tear_down_tc)->AddTestInfo(test_info);
1053 #if GTEST_HAS_PARAM_TEST
1054 // Returns ParameterizedTestCaseRegistry object used to keep track of
1055 // value-parameterized tests and instantiate and register them.
1056 internal::ParameterizedTestCaseRegistry& parameterized_test_registry() {
1057 return parameterized_test_registry_;
1059 #endif // GTEST_HAS_PARAM_TEST
1061 // Sets the TestCase object for the test that's currently running.
1062 void set_current_test_case(TestCase* a_current_test_case) {
1063 current_test_case_ = a_current_test_case;
1066 // Sets the TestInfo object for the test that's currently running. If
1067 // current_test_info is NULL, the assertion results will be stored in
1068 // ad_hoc_test_result_.
1069 void set_current_test_info(TestInfo* a_current_test_info) {
1070 current_test_info_ = a_current_test_info;
1073 // Registers all parameterized tests defined using TEST_P and
1074 // INSTANTIATE_TEST_CASE_P, creating regular tests for each test/parameter
1075 // combination. This method can be called more then once; it has guards
1076 // protecting from registering the tests more then once. If
1077 // value-parameterized tests are disabled, RegisterParameterizedTests is
1078 // present but does nothing.
1079 void RegisterParameterizedTests();
1081 // Runs all tests in this UnitTest object, prints the result, and
1082 // returns true if all tests are successful. If any exception is
1083 // thrown during a test, this test is considered to be failed, but
1084 // the rest of the tests will still be run.
1087 // Clears the results of all tests, except the ad hoc tests.
1088 void ClearNonAdHocTestResult() {
1089 ForEach(test_cases_, TestCase::ClearTestCaseResult);
1092 // Clears the results of ad-hoc test assertions.
1093 void ClearAdHocTestResult() {
1094 ad_hoc_test_result_.Clear();
1097 enum ReactionToSharding {
1098 HONOR_SHARDING_PROTOCOL,
1099 IGNORE_SHARDING_PROTOCOL
1102 // Matches the full name of each test against the user-specified
1103 // filter to decide whether the test should run, then records the
1104 // result in each TestCase and TestInfo object.
1105 // If shard_tests == HONOR_SHARDING_PROTOCOL, further filters tests
1106 // based on sharding variables in the environment.
1107 // Returns the number of tests that should run.
1108 int FilterTests(ReactionToSharding shard_tests);
1110 // Prints the names of the tests matching the user-specified filter flag.
1111 void ListTestsMatchingFilter();
1113 const TestCase* current_test_case() const { return current_test_case_; }
1114 TestInfo* current_test_info() { return current_test_info_; }
1115 const TestInfo* current_test_info() const { return current_test_info_; }
1117 // Returns the vector of environments that need to be set-up/torn-down
1118 // before/after the tests are run.
1119 std::vector<Environment*>& environments() { return environments_; }
1121 // Getters for the per-thread Google Test trace stack.
1122 std::vector<TraceInfo>& gtest_trace_stack() {
1123 return *(gtest_trace_stack_.pointer());
1125 const std::vector<TraceInfo>& gtest_trace_stack() const {
1126 return gtest_trace_stack_.get();
1129 #if GTEST_HAS_DEATH_TEST
1130 void InitDeathTestSubprocessControlInfo() {
1131 internal_run_death_test_flag_.reset(ParseInternalRunDeathTestFlag());
1133 // Returns a pointer to the parsed --gtest_internal_run_death_test
1134 // flag, or NULL if that flag was not specified.
1135 // This information is useful only in a death test child process.
1136 // Must not be called before a call to InitGoogleTest.
1137 const InternalRunDeathTestFlag* internal_run_death_test_flag() const {
1138 return internal_run_death_test_flag_.get();
1141 // Returns a pointer to the current death test factory.
1142 internal::DeathTestFactory* death_test_factory() {
1143 return death_test_factory_.get();
1146 void SuppressTestEventsIfInSubprocess();
1148 friend class ReplaceDeathTestFactory;
1149 #endif // GTEST_HAS_DEATH_TEST
1151 // Initializes the event listener performing XML output as specified by
1152 // UnitTestOptions. Must not be called before InitGoogleTest.
1153 void ConfigureXmlOutput();
1155 #if GTEST_CAN_STREAM_RESULTS_
1156 // Initializes the event listener for streaming test results to a socket.
1157 // Must not be called before InitGoogleTest.
1158 void ConfigureStreamingOutput();
1161 // Performs initialization dependent upon flag values obtained in
1162 // ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to
1163 // ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest
1164 // this function is also called from RunAllTests. Since this function can be
1165 // called more than once, it has to be idempotent.
1166 void PostFlagParsingInit();
1168 // Gets the random seed used at the start of the current test iteration.
1169 int random_seed() const { return random_seed_; }
1171 // Gets the random number generator.
1172 internal::Random* random() { return &random_; }
1174 // Shuffles all test cases, and the tests within each test case,
1175 // making sure that death tests are still run first.
1176 void ShuffleTests();
1178 // Restores the test cases and tests to their order before the first shuffle.
1179 void UnshuffleTests();
1181 // Returns the value of GTEST_FLAG(catch_exceptions) at the moment
1182 // UnitTest::Run() starts.
1183 bool catch_exceptions() const { return catch_exceptions_; }
1186 friend class ::testing::UnitTest;
1188 // Used by UnitTest::Run() to capture the state of
1189 // GTEST_FLAG(catch_exceptions) at the moment it starts.
1190 void set_catch_exceptions(bool value) { catch_exceptions_ = value; }
1192 // The UnitTest object that owns this implementation object.
1193 UnitTest* const parent_;
1195 // The working directory when the first TEST() or TEST_F() was
1197 internal::FilePath original_working_dir_;
1199 // The default test part result reporters.
1200 DefaultGlobalTestPartResultReporter default_global_test_part_result_reporter_;
1201 DefaultPerThreadTestPartResultReporter
1202 default_per_thread_test_part_result_reporter_;
1204 // Points to (but doesn't own) the global test part result reporter.
1205 TestPartResultReporterInterface* global_test_part_result_repoter_;
1207 // Protects read and write access to global_test_part_result_reporter_.
1208 internal::Mutex global_test_part_result_reporter_mutex_;
1210 // Points to (but doesn't own) the per-thread test part result reporter.
1211 internal::ThreadLocal<TestPartResultReporterInterface*>
1212 per_thread_test_part_result_reporter_;
1214 // The vector of environments that need to be set-up/torn-down
1215 // before/after the tests are run.
1216 std::vector<Environment*> environments_;
1218 // The vector of TestCases in their original order. It owns the
1219 // elements in the vector.
1220 std::vector<TestCase*> test_cases_;
1222 // Provides a level of indirection for the test case list to allow
1223 // easy shuffling and restoring the test case order. The i-th
1224 // element of this vector is the index of the i-th test case in the
1226 std::vector<int> test_case_indices_;
1228 #if GTEST_HAS_PARAM_TEST
1229 // ParameterizedTestRegistry object used to register value-parameterized
1231 internal::ParameterizedTestCaseRegistry parameterized_test_registry_;
1233 // Indicates whether RegisterParameterizedTests() has been called already.
1234 bool parameterized_tests_registered_;
1235 #endif // GTEST_HAS_PARAM_TEST
1237 // Index of the last death test case registered. Initially -1.
1238 int last_death_test_case_;
1240 // This points to the TestCase for the currently running test. It
1241 // changes as Google Test goes through one test case after another.
1242 // When no test is running, this is set to NULL and Google Test
1243 // stores assertion results in ad_hoc_test_result_. Initially NULL.
1244 TestCase* current_test_case_;
1246 // This points to the TestInfo for the currently running test. It
1247 // changes as Google Test goes through one test after another. When
1248 // no test is running, this is set to NULL and Google Test stores
1249 // assertion results in ad_hoc_test_result_. Initially NULL.
1250 TestInfo* current_test_info_;
1252 // Normally, a user only writes assertions inside a TEST or TEST_F,
1253 // or inside a function called by a TEST or TEST_F. Since Google
1254 // Test keeps track of which test is current running, it can
1255 // associate such an assertion with the test it belongs to.
1257 // If an assertion is encountered when no TEST or TEST_F is running,
1258 // Google Test attributes the assertion result to an imaginary "ad hoc"
1259 // test, and records the result in ad_hoc_test_result_.
1260 TestResult ad_hoc_test_result_;
1262 // The list of event listeners that can be used to track events inside
1264 TestEventListeners listeners_;
1266 // The OS stack trace getter. Will be deleted when the UnitTest
1267 // object is destructed. By default, an OsStackTraceGetter is used,
1268 // but the user can set this field to use a custom getter if that is
1270 OsStackTraceGetterInterface* os_stack_trace_getter_;
1272 // True iff PostFlagParsingInit() has been called.
1273 bool post_flag_parse_init_performed_;
1275 // The random number seed used at the beginning of the test run.
1278 // Our random number generator.
1279 internal::Random random_;
1281 // How long the test took to run, in milliseconds.
1282 TimeInMillis elapsed_time_;
1284 #if GTEST_HAS_DEATH_TEST
1285 // The decomposed components of the gtest_internal_run_death_test flag,
1286 // parsed when RUN_ALL_TESTS is called.
1287 internal::scoped_ptr<InternalRunDeathTestFlag> internal_run_death_test_flag_;
1288 internal::scoped_ptr<internal::DeathTestFactory> death_test_factory_;
1289 #endif // GTEST_HAS_DEATH_TEST
1291 // A per-thread stack of traces created by the SCOPED_TRACE() macro.
1292 internal::ThreadLocal<std::vector<TraceInfo> > gtest_trace_stack_;
1294 // The value of GTEST_FLAG(catch_exceptions) at the moment RunAllTests()
1296 bool catch_exceptions_;
1298 GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTestImpl);
1299 }; // class UnitTestImpl
1301 // Convenience function for accessing the global UnitTest
1302 // implementation object.
1303 inline UnitTestImpl* GetUnitTestImpl() {
1304 return UnitTest::GetInstance()->impl();
1307 #if GTEST_USES_SIMPLE_RE
1309 // Internal helper functions for implementing the simple regular
1310 // expression matcher.
1311 GTEST_API_ bool IsInSet(char ch, const char* str);
1312 GTEST_API_ bool IsAsciiDigit(char ch);
1313 GTEST_API_ bool IsAsciiPunct(char ch);
1314 GTEST_API_ bool IsRepeat(char ch);
1315 GTEST_API_ bool IsAsciiWhiteSpace(char ch);
1316 GTEST_API_ bool IsAsciiWordChar(char ch);
1317 GTEST_API_ bool IsValidEscape(char ch);
1318 GTEST_API_ bool AtomMatchesChar(bool escaped, char pattern, char ch);
1319 GTEST_API_ bool ValidateRegex(const char* regex);
1320 GTEST_API_ bool MatchRegexAtHead(const char* regex, const char* str);
1321 GTEST_API_ bool MatchRepetitionAndRegexAtHead(
1322 bool escaped, char ch, char repeat, const char* regex, const char* str);
1323 GTEST_API_ bool MatchRegexAnywhere(const char* regex, const char* str);
1325 #endif // GTEST_USES_SIMPLE_RE
1327 // Parses the command line for Google Test flags, without initializing
1328 // other parts of Google Test.
1329 GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, char** argv);
1330 GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv);
1332 #if GTEST_HAS_DEATH_TEST
1334 // Returns the message describing the last system error, regardless of the
1336 GTEST_API_ String GetLastErrnoDescription();
1338 # if GTEST_OS_WINDOWS
1339 // Provides leak-safe Windows kernel handle ownership.
1342 AutoHandle() : handle_(INVALID_HANDLE_VALUE) {}
1343 explicit AutoHandle(HANDLE handle) : handle_(handle) {}
1345 ~AutoHandle() { Reset(); }
1347 HANDLE Get() const { return handle_; }
1348 void Reset() { Reset(INVALID_HANDLE_VALUE); }
1349 void Reset(HANDLE handle) {
1350 if (handle != handle_) {
1351 if (handle_ != INVALID_HANDLE_VALUE)
1352 ::CloseHandle(handle_);
1360 GTEST_DISALLOW_COPY_AND_ASSIGN_(AutoHandle);
1362 # endif // GTEST_OS_WINDOWS
1364 // Attempts to parse a string into a positive integer pointed to by the
1365 // number parameter. Returns true if that is possible.
1366 // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we can use
1368 template <typename Integer>
1369 bool ParseNaturalNumber(const ::std::string& str, Integer* number) {
1370 // Fail fast if the given string does not begin with a digit;
1371 // this bypasses strtoXXX's "optional leading whitespace and plus
1372 // or minus sign" semantics, which are undesirable here.
1373 if (str.empty() || !IsDigit(str[0])) {
1379 // BiggestConvertible is the largest integer type that system-provided
1380 // string-to-number conversion routines can return.
1382 # if GTEST_OS_WINDOWS && !defined(__GNUC__)
1384 // MSVC and C++ Builder define __int64 instead of the standard long long.
1385 typedef unsigned __int64 BiggestConvertible;
1386 const BiggestConvertible parsed = _strtoui64(str.c_str(), &end, 10);
1390 typedef unsigned long long BiggestConvertible; // NOLINT
1391 const BiggestConvertible parsed = strtoull(str.c_str(), &end, 10);
1393 # endif // GTEST_OS_WINDOWS && !defined(__GNUC__)
1395 const bool parse_success = *end == '\0' && errno == 0;
1397 // TODO(vladl@google.com): Convert this to compile time assertion when it is
1399 GTEST_CHECK_(sizeof(Integer) <= sizeof(parsed));
1401 const Integer result = static_cast<Integer>(parsed);
1402 if (parse_success && static_cast<BiggestConvertible>(result) == parsed) {
1408 #endif // GTEST_HAS_DEATH_TEST
1410 // TestResult contains some private methods that should be hidden from
1411 // Google Test user but are required for testing. This class allow our tests
1414 // This class is supplied only for the purpose of testing Google Test's own
1415 // constructs. Do not use it in user tests, either directly or indirectly.
1416 class TestResultAccessor {
1418 static void RecordProperty(TestResult* test_result,
1419 const TestProperty& property) {
1420 test_result->RecordProperty(property);
1423 static void ClearTestPartResults(TestResult* test_result) {
1424 test_result->ClearTestPartResults();
1427 static const std::vector<testing::TestPartResult>& test_part_results(
1428 const TestResult& test_result) {
1429 return test_result.test_part_results();
1433 } // namespace internal
1434 } // namespace testing
1436 #endif // GTEST_SRC_GTEST_INTERNAL_INL_H_
1437 #undef GTEST_IMPLEMENTATION_
1439 #if GTEST_OS_WINDOWS
1440 # define vsnprintf _vsnprintf
1441 #endif // GTEST_OS_WINDOWS
1445 using internal::CountIf;
1446 using internal::ForEach;
1447 using internal::GetElementOr;
1448 using internal::Shuffle;
1452 // A test whose test case name or test name matches this filter is
1453 // disabled and not run.
1454 static const char kDisableTestFilter[] = "DISABLED_*:*/DISABLED_*";
1456 // A test case whose name matches this filter is considered a death
1457 // test case and will be run before test cases whose name doesn't
1458 // match this filter.
1459 static const char kDeathTestCaseFilter[] = "*DeathTest:*DeathTest/*";
1461 // A test filter that matches everything.
1462 static const char kUniversalFilter[] = "*";
1464 // The default output file for XML output.
1465 static const char kDefaultOutputFile[] = "test_detail.xml";
1467 // The environment variable name for the test shard index.
1468 static const char kTestShardIndex[] = "GTEST_SHARD_INDEX";
1469 // The environment variable name for the total number of test shards.
1470 static const char kTestTotalShards[] = "GTEST_TOTAL_SHARDS";
1471 // The environment variable name for the test shard status file.
1472 static const char kTestShardStatusFile[] = "GTEST_SHARD_STATUS_FILE";
1474 namespace internal {
1476 // The text used in failure messages to indicate the start of the
1478 const char kStackTraceMarker[] = "\nStack trace:\n";
1480 // g_help_flag is true iff the --help flag or an equivalent form is
1481 // specified on the command line.
1482 bool g_help_flag = false;
1484 } // namespace internal
1487 also_run_disabled_tests,
1488 internal::BoolFromGTestEnv("also_run_disabled_tests", false),
1489 "Run disabled tests too, in addition to the tests normally being run.");
1493 internal::BoolFromGTestEnv("break_on_failure", false),
1494 "True iff a failed assertion should be a debugger break-point.");
1498 internal::BoolFromGTestEnv("catch_exceptions", true),
1499 "True iff " GTEST_NAME_
1500 " should catch exceptions and treat them as test failures.");
1502 GTEST_DEFINE_string_(
1504 internal::StringFromGTestEnv("color", "auto"),
1505 "Whether to use colors in the output. Valid values: yes, no, "
1506 "and auto. 'auto' means to use colors if the output is "
1507 "being sent to a terminal and the TERM environment variable "
1508 "is set to xterm, xterm-color, xterm-256color, linux or cygwin.");
1510 GTEST_DEFINE_string_(
1512 internal::StringFromGTestEnv("filter", kUniversalFilter),
1513 "A colon-separated list of glob (not regex) patterns "
1514 "for filtering the tests to run, optionally followed by a "
1515 "'-' and a : separated list of negative patterns (tests to "
1516 "exclude). A test is run if it matches one of the positive "
1517 "patterns and does not match any of the negative patterns.");
1519 GTEST_DEFINE_bool_(list_tests, false,
1520 "List all tests without running them.");
1522 GTEST_DEFINE_string_(
1524 internal::StringFromGTestEnv("output", ""),
1525 "A format (currently must be \"xml\"), optionally followed "
1526 "by a colon and an output file name or directory. A directory "
1527 "is indicated by a trailing pathname separator. "
1528 "Examples: \"xml:filename.xml\", \"xml::directoryname/\". "
1529 "If a directory is specified, output files will be created "
1530 "within that directory, with file-names based on the test "
1531 "executable's name and, if necessary, made unique by adding "
1536 internal::BoolFromGTestEnv("print_time", true),
1537 "True iff " GTEST_NAME_
1538 " should display elapsed time in text output.");
1540 GTEST_DEFINE_int32_(
1542 internal::Int32FromGTestEnv("random_seed", 0),
1543 "Random number seed to use when shuffling test orders. Must be in range "
1544 "[1, 99999], or 0 to use a seed based on the current time.");
1546 GTEST_DEFINE_int32_(
1548 internal::Int32FromGTestEnv("repeat", 1),
1549 "How many times to repeat each test. Specify a negative number "
1550 "for repeating forever. Useful for shaking out flaky tests.");
1553 show_internal_stack_frames, false,
1554 "True iff " GTEST_NAME_ " should include internal stack frames when "
1555 "printing test failure stack traces.");
1559 internal::BoolFromGTestEnv("shuffle", false),
1560 "True iff " GTEST_NAME_
1561 " should randomize tests' order on every run.");
1563 GTEST_DEFINE_int32_(
1565 internal::Int32FromGTestEnv("stack_trace_depth", kMaxStackTraceDepth),
1566 "The maximum number of stack frames to print when an "
1567 "assertion fails. The valid range is 0 through 100, inclusive.");
1569 GTEST_DEFINE_string_(
1571 internal::StringFromGTestEnv("stream_result_to", ""),
1572 "This flag specifies the host name and the port number on which to stream "
1573 "test results. Example: \"localhost:555\". The flag is effective only on "
1578 internal::BoolFromGTestEnv("throw_on_failure", false),
1579 "When this flag is specified, a failed assertion will throw an exception "
1580 "if exceptions are enabled or exit the program with a non-zero code "
1583 namespace internal {
1585 // Generates a random number from [0, range), using a Linear
1586 // Congruential Generator (LCG). Crashes if 'range' is 0 or greater
1588 UInt32 Random::Generate(UInt32 range) {
1589 // These constants are the same as are used in glibc's rand(3).
1590 state_ = (1103515245U*state_ + 12345U) % kMaxRange;
1592 GTEST_CHECK_(range > 0)
1593 << "Cannot generate a number in the range [0, 0).";
1594 GTEST_CHECK_(range <= kMaxRange)
1595 << "Generation of a number in [0, " << range << ") was requested, "
1596 << "but this can only generate numbers in [0, " << kMaxRange << ").";
1598 // Converting via modulus introduces a bit of downward bias, but
1599 // it's simple, and a linear congruential generator isn't too good
1601 return state_ % range;
1604 // GTestIsInitialized() returns true iff the user has initialized
1605 // Google Test. Useful for catching the user mistake of not initializing
1606 // Google Test before calling RUN_ALL_TESTS().
1608 // A user must call testing::InitGoogleTest() to initialize Google
1609 // Test. g_init_gtest_count is set to the number of times
1610 // InitGoogleTest() has been called. We don't protect this variable
1611 // under a mutex as it is only accessed in the main thread.
1612 int g_init_gtest_count = 0;
1613 static bool GTestIsInitialized() { return g_init_gtest_count != 0; }
1615 // Iterates over a vector of TestCases, keeping a running sum of the
1616 // results of calling a given int-returning method on each.
1618 static int SumOverTestCaseList(const std::vector<TestCase*>& case_list,
1619 int (TestCase::*method)() const) {
1621 for (size_t i = 0; i < case_list.size(); i++) {
1622 sum += (case_list[i]->*method)();
1627 // Returns true iff the test case passed.
1628 static bool TestCasePassed(const TestCase* test_case) {
1629 return test_case->should_run() && test_case->Passed();
1632 // Returns true iff the test case failed.
1633 static bool TestCaseFailed(const TestCase* test_case) {
1634 return test_case->should_run() && test_case->Failed();
1637 // Returns true iff test_case contains at least one test that should
1639 static bool ShouldRunTestCase(const TestCase* test_case) {
1640 return test_case->should_run();
1643 // AssertHelper constructor.
1644 AssertHelper::AssertHelper(TestPartResult::Type type,
1647 const char* message)
1648 : data_(new AssertHelperData(type, file, line, message)) {
1651 AssertHelper::~AssertHelper() {
1655 // Message assignment, for assertion streaming support.
1656 void AssertHelper::operator=(const Message& message) const {
1657 UnitTest::GetInstance()->
1658 AddTestPartResult(data_->type, data_->file, data_->line,
1659 AppendUserMessage(data_->message, message),
1660 UnitTest::GetInstance()->impl()
1661 ->CurrentOsStackTraceExceptTop(1)
1662 // Skips the stack frame for this function itself.
1666 // Mutex for linked pointers.
1667 GTEST_DEFINE_STATIC_MUTEX_(g_linked_ptr_mutex);
1669 // Application pathname gotten in InitGoogleTest.
1670 String g_executable_path;
1672 // Returns the current application's name, removing directory path if that
1674 FilePath GetCurrentExecutableName() {
1677 #if GTEST_OS_WINDOWS
1678 result.Set(FilePath(g_executable_path).RemoveExtension("exe"));
1680 result.Set(FilePath(g_executable_path));
1681 #endif // GTEST_OS_WINDOWS
1683 return result.RemoveDirectoryName();
1686 // Functions for processing the gtest_output flag.
1688 // Returns the output format, or "" for normal printed output.
1689 String UnitTestOptions::GetOutputFormat() {
1690 const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
1691 if (gtest_output_flag == NULL) return String("");
1693 const char* const colon = strchr(gtest_output_flag, ':');
1694 return (colon == NULL) ?
1695 String(gtest_output_flag) :
1696 String(gtest_output_flag, colon - gtest_output_flag);
1699 // Returns the name of the requested output file, or the default if none
1700 // was explicitly specified.
1701 String UnitTestOptions::GetAbsolutePathToOutputFile() {
1702 const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
1703 if (gtest_output_flag == NULL)
1706 const char* const colon = strchr(gtest_output_flag, ':');
1708 return String(internal::FilePath::ConcatPaths(
1710 UnitTest::GetInstance()->original_working_dir()),
1711 internal::FilePath(kDefaultOutputFile)).ToString() );
1713 internal::FilePath output_name(colon + 1);
1714 if (!output_name.IsAbsolutePath())
1715 // TODO(wan@google.com): on Windows \some\path is not an absolute
1716 // path (as its meaning depends on the current drive), yet the
1717 // following logic for turning it into an absolute path is wrong.
1719 output_name = internal::FilePath::ConcatPaths(
1720 internal::FilePath(UnitTest::GetInstance()->original_working_dir()),
1721 internal::FilePath(colon + 1));
1723 if (!output_name.IsDirectory())
1724 return output_name.ToString();
1726 internal::FilePath result(internal::FilePath::GenerateUniqueFileName(
1727 output_name, internal::GetCurrentExecutableName(),
1728 GetOutputFormat().c_str()));
1729 return result.ToString();
1732 // Returns true iff the wildcard pattern matches the string. The
1733 // first ':' or '\0' character in pattern marks the end of it.
1735 // This recursive algorithm isn't very efficient, but is clear and
1736 // works well enough for matching test names, which are short.
1737 bool UnitTestOptions::PatternMatchesString(const char *pattern,
1741 case ':': // Either ':' or '\0' marks the end of the pattern.
1742 return *str == '\0';
1743 case '?': // Matches any single character.
1744 return *str != '\0' && PatternMatchesString(pattern + 1, str + 1);
1745 case '*': // Matches any string (possibly empty) of characters.
1746 return (*str != '\0' && PatternMatchesString(pattern, str + 1)) ||
1747 PatternMatchesString(pattern + 1, str);
1748 default: // Non-special character. Matches itself.
1749 return *pattern == *str &&
1750 PatternMatchesString(pattern + 1, str + 1);
1754 bool UnitTestOptions::MatchesFilter(const String& name, const char* filter) {
1755 const char *cur_pattern = filter;
1757 if (PatternMatchesString(cur_pattern, name.c_str())) {
1761 // Finds the next pattern in the filter.
1762 cur_pattern = strchr(cur_pattern, ':');
1764 // Returns if no more pattern can be found.
1765 if (cur_pattern == NULL) {
1769 // Skips the pattern separater (the ':' character).
1774 // TODO(keithray): move String function implementations to gtest-string.cc.
1776 // Returns true iff the user-specified filter matches the test case
1777 // name and the test name.
1778 bool UnitTestOptions::FilterMatchesTest(const String &test_case_name,
1779 const String &test_name) {
1780 const String& full_name = String::Format("%s.%s",
1781 test_case_name.c_str(),
1784 // Split --gtest_filter at '-', if there is one, to separate into
1785 // positive filter and negative filter portions
1786 const char* const p = GTEST_FLAG(filter).c_str();
1787 const char* const dash = strchr(p, '-');
1791 positive = GTEST_FLAG(filter).c_str(); // Whole string is a positive filter
1792 negative = String("");
1794 positive = String(p, dash - p); // Everything up to the dash
1795 negative = String(dash+1); // Everything after the dash
1796 if (positive.empty()) {
1797 // Treat '-test1' as the same as '*-test1'
1798 positive = kUniversalFilter;
1802 // A filter is a colon-separated list of patterns. It matches a
1803 // test if any pattern in it matches the test.
1804 return (MatchesFilter(full_name, positive.c_str()) &&
1805 !MatchesFilter(full_name, negative.c_str()));
1809 // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
1810 // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
1811 // This function is useful as an __except condition.
1812 int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) {
1813 // Google Test should handle a SEH exception if:
1814 // 1. the user wants it to, AND
1815 // 2. this is not a breakpoint exception, AND
1816 // 3. this is not a C++ exception (VC++ implements them via SEH,
1819 // SEH exception code for C++ exceptions.
1820 // (see http://support.microsoft.com/kb/185294 for more information).
1821 const DWORD kCxxExceptionCode = 0xe06d7363;
1823 bool should_handle = true;
1825 if (!GTEST_FLAG(catch_exceptions))
1826 should_handle = false;
1827 else if (exception_code == EXCEPTION_BREAKPOINT)
1828 should_handle = false;
1829 else if (exception_code == kCxxExceptionCode)
1830 should_handle = false;
1832 return should_handle ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH;
1834 #endif // GTEST_HAS_SEH
1836 } // namespace internal
1838 // The c'tor sets this object as the test part result reporter used by
1839 // Google Test. The 'result' parameter specifies where to report the
1840 // results. Intercepts only failures from the current thread.
1841 ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
1842 TestPartResultArray* result)
1843 : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD),
1848 // The c'tor sets this object as the test part result reporter used by
1849 // Google Test. The 'result' parameter specifies where to report the
1851 ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
1852 InterceptMode intercept_mode, TestPartResultArray* result)
1853 : intercept_mode_(intercept_mode),
1858 void ScopedFakeTestPartResultReporter::Init() {
1859 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
1860 if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
1861 old_reporter_ = impl->GetGlobalTestPartResultReporter();
1862 impl->SetGlobalTestPartResultReporter(this);
1864 old_reporter_ = impl->GetTestPartResultReporterForCurrentThread();
1865 impl->SetTestPartResultReporterForCurrentThread(this);
1869 // The d'tor restores the test part result reporter used by Google Test
1871 ScopedFakeTestPartResultReporter::~ScopedFakeTestPartResultReporter() {
1872 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
1873 if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
1874 impl->SetGlobalTestPartResultReporter(old_reporter_);
1876 impl->SetTestPartResultReporterForCurrentThread(old_reporter_);
1880 // Increments the test part result count and remembers the result.
1881 // This method is from the TestPartResultReporterInterface interface.
1882 void ScopedFakeTestPartResultReporter::ReportTestPartResult(
1883 const TestPartResult& result) {
1884 result_->Append(result);
1887 namespace internal {
1889 // Returns the type ID of ::testing::Test. We should always call this
1890 // instead of GetTypeId< ::testing::Test>() to get the type ID of
1891 // testing::Test. This is to work around a suspected linker bug when
1892 // using Google Test as a framework on Mac OS X. The bug causes
1893 // GetTypeId< ::testing::Test>() to return different values depending
1894 // on whether the call is from the Google Test framework itself or
1895 // from user test code. GetTestTypeId() is guaranteed to always
1896 // return the same value, as it always calls GetTypeId<>() from the
1897 // gtest.cc, which is within the Google Test framework.
1898 TypeId GetTestTypeId() {
1899 return GetTypeId<Test>();
1902 // The value of GetTestTypeId() as seen from within the Google Test
1903 // library. This is solely for testing GetTestTypeId().
1904 extern const TypeId kTestTypeIdInGoogleTest = GetTestTypeId();
1906 // This predicate-formatter checks that 'results' contains a test part
1907 // failure of the given type and that the failure message contains the
1909 AssertionResult HasOneFailure(const char* /* results_expr */,
1910 const char* /* type_expr */,
1911 const char* /* substr_expr */,
1912 const TestPartResultArray& results,
1913 TestPartResult::Type type,
1914 const string& substr) {
1915 const String expected(type == TestPartResult::kFatalFailure ?
1917 "1 non-fatal failure");
1919 if (results.size() != 1) {
1920 msg << "Expected: " << expected << "\n"
1921 << " Actual: " << results.size() << " failures";
1922 for (int i = 0; i < results.size(); i++) {
1923 msg << "\n" << results.GetTestPartResult(i);
1925 return AssertionFailure() << msg;
1928 const TestPartResult& r = results.GetTestPartResult(0);
1929 if (r.type() != type) {
1930 return AssertionFailure() << "Expected: " << expected << "\n"
1935 if (strstr(r.message(), substr.c_str()) == NULL) {
1936 return AssertionFailure() << "Expected: " << expected << " containing \""
1942 return AssertionSuccess();
1945 // The constructor of SingleFailureChecker remembers where to look up
1946 // test part results, what type of failure we expect, and what
1947 // substring the failure message should contain.
1948 SingleFailureChecker:: SingleFailureChecker(
1949 const TestPartResultArray* results,
1950 TestPartResult::Type type,
1951 const string& substr)
1952 : results_(results),
1956 // The destructor of SingleFailureChecker verifies that the given
1957 // TestPartResultArray contains exactly one failure that has the given
1958 // type and contains the given substring. If that's not the case, a
1959 // non-fatal failure will be generated.
1960 SingleFailureChecker::~SingleFailureChecker() {
1961 EXPECT_PRED_FORMAT3(HasOneFailure, *results_, type_, substr_);
1964 DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter(
1965 UnitTestImpl* unit_test) : unit_test_(unit_test) {}
1967 void DefaultGlobalTestPartResultReporter::ReportTestPartResult(
1968 const TestPartResult& result) {
1969 unit_test_->current_test_result()->AddTestPartResult(result);
1970 unit_test_->listeners()->repeater()->OnTestPartResult(result);
1973 DefaultPerThreadTestPartResultReporter::DefaultPerThreadTestPartResultReporter(
1974 UnitTestImpl* unit_test) : unit_test_(unit_test) {}
1976 void DefaultPerThreadTestPartResultReporter::ReportTestPartResult(
1977 const TestPartResult& result) {
1978 unit_test_->GetGlobalTestPartResultReporter()->ReportTestPartResult(result);
1981 // Returns the global test part result reporter.
1982 TestPartResultReporterInterface*
1983 UnitTestImpl::GetGlobalTestPartResultReporter() {
1984 internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
1985 return global_test_part_result_repoter_;
1988 // Sets the global test part result reporter.
1989 void UnitTestImpl::SetGlobalTestPartResultReporter(
1990 TestPartResultReporterInterface* reporter) {
1991 internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
1992 global_test_part_result_repoter_ = reporter;
1995 // Returns the test part result reporter for the current thread.
1996 TestPartResultReporterInterface*
1997 UnitTestImpl::GetTestPartResultReporterForCurrentThread() {
1998 return per_thread_test_part_result_reporter_.get();
2001 // Sets the test part result reporter for the current thread.
2002 void UnitTestImpl::SetTestPartResultReporterForCurrentThread(
2003 TestPartResultReporterInterface* reporter) {
2004 per_thread_test_part_result_reporter_.set(reporter);
2007 // Gets the number of successful test cases.
2008 int UnitTestImpl::successful_test_case_count() const {
2009 return CountIf(test_cases_, TestCasePassed);
2012 // Gets the number of failed test cases.
2013 int UnitTestImpl::failed_test_case_count() const {
2014 return CountIf(test_cases_, TestCaseFailed);
2017 // Gets the number of all test cases.
2018 int UnitTestImpl::total_test_case_count() const {
2019 return static_cast<int>(test_cases_.size());
2022 // Gets the number of all test cases that contain at least one test
2024 int UnitTestImpl::test_case_to_run_count() const {
2025 return CountIf(test_cases_, ShouldRunTestCase);
2028 // Gets the number of successful tests.
2029 int UnitTestImpl::successful_test_count() const {
2030 return SumOverTestCaseList(test_cases_, &TestCase::successful_test_count);
2033 // Gets the number of failed tests.
2034 int UnitTestImpl::failed_test_count() const {
2035 return SumOverTestCaseList(test_cases_, &TestCase::failed_test_count);
2038 // Gets the number of disabled tests.
2039 int UnitTestImpl::disabled_test_count() const {
2040 return SumOverTestCaseList(test_cases_, &TestCase::disabled_test_count);
2043 // Gets the number of all tests.
2044 int UnitTestImpl::total_test_count() const {
2045 return SumOverTestCaseList(test_cases_, &TestCase::total_test_count);
2048 // Gets the number of tests that should run.
2049 int UnitTestImpl::test_to_run_count() const {
2050 return SumOverTestCaseList(test_cases_, &TestCase::test_to_run_count);
2053 // Returns the current OS stack trace as a String.
2055 // The maximum number of stack frames to be included is specified by
2056 // the gtest_stack_trace_depth flag. The skip_count parameter
2057 // specifies the number of top frames to be skipped, which doesn't
2058 // count against the number of frames to be included.
2060 // For example, if Foo() calls Bar(), which in turn calls
2061 // CurrentOsStackTraceExceptTop(1), Foo() will be included in the
2062 // trace but Bar() and CurrentOsStackTraceExceptTop() won't.
2063 String UnitTestImpl::CurrentOsStackTraceExceptTop(int skip_count) {
2068 // Returns the current time in milliseconds.
2069 TimeInMillis GetTimeInMillis() {
2070 #if GTEST_OS_WINDOWS_MOBILE || defined(__BORLANDC__)
2071 // Difference between 1970-01-01 and 1601-01-01 in milliseconds.
2072 // http://analogous.blogspot.com/2005/04/epoch.html
2073 const TimeInMillis kJavaEpochToWinFileTimeDelta =
2074 static_cast<TimeInMillis>(116444736UL) * 100000UL;
2075 const DWORD kTenthMicrosInMilliSecond = 10000;
2077 SYSTEMTIME now_systime;
2078 FILETIME now_filetime;
2079 ULARGE_INTEGER now_int64;
2080 // TODO(kenton@google.com): Shouldn't this just use
2081 // GetSystemTimeAsFileTime()?
2082 GetSystemTime(&now_systime);
2083 if (SystemTimeToFileTime(&now_systime, &now_filetime)) {
2084 now_int64.LowPart = now_filetime.dwLowDateTime;
2085 now_int64.HighPart = now_filetime.dwHighDateTime;
2086 now_int64.QuadPart = (now_int64.QuadPart / kTenthMicrosInMilliSecond) -
2087 kJavaEpochToWinFileTimeDelta;
2088 return now_int64.QuadPart;
2091 #elif GTEST_OS_WINDOWS && !GTEST_HAS_GETTIMEOFDAY_
2096 // MSVC 8 deprecates _ftime64(), so we want to suppress warning 4996
2097 // (deprecated function) there.
2098 // TODO(kenton@google.com): Use GetTickCount()? Or use
2099 // SystemTimeToFileTime()
2100 # pragma warning(push) // Saves the current warning state.
2101 # pragma warning(disable:4996) // Temporarily disables warning 4996.
2103 # pragma warning(pop) // Restores the warning state.
2110 return static_cast<TimeInMillis>(now.time) * 1000 + now.millitm;
2111 #elif GTEST_HAS_GETTIMEOFDAY_
2113 gettimeofday(&now, NULL);
2114 return static_cast<TimeInMillis>(now.tv_sec) * 1000 + now.tv_usec / 1000;
2116 # error "Don't know how to get the current time on your system."
2124 // Returns the input enclosed in double quotes if it's not NULL;
2125 // otherwise returns "(null)". For example, "\"Hello\"" is returned
2126 // for input "Hello".
2128 // This is useful for printing a C string in the syntax of a literal.
2130 // Known issue: escape sequences are not handled yet.
2131 String String::ShowCStringQuoted(const char* c_str) {
2132 return c_str ? String::Format("\"%s\"", c_str) : String("(null)");
2135 // Copies at most length characters from str into a newly-allocated
2136 // piece of memory of size length+1. The memory is allocated with new[].
2137 // A terminating null byte is written to the memory, and a pointer to it
2138 // is returned. If str is NULL, NULL is returned.
2139 static char* CloneString(const char* str, size_t length) {
2143 char* const clone = new char[length + 1];
2144 posix::StrNCpy(clone, str, length);
2145 clone[length] = '\0';
2150 // Clones a 0-terminated C string, allocating memory using new. The
2151 // caller is responsible for deleting[] the return value. Returns the
2152 // cloned string, or NULL if the input is NULL.
2153 const char * String::CloneCString(const char* c_str) {
2154 return (c_str == NULL) ?
2155 NULL : CloneString(c_str, strlen(c_str));
2158 #if GTEST_OS_WINDOWS_MOBILE
2159 // Creates a UTF-16 wide string from the given ANSI string, allocating
2160 // memory using new. The caller is responsible for deleting the return
2161 // value using delete[]. Returns the wide string, or NULL if the
2163 LPCWSTR String::AnsiToUtf16(const char* ansi) {
2164 if (!ansi) return NULL;
2165 const int length = strlen(ansi);
2166 const int unicode_length =
2167 MultiByteToWideChar(CP_ACP, 0, ansi, length,
2169 WCHAR* unicode = new WCHAR[unicode_length + 1];
2170 MultiByteToWideChar(CP_ACP, 0, ansi, length,
2171 unicode, unicode_length);
2172 unicode[unicode_length] = 0;
2176 // Creates an ANSI string from the given wide string, allocating
2177 // memory using new. The caller is responsible for deleting the return
2178 // value using delete[]. Returns the ANSI string, or NULL if the
2180 const char* String::Utf16ToAnsi(LPCWSTR utf16_str) {
2181 if (!utf16_str) return NULL;
2182 const int ansi_length =
2183 WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
2184 NULL, 0, NULL, NULL);
2185 char* ansi = new char[ansi_length + 1];
2186 WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
2187 ansi, ansi_length, NULL, NULL);
2188 ansi[ansi_length] = 0;
2192 #endif // GTEST_OS_WINDOWS_MOBILE
2194 // Compares two C strings. Returns true iff they have the same content.
2196 // Unlike strcmp(), this function can handle NULL argument(s). A NULL
2197 // C string is considered different to any non-NULL C string,
2198 // including the empty string.
2199 bool String::CStringEquals(const char * lhs, const char * rhs) {
2200 if ( lhs == NULL ) return rhs == NULL;
2202 if ( rhs == NULL ) return false;
2204 return strcmp(lhs, rhs) == 0;
2207 #if GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
2209 // Converts an array of wide chars to a narrow string using the UTF-8
2210 // encoding, and streams the result to the given Message object.
2211 static void StreamWideCharsToMessage(const wchar_t* wstr, size_t length,
2213 // TODO(wan): consider allowing a testing::String object to
2214 // contain '\0'. This will make it behave more like std::string,
2215 // and will allow ToUtf8String() to return the correct encoding
2216 // for '\0' s.t. we can get rid of the conditional here (and in
2217 // several other places).
2218 for (size_t i = 0; i != length; ) { // NOLINT
2219 if (wstr[i] != L'\0') {
2220 *msg << WideStringToUtf8(wstr + i, static_cast<int>(length - i));
2221 while (i != length && wstr[i] != L'\0')
2230 #endif // GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
2232 } // namespace internal
2234 #if GTEST_HAS_STD_WSTRING
2235 // Converts the given wide string to a narrow string using the UTF-8
2236 // encoding, and streams the result to this Message object.
2237 Message& Message::operator <<(const ::std::wstring& wstr) {
2238 internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
2241 #endif // GTEST_HAS_STD_WSTRING
2243 #if GTEST_HAS_GLOBAL_WSTRING
2244 // Converts the given wide string to a narrow string using the UTF-8
2245 // encoding, and streams the result to this Message object.
2246 Message& Message::operator <<(const ::wstring& wstr) {
2247 internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
2250 #endif // GTEST_HAS_GLOBAL_WSTRING
2252 // AssertionResult constructors.
2253 // Used in EXPECT_TRUE/FALSE(assertion_result).
2254 AssertionResult::AssertionResult(const AssertionResult& other)
2255 : success_(other.success_),
2256 message_(other.message_.get() != NULL ?
2257 new ::std::string(*other.message_) :
2258 static_cast< ::std::string*>(NULL)) {
2261 // Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE.
2262 AssertionResult AssertionResult::operator!() const {
2263 AssertionResult negation(!success_);
2264 if (message_.get() != NULL)
2265 negation << *message_;
2269 // Makes a successful assertion result.
2270 AssertionResult AssertionSuccess() {
2271 return AssertionResult(true);
2274 // Makes a failed assertion result.
2275 AssertionResult AssertionFailure() {
2276 return AssertionResult(false);
2279 // Makes a failed assertion result with the given failure message.
2280 // Deprecated; use AssertionFailure() << message.
2281 AssertionResult AssertionFailure(const Message& message) {
2282 return AssertionFailure() << message;
2285 namespace internal {
2287 // Constructs and returns the message for an equality assertion
2288 // (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure.
2290 // The first four parameters are the expressions used in the assertion
2291 // and their values, as strings. For example, for ASSERT_EQ(foo, bar)
2292 // where foo is 5 and bar is 6, we have:
2294 // expected_expression: "foo"
2295 // actual_expression: "bar"
2296 // expected_value: "5"
2297 // actual_value: "6"
2299 // The ignoring_case parameter is true iff the assertion is a
2300 // *_STRCASEEQ*. When it's true, the string " (ignoring case)" will
2301 // be inserted into the message.
2302 AssertionResult EqFailure(const char* expected_expression,
2303 const char* actual_expression,
2304 const String& expected_value,
2305 const String& actual_value,
2306 bool ignoring_case) {
2308 msg << "Value of: " << actual_expression;
2309 if (actual_value != actual_expression) {
2310 msg << "\n Actual: " << actual_value;
2313 msg << "\nExpected: " << expected_expression;
2314 if (ignoring_case) {
2315 msg << " (ignoring case)";
2317 if (expected_value != expected_expression) {
2318 msg << "\nWhich is: " << expected_value;
2321 return AssertionFailure() << msg;
2324 // Constructs a failure message for Boolean assertions such as EXPECT_TRUE.
2325 String GetBoolAssertionFailureMessage(const AssertionResult& assertion_result,
2326 const char* expression_text,
2327 const char* actual_predicate_value,
2328 const char* expected_predicate_value) {
2329 const char* actual_message = assertion_result.message();
2331 msg << "Value of: " << expression_text
2332 << "\n Actual: " << actual_predicate_value;
2333 if (actual_message[0] != '\0')
2334 msg << " (" << actual_message << ")";
2335 msg << "\nExpected: " << expected_predicate_value;
2336 return msg.GetString();
2339 // Helper function for implementing ASSERT_NEAR.
2340 AssertionResult DoubleNearPredFormat(const char* expr1,
2342 const char* abs_error_expr,
2346 const double diff = fabs(val1 - val2);
2347 if (diff <= abs_error) return AssertionSuccess();
2349 // TODO(wan): do not print the value of an expression if it's
2350 // already a literal.
2351 return AssertionFailure()
2352 << "The difference between " << expr1 << " and " << expr2
2353 << " is " << diff << ", which exceeds " << abs_error_expr << ", where\n"
2354 << expr1 << " evaluates to " << val1 << ",\n"
2355 << expr2 << " evaluates to " << val2 << ", and\n"
2356 << abs_error_expr << " evaluates to " << abs_error << ".";
2360 // Helper template for implementing FloatLE() and DoubleLE().
2361 template <typename RawType>
2362 AssertionResult FloatingPointLE(const char* expr1,
2366 // Returns success if val1 is less than val2,
2368 return AssertionSuccess();
2371 // or if val1 is almost equal to val2.
2372 const FloatingPoint<RawType> lhs(val1), rhs(val2);
2373 if (lhs.AlmostEquals(rhs)) {
2374 return AssertionSuccess();
2377 // Note that the above two checks will both fail if either val1 or
2378 // val2 is NaN, as the IEEE floating-point standard requires that
2379 // any predicate involving a NaN must return false.
2381 ::std::stringstream val1_ss;
2382 val1_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
2385 ::std::stringstream val2_ss;
2386 val2_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
2389 return AssertionFailure()
2390 << "Expected: (" << expr1 << ") <= (" << expr2 << ")\n"
2391 << " Actual: " << StringStreamToString(&val1_ss) << " vs "
2392 << StringStreamToString(&val2_ss);
2395 } // namespace internal
2397 // Asserts that val1 is less than, or almost equal to, val2. Fails
2398 // otherwise. In particular, it fails if either val1 or val2 is NaN.
2399 AssertionResult FloatLE(const char* expr1, const char* expr2,
2400 float val1, float val2) {
2401 return internal::FloatingPointLE<float>(expr1, expr2, val1, val2);
2404 // Asserts that val1 is less than, or almost equal to, val2. Fails
2405 // otherwise. In particular, it fails if either val1 or val2 is NaN.
2406 AssertionResult DoubleLE(const char* expr1, const char* expr2,
2407 double val1, double val2) {
2408 return internal::FloatingPointLE<double>(expr1, expr2, val1, val2);
2411 namespace internal {
2413 // The helper function for {ASSERT|EXPECT}_EQ with int or enum
2415 AssertionResult CmpHelperEQ(const char* expected_expression,
2416 const char* actual_expression,
2417 BiggestInt expected,
2418 BiggestInt actual) {
2419 if (expected == actual) {
2420 return AssertionSuccess();
2423 return EqFailure(expected_expression,
2425 FormatForComparisonFailureMessage(expected, actual),
2426 FormatForComparisonFailureMessage(actual, expected),
2430 // A macro for implementing the helper functions needed to implement
2431 // ASSERT_?? and EXPECT_?? with integer or enum arguments. It is here
2432 // just to avoid copy-and-paste of similar code.
2433 #define GTEST_IMPL_CMP_HELPER_(op_name, op)\
2434 AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \
2435 BiggestInt val1, BiggestInt val2) {\
2436 if (val1 op val2) {\
2437 return AssertionSuccess();\
2439 return AssertionFailure() \
2440 << "Expected: (" << expr1 << ") " #op " (" << expr2\
2441 << "), actual: " << FormatForComparisonFailureMessage(val1, val2)\
2442 << " vs " << FormatForComparisonFailureMessage(val2, val1);\
2446 // Implements the helper function for {ASSERT|EXPECT}_NE with int or
2448 GTEST_IMPL_CMP_HELPER_(NE, !=)
2449 // Implements the helper function for {ASSERT|EXPECT}_LE with int or
2451 GTEST_IMPL_CMP_HELPER_(LE, <=)
2452 // Implements the helper function for {ASSERT|EXPECT}_LT with int or
2454 GTEST_IMPL_CMP_HELPER_(LT, < )
2455 // Implements the helper function for {ASSERT|EXPECT}_GE with int or
2457 GTEST_IMPL_CMP_HELPER_(GE, >=)
2458 // Implements the helper function for {ASSERT|EXPECT}_GT with int or
2460 GTEST_IMPL_CMP_HELPER_(GT, > )
2462 #undef GTEST_IMPL_CMP_HELPER_
2464 // The helper function for {ASSERT|EXPECT}_STREQ.
2465 AssertionResult CmpHelperSTREQ(const char* expected_expression,
2466 const char* actual_expression,
2467 const char* expected,
2468 const char* actual) {
2469 if (String::CStringEquals(expected, actual)) {
2470 return AssertionSuccess();
2473 return EqFailure(expected_expression,
2475 String::ShowCStringQuoted(expected),
2476 String::ShowCStringQuoted(actual),
2480 // The helper function for {ASSERT|EXPECT}_STRCASEEQ.
2481 AssertionResult CmpHelperSTRCASEEQ(const char* expected_expression,
2482 const char* actual_expression,
2483 const char* expected,
2484 const char* actual) {
2485 if (String::CaseInsensitiveCStringEquals(expected, actual)) {
2486 return AssertionSuccess();
2489 return EqFailure(expected_expression,
2491 String::ShowCStringQuoted(expected),
2492 String::ShowCStringQuoted(actual),
2496 // The helper function for {ASSERT|EXPECT}_STRNE.
2497 AssertionResult CmpHelperSTRNE(const char* s1_expression,
2498 const char* s2_expression,
2501 if (!String::CStringEquals(s1, s2)) {
2502 return AssertionSuccess();
2504 return AssertionFailure() << "Expected: (" << s1_expression << ") != ("
2505 << s2_expression << "), actual: \""
2506 << s1 << "\" vs \"" << s2 << "\"";
2510 // The helper function for {ASSERT|EXPECT}_STRCASENE.
2511 AssertionResult CmpHelperSTRCASENE(const char* s1_expression,
2512 const char* s2_expression,
2515 if (!String::CaseInsensitiveCStringEquals(s1, s2)) {
2516 return AssertionSuccess();
2518 return AssertionFailure()
2519 << "Expected: (" << s1_expression << ") != ("
2520 << s2_expression << ") (ignoring case), actual: \""
2521 << s1 << "\" vs \"" << s2 << "\"";
2525 } // namespace internal
2529 // Helper functions for implementing IsSubString() and IsNotSubstring().
2531 // This group of overloaded functions return true iff needle is a
2532 // substring of haystack. NULL is considered a substring of itself
2535 bool IsSubstringPred(const char* needle, const char* haystack) {
2536 if (needle == NULL || haystack == NULL)
2537 return needle == haystack;
2539 return strstr(haystack, needle) != NULL;
2542 bool IsSubstringPred(const wchar_t* needle, const wchar_t* haystack) {
2543 if (needle == NULL || haystack == NULL)
2544 return needle == haystack;
2546 return wcsstr(haystack, needle) != NULL;
2549 // StringType here can be either ::std::string or ::std::wstring.
2550 template <typename StringType>
2551 bool IsSubstringPred(const StringType& needle,
2552 const StringType& haystack) {
2553 return haystack.find(needle) != StringType::npos;
2556 // This function implements either IsSubstring() or IsNotSubstring(),
2557 // depending on the value of the expected_to_be_substring parameter.
2558 // StringType here can be const char*, const wchar_t*, ::std::string,
2559 // or ::std::wstring.
2560 template <typename StringType>
2561 AssertionResult IsSubstringImpl(
2562 bool expected_to_be_substring,
2563 const char* needle_expr, const char* haystack_expr,
2564 const StringType& needle, const StringType& haystack) {
2565 if (IsSubstringPred(needle, haystack) == expected_to_be_substring)
2566 return AssertionSuccess();
2568 const bool is_wide_string = sizeof(needle[0]) > 1;
2569 const char* const begin_string_quote = is_wide_string ? "L\"" : "\"";
2570 return AssertionFailure()
2571 << "Value of: " << needle_expr << "\n"
2572 << " Actual: " << begin_string_quote << needle << "\"\n"
2573 << "Expected: " << (expected_to_be_substring ? "" : "not ")
2574 << "a substring of " << haystack_expr << "\n"
2575 << "Which is: " << begin_string_quote << haystack << "\"";
2580 // IsSubstring() and IsNotSubstring() check whether needle is a
2581 // substring of haystack (NULL is considered a substring of itself
2582 // only), and return an appropriate error message when they fail.
2584 AssertionResult IsSubstring(
2585 const char* needle_expr, const char* haystack_expr,
2586 const char* needle, const char* haystack) {
2587 return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
2590 AssertionResult IsSubstring(
2591 const char* needle_expr, const char* haystack_expr,
2592 const wchar_t* needle, const wchar_t* haystack) {
2593 return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
2596 AssertionResult IsNotSubstring(
2597 const char* needle_expr, const char* haystack_expr,
2598 const char* needle, const char* haystack) {
2599 return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
2602 AssertionResult IsNotSubstring(
2603 const char* needle_expr, const char* haystack_expr,
2604 const wchar_t* needle, const wchar_t* haystack) {
2605 return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
2608 AssertionResult IsSubstring(
2609 const char* needle_expr, const char* haystack_expr,
2610 const ::std::string& needle, const ::std::string& haystack) {
2611 return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
2614 AssertionResult IsNotSubstring(
2615 const char* needle_expr, const char* haystack_expr,
2616 const ::std::string& needle, const ::std::string& haystack) {
2617 return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
2620 #if GTEST_HAS_STD_WSTRING
2621 AssertionResult IsSubstring(
2622 const char* needle_expr, const char* haystack_expr,
2623 const ::std::wstring& needle, const ::std::wstring& haystack) {
2624 return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
2627 AssertionResult IsNotSubstring(
2628 const char* needle_expr, const char* haystack_expr,
2629 const ::std::wstring& needle, const ::std::wstring& haystack) {
2630 return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
2632 #endif // GTEST_HAS_STD_WSTRING
2634 namespace internal {
2636 #if GTEST_OS_WINDOWS
2640 // Helper function for IsHRESULT{SuccessFailure} predicates
2641 AssertionResult HRESULTFailureHelper(const char* expr,
2642 const char* expected,
2643 long hr) { // NOLINT
2644 # if GTEST_OS_WINDOWS_MOBILE
2646 // Windows CE doesn't support FormatMessage.
2647 const char error_text[] = "";
2651 // Looks up the human-readable system message for the HRESULT code
2652 // and since we're not passing any params to FormatMessage, we don't
2653 // want inserts expanded.
2654 const DWORD kFlags = FORMAT_MESSAGE_FROM_SYSTEM |
2655 FORMAT_MESSAGE_IGNORE_INSERTS;
2656 const DWORD kBufSize = 4096; // String::Format can't exceed this length.
2657 // Gets the system's human readable message string for this HRESULT.
2658 char error_text[kBufSize] = { '\0' };
2659 DWORD message_length = ::FormatMessageA(kFlags,
2660 0, // no source, we're asking system
2662 0, // no line width restrictions
2663 error_text, // output buffer
2664 kBufSize, // buf size
2665 NULL); // no arguments for inserts
2666 // Trims tailing white space (FormatMessage leaves a trailing cr-lf)
2667 for (; message_length && IsSpace(error_text[message_length - 1]);
2669 error_text[message_length - 1] = '\0';
2672 # endif // GTEST_OS_WINDOWS_MOBILE
2674 const String error_hex(String::Format("0x%08X ", hr));
2675 return ::testing::AssertionFailure()
2676 << "Expected: " << expr << " " << expected << ".\n"
2677 << " Actual: " << error_hex << error_text << "\n";
2682 AssertionResult IsHRESULTSuccess(const char* expr, long hr) { // NOLINT
2683 if (SUCCEEDED(hr)) {
2684 return AssertionSuccess();
2686 return HRESULTFailureHelper(expr, "succeeds", hr);
2689 AssertionResult IsHRESULTFailure(const char* expr, long hr) { // NOLINT
2691 return AssertionSuccess();
2693 return HRESULTFailureHelper(expr, "fails", hr);
2696 #endif // GTEST_OS_WINDOWS
2698 // Utility functions for encoding Unicode text (wide strings) in
2701 // A Unicode code-point can have upto 21 bits, and is encoded in UTF-8
2704 // Code-point length Encoding
2705 // 0 - 7 bits 0xxxxxxx
2706 // 8 - 11 bits 110xxxxx 10xxxxxx
2707 // 12 - 16 bits 1110xxxx 10xxxxxx 10xxxxxx
2708 // 17 - 21 bits 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
2710 // The maximum code-point a one-byte UTF-8 sequence can represent.
2711 const UInt32 kMaxCodePoint1 = (static_cast<UInt32>(1) << 7) - 1;
2713 // The maximum code-point a two-byte UTF-8 sequence can represent.
2714 const UInt32 kMaxCodePoint2 = (static_cast<UInt32>(1) << (5 + 6)) - 1;
2716 // The maximum code-point a three-byte UTF-8 sequence can represent.
2717 const UInt32 kMaxCodePoint3 = (static_cast<UInt32>(1) << (4 + 2*6)) - 1;
2719 // The maximum code-point a four-byte UTF-8 sequence can represent.
2720 const UInt32 kMaxCodePoint4 = (static_cast<UInt32>(1) << (3 + 3*6)) - 1;
2722 // Chops off the n lowest bits from a bit pattern. Returns the n
2723 // lowest bits. As a side effect, the original bit pattern will be
2724 // shifted to the right by n bits.
2725 inline UInt32 ChopLowBits(UInt32* bits, int n) {
2726 const UInt32 low_bits = *bits & ((static_cast<UInt32>(1) << n) - 1);
2731 // Converts a Unicode code point to a narrow string in UTF-8 encoding.
2732 // code_point parameter is of type UInt32 because wchar_t may not be
2733 // wide enough to contain a code point.
2734 // The output buffer str must containt at least 32 characters.
2735 // The function returns the address of the output buffer.
2736 // If the code_point is not a valid Unicode code point
2737 // (i.e. outside of Unicode range U+0 to U+10FFFF) it will be output
2738 // as '(Invalid Unicode 0xXXXXXXXX)'.
2739 char* CodePointToUtf8(UInt32 code_point, char* str) {
2740 if (code_point <= kMaxCodePoint1) {
2742 str[0] = static_cast<char>(code_point); // 0xxxxxxx
2743 } else if (code_point <= kMaxCodePoint2) {
2745 str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
2746 str[0] = static_cast<char>(0xC0 | code_point); // 110xxxxx
2747 } else if (code_point <= kMaxCodePoint3) {
2749 str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
2750 str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
2751 str[0] = static_cast<char>(0xE0 | code_point); // 1110xxxx
2752 } else if (code_point <= kMaxCodePoint4) {
2754 str[3] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
2755 str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
2756 str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
2757 str[0] = static_cast<char>(0xF0 | code_point); // 11110xxx
2759 // The longest string String::Format can produce when invoked
2760 // with these parameters is 28 character long (not including
2761 // the terminating nul character). We are asking for 32 character
2762 // buffer just in case. This is also enough for strncpy to
2763 // null-terminate the destination string.
2765 str, String::Format("(Invalid Unicode 0x%X)", code_point).c_str(), 32);
2766 str[31] = '\0'; // Makes sure no change in the format to strncpy leaves
2767 // the result unterminated.
2772 // The following two functions only make sense if the the system
2773 // uses UTF-16 for wide string encoding. All supported systems
2774 // with 16 bit wchar_t (Windows, Cygwin, Symbian OS) do use UTF-16.
2776 // Determines if the arguments constitute UTF-16 surrogate pair
2777 // and thus should be combined into a single Unicode code point
2778 // using CreateCodePointFromUtf16SurrogatePair.
2779 inline bool IsUtf16SurrogatePair(wchar_t first, wchar_t second) {
2780 return sizeof(wchar_t) == 2 &&
2781 (first & 0xFC00) == 0xD800 && (second & 0xFC00) == 0xDC00;
2784 // Creates a Unicode code point from UTF16 surrogate pair.
2785 inline UInt32 CreateCodePointFromUtf16SurrogatePair(wchar_t first,
2787 const UInt32 mask = (1 << 10) - 1;
2788 return (sizeof(wchar_t) == 2) ?
2789 (((first & mask) << 10) | (second & mask)) + 0x10000 :
2790 // This function should not be called when the condition is
2791 // false, but we provide a sensible default in case it is.
2792 static_cast<UInt32>(first);
2795 // Converts a wide string to a narrow string in UTF-8 encoding.
2796 // The wide string is assumed to have the following encoding:
2797 // UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS)
2798 // UTF-32 if sizeof(wchar_t) == 4 (on Linux)
2799 // Parameter str points to a null-terminated wide string.
2800 // Parameter num_chars may additionally limit the number
2801 // of wchar_t characters processed. -1 is used when the entire string
2802 // should be processed.
2803 // If the string contains code points that are not valid Unicode code points
2804 // (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
2805 // as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
2806 // and contains invalid UTF-16 surrogate pairs, values in those pairs
2807 // will be encoded as individual Unicode characters from Basic Normal Plane.
2808 String WideStringToUtf8(const wchar_t* str, int num_chars) {
2809 if (num_chars == -1)
2810 num_chars = static_cast<int>(wcslen(str));
2812 ::std::stringstream stream;
2813 for (int i = 0; i < num_chars; ++i) {
2814 UInt32 unicode_code_point;
2816 if (str[i] == L'\0') {
2818 } else if (i + 1 < num_chars && IsUtf16SurrogatePair(str[i], str[i + 1])) {
2819 unicode_code_point = CreateCodePointFromUtf16SurrogatePair(str[i],
2823 unicode_code_point = static_cast<UInt32>(str[i]);
2826 char buffer[32]; // CodePointToUtf8 requires a buffer this big.
2827 stream << CodePointToUtf8(unicode_code_point, buffer);
2829 return StringStreamToString(&stream);
2832 // Converts a wide C string to a String using the UTF-8 encoding.
2833 // NULL will be converted to "(null)".
2834 String String::ShowWideCString(const wchar_t * wide_c_str) {
2835 if (wide_c_str == NULL) return String("(null)");
2837 return String(internal::WideStringToUtf8(wide_c_str, -1).c_str());
2840 // Similar to ShowWideCString(), except that this function encloses
2841 // the converted string in double quotes.
2842 String String::ShowWideCStringQuoted(const wchar_t* wide_c_str) {
2843 if (wide_c_str == NULL) return String("(null)");
2845 return String::Format("L\"%s\"",
2846 String::ShowWideCString(wide_c_str).c_str());
2849 // Compares two wide C strings. Returns true iff they have the same
2852 // Unlike wcscmp(), this function can handle NULL argument(s). A NULL
2853 // C string is considered different to any non-NULL C string,
2854 // including the empty string.
2855 bool String::WideCStringEquals(const wchar_t * lhs, const wchar_t * rhs) {
2856 if (lhs == NULL) return rhs == NULL;
2858 if (rhs == NULL) return false;
2860 return wcscmp(lhs, rhs) == 0;
2863 // Helper function for *_STREQ on wide strings.
2864 AssertionResult CmpHelperSTREQ(const char* expected_expression,
2865 const char* actual_expression,
2866 const wchar_t* expected,
2867 const wchar_t* actual) {
2868 if (String::WideCStringEquals(expected, actual)) {
2869 return AssertionSuccess();
2872 return EqFailure(expected_expression,
2874 String::ShowWideCStringQuoted(expected),
2875 String::ShowWideCStringQuoted(actual),
2879 // Helper function for *_STRNE on wide strings.
2880 AssertionResult CmpHelperSTRNE(const char* s1_expression,
2881 const char* s2_expression,
2883 const wchar_t* s2) {
2884 if (!String::WideCStringEquals(s1, s2)) {
2885 return AssertionSuccess();
2888 return AssertionFailure() << "Expected: (" << s1_expression << ") != ("
2889 << s2_expression << "), actual: "
2890 << String::ShowWideCStringQuoted(s1)
2891 << " vs " << String::ShowWideCStringQuoted(s2);
2894 // Compares two C strings, ignoring case. Returns true iff they have
2895 // the same content.
2897 // Unlike strcasecmp(), this function can handle NULL argument(s). A
2898 // NULL C string is considered different to any non-NULL C string,
2899 // including the empty string.
2900 bool String::CaseInsensitiveCStringEquals(const char * lhs, const char * rhs) {
2905 return posix::StrCaseCmp(lhs, rhs) == 0;
2908 // Compares two wide C strings, ignoring case. Returns true iff they
2909 // have the same content.
2911 // Unlike wcscasecmp(), this function can handle NULL argument(s).
2912 // A NULL C string is considered different to any non-NULL wide C string,
2913 // including the empty string.
2914 // NB: The implementations on different platforms slightly differ.
2915 // On windows, this method uses _wcsicmp which compares according to LC_CTYPE
2916 // environment variable. On GNU platform this method uses wcscasecmp
2917 // which compares according to LC_CTYPE category of the current locale.
2918 // On MacOS X, it uses towlower, which also uses LC_CTYPE category of the
2920 bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs,
2921 const wchar_t* rhs) {
2922 if (lhs == NULL) return rhs == NULL;
2924 if (rhs == NULL) return false;
2926 #if GTEST_OS_WINDOWS
2927 return _wcsicmp(lhs, rhs) == 0;
2928 #elif GTEST_OS_LINUX && !GTEST_OS_LINUX_ANDROID
2929 return wcscasecmp(lhs, rhs) == 0;
2931 // Android, Mac OS X and Cygwin don't define wcscasecmp.
2932 // Other unknown OSes may not define it either.
2935 left = towlower(*lhs++);
2936 right = towlower(*rhs++);
2937 } while (left && left == right);
2938 return left == right;
2939 #endif // OS selector
2942 // Compares this with another String.
2943 // Returns < 0 if this is less than rhs, 0 if this is equal to rhs, or > 0
2944 // if this is greater than rhs.
2945 int String::Compare(const String & rhs) const {
2946 const char* const lhs_c_str = c_str();
2947 const char* const rhs_c_str = rhs.c_str();
2949 if (lhs_c_str == NULL) {
2950 return rhs_c_str == NULL ? 0 : -1; // NULL < anything except NULL
2951 } else if (rhs_c_str == NULL) {
2955 const size_t shorter_str_len =
2956 length() <= rhs.length() ? length() : rhs.length();
2957 for (size_t i = 0; i != shorter_str_len; i++) {
2958 if (lhs_c_str[i] < rhs_c_str[i]) {
2960 } else if (lhs_c_str[i] > rhs_c_str[i]) {
2964 return (length() < rhs.length()) ? -1 :
2965 (length() > rhs.length()) ? 1 : 0;
2968 // Returns true iff this String ends with the given suffix. *Any*
2969 // String is considered to end with a NULL or empty suffix.
2970 bool String::EndsWith(const char* suffix) const {
2971 if (suffix == NULL || CStringEquals(suffix, "")) return true;
2973 if (c_str() == NULL) return false;
2975 const size_t this_len = strlen(c_str());
2976 const size_t suffix_len = strlen(suffix);
2977 return (this_len >= suffix_len) &&
2978 CStringEquals(c_str() + this_len - suffix_len, suffix);
2981 // Returns true iff this String ends with the given suffix, ignoring case.
2982 // Any String is considered to end with a NULL or empty suffix.
2983 bool String::EndsWithCaseInsensitive(const char* suffix) const {
2984 if (suffix == NULL || CStringEquals(suffix, "")) return true;
2986 if (c_str() == NULL) return false;
2988 const size_t this_len = strlen(c_str());
2989 const size_t suffix_len = strlen(suffix);
2990 return (this_len >= suffix_len) &&
2991 CaseInsensitiveCStringEquals(c_str() + this_len - suffix_len, suffix);
2994 // Formats a list of arguments to a String, using the same format
2995 // spec string as for printf.
2997 // We do not use the StringPrintf class as it is not universally
3000 // The result is limited to 4096 characters (including the tailing 0).
3001 // If 4096 characters are not enough to format the input, or if
3002 // there's an error, "<formatting error or buffer exceeded>" is
3004 String String::Format(const char * format, ...) {
3006 va_start(args, format);
3009 const int kBufferSize = sizeof(buffer)/sizeof(buffer[0]);
3011 // MSVC 8 deprecates vsnprintf(), so we want to suppress warning
3012 // 4996 (deprecated function) there.
3013 #ifdef _MSC_VER // We are using MSVC.
3014 # pragma warning(push) // Saves the current warning state.
3015 # pragma warning(disable:4996) // Temporarily disables warning 4996.
3017 const int size = vsnprintf(buffer, kBufferSize, format, args);
3019 # pragma warning(pop) // Restores the warning state.
3020 #else // We are not using MSVC.
3021 const int size = vsnprintf(buffer, kBufferSize, format, args);
3025 // vsnprintf()'s behavior is not portable. When the buffer is not
3026 // big enough, it returns a negative value in MSVC, and returns the
3027 // needed buffer size on Linux. When there is an output error, it
3028 // always returns a negative value. For simplicity, we lump the two
3029 // error cases together.
3030 if (size < 0 || size >= kBufferSize) {
3031 return String("<formatting error or buffer exceeded>");
3033 return String(buffer, size);
3037 // Converts the buffer in a stringstream to a String, converting NUL
3038 // bytes to "\\0" along the way.
3039 String StringStreamToString(::std::stringstream* ss) {
3040 const ::std::string& str = ss->str();
3041 const char* const start = str.c_str();
3042 const char* const end = start + str.length();
3044 // We need to use a helper stringstream to do this transformation
3045 // because String doesn't support push_back().
3046 ::std::stringstream helper;
3047 for (const char* ch = start; ch != end; ++ch) {
3049 helper << "\\0"; // Replaces NUL with "\\0";
3055 return String(helper.str().c_str());
3058 // Appends the user-supplied message to the Google-Test-generated message.
3059 String AppendUserMessage(const String& gtest_msg,
3060 const Message& user_msg) {
3061 // Appends the user message if it's non-empty.
3062 const String user_msg_string = user_msg.GetString();
3063 if (user_msg_string.empty()) {
3068 msg << gtest_msg << "\n" << user_msg_string;
3070 return msg.GetString();
3073 } // namespace internal
3077 // Creates an empty TestResult.
3078 TestResult::TestResult()
3079 : death_test_count_(0),
3084 TestResult::~TestResult() {
3087 // Returns the i-th test part result among all the results. i can
3088 // range from 0 to total_part_count() - 1. If i is not in that range,
3089 // aborts the program.
3090 const TestPartResult& TestResult::GetTestPartResult(int i) const {
3091 if (i < 0 || i >= total_part_count())
3092 internal::posix::Abort();
3093 return test_part_results_.at(i);
3096 // Returns the i-th test property. i can range from 0 to
3097 // test_property_count() - 1. If i is not in that range, aborts the
3099 const TestProperty& TestResult::GetTestProperty(int i) const {
3100 if (i < 0 || i >= test_property_count())
3101 internal::posix::Abort();
3102 return test_properties_.at(i);
3105 // Clears the test part results.
3106 void TestResult::ClearTestPartResults() {
3107 test_part_results_.clear();
3110 // Adds a test part result to the list.
3111 void TestResult::AddTestPartResult(const TestPartResult& test_part_result) {
3112 test_part_results_.push_back(test_part_result);
3115 // Adds a test property to the list. If a property with the same key as the
3116 // supplied property is already represented, the value of this test_property
3117 // replaces the old value for that key.
3118 void TestResult::RecordProperty(const TestProperty& test_property) {
3119 if (!ValidateTestProperty(test_property)) {
3122 internal::MutexLock lock(&test_properites_mutex_);
3123 const std::vector<TestProperty>::iterator property_with_matching_key =
3124 std::find_if(test_properties_.begin(), test_properties_.end(),
3125 internal::TestPropertyKeyIs(test_property.key()));
3126 if (property_with_matching_key == test_properties_.end()) {
3127 test_properties_.push_back(test_property);
3130 property_with_matching_key->SetValue(test_property.value());
3133 // Adds a failure if the key is a reserved attribute of Google Test
3134 // testcase tags. Returns true if the property is valid.
3135 bool TestResult::ValidateTestProperty(const TestProperty& test_property) {
3136 internal::String key(test_property.key());
3137 if (key == "name" || key == "status" || key == "time" || key == "classname") {
3139 << "Reserved key used in RecordProperty(): "
3141 << " ('name', 'status', 'time', and 'classname' are reserved by "
3142 << GTEST_NAME_ << ")";
3148 // Clears the object.
3149 void TestResult::Clear() {
3150 test_part_results_.clear();
3151 test_properties_.clear();
3152 death_test_count_ = 0;
3156 // Returns true iff the test failed.
3157 bool TestResult::Failed() const {
3158 for (int i = 0; i < total_part_count(); ++i) {
3159 if (GetTestPartResult(i).failed())
3165 // Returns true iff the test part fatally failed.
3166 static bool TestPartFatallyFailed(const TestPartResult& result) {
3167 return result.fatally_failed();
3170 // Returns true iff the test fatally failed.
3171 bool TestResult::HasFatalFailure() const {
3172 return CountIf(test_part_results_, TestPartFatallyFailed) > 0;
3175 // Returns true iff the test part non-fatally failed.
3176 static bool TestPartNonfatallyFailed(const TestPartResult& result) {
3177 return result.nonfatally_failed();
3180 // Returns true iff the test has a non-fatal failure.
3181 bool TestResult::HasNonfatalFailure() const {
3182 return CountIf(test_part_results_, TestPartNonfatallyFailed) > 0;
3185 // Gets the number of all test parts. This is the sum of the number
3186 // of successful test parts and the number of failed test parts.
3187 int TestResult::total_part_count() const {
3188 return static_cast<int>(test_part_results_.size());
3191 // Returns the number of the test properties.
3192 int TestResult::test_property_count() const {
3193 return static_cast<int>(test_properties_.size());
3198 // Creates a Test object.
3200 // The c'tor saves the values of all Google Test flags.
3202 : gtest_flag_saver_(new internal::GTestFlagSaver) {
3205 // The d'tor restores the values of all Google Test flags.
3207 delete gtest_flag_saver_;
3210 // Sets up the test fixture.
3212 // A sub-class may override this.
3213 void Test::SetUp() {
3216 // Tears down the test fixture.
3218 // A sub-class may override this.
3219 void Test::TearDown() {
3222 // Allows user supplied key value pairs to be recorded for later output.
3223 void Test::RecordProperty(const char* key, const char* value) {
3224 UnitTest::GetInstance()->RecordPropertyForCurrentTest(key, value);
3227 // Allows user supplied key value pairs to be recorded for later output.
3228 void Test::RecordProperty(const char* key, int value) {
3229 Message value_message;
3230 value_message << value;
3231 RecordProperty(key, value_message.GetString().c_str());
3234 namespace internal {
3236 void ReportFailureInUnknownLocation(TestPartResult::Type result_type,
3237 const String& message) {
3238 // This function is a friend of UnitTest and as such has access to
3239 // AddTestPartResult.
3240 UnitTest::GetInstance()->AddTestPartResult(
3242 NULL, // No info about the source file where the exception occurred.
3243 -1, // We have no info on which line caused the exception.
3245 String()); // No stack trace, either.
3248 } // namespace internal
3250 // Google Test requires all tests in the same test case to use the same test
3251 // fixture class. This function checks if the current test has the
3252 // same fixture class as the first test in the current test case. If
3253 // yes, it returns true; otherwise it generates a Google Test failure and
3255 bool Test::HasSameFixtureClass() {
3256 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
3257 const TestCase* const test_case = impl->current_test_case();
3259 // Info about the first test in the current test case.
3260 const TestInfo* const first_test_info = test_case->test_info_list()[0];
3261 const internal::TypeId first_fixture_id = first_test_info->fixture_class_id_;
3262 const char* const first_test_name = first_test_info->name();
3264 // Info about the current test.
3265 const TestInfo* const this_test_info = impl->current_test_info();
3266 const internal::TypeId this_fixture_id = this_test_info->fixture_class_id_;
3267 const char* const this_test_name = this_test_info->name();
3269 if (this_fixture_id != first_fixture_id) {
3270 // Is the first test defined using TEST?
3271 const bool first_is_TEST = first_fixture_id == internal::GetTestTypeId();
3272 // Is this test defined using TEST?
3273 const bool this_is_TEST = this_fixture_id == internal::GetTestTypeId();
3275 if (first_is_TEST || this_is_TEST) {
3276 // The user mixed TEST and TEST_F in this test case - we'll tell
3277 // him/her how to fix it.
3279 // Gets the name of the TEST and the name of the TEST_F. Note
3280 // that first_is_TEST and this_is_TEST cannot both be true, as
3281 // the fixture IDs are different for the two tests.
3282 const char* const TEST_name =
3283 first_is_TEST ? first_test_name : this_test_name;
3284 const char* const TEST_F_name =
3285 first_is_TEST ? this_test_name : first_test_name;
3288 << "All tests in the same test case must use the same test fixture\n"
3289 << "class, so mixing TEST_F and TEST in the same test case is\n"
3290 << "illegal. In test case " << this_test_info->test_case_name()
3292 << "test " << TEST_F_name << " is defined using TEST_F but\n"
3293 << "test " << TEST_name << " is defined using TEST. You probably\n"
3294 << "want to change the TEST to TEST_F or move it to another test\n"
3297 // The user defined two fixture classes with the same name in
3298 // two namespaces - we'll tell him/her how to fix it.
3300 << "All tests in the same test case must use the same test fixture\n"
3301 << "class. However, in test case "
3302 << this_test_info->test_case_name() << ",\n"
3303 << "you defined test " << first_test_name
3304 << " and test " << this_test_name << "\n"
3305 << "using two different test fixture classes. This can happen if\n"
3306 << "the two classes are from different namespaces or translation\n"
3307 << "units and have the same name. You should probably rename one\n"
3308 << "of the classes to put the tests into different test cases.";
3318 // Adds an "exception thrown" fatal failure to the current test. This
3319 // function returns its result via an output parameter pointer because VC++
3320 // prohibits creation of objects with destructors on stack in functions
3321 // using __try (see error C2712).
3322 static internal::String* FormatSehExceptionMessage(DWORD exception_code,
3323 const char* location) {
3325 message << "SEH exception with code 0x" << std::setbase(16) <<
3326 exception_code << std::setbase(10) << " thrown in " << location << ".";
3328 return new internal::String(message.GetString());
3331 #endif // GTEST_HAS_SEH
3333 #if GTEST_HAS_EXCEPTIONS
3335 // Adds an "exception thrown" fatal failure to the current test.
3336 static internal::String FormatCxxExceptionMessage(const char* description,
3337 const char* location) {
3339 if (description != NULL) {
3340 message << "C++ exception with description \"" << description << "\"";
3342 message << "Unknown C++ exception";
3344 message << " thrown in " << location << ".";
3346 return message.GetString();
3349 static internal::String PrintTestPartResultToString(
3350 const TestPartResult& test_part_result);
3352 // A failed Google Test assertion will throw an exception of this type when
3353 // GTEST_FLAG(throw_on_failure) is true (if exceptions are enabled). We
3354 // derive it from std::runtime_error, which is for errors presumably
3355 // detectable only at run time. Since std::runtime_error inherits from
3356 // std::exception, many testing frameworks know how to extract and print the
3357 // message inside it.
3358 class GoogleTestFailureException : public ::std::runtime_error {
3360 explicit GoogleTestFailureException(const TestPartResult& failure)
3361 : ::std::runtime_error(PrintTestPartResultToString(failure).c_str()) {}
3363 #endif // GTEST_HAS_EXCEPTIONS
3365 namespace internal {
3366 // We put these helper functions in the internal namespace as IBM's xlC
3367 // compiler rejects the code if they were declared static.
3369 // Runs the given method and handles SEH exceptions it throws, when
3370 // SEH is supported; returns the 0-value for type Result in case of an
3371 // SEH exception. (Microsoft compilers cannot handle SEH and C++
3372 // exceptions in the same function. Therefore, we provide a separate
3373 // wrapper function for handling SEH exceptions.)
3374 template <class T, typename Result>
3375 Result HandleSehExceptionsInMethodIfSupported(
3376 T* object, Result (T::*method)(), const char* location) {
3379 return (object->*method)();
3380 } __except (internal::UnitTestOptions::GTestShouldProcessSEH( // NOLINT
3381 GetExceptionCode())) {
3382 // We create the exception message on the heap because VC++ prohibits
3383 // creation of objects with destructors on stack in functions using __try
3384 // (see error C2712).
3385 internal::String* exception_message = FormatSehExceptionMessage(
3386 GetExceptionCode(), location);
3387 internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure,
3388 *exception_message);
3389 delete exception_message;
3390 return static_cast<Result>(0);
3394 return (object->*method)();
3395 #endif // GTEST_HAS_SEH
3398 // Runs the given method and catches and reports C++ and/or SEH-style
3399 // exceptions, if they are supported; returns the 0-value for type
3400 // Result in case of an SEH exception.
3401 template <class T, typename Result>
3402 Result HandleExceptionsInMethodIfSupported(
3403 T* object, Result (T::*method)(), const char* location) {
3404 // NOTE: The user code can affect the way in which Google Test handles
3405 // exceptions by setting GTEST_FLAG(catch_exceptions), but only before
3406 // RUN_ALL_TESTS() starts. It is technically possible to check the flag
3407 // after the exception is caught and either report or re-throw the
3408 // exception based on the flag's value:
3411 // // Perform the test method.
3413 // if (GTEST_FLAG(catch_exceptions))
3414 // // Report the exception as failure.
3416 // throw; // Re-throws the original exception.
3419 // However, the purpose of this flag is to allow the program to drop into
3420 // the debugger when the exception is thrown. On most platforms, once the
3421 // control enters the catch block, the exception origin information is
3422 // lost and the debugger will stop the program at the point of the
3423 // re-throw in this function -- instead of at the point of the original
3424 // throw statement in the code under test. For this reason, we perform
3425 // the check early, sacrificing the ability to affect Google Test's
3426 // exception handling in the method where the exception is thrown.
3427 if (internal::GetUnitTestImpl()->catch_exceptions()) {
3428 #if GTEST_HAS_EXCEPTIONS
3430 return HandleSehExceptionsInMethodIfSupported(object, method, location);
3431 } catch (const GoogleTestFailureException&) { // NOLINT
3432 // This exception doesn't originate in code under test. It makes no
3433 // sense to report it as a test failure.
3435 } catch (const std::exception& e) { // NOLINT
3436 internal::ReportFailureInUnknownLocation(
3437 TestPartResult::kFatalFailure,
3438 FormatCxxExceptionMessage(e.what(), location));
3439 } catch (...) { // NOLINT
3440 internal::ReportFailureInUnknownLocation(
3441 TestPartResult::kFatalFailure,
3442 FormatCxxExceptionMessage(NULL, location));
3444 return static_cast<Result>(0);
3446 return HandleSehExceptionsInMethodIfSupported(object, method, location);
3447 #endif // GTEST_HAS_EXCEPTIONS
3449 return (object->*method)();
3453 } // namespace internal
3455 // Runs the test and updates the test result.
3457 if (!HasSameFixtureClass()) return;
3459 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
3460 impl->os_stack_trace_getter()->UponLeavingGTest();
3461 internal::HandleExceptionsInMethodIfSupported(this, &Test::SetUp, "SetUp()");
3462 // We will run the test only if SetUp() was successful.
3463 if (!HasFatalFailure()) {
3464 impl->os_stack_trace_getter()->UponLeavingGTest();
3465 internal::HandleExceptionsInMethodIfSupported(
3466 this, &Test::TestBody, "the test body");
3469 // However, we want to clean up as much as possible. Hence we will
3470 // always call TearDown(), even if SetUp() or the test body has
3472 impl->os_stack_trace_getter()->UponLeavingGTest();
3473 internal::HandleExceptionsInMethodIfSupported(
3474 this, &Test::TearDown, "TearDown()");
3477 // Returns true iff the current test has a fatal failure.
3478 bool Test::HasFatalFailure() {
3479 return internal::GetUnitTestImpl()->current_test_result()->HasFatalFailure();
3482 // Returns true iff the current test has a non-fatal failure.
3483 bool Test::HasNonfatalFailure() {
3484 return internal::GetUnitTestImpl()->current_test_result()->
3485 HasNonfatalFailure();
3490 // Constructs a TestInfo object. It assumes ownership of the test factory
3492 // TODO(vladl@google.com): Make a_test_case_name and a_name const string&'s
3493 // to signify they cannot be NULLs.
3494 TestInfo::TestInfo(const char* a_test_case_name,
3496 const char* a_type_param,
3497 const char* a_value_param,
3498 internal::TypeId fixture_class_id,
3499 internal::TestFactoryBase* factory)
3500 : test_case_name_(a_test_case_name),
3502 type_param_(a_type_param ? new std::string(a_type_param) : NULL),
3503 value_param_(a_value_param ? new std::string(a_value_param) : NULL),
3504 fixture_class_id_(fixture_class_id),
3506 is_disabled_(false),
3507 matches_filter_(false),
3511 // Destructs a TestInfo object.
3512 TestInfo::~TestInfo() { delete factory_; }
3514 namespace internal {
3516 // Creates a new TestInfo object and registers it with Google Test;
3517 // returns the created object.
3521 // test_case_name: name of the test case
3522 // name: name of the test
3523 // type_param: the name of the test's type parameter, or NULL if
3524 // this is not a typed or a type-parameterized test.
3525 // value_param: text representation of the test's value parameter,
3526 // or NULL if this is not a value-parameterized test.
3527 // fixture_class_id: ID of the test fixture class
3528 // set_up_tc: pointer to the function that sets up the test case
3529 // tear_down_tc: pointer to the function that tears down the test case
3530 // factory: pointer to the factory that creates a test object.
3531 // The newly created TestInfo instance will assume
3532 // ownership of the factory object.
3533 TestInfo* MakeAndRegisterTestInfo(
3534 const char* test_case_name, const char* name,
3535 const char* type_param,
3536 const char* value_param,
3537 TypeId fixture_class_id,
3538 SetUpTestCaseFunc set_up_tc,
3539 TearDownTestCaseFunc tear_down_tc,
3540 TestFactoryBase* factory) {
3541 TestInfo* const test_info =
3542 new TestInfo(test_case_name, name, type_param, value_param,
3543 fixture_class_id, factory);
3544 GetUnitTestImpl()->AddTestInfo(set_up_tc, tear_down_tc, test_info);
3548 #if GTEST_HAS_PARAM_TEST
3549 void ReportInvalidTestCaseType(const char* test_case_name,
3550 const char* file, int line) {
3553 << "Attempted redefinition of test case " << test_case_name << ".\n"
3554 << "All tests in the same test case must use the same test fixture\n"
3555 << "class. However, in test case " << test_case_name << ", you tried\n"
3556 << "to define a test using a fixture class different from the one\n"
3557 << "used earlier. This can happen if the two fixture classes are\n"
3558 << "from different namespaces and have the same name. You should\n"
3559 << "probably rename one of the classes to put the tests into different\n"
3562 fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(),
3563 errors.GetString().c_str());
3565 #endif // GTEST_HAS_PARAM_TEST
3567 } // namespace internal
3571 // A predicate that checks the test name of a TestInfo against a known
3574 // This is used for implementation of the TestCase class only. We put
3575 // it in the anonymous namespace to prevent polluting the outer
3578 // TestNameIs is copyable.
3583 // TestNameIs has NO default constructor.
3584 explicit TestNameIs(const char* name)
3587 // Returns true iff the test name of test_info matches name_.
3588 bool operator()(const TestInfo * test_info) const {
3589 return test_info && internal::String(test_info->name()).Compare(name_) == 0;
3593 internal::String name_;
3598 namespace internal {
3600 // This method expands all parameterized tests registered with macros TEST_P
3601 // and INSTANTIATE_TEST_CASE_P into regular tests and registers those.
3602 // This will be done just once during the program runtime.
3603 void UnitTestImpl::RegisterParameterizedTests() {
3604 #if GTEST_HAS_PARAM_TEST
3605 if (!parameterized_tests_registered_) {
3606 parameterized_test_registry_.RegisterTests();
3607 parameterized_tests_registered_ = true;
3612 } // namespace internal
3614 // Creates the test object, runs it, records its result, and then
3616 void TestInfo::Run() {
3617 if (!should_run_) return;
3619 // Tells UnitTest where to store test result.
3620 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
3621 impl->set_current_test_info(this);
3623 TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
3625 // Notifies the unit test event listeners that a test is about to start.
3626 repeater->OnTestStart(*this);
3628 const TimeInMillis start = internal::GetTimeInMillis();
3630 impl->os_stack_trace_getter()->UponLeavingGTest();
3632 // Creates the test object.
3633 Test* const test = internal::HandleExceptionsInMethodIfSupported(
3634 factory_, &internal::TestFactoryBase::CreateTest,
3635 "the test fixture's constructor");
3637 // Runs the test only if the test object was created and its
3638 // constructor didn't generate a fatal failure.
3639 if ((test != NULL) && !Test::HasFatalFailure()) {
3640 // This doesn't throw as all user code that can throw are wrapped into
3641 // exception handling code.
3645 // Deletes the test object.
3646 impl->os_stack_trace_getter()->UponLeavingGTest();
3647 internal::HandleExceptionsInMethodIfSupported(
3648 test, &Test::DeleteSelf_, "the test fixture's destructor");
3650 result_.set_elapsed_time(internal::GetTimeInMillis() - start);
3652 // Notifies the unit test event listener that a test has just finished.
3653 repeater->OnTestEnd(*this);
3655 // Tells UnitTest to stop associating assertion results to this
3657 impl->set_current_test_info(NULL);
3662 // Gets the number of successful tests in this test case.
3663 int TestCase::successful_test_count() const {
3664 return CountIf(test_info_list_, TestPassed);
3667 // Gets the number of failed tests in this test case.
3668 int TestCase::failed_test_count() const {
3669 return CountIf(test_info_list_, TestFailed);
3672 int TestCase::disabled_test_count() const {
3673 return CountIf(test_info_list_, TestDisabled);
3676 // Get the number of tests in this test case that should run.
3677 int TestCase::test_to_run_count() const {
3678 return CountIf(test_info_list_, ShouldRunTest);
3681 // Gets the number of all tests.
3682 int TestCase::total_test_count() const {
3683 return static_cast<int>(test_info_list_.size());
3686 // Creates a TestCase with the given name.
3690 // name: name of the test case
3691 // a_type_param: the name of the test case's type parameter, or NULL if
3692 // this is not a typed or a type-parameterized test case.
3693 // set_up_tc: pointer to the function that sets up the test case
3694 // tear_down_tc: pointer to the function that tears down the test case
3695 TestCase::TestCase(const char* a_name, const char* a_type_param,
3696 Test::SetUpTestCaseFunc set_up_tc,
3697 Test::TearDownTestCaseFunc tear_down_tc)
3699 type_param_(a_type_param ? new std::string(a_type_param) : NULL),
3700 set_up_tc_(set_up_tc),
3701 tear_down_tc_(tear_down_tc),
3706 // Destructor of TestCase.
3707 TestCase::~TestCase() {
3708 // Deletes every Test in the collection.
3709 ForEach(test_info_list_, internal::Delete<TestInfo>);
3712 // Returns the i-th test among all the tests. i can range from 0 to
3713 // total_test_count() - 1. If i is not in that range, returns NULL.
3714 const TestInfo* TestCase::GetTestInfo(int i) const {
3715 const int index = GetElementOr(test_indices_, i, -1);
3716 return index < 0 ? NULL : test_info_list_[index];
3719 // Returns the i-th test among all the tests. i can range from 0 to
3720 // total_test_count() - 1. If i is not in that range, returns NULL.
3721 TestInfo* TestCase::GetMutableTestInfo(int i) {
3722 const int index = GetElementOr(test_indices_, i, -1);
3723 return index < 0 ? NULL : test_info_list_[index];
3726 // Adds a test to this test case. Will delete the test upon
3727 // destruction of the TestCase object.
3728 void TestCase::AddTestInfo(TestInfo * test_info) {
3729 test_info_list_.push_back(test_info);
3730 test_indices_.push_back(static_cast<int>(test_indices_.size()));
3733 // Runs every test in this TestCase.
3734 void TestCase::Run() {
3735 if (!should_run_) return;
3737 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
3738 impl->set_current_test_case(this);
3740 TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
3742 repeater->OnTestCaseStart(*this);
3743 impl->os_stack_trace_getter()->UponLeavingGTest();
3744 internal::HandleExceptionsInMethodIfSupported(
3745 this, &TestCase::RunSetUpTestCase, "SetUpTestCase()");
3747 const internal::TimeInMillis start = internal::GetTimeInMillis();
3748 for (int i = 0; i < total_test_count(); i++) {
3749 GetMutableTestInfo(i)->Run();
3751 elapsed_time_ = internal::GetTimeInMillis() - start;
3753 impl->os_stack_trace_getter()->UponLeavingGTest();
3754 internal::HandleExceptionsInMethodIfSupported(
3755 this, &TestCase::RunTearDownTestCase, "TearDownTestCase()");
3757 repeater->OnTestCaseEnd(*this);
3758 impl->set_current_test_case(NULL);
3761 // Clears the results of all tests in this test case.
3762 void TestCase::ClearResult() {
3763 ForEach(test_info_list_, TestInfo::ClearTestResult);
3766 // Shuffles the tests in this test case.
3767 void TestCase::ShuffleTests(internal::Random* random) {
3768 Shuffle(random, &test_indices_);
3771 // Restores the test order to before the first shuffle.
3772 void TestCase::UnshuffleTests() {
3773 for (size_t i = 0; i < test_indices_.size(); i++) {
3774 test_indices_[i] = static_cast<int>(i);
3778 // Formats a countable noun. Depending on its quantity, either the
3779 // singular form or the plural form is used. e.g.
3781 // FormatCountableNoun(1, "formula", "formuli") returns "1 formula".
3782 // FormatCountableNoun(5, "book", "books") returns "5 books".
3783 static internal::String FormatCountableNoun(int count,
3784 const char * singular_form,
3785 const char * plural_form) {
3786 return internal::String::Format("%d %s", count,
3787 count == 1 ? singular_form : plural_form);
3790 // Formats the count of tests.
3791 static internal::String FormatTestCount(int test_count) {
3792 return FormatCountableNoun(test_count, "test", "tests");
3795 // Formats the count of test cases.
3796 static internal::String FormatTestCaseCount(int test_case_count) {
3797 return FormatCountableNoun(test_case_count, "test case", "test cases");
3800 // Converts a TestPartResult::Type enum to human-friendly string
3801 // representation. Both kNonFatalFailure and kFatalFailure are translated
3802 // to "Failure", as the user usually doesn't care about the difference
3803 // between the two when viewing the test result.
3804 static const char * TestPartResultTypeToString(TestPartResult::Type type) {
3806 case TestPartResult::kSuccess:
3809 case TestPartResult::kNonFatalFailure:
3810 case TestPartResult::kFatalFailure:
3817 return "Unknown result type";
3821 // Prints a TestPartResult to a String.
3822 static internal::String PrintTestPartResultToString(
3823 const TestPartResult& test_part_result) {
3825 << internal::FormatFileLocation(test_part_result.file_name(),
3826 test_part_result.line_number())
3827 << " " << TestPartResultTypeToString(test_part_result.type())
3828 << test_part_result.message()).GetString();
3831 // Prints a TestPartResult.
3832 static void PrintTestPartResult(const TestPartResult& test_part_result) {
3833 const internal::String& result =
3834 PrintTestPartResultToString(test_part_result);
3835 printf("%s\n", result.c_str());
3837 // If the test program runs in Visual Studio or a debugger, the
3838 // following statements add the test part result message to the Output
3839 // window such that the user can double-click on it to jump to the
3840 // corresponding source code location; otherwise they do nothing.
3841 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
3842 // We don't call OutputDebugString*() on Windows Mobile, as printing
3843 // to stdout is done by OutputDebugString() there already - we don't
3844 // want the same message printed twice.
3845 ::OutputDebugStringA(result.c_str());
3846 ::OutputDebugStringA("\n");
3850 // class PrettyUnitTestResultPrinter
3852 namespace internal {
3861 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
3863 // Returns the character attribute for the given color.
3864 WORD GetColorAttribute(GTestColor color) {
3866 case COLOR_RED: return FOREGROUND_RED;
3867 case COLOR_GREEN: return FOREGROUND_GREEN;
3868 case COLOR_YELLOW: return FOREGROUND_RED | FOREGROUND_GREEN;
3875 // Returns the ANSI color code for the given color. COLOR_DEFAULT is
3876 // an invalid input.
3877 const char* GetAnsiColorCode(GTestColor color) {
3879 case COLOR_RED: return "1";
3880 case COLOR_GREEN: return "2";
3881 case COLOR_YELLOW: return "3";
3882 default: return NULL;
3886 #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
3888 // Returns true iff Google Test should use colors in the output.
3889 bool ShouldUseColor(bool stdout_is_tty) {
3890 const char* const gtest_color = GTEST_FLAG(color).c_str();
3892 if (String::CaseInsensitiveCStringEquals(gtest_color, "auto")) {
3893 #if GTEST_OS_WINDOWS
3894 // On Windows the TERM variable is usually not set, but the
3895 // console there does support colors.
3896 return stdout_is_tty;
3898 // On non-Windows platforms, we rely on the TERM variable.
3899 const char* const term = posix::GetEnv("TERM");
3900 const bool term_supports_color =
3901 String::CStringEquals(term, "xterm") ||
3902 String::CStringEquals(term, "xterm-color") ||
3903 String::CStringEquals(term, "xterm-256color") ||
3904 String::CStringEquals(term, "screen") ||
3905 String::CStringEquals(term, "linux") ||
3906 String::CStringEquals(term, "cygwin");
3907 return stdout_is_tty && term_supports_color;
3908 #endif // GTEST_OS_WINDOWS
3911 return String::CaseInsensitiveCStringEquals(gtest_color, "yes") ||
3912 String::CaseInsensitiveCStringEquals(gtest_color, "true") ||
3913 String::CaseInsensitiveCStringEquals(gtest_color, "t") ||
3914 String::CStringEquals(gtest_color, "1");
3915 // We take "yes", "true", "t", and "1" as meaning "yes". If the
3916 // value is neither one of these nor "auto", we treat it as "no" to
3920 // Helpers for printing colored strings to stdout. Note that on Windows, we
3921 // cannot simply emit special characters and have the terminal change colors.
3922 // This routine must actually emit the characters rather than return a string
3923 // that would be colored when printed, as can be done on Linux.
3924 void ColoredPrintf(GTestColor color, const char* fmt, ...) {
3926 va_start(args, fmt);
3928 #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS
3929 const bool use_color = false;
3931 static const bool in_color_mode =
3932 ShouldUseColor(posix::IsATTY(posix::FileNo(stdout)) != 0);
3933 const bool use_color = in_color_mode && (color != COLOR_DEFAULT);
3934 #endif // GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS
3935 // The '!= 0' comparison is necessary to satisfy MSVC 7.1.
3943 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
3944 const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
3946 // Gets the current text color.
3947 CONSOLE_SCREEN_BUFFER_INFO buffer_info;
3948 GetConsoleScreenBufferInfo(stdout_handle, &buffer_info);
3949 const WORD old_color_attrs = buffer_info.wAttributes;
3951 // We need to flush the stream buffers into the console before each
3952 // SetConsoleTextAttribute call lest it affect the text that is already
3953 // printed but has not yet reached the console.
3955 SetConsoleTextAttribute(stdout_handle,
3956 GetColorAttribute(color) | FOREGROUND_INTENSITY);
3960 // Restores the text color.
3961 SetConsoleTextAttribute(stdout_handle, old_color_attrs);
3963 printf("\033[0;3%sm", GetAnsiColorCode(color));
3965 printf("\033[m"); // Resets the terminal to default.
3966 #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
3970 void PrintFullTestCommentIfPresent(const TestInfo& test_info) {
3971 const char* const type_param = test_info.type_param();
3972 const char* const value_param = test_info.value_param();
3974 if (type_param != NULL || value_param != NULL) {
3976 if (type_param != NULL) {
3977 printf("TypeParam = %s", type_param);
3978 if (value_param != NULL)
3981 if (value_param != NULL) {
3982 printf("GetParam() = %s", value_param);
3987 // This class implements the TestEventListener interface.
3989 // Class PrettyUnitTestResultPrinter is copyable.
3990 class PrettyUnitTestResultPrinter : public TestEventListener {
3992 PrettyUnitTestResultPrinter() {}
3993 static void PrintTestName(const char * test_case, const char * test) {
3994 printf("%s.%s", test_case, test);
3997 // The following methods override what's in the TestEventListener class.
3998 virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {}
3999 virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration);
4000 virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test);
4001 virtual void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) {}
4002 virtual void OnTestCaseStart(const TestCase& test_case);
4003 virtual void OnTestStart(const TestInfo& test_info);
4004 virtual void OnTestPartResult(const TestPartResult& result);
4005 virtual void OnTestEnd(const TestInfo& test_info);
4006 virtual void OnTestCaseEnd(const TestCase& test_case);
4007 virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test);
4008 virtual void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) {}
4009 virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
4010 virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) {}
4013 static void PrintFailedTests(const UnitTest& unit_test);
4015 internal::String test_case_name_;
4018 // Fired before each iteration of tests starts.
4019 void PrettyUnitTestResultPrinter::OnTestIterationStart(
4020 const UnitTest& unit_test, int iteration) {
4021 if (GTEST_FLAG(repeat) != 1)
4022 printf("\nRepeating all tests (iteration %d) . . .\n\n", iteration + 1);
4024 const char* const filter = GTEST_FLAG(filter).c_str();
4026 // Prints the filter if it's not *. This reminds the user that some
4027 // tests may be skipped.
4028 if (!internal::String::CStringEquals(filter, kUniversalFilter)) {
4029 ColoredPrintf(COLOR_YELLOW,
4030 "Note: %s filter = %s\n", GTEST_NAME_, filter);
4033 if (internal::ShouldShard(kTestTotalShards, kTestShardIndex, false)) {
4034 const Int32 shard_index = Int32FromEnvOrDie(kTestShardIndex, -1);
4035 ColoredPrintf(COLOR_YELLOW,
4036 "Note: This is test shard %d of %s.\n",
4037 static_cast<int>(shard_index) + 1,
4038 internal::posix::GetEnv(kTestTotalShards));
4041 if (GTEST_FLAG(shuffle)) {
4042 ColoredPrintf(COLOR_YELLOW,
4043 "Note: Randomizing tests' orders with a seed of %d .\n",
4044 unit_test.random_seed());
4047 ColoredPrintf(COLOR_GREEN, "[==========] ");
4048 printf("Running %s from %s.\n",
4049 FormatTestCount(unit_test.test_to_run_count()).c_str(),
4050 FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str());
4054 void PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart(
4055 const UnitTest& /*unit_test*/) {
4056 ColoredPrintf(COLOR_GREEN, "[----------] ");
4057 printf("Global test environment set-up.\n");
4061 void PrettyUnitTestResultPrinter::OnTestCaseStart(const TestCase& test_case) {
4062 test_case_name_ = test_case.name();
4063 const internal::String counts =
4064 FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
4065 ColoredPrintf(COLOR_GREEN, "[----------] ");
4066 printf("%s from %s", counts.c_str(), test_case_name_.c_str());
4067 if (test_case.type_param() == NULL) {
4070 printf(", where TypeParam = %s\n", test_case.type_param());
4075 void PrettyUnitTestResultPrinter::OnTestStart(const TestInfo& test_info) {
4076 ColoredPrintf(COLOR_GREEN, "[ RUN ] ");
4077 PrintTestName(test_case_name_.c_str(), test_info.name());
4082 // Called after an assertion failure.
4083 void PrettyUnitTestResultPrinter::OnTestPartResult(
4084 const TestPartResult& result) {
4085 // If the test part succeeded, we don't need to do anything.
4086 if (result.type() == TestPartResult::kSuccess)
4089 // Print failure message from the assertion (e.g. expected this and got that).
4090 PrintTestPartResult(result);
4094 void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) {
4095 if (test_info.result()->Passed()) {
4096 ColoredPrintf(COLOR_GREEN, "[ OK ] ");
4098 ColoredPrintf(COLOR_RED, "[ FAILED ] ");
4100 PrintTestName(test_case_name_.c_str(), test_info.name());
4101 if (test_info.result()->Failed())
4102 PrintFullTestCommentIfPresent(test_info);
4104 if (GTEST_FLAG(print_time)) {
4105 printf(" (%s ms)\n", internal::StreamableToString(
4106 test_info.result()->elapsed_time()).c_str());
4113 void PrettyUnitTestResultPrinter::OnTestCaseEnd(const TestCase& test_case) {
4114 if (!GTEST_FLAG(print_time)) return;
4116 test_case_name_ = test_case.name();
4117 const internal::String counts =
4118 FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
4119 ColoredPrintf(COLOR_GREEN, "[----------] ");
4120 printf("%s from %s (%s ms total)\n\n",
4121 counts.c_str(), test_case_name_.c_str(),
4122 internal::StreamableToString(test_case.elapsed_time()).c_str());
4126 void PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart(
4127 const UnitTest& /*unit_test*/) {
4128 ColoredPrintf(COLOR_GREEN, "[----------] ");
4129 printf("Global test environment tear-down\n");
4133 // Internal helper for printing the list of failed tests.
4134 void PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest& unit_test) {
4135 const int failed_test_count = unit_test.failed_test_count();
4136 if (failed_test_count == 0) {
4140 for (int i = 0; i < unit_test.total_test_case_count(); ++i) {
4141 const TestCase& test_case = *unit_test.GetTestCase(i);
4142 if (!test_case.should_run() || (test_case.failed_test_count() == 0)) {
4145 for (int j = 0; j < test_case.total_test_count(); ++j) {
4146 const TestInfo& test_info = *test_case.GetTestInfo(j);
4147 if (!test_info.should_run() || test_info.result()->Passed()) {
4150 ColoredPrintf(COLOR_RED, "[ FAILED ] ");
4151 printf("%s.%s", test_case.name(), test_info.name());
4152 PrintFullTestCommentIfPresent(test_info);
4158 void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
4159 int /*iteration*/) {
4160 ColoredPrintf(COLOR_GREEN, "[==========] ");
4161 printf("%s from %s ran.",
4162 FormatTestCount(unit_test.test_to_run_count()).c_str(),
4163 FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str());
4164 if (GTEST_FLAG(print_time)) {
4165 printf(" (%s ms total)",
4166 internal::StreamableToString(unit_test.elapsed_time()).c_str());
4169 ColoredPrintf(COLOR_GREEN, "[ PASSED ] ");
4170 printf("%s.\n", FormatTestCount(unit_test.successful_test_count()).c_str());
4172 int num_failures = unit_test.failed_test_count();
4173 if (!unit_test.Passed()) {
4174 const int failed_test_count = unit_test.failed_test_count();
4175 ColoredPrintf(COLOR_RED, "[ FAILED ] ");
4176 printf("%s, listed below:\n", FormatTestCount(failed_test_count).c_str());
4177 PrintFailedTests(unit_test);
4178 printf("\n%2d FAILED %s\n", num_failures,
4179 num_failures == 1 ? "TEST" : "TESTS");
4182 int num_disabled = unit_test.disabled_test_count();
4183 if (num_disabled && !GTEST_FLAG(also_run_disabled_tests)) {
4184 if (!num_failures) {
4185 printf("\n"); // Add a spacer if no FAILURE banner is displayed.
4187 ColoredPrintf(COLOR_YELLOW,
4188 " YOU HAVE %d DISABLED %s\n\n",
4190 num_disabled == 1 ? "TEST" : "TESTS");
4192 // Ensure that Google Test output is printed before, e.g., heapchecker output.
4196 // End PrettyUnitTestResultPrinter
4198 // class TestEventRepeater
4200 // This class forwards events to other event listeners.
4201 class TestEventRepeater : public TestEventListener {
4203 TestEventRepeater() : forwarding_enabled_(true) {}
4204 virtual ~TestEventRepeater();
4205 void Append(TestEventListener *listener);
4206 TestEventListener* Release(TestEventListener* listener);
4208 // Controls whether events will be forwarded to listeners_. Set to false
4209 // in death test child processes.
4210 bool forwarding_enabled() const { return forwarding_enabled_; }
4211 void set_forwarding_enabled(bool enable) { forwarding_enabled_ = enable; }
4213 virtual void OnTestProgramStart(const UnitTest& unit_test);
4214 virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration);
4215 virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test);
4216 virtual void OnEnvironmentsSetUpEnd(const UnitTest& unit_test);
4217 virtual void OnTestCaseStart(const TestCase& test_case);
4218 virtual void OnTestStart(const TestInfo& test_info);
4219 virtual void OnTestPartResult(const TestPartResult& result);
4220 virtual void OnTestEnd(const TestInfo& test_info);
4221 virtual void OnTestCaseEnd(const TestCase& test_case);
4222 virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test);
4223 virtual void OnEnvironmentsTearDownEnd(const UnitTest& unit_test);
4224 virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
4225 virtual void OnTestProgramEnd(const UnitTest& unit_test);
4228 // Controls whether events will be forwarded to listeners_. Set to false
4229 // in death test child processes.
4230 bool forwarding_enabled_;
4231 // The list of listeners that receive events.
4232 std::vector<TestEventListener*> listeners_;
4234 GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventRepeater);
4237 TestEventRepeater::~TestEventRepeater() {
4238 ForEach(listeners_, Delete<TestEventListener>);
4241 void TestEventRepeater::Append(TestEventListener *listener) {
4242 listeners_.push_back(listener);
4245 // TODO(vladl@google.com): Factor the search functionality into Vector::Find.
4246 TestEventListener* TestEventRepeater::Release(TestEventListener *listener) {
4247 for (size_t i = 0; i < listeners_.size(); ++i) {
4248 if (listeners_[i] == listener) {
4249 listeners_.erase(listeners_.begin() + i);
4257 // Since most methods are very similar, use macros to reduce boilerplate.
4258 // This defines a member that forwards the call to all listeners.
4259 #define GTEST_REPEATER_METHOD_(Name, Type) \
4260 void TestEventRepeater::Name(const Type& parameter) { \
4261 if (forwarding_enabled_) { \
4262 for (size_t i = 0; i < listeners_.size(); i++) { \
4263 listeners_[i]->Name(parameter); \
4267 // This defines a member that forwards the call to all listeners in reverse
4269 #define GTEST_REVERSE_REPEATER_METHOD_(Name, Type) \
4270 void TestEventRepeater::Name(const Type& parameter) { \
4271 if (forwarding_enabled_) { \
4272 for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) { \
4273 listeners_[i]->Name(parameter); \
4278 GTEST_REPEATER_METHOD_(OnTestProgramStart, UnitTest)
4279 GTEST_REPEATER_METHOD_(OnEnvironmentsSetUpStart, UnitTest)
4280 GTEST_REPEATER_METHOD_(OnTestCaseStart, TestCase)
4281 GTEST_REPEATER_METHOD_(OnTestStart, TestInfo)
4282 GTEST_REPEATER_METHOD_(OnTestPartResult, TestPartResult)
4283 GTEST_REPEATER_METHOD_(OnEnvironmentsTearDownStart, UnitTest)
4284 GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsSetUpEnd, UnitTest)
4285 GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsTearDownEnd, UnitTest)
4286 GTEST_REVERSE_REPEATER_METHOD_(OnTestEnd, TestInfo)
4287 GTEST_REVERSE_REPEATER_METHOD_(OnTestCaseEnd, TestCase)
4288 GTEST_REVERSE_REPEATER_METHOD_(OnTestProgramEnd, UnitTest)
4290 #undef GTEST_REPEATER_METHOD_
4291 #undef GTEST_REVERSE_REPEATER_METHOD_
4293 void TestEventRepeater::OnTestIterationStart(const UnitTest& unit_test,
4295 if (forwarding_enabled_) {
4296 for (size_t i = 0; i < listeners_.size(); i++) {
4297 listeners_[i]->OnTestIterationStart(unit_test, iteration);
4302 void TestEventRepeater::OnTestIterationEnd(const UnitTest& unit_test,
4304 if (forwarding_enabled_) {
4305 for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) {
4306 listeners_[i]->OnTestIterationEnd(unit_test, iteration);
4311 // End TestEventRepeater
4313 // This class generates an XML output file.
4314 class XmlUnitTestResultPrinter : public EmptyTestEventListener {
4316 explicit XmlUnitTestResultPrinter(const char* output_file);
4318 virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
4321 // Is c a whitespace character that is normalized to a space character
4322 // when it appears in an XML attribute value?
4323 static bool IsNormalizableWhitespace(char c) {
4324 return c == 0x9 || c == 0xA || c == 0xD;
4327 // May c appear in a well-formed XML document?
4328 static bool IsValidXmlCharacter(char c) {
4329 return IsNormalizableWhitespace(c) || c >= 0x20;
4332 // Returns an XML-escaped copy of the input string str. If
4333 // is_attribute is true, the text is meant to appear as an attribute
4334 // value, and normalizable whitespace is preserved by replacing it
4335 // with character references.
4336 static String EscapeXml(const char* str, bool is_attribute);
4338 // Returns the given string with all characters invalid in XML removed.
4339 static string RemoveInvalidXmlCharacters(const string& str);
4341 // Convenience wrapper around EscapeXml when str is an attribute value.
4342 static String EscapeXmlAttribute(const char* str) {
4343 return EscapeXml(str, true);
4346 // Convenience wrapper around EscapeXml when str is not an attribute value.
4347 static String EscapeXmlText(const char* str) { return EscapeXml(str, false); }
4349 // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
4350 static void OutputXmlCDataSection(::std::ostream* stream, const char* data);
4352 // Streams an XML representation of a TestInfo object.
4353 static void OutputXmlTestInfo(::std::ostream* stream,
4354 const char* test_case_name,
4355 const TestInfo& test_info);
4357 // Prints an XML representation of a TestCase object
4358 static void PrintXmlTestCase(FILE* out, const TestCase& test_case);
4360 // Prints an XML summary of unit_test to output stream out.
4361 static void PrintXmlUnitTest(FILE* out, const UnitTest& unit_test);
4363 // Produces a string representing the test properties in a result as space
4364 // delimited XML attributes based on the property key="value" pairs.
4365 // When the String is not empty, it includes a space at the beginning,
4366 // to delimit this attribute from prior attributes.
4367 static String TestPropertiesAsXmlAttributes(const TestResult& result);
4370 const String output_file_;
4372 GTEST_DISALLOW_COPY_AND_ASSIGN_(XmlUnitTestResultPrinter);
4375 // Creates a new XmlUnitTestResultPrinter.
4376 XmlUnitTestResultPrinter::XmlUnitTestResultPrinter(const char* output_file)
4377 : output_file_(output_file) {
4378 if (output_file_.c_str() == NULL || output_file_.empty()) {
4379 fprintf(stderr, "XML output file may not be null\n");
4385 // Called after the unit test ends.
4386 void XmlUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
4387 int /*iteration*/) {
4388 FILE* xmlout = NULL;
4389 FilePath output_file(output_file_);
4390 FilePath output_dir(output_file.RemoveFileName());
4392 if (output_dir.CreateDirectoriesRecursively()) {
4393 xmlout = posix::FOpen(output_file_.c_str(), "w");
4395 if (xmlout == NULL) {
4396 // TODO(wan): report the reason of the failure.
4398 // We don't do it for now as:
4400 // 1. There is no urgent need for it.
4401 // 2. It's a bit involved to make the errno variable thread-safe on
4402 // all three operating systems (Linux, Windows, and Mac OS).
4403 // 3. To interpret the meaning of errno in a thread-safe way,
4404 // we need the strerror_r() function, which is not available on
4407 "Unable to open file \"%s\"\n",
4408 output_file_.c_str());
4412 PrintXmlUnitTest(xmlout, unit_test);
4416 // Returns an XML-escaped copy of the input string str. If is_attribute
4417 // is true, the text is meant to appear as an attribute value, and
4418 // normalizable whitespace is preserved by replacing it with character
4421 // Invalid XML characters in str, if any, are stripped from the output.
4422 // It is expected that most, if not all, of the text processed by this
4423 // module will consist of ordinary English text.
4424 // If this module is ever modified to produce version 1.1 XML output,
4425 // most invalid characters can be retained using character references.
4426 // TODO(wan): It might be nice to have a minimally invasive, human-readable
4427 // escaping scheme for invalid characters, rather than dropping them.
4428 String XmlUnitTestResultPrinter::EscapeXml(const char* str, bool is_attribute) {
4432 for (const char* src = str; *src; ++src) {
4456 if (IsValidXmlCharacter(*src)) {
4457 if (is_attribute && IsNormalizableWhitespace(*src))
4458 m << String::Format("&#x%02X;", unsigned(*src));
4467 return m.GetString();
4470 // Returns the given string with all characters invalid in XML removed.
4471 // Currently invalid characters are dropped from the string. An
4472 // alternative is to replace them with certain characters such as . or ?.
4473 string XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters(const string& str) {
4475 output.reserve(str.size());
4476 for (string::const_iterator it = str.begin(); it != str.end(); ++it)
4477 if (IsValidXmlCharacter(*it))
4478 output.push_back(*it);
4483 // The following routines generate an XML representation of a UnitTest
4486 // This is how Google Test concepts map to the DTD:
4488 // <testsuites name="AllTests"> <-- corresponds to a UnitTest object
4489 // <testsuite name="testcase-name"> <-- corresponds to a TestCase object
4490 // <testcase name="test-name"> <-- corresponds to a TestInfo object
4491 // <failure message="...">...</failure>
4492 // <failure message="...">...</failure>
4493 // <failure message="...">...</failure>
4494 // <-- individual assertion failures
4499 // Formats the given time in milliseconds as seconds.
4500 std::string FormatTimeInMillisAsSeconds(TimeInMillis ms) {
4501 ::std::stringstream ss;
4506 // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
4507 void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream,
4509 const char* segment = data;
4510 *stream << "<![CDATA[";
4512 const char* const next_segment = strstr(segment, "]]>");
4513 if (next_segment != NULL) {
4515 segment, static_cast<std::streamsize>(next_segment - segment));
4516 *stream << "]]>]]><![CDATA[";
4517 segment = next_segment + strlen("]]>");
4526 // Prints an XML representation of a TestInfo object.
4527 // TODO(wan): There is also value in printing properties with the plain printer.
4528 void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream,
4529 const char* test_case_name,
4530 const TestInfo& test_info) {
4531 const TestResult& result = *test_info.result();
4532 *stream << " <testcase name=\""
4533 << EscapeXmlAttribute(test_info.name()).c_str() << "\"";
4535 if (test_info.value_param() != NULL) {
4536 *stream << " value_param=\"" << EscapeXmlAttribute(test_info.value_param())
4539 if (test_info.type_param() != NULL) {
4540 *stream << " type_param=\"" << EscapeXmlAttribute(test_info.type_param())
4544 *stream << " status=\""
4545 << (test_info.should_run() ? "run" : "notrun")
4547 << FormatTimeInMillisAsSeconds(result.elapsed_time())
4548 << "\" classname=\"" << EscapeXmlAttribute(test_case_name).c_str()
4549 << "\"" << TestPropertiesAsXmlAttributes(result).c_str();
4552 for (int i = 0; i < result.total_part_count(); ++i) {
4553 const TestPartResult& part = result.GetTestPartResult(i);
4554 if (part.failed()) {
4555 if (++failures == 1)
4557 *stream << " <failure message=\""
4558 << EscapeXmlAttribute(part.summary()).c_str()
4560 const string location = internal::FormatCompilerIndependentFileLocation(
4561 part.file_name(), part.line_number());
4562 const string message = location + "\n" + part.message();
4563 OutputXmlCDataSection(stream,
4564 RemoveInvalidXmlCharacters(message).c_str());
4565 *stream << "</failure>\n";
4572 *stream << " </testcase>\n";
4575 // Prints an XML representation of a TestCase object
4576 void XmlUnitTestResultPrinter::PrintXmlTestCase(FILE* out,
4577 const TestCase& test_case) {
4579 " <testsuite name=\"%s\" tests=\"%d\" failures=\"%d\" "
4581 EscapeXmlAttribute(test_case.name()).c_str(),
4582 test_case.total_test_count(),
4583 test_case.failed_test_count(),
4584 test_case.disabled_test_count());
4586 "errors=\"0\" time=\"%s\">\n",
4587 FormatTimeInMillisAsSeconds(test_case.elapsed_time()).c_str());
4588 for (int i = 0; i < test_case.total_test_count(); ++i) {
4589 ::std::stringstream stream;
4590 OutputXmlTestInfo(&stream, test_case.name(), *test_case.GetTestInfo(i));
4591 fprintf(out, "%s", StringStreamToString(&stream).c_str());
4593 fprintf(out, " </testsuite>\n");
4596 // Prints an XML summary of unit_test to output stream out.
4597 void XmlUnitTestResultPrinter::PrintXmlUnitTest(FILE* out,
4598 const UnitTest& unit_test) {
4599 fprintf(out, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
4601 "<testsuites tests=\"%d\" failures=\"%d\" disabled=\"%d\" "
4602 "errors=\"0\" time=\"%s\" ",
4603 unit_test.total_test_count(),
4604 unit_test.failed_test_count(),
4605 unit_test.disabled_test_count(),
4606 FormatTimeInMillisAsSeconds(unit_test.elapsed_time()).c_str());
4607 if (GTEST_FLAG(shuffle)) {
4608 fprintf(out, "random_seed=\"%d\" ", unit_test.random_seed());
4610 fprintf(out, "name=\"AllTests\">\n");
4611 for (int i = 0; i < unit_test.total_test_case_count(); ++i)
4612 PrintXmlTestCase(out, *unit_test.GetTestCase(i));
4613 fprintf(out, "</testsuites>\n");
4616 // Produces a string representing the test properties in a result as space
4617 // delimited XML attributes based on the property key="value" pairs.
4618 String XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes(
4619 const TestResult& result) {
4621 for (int i = 0; i < result.test_property_count(); ++i) {
4622 const TestProperty& property = result.GetTestProperty(i);
4623 attributes << " " << property.key() << "="
4624 << "\"" << EscapeXmlAttribute(property.value()) << "\"";
4626 return attributes.GetString();
4629 // End XmlUnitTestResultPrinter
4631 #if GTEST_CAN_STREAM_RESULTS_
4633 // Streams test results to the given port on the given host machine.
4634 class StreamingListener : public EmptyTestEventListener {
4636 // Escapes '=', '&', '%', and '\n' characters in str as "%xx".
4637 static string UrlEncode(const char* str);
4639 StreamingListener(const string& host, const string& port)
4640 : sockfd_(-1), host_name_(host), port_num_(port) {
4642 Send("gtest_streaming_protocol_version=1.0\n");
4645 virtual ~StreamingListener() {
4650 void OnTestProgramStart(const UnitTest& /* unit_test */) {
4651 Send("event=TestProgramStart\n");
4654 void OnTestProgramEnd(const UnitTest& unit_test) {
4655 // Note that Google Test current only report elapsed time for each
4656 // test iteration, not for the entire test program.
4657 Send(String::Format("event=TestProgramEnd&passed=%d\n",
4658 unit_test.Passed()));
4660 // Notify the streaming server to stop.
4664 void OnTestIterationStart(const UnitTest& /* unit_test */, int iteration) {
4665 Send(String::Format("event=TestIterationStart&iteration=%d\n",
4669 void OnTestIterationEnd(const UnitTest& unit_test, int /* iteration */) {
4670 Send(String::Format("event=TestIterationEnd&passed=%d&elapsed_time=%sms\n",
4672 StreamableToString(unit_test.elapsed_time()).c_str()));
4675 void OnTestCaseStart(const TestCase& test_case) {
4676 Send(String::Format("event=TestCaseStart&name=%s\n", test_case.name()));
4679 void OnTestCaseEnd(const TestCase& test_case) {
4680 Send(String::Format("event=TestCaseEnd&passed=%d&elapsed_time=%sms\n",
4682 StreamableToString(test_case.elapsed_time()).c_str()));
4685 void OnTestStart(const TestInfo& test_info) {
4686 Send(String::Format("event=TestStart&name=%s\n", test_info.name()));
4689 void OnTestEnd(const TestInfo& test_info) {
4690 Send(String::Format(
4691 "event=TestEnd&passed=%d&elapsed_time=%sms\n",
4692 (test_info.result())->Passed(),
4693 StreamableToString((test_info.result())->elapsed_time()).c_str()));
4696 void OnTestPartResult(const TestPartResult& test_part_result) {
4697 const char* file_name = test_part_result.file_name();
4698 if (file_name == NULL)
4700 Send(String::Format("event=TestPartResult&file=%s&line=%d&message=",
4701 UrlEncode(file_name).c_str(),
4702 test_part_result.line_number()));
4703 Send(UrlEncode(test_part_result.message()) + "\n");
4707 // Creates a client socket and connects to the server.
4708 void MakeConnection();
4710 // Closes the socket.
4711 void CloseConnection() {
4712 GTEST_CHECK_(sockfd_ != -1)
4713 << "CloseConnection() can be called only when there is a connection.";
4719 // Sends a string to the socket.
4720 void Send(const string& message) {
4721 GTEST_CHECK_(sockfd_ != -1)
4722 << "Send() can be called only when there is a connection.";
4724 const int len = static_cast<int>(message.length());
4725 if (write(sockfd_, message.c_str(), len) != len) {
4727 << "stream_result_to: failed to stream to "
4728 << host_name_ << ":" << port_num_;
4732 int sockfd_; // socket file descriptor
4733 const string host_name_;
4734 const string port_num_;
4736 GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamingListener);
4737 }; // class StreamingListener
4739 // Checks if str contains '=', '&', '%' or '\n' characters. If yes,
4740 // replaces them by "%xx" where xx is their hexadecimal value. For
4741 // example, replaces "=" with "%3D". This algorithm is O(strlen(str))
4742 // in both time and space -- important as the input str may contain an
4743 // arbitrarily long test failure message and stack trace.
4744 string StreamingListener::UrlEncode(const char* str) {
4746 result.reserve(strlen(str) + 1);
4747 for (char ch = *str; ch != '\0'; ch = *++str) {
4753 result.append(String::Format("%%%02x", static_cast<unsigned char>(ch)));
4756 result.push_back(ch);
4763 void StreamingListener::MakeConnection() {
4764 GTEST_CHECK_(sockfd_ == -1)
4765 << "MakeConnection() can't be called when there is already a connection.";
4768 memset(&hints, 0, sizeof(hints));
4769 hints.ai_family = AF_UNSPEC; // To allow both IPv4 and IPv6 addresses.
4770 hints.ai_socktype = SOCK_STREAM;
4771 addrinfo* servinfo = NULL;
4773 // Use the getaddrinfo() to get a linked list of IP addresses for
4774 // the given host name.
4775 const int error_num = getaddrinfo(
4776 host_name_.c_str(), port_num_.c_str(), &hints, &servinfo);
4777 if (error_num != 0) {
4778 GTEST_LOG_(WARNING) << "stream_result_to: getaddrinfo() failed: "
4779 << gai_strerror(error_num);
4782 // Loop through all the results and connect to the first we can.
4783 for (addrinfo* cur_addr = servinfo; sockfd_ == -1 && cur_addr != NULL;
4784 cur_addr = cur_addr->ai_next) {
4786 cur_addr->ai_family, cur_addr->ai_socktype, cur_addr->ai_protocol);
4787 if (sockfd_ != -1) {
4788 // Connect the client socket to the server socket.
4789 if (connect(sockfd_, cur_addr->ai_addr, cur_addr->ai_addrlen) == -1) {
4796 freeaddrinfo(servinfo); // all done with this structure
4798 if (sockfd_ == -1) {
4799 GTEST_LOG_(WARNING) << "stream_result_to: failed to connect to "
4800 << host_name_ << ":" << port_num_;
4804 // End of class Streaming Listener
4805 #endif // GTEST_CAN_STREAM_RESULTS__
4807 // Class ScopedTrace
4809 // Pushes the given source file location and message onto a per-thread
4810 // trace stack maintained by Google Test.
4811 // L < UnitTest::mutex_
4812 ScopedTrace::ScopedTrace(const char* file, int line, const Message& message) {
4816 trace.message = message.GetString();
4818 UnitTest::GetInstance()->PushGTestTrace(trace);
4821 // Pops the info pushed by the c'tor.
4822 // L < UnitTest::mutex_
4823 ScopedTrace::~ScopedTrace() {
4824 UnitTest::GetInstance()->PopGTestTrace();
4828 // class OsStackTraceGetter
4830 // Returns the current OS stack trace as a String. Parameters:
4832 // max_depth - the maximum number of stack frames to be included
4834 // skip_count - the number of top frames to be skipped; doesn't count
4835 // against max_depth.
4838 // We use "L < mutex_" to denote that the function may acquire mutex_.
4839 String OsStackTraceGetter::CurrentStackTrace(int, int) {
4844 void OsStackTraceGetter::UponLeavingGTest() {
4848 OsStackTraceGetter::kElidedFramesMarker =
4849 "... " GTEST_NAME_ " internal frames ...";
4851 } // namespace internal
4853 // class TestEventListeners
4855 TestEventListeners::TestEventListeners()
4856 : repeater_(new internal::TestEventRepeater()),
4857 default_result_printer_(NULL),
4858 default_xml_generator_(NULL) {
4861 TestEventListeners::~TestEventListeners() { delete repeater_; }
4863 // Returns the standard listener responsible for the default console
4864 // output. Can be removed from the listeners list to shut down default
4865 // console output. Note that removing this object from the listener list
4866 // with Release transfers its ownership to the user.
4867 void TestEventListeners::Append(TestEventListener* listener) {
4868 repeater_->Append(listener);
4871 // Removes the given event listener from the list and returns it. It then
4872 // becomes the caller's responsibility to delete the listener. Returns
4873 // NULL if the listener is not found in the list.
4874 TestEventListener* TestEventListeners::Release(TestEventListener* listener) {
4875 if (listener == default_result_printer_)
4876 default_result_printer_ = NULL;
4877 else if (listener == default_xml_generator_)
4878 default_xml_generator_ = NULL;
4879 return repeater_->Release(listener);
4882 // Returns repeater that broadcasts the TestEventListener events to all
4884 TestEventListener* TestEventListeners::repeater() { return repeater_; }
4886 // Sets the default_result_printer attribute to the provided listener.
4887 // The listener is also added to the listener list and previous
4888 // default_result_printer is removed from it and deleted. The listener can
4889 // also be NULL in which case it will not be added to the list. Does
4890 // nothing if the previous and the current listener objects are the same.
4891 void TestEventListeners::SetDefaultResultPrinter(TestEventListener* listener) {
4892 if (default_result_printer_ != listener) {
4893 // It is an error to pass this method a listener that is already in the
4895 delete Release(default_result_printer_);
4896 default_result_printer_ = listener;
4897 if (listener != NULL)
4902 // Sets the default_xml_generator attribute to the provided listener. The
4903 // listener is also added to the listener list and previous
4904 // default_xml_generator is removed from it and deleted. The listener can
4905 // also be NULL in which case it will not be added to the list. Does
4906 // nothing if the previous and the current listener objects are the same.
4907 void TestEventListeners::SetDefaultXmlGenerator(TestEventListener* listener) {
4908 if (default_xml_generator_ != listener) {
4909 // It is an error to pass this method a listener that is already in the
4911 delete Release(default_xml_generator_);
4912 default_xml_generator_ = listener;
4913 if (listener != NULL)
4918 // Controls whether events will be forwarded by the repeater to the
4919 // listeners in the list.
4920 bool TestEventListeners::EventForwardingEnabled() const {
4921 return repeater_->forwarding_enabled();
4924 void TestEventListeners::SuppressEventForwarding() {
4925 repeater_->set_forwarding_enabled(false);
4930 // Gets the singleton UnitTest object. The first time this method is
4931 // called, a UnitTest object is constructed and returned. Consecutive
4932 // calls will return the same object.
4934 // We don't protect this under mutex_ as a user is not supposed to
4935 // call this before main() starts, from which point on the return
4936 // value will never change.
4937 UnitTest * UnitTest::GetInstance() {
4938 // When compiled with MSVC 7.1 in optimized mode, destroying the
4939 // UnitTest object upon exiting the program messes up the exit code,
4940 // causing successful tests to appear failed. We have to use a
4941 // different implementation in this case to bypass the compiler bug.
4942 // This implementation makes the compiler happy, at the cost of
4943 // leaking the UnitTest object.
4945 // CodeGear C++Builder insists on a public destructor for the
4946 // default implementation. Use this implementation to keep good OO
4947 // design with private destructor.
4949 #if (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)
4950 static UnitTest* const instance = new UnitTest;
4953 static UnitTest instance;
4955 #endif // (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)
4958 // Gets the number of successful test cases.
4959 int UnitTest::successful_test_case_count() const {
4960 return impl()->successful_test_case_count();
4963 // Gets the number of failed test cases.
4964 int UnitTest::failed_test_case_count() const {
4965 return impl()->failed_test_case_count();
4968 // Gets the number of all test cases.
4969 int UnitTest::total_test_case_count() const {
4970 return impl()->total_test_case_count();
4973 // Gets the number of all test cases that contain at least one test
4975 int UnitTest::test_case_to_run_count() const {
4976 return impl()->test_case_to_run_count();
4979 // Gets the number of successful tests.
4980 int UnitTest::successful_test_count() const {
4981 return impl()->successful_test_count();
4984 // Gets the number of failed tests.
4985 int UnitTest::failed_test_count() const { return impl()->failed_test_count(); }
4987 // Gets the number of disabled tests.
4988 int UnitTest::disabled_test_count() const {
4989 return impl()->disabled_test_count();
4992 // Gets the number of all tests.
4993 int UnitTest::total_test_count() const { return impl()->total_test_count(); }
4995 // Gets the number of tests that should run.
4996 int UnitTest::test_to_run_count() const { return impl()->test_to_run_count(); }
4998 // Gets the elapsed time, in milliseconds.
4999 internal::TimeInMillis UnitTest::elapsed_time() const {
5000 return impl()->elapsed_time();
5003 // Returns true iff the unit test passed (i.e. all test cases passed).
5004 bool UnitTest::Passed() const { return impl()->Passed(); }
5006 // Returns true iff the unit test failed (i.e. some test case failed
5007 // or something outside of all tests failed).
5008 bool UnitTest::Failed() const { return impl()->Failed(); }
5010 // Gets the i-th test case among all the test cases. i can range from 0 to
5011 // total_test_case_count() - 1. If i is not in that range, returns NULL.
5012 const TestCase* UnitTest::GetTestCase(int i) const {
5013 return impl()->GetTestCase(i);
5016 // Gets the i-th test case among all the test cases. i can range from 0 to
5017 // total_test_case_count() - 1. If i is not in that range, returns NULL.
5018 TestCase* UnitTest::GetMutableTestCase(int i) {
5019 return impl()->GetMutableTestCase(i);
5022 // Returns the list of event listeners that can be used to track events
5023 // inside Google Test.
5024 TestEventListeners& UnitTest::listeners() {
5025 return *impl()->listeners();
5028 // Registers and returns a global test environment. When a test
5029 // program is run, all global test environments will be set-up in the
5030 // order they were registered. After all tests in the program have
5031 // finished, all global test environments will be torn-down in the
5032 // *reverse* order they were registered.
5034 // The UnitTest object takes ownership of the given environment.
5036 // We don't protect this under mutex_, as we only support calling it
5037 // from the main thread.
5038 Environment* UnitTest::AddEnvironment(Environment* env) {
5043 impl_->environments().push_back(env);
5047 // Adds a TestPartResult to the current TestResult object. All Google Test
5048 // assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) eventually call
5049 // this to report their results. The user code should use the
5050 // assertion macros instead of calling this directly.
5052 void UnitTest::AddTestPartResult(TestPartResult::Type result_type,
5053 const char* file_name,
5055 const internal::String& message,
5056 const internal::String& os_stack_trace) {
5060 internal::MutexLock lock(&mutex_);
5061 if (impl_->gtest_trace_stack().size() > 0) {
5062 msg << "\n" << GTEST_NAME_ << " trace:";
5064 for (int i = static_cast<int>(impl_->gtest_trace_stack().size());
5066 const internal::TraceInfo& trace = impl_->gtest_trace_stack()[i - 1];
5067 msg << "\n" << internal::FormatFileLocation(trace.file, trace.line)
5068 << " " << trace.message;
5072 if (os_stack_trace.c_str() != NULL && !os_stack_trace.empty()) {
5073 msg << internal::kStackTraceMarker << os_stack_trace;
5076 const TestPartResult result =
5077 TestPartResult(result_type, file_name, line_number,
5078 msg.GetString().c_str());
5079 impl_->GetTestPartResultReporterForCurrentThread()->
5080 ReportTestPartResult(result);
5082 if (result_type != TestPartResult::kSuccess) {
5083 // gtest_break_on_failure takes precedence over
5084 // gtest_throw_on_failure. This allows a user to set the latter
5085 // in the code (perhaps in order to use Google Test assertions
5086 // with another testing framework) and specify the former on the
5087 // command line for debugging.
5088 if (GTEST_FLAG(break_on_failure)) {
5089 #if GTEST_OS_WINDOWS
5090 // Using DebugBreak on Windows allows gtest to still break into a debugger
5091 // when a failure happens and both the --gtest_break_on_failure and
5092 // the --gtest_catch_exceptions flags are specified.
5095 // Dereference NULL through a volatile pointer to prevent the compiler
5096 // from removing. We use this rather than abort() or __builtin_trap() for
5097 // portability: Symbian doesn't implement abort() well, and some debuggers
5098 // don't correctly trap abort().
5099 *static_cast<volatile int*>(NULL) = 1;
5100 #endif // GTEST_OS_WINDOWS
5101 } else if (GTEST_FLAG(throw_on_failure)) {
5102 #if GTEST_HAS_EXCEPTIONS
5103 throw GoogleTestFailureException(result);
5105 // We cannot call abort() as it generates a pop-up in debug mode
5106 // that cannot be suppressed in VC 7.1 or below.
5113 // Creates and adds a property to the current TestResult. If a property matching
5114 // the supplied value already exists, updates its value instead.
5115 void UnitTest::RecordPropertyForCurrentTest(const char* key,
5116 const char* value) {
5117 const TestProperty test_property(key, value);
5118 impl_->current_test_result()->RecordProperty(test_property);
5121 // Runs all tests in this UnitTest object and prints the result.
5122 // Returns 0 if successful, or 1 otherwise.
5124 // We don't protect this under mutex_, as we only support calling it
5125 // from the main thread.
5126 int UnitTest::Run() {
5127 // Captures the value of GTEST_FLAG(catch_exceptions). This value will be
5128 // used for the duration of the program.
5129 impl()->set_catch_exceptions(GTEST_FLAG(catch_exceptions));
5132 const bool in_death_test_child_process =
5133 internal::GTEST_FLAG(internal_run_death_test).length() > 0;
5135 // Either the user wants Google Test to catch exceptions thrown by the
5136 // tests or this is executing in the context of death test child
5137 // process. In either case the user does not want to see pop-up dialogs
5138 // about crashes - they are expected.
5139 if (impl()->catch_exceptions() || in_death_test_child_process) {
5141 # if !GTEST_OS_WINDOWS_MOBILE
5142 // SetErrorMode doesn't exist on CE.
5143 SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT |
5144 SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);
5145 # endif // !GTEST_OS_WINDOWS_MOBILE
5147 # if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE
5148 // Death test children can be terminated with _abort(). On Windows,
5149 // _abort() can show a dialog with a warning message. This forces the
5150 // abort message to go to stderr instead.
5151 _set_error_mode(_OUT_TO_STDERR);
5154 # if _MSC_VER >= 1400 && !GTEST_OS_WINDOWS_MOBILE
5155 // In the debug version, Visual Studio pops up a separate dialog
5156 // offering a choice to debug the aborted program. We need to suppress
5157 // this dialog or it will pop up for every EXPECT/ASSERT_DEATH statement
5158 // executed. Google Test will notify the user of any unexpected
5159 // failure via stderr.
5161 // VC++ doesn't define _set_abort_behavior() prior to the version 8.0.
5162 // Users of prior VC versions shall suffer the agony and pain of
5163 // clicking through the countless debug dialogs.
5164 // TODO(vladl@google.com): find a way to suppress the abort dialog() in the
5165 // debug mode when compiled with VC 7.1 or lower.
5166 if (!GTEST_FLAG(break_on_failure))
5167 _set_abort_behavior(
5168 0x0, // Clear the following flags:
5169 _WRITE_ABORT_MSG | _CALL_REPORTFAULT); // pop-up window, core dump.
5173 #endif // GTEST_HAS_SEH
5175 return internal::HandleExceptionsInMethodIfSupported(
5177 &internal::UnitTestImpl::RunAllTests,
5178 "auxiliary test code (environments or event listeners)") ? 0 : 1;
5181 // Returns the working directory when the first TEST() or TEST_F() was
5183 const char* UnitTest::original_working_dir() const {
5184 return impl_->original_working_dir_.c_str();
5187 // Returns the TestCase object for the test that's currently running,
5188 // or NULL if no test is running.
5190 const TestCase* UnitTest::current_test_case() const {
5191 internal::MutexLock lock(&mutex_);
5192 return impl_->current_test_case();
5195 // Returns the TestInfo object for the test that's currently running,
5196 // or NULL if no test is running.
5198 const TestInfo* UnitTest::current_test_info() const {
5199 internal::MutexLock lock(&mutex_);
5200 return impl_->current_test_info();
5203 // Returns the random seed used at the start of the current test run.
5204 int UnitTest::random_seed() const { return impl_->random_seed(); }
5206 #if GTEST_HAS_PARAM_TEST
5207 // Returns ParameterizedTestCaseRegistry object used to keep track of
5208 // value-parameterized tests and instantiate and register them.
5210 internal::ParameterizedTestCaseRegistry&
5211 UnitTest::parameterized_test_registry() {
5212 return impl_->parameterized_test_registry();
5214 #endif // GTEST_HAS_PARAM_TEST
5216 // Creates an empty UnitTest.
5217 UnitTest::UnitTest() {
5218 impl_ = new internal::UnitTestImpl(this);
5221 // Destructor of UnitTest.
5222 UnitTest::~UnitTest() {
5226 // Pushes a trace defined by SCOPED_TRACE() on to the per-thread
5227 // Google Test trace stack.
5229 void UnitTest::PushGTestTrace(const internal::TraceInfo& trace) {
5230 internal::MutexLock lock(&mutex_);
5231 impl_->gtest_trace_stack().push_back(trace);
5234 // Pops a trace from the per-thread Google Test trace stack.
5236 void UnitTest::PopGTestTrace() {
5237 internal::MutexLock lock(&mutex_);
5238 impl_->gtest_trace_stack().pop_back();
5241 namespace internal {
5243 UnitTestImpl::UnitTestImpl(UnitTest* parent)
5246 # pragma warning(push) // Saves the current warning state.
5247 # pragma warning(disable:4355) // Temporarily disables warning 4355
5248 // (using this in initializer).
5249 default_global_test_part_result_reporter_(this),
5250 default_per_thread_test_part_result_reporter_(this),
5251 # pragma warning(pop) // Restores the warning state again.
5253 default_global_test_part_result_reporter_(this),
5254 default_per_thread_test_part_result_reporter_(this),
5256 global_test_part_result_repoter_(
5257 &default_global_test_part_result_reporter_),
5258 per_thread_test_part_result_reporter_(
5259 &default_per_thread_test_part_result_reporter_),
5260 #if GTEST_HAS_PARAM_TEST
5261 parameterized_test_registry_(),
5262 parameterized_tests_registered_(false),
5263 #endif // GTEST_HAS_PARAM_TEST
5264 last_death_test_case_(-1),
5265 current_test_case_(NULL),
5266 current_test_info_(NULL),
5267 ad_hoc_test_result_(),
5268 os_stack_trace_getter_(NULL),
5269 post_flag_parse_init_performed_(false),
5270 random_seed_(0), // Will be overridden by the flag before first use.
5271 random_(0), // Will be reseeded before first use.
5273 #if GTEST_HAS_DEATH_TEST
5274 internal_run_death_test_flag_(NULL),
5275 death_test_factory_(new DefaultDeathTestFactory),
5277 // Will be overridden by the flag before first use.
5278 catch_exceptions_(false) {
5279 listeners()->SetDefaultResultPrinter(new PrettyUnitTestResultPrinter);
5282 UnitTestImpl::~UnitTestImpl() {
5283 // Deletes every TestCase.
5284 ForEach(test_cases_, internal::Delete<TestCase>);
5286 // Deletes every Environment.
5287 ForEach(environments_, internal::Delete<Environment>);
5289 delete os_stack_trace_getter_;
5292 #if GTEST_HAS_DEATH_TEST
5293 // Disables event forwarding if the control is currently in a death test
5294 // subprocess. Must not be called before InitGoogleTest.
5295 void UnitTestImpl::SuppressTestEventsIfInSubprocess() {
5296 if (internal_run_death_test_flag_.get() != NULL)
5297 listeners()->SuppressEventForwarding();
5299 #endif // GTEST_HAS_DEATH_TEST
5301 // Initializes event listeners performing XML output as specified by
5302 // UnitTestOptions. Must not be called before InitGoogleTest.
5303 void UnitTestImpl::ConfigureXmlOutput() {
5304 const String& output_format = UnitTestOptions::GetOutputFormat();
5305 if (output_format == "xml") {
5306 listeners()->SetDefaultXmlGenerator(new XmlUnitTestResultPrinter(
5307 UnitTestOptions::GetAbsolutePathToOutputFile().c_str()));
5308 } else if (output_format != "") {
5309 printf("WARNING: unrecognized output format \"%s\" ignored.\n",
5310 output_format.c_str());
5315 #if GTEST_CAN_STREAM_RESULTS_
5316 // Initializes event listeners for streaming test results in String form.
5317 // Must not be called before InitGoogleTest.
5318 void UnitTestImpl::ConfigureStreamingOutput() {
5319 const string& target = GTEST_FLAG(stream_result_to);
5320 if (!target.empty()) {
5321 const size_t pos = target.find(':');
5322 if (pos != string::npos) {
5323 listeners()->Append(new StreamingListener(target.substr(0, pos),
5324 target.substr(pos+1)));
5326 printf("WARNING: unrecognized streaming target \"%s\" ignored.\n",
5332 #endif // GTEST_CAN_STREAM_RESULTS_
5334 // Performs initialization dependent upon flag values obtained in
5335 // ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to
5336 // ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest
5337 // this function is also called from RunAllTests. Since this function can be
5338 // called more than once, it has to be idempotent.
5339 void UnitTestImpl::PostFlagParsingInit() {
5340 // Ensures that this function does not execute more than once.
5341 if (!post_flag_parse_init_performed_) {
5342 post_flag_parse_init_performed_ = true;
5344 #if GTEST_HAS_DEATH_TEST
5345 InitDeathTestSubprocessControlInfo();
5346 SuppressTestEventsIfInSubprocess();
5347 #endif // GTEST_HAS_DEATH_TEST
5349 // Registers parameterized tests. This makes parameterized tests
5350 // available to the UnitTest reflection API without running
5352 RegisterParameterizedTests();
5354 // Configures listeners for XML output. This makes it possible for users
5355 // to shut down the default XML output before invoking RUN_ALL_TESTS.
5356 ConfigureXmlOutput();
5358 #if GTEST_CAN_STREAM_RESULTS_
5359 // Configures listeners for streaming test results to the specified server.
5360 ConfigureStreamingOutput();
5361 #endif // GTEST_CAN_STREAM_RESULTS_
5365 // A predicate that checks the name of a TestCase against a known
5368 // This is used for implementation of the UnitTest class only. We put
5369 // it in the anonymous namespace to prevent polluting the outer
5372 // TestCaseNameIs is copyable.
5373 class TestCaseNameIs {
5376 explicit TestCaseNameIs(const String& name)
5379 // Returns true iff the name of test_case matches name_.
5380 bool operator()(const TestCase* test_case) const {
5381 return test_case != NULL && strcmp(test_case->name(), name_.c_str()) == 0;
5388 // Finds and returns a TestCase with the given name. If one doesn't
5389 // exist, creates one and returns it. It's the CALLER'S
5390 // RESPONSIBILITY to ensure that this function is only called WHEN THE
5391 // TESTS ARE NOT SHUFFLED.
5395 // test_case_name: name of the test case
5396 // type_param: the name of the test case's type parameter, or NULL if
5397 // this is not a typed or a type-parameterized test case.
5398 // set_up_tc: pointer to the function that sets up the test case
5399 // tear_down_tc: pointer to the function that tears down the test case
5400 TestCase* UnitTestImpl::GetTestCase(const char* test_case_name,
5401 const char* type_param,
5402 Test::SetUpTestCaseFunc set_up_tc,
5403 Test::TearDownTestCaseFunc tear_down_tc) {
5404 // Can we find a TestCase with the given name?
5405 const std::vector<TestCase*>::const_iterator test_case =
5406 std::find_if(test_cases_.begin(), test_cases_.end(),
5407 TestCaseNameIs(test_case_name));
5409 if (test_case != test_cases_.end())
5412 // No. Let's create one.
5413 TestCase* const new_test_case =
5414 new TestCase(test_case_name, type_param, set_up_tc, tear_down_tc);
5416 // Is this a death test case?
5417 if (internal::UnitTestOptions::MatchesFilter(String(test_case_name),
5418 kDeathTestCaseFilter)) {
5419 // Yes. Inserts the test case after the last death test case
5420 // defined so far. This only works when the test cases haven't
5421 // been shuffled. Otherwise we may end up running a death test
5422 // after a non-death test.
5423 ++last_death_test_case_;
5424 test_cases_.insert(test_cases_.begin() + last_death_test_case_,
5427 // No. Appends to the end of the list.
5428 test_cases_.push_back(new_test_case);
5431 test_case_indices_.push_back(static_cast<int>(test_case_indices_.size()));
5432 return new_test_case;
5435 // Helpers for setting up / tearing down the given environment. They
5436 // are for use in the ForEach() function.
5437 static void SetUpEnvironment(Environment* env) { env->SetUp(); }
5438 static void TearDownEnvironment(Environment* env) { env->TearDown(); }
5440 // Runs all tests in this UnitTest object, prints the result, and
5441 // returns true if all tests are successful. If any exception is
5442 // thrown during a test, the test is considered to be failed, but the
5443 // rest of the tests will still be run.
5445 // When parameterized tests are enabled, it expands and registers
5446 // parameterized tests first in RegisterParameterizedTests().
5447 // All other functions called from RunAllTests() may safely assume that
5448 // parameterized tests are ready to be counted and run.
5449 bool UnitTestImpl::RunAllTests() {
5450 // Makes sure InitGoogleTest() was called.
5451 if (!GTestIsInitialized()) {
5453 "\nThis test program did NOT call ::testing::InitGoogleTest "
5454 "before calling RUN_ALL_TESTS(). Please fix it.\n");
5458 // Do not run any test if the --help flag was specified.
5462 // Repeats the call to the post-flag parsing initialization in case the
5463 // user didn't call InitGoogleTest.
5464 PostFlagParsingInit();
5466 // Even if sharding is not on, test runners may want to use the
5467 // GTEST_SHARD_STATUS_FILE to query whether the test supports the sharding
5469 internal::WriteToShardStatusFileIfNeeded();
5471 // True iff we are in a subprocess for running a thread-safe-style
5473 bool in_subprocess_for_death_test = false;
5475 #if GTEST_HAS_DEATH_TEST
5476 in_subprocess_for_death_test = (internal_run_death_test_flag_.get() != NULL);
5477 #endif // GTEST_HAS_DEATH_TEST
5479 const bool should_shard = ShouldShard(kTestTotalShards, kTestShardIndex,
5480 in_subprocess_for_death_test);
5482 // Compares the full test names with the filter to decide which
5484 const bool has_tests_to_run = FilterTests(should_shard
5485 ? HONOR_SHARDING_PROTOCOL
5486 : IGNORE_SHARDING_PROTOCOL) > 0;
5488 // Lists the tests and exits if the --gtest_list_tests flag was specified.
5489 if (GTEST_FLAG(list_tests)) {
5490 // This must be called *after* FilterTests() has been called.
5491 ListTestsMatchingFilter();
5495 random_seed_ = GTEST_FLAG(shuffle) ?
5496 GetRandomSeedFromFlag(GTEST_FLAG(random_seed)) : 0;
5498 // True iff at least one test has failed.
5499 bool failed = false;
5501 TestEventListener* repeater = listeners()->repeater();
5503 repeater->OnTestProgramStart(*parent_);
5505 // How many times to repeat the tests? We don't want to repeat them
5506 // when we are inside the subprocess of a death test.
5507 const int repeat = in_subprocess_for_death_test ? 1 : GTEST_FLAG(repeat);
5508 // Repeats forever if the repeat count is negative.
5509 const bool forever = repeat < 0;
5510 for (int i = 0; forever || i != repeat; i++) {
5511 // We want to preserve failures generated by ad-hoc test
5512 // assertions executed before RUN_ALL_TESTS().
5513 ClearNonAdHocTestResult();
5515 const TimeInMillis start = GetTimeInMillis();
5517 // Shuffles test cases and tests if requested.
5518 if (has_tests_to_run && GTEST_FLAG(shuffle)) {
5519 random()->Reseed(random_seed_);
5520 // This should be done before calling OnTestIterationStart(),
5521 // such that a test event listener can see the actual test order
5526 // Tells the unit test event listeners that the tests are about to start.
5527 repeater->OnTestIterationStart(*parent_, i);
5529 // Runs each test case if there is at least one test to run.
5530 if (has_tests_to_run) {
5531 // Sets up all environments beforehand.
5532 repeater->OnEnvironmentsSetUpStart(*parent_);
5533 ForEach(environments_, SetUpEnvironment);
5534 repeater->OnEnvironmentsSetUpEnd(*parent_);
5536 // Runs the tests only if there was no fatal failure during global
5538 if (!Test::HasFatalFailure()) {
5539 for (int test_index = 0; test_index < total_test_case_count();
5541 GetMutableTestCase(test_index)->Run();
5545 // Tears down all environments in reverse order afterwards.
5546 repeater->OnEnvironmentsTearDownStart(*parent_);
5547 std::for_each(environments_.rbegin(), environments_.rend(),
5548 TearDownEnvironment);
5549 repeater->OnEnvironmentsTearDownEnd(*parent_);
5552 elapsed_time_ = GetTimeInMillis() - start;
5554 // Tells the unit test event listener that the tests have just finished.
5555 repeater->OnTestIterationEnd(*parent_, i);
5557 // Gets the result and clears it.
5562 // Restores the original test order after the iteration. This
5563 // allows the user to quickly repro a failure that happens in the
5564 // N-th iteration without repeating the first (N - 1) iterations.
5565 // This is not enclosed in "if (GTEST_FLAG(shuffle)) { ... }", in
5566 // case the user somehow changes the value of the flag somewhere
5567 // (it's always safe to unshuffle the tests).
5570 if (GTEST_FLAG(shuffle)) {
5571 // Picks a new random seed for each iteration.
5572 random_seed_ = GetNextRandomSeed(random_seed_);
5576 repeater->OnTestProgramEnd(*parent_);
5581 // Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
5582 // if the variable is present. If a file already exists at this location, this
5583 // function will write over it. If the variable is present, but the file cannot
5584 // be created, prints an error and exits.
5585 void WriteToShardStatusFileIfNeeded() {
5586 const char* const test_shard_file = posix::GetEnv(kTestShardStatusFile);
5587 if (test_shard_file != NULL) {
5588 FILE* const file = posix::FOpen(test_shard_file, "w");
5590 ColoredPrintf(COLOR_RED,
5591 "Could not write to the test shard status file \"%s\" "
5592 "specified by the %s environment variable.\n",
5593 test_shard_file, kTestShardStatusFile);
5601 // Checks whether sharding is enabled by examining the relevant
5602 // environment variable values. If the variables are present,
5603 // but inconsistent (i.e., shard_index >= total_shards), prints
5604 // an error and exits. If in_subprocess_for_death_test, sharding is
5605 // disabled because it must only be applied to the original test
5606 // process. Otherwise, we could filter out death tests we intended to execute.
5607 bool ShouldShard(const char* total_shards_env,
5608 const char* shard_index_env,
5609 bool in_subprocess_for_death_test) {
5610 if (in_subprocess_for_death_test) {
5614 const Int32 total_shards = Int32FromEnvOrDie(total_shards_env, -1);
5615 const Int32 shard_index = Int32FromEnvOrDie(shard_index_env, -1);
5617 if (total_shards == -1 && shard_index == -1) {
5619 } else if (total_shards == -1 && shard_index != -1) {
5620 const Message msg = Message()
5621 << "Invalid environment variables: you have "
5622 << kTestShardIndex << " = " << shard_index
5623 << ", but have left " << kTestTotalShards << " unset.\n";
5624 ColoredPrintf(COLOR_RED, msg.GetString().c_str());
5627 } else if (total_shards != -1 && shard_index == -1) {
5628 const Message msg = Message()
5629 << "Invalid environment variables: you have "
5630 << kTestTotalShards << " = " << total_shards
5631 << ", but have left " << kTestShardIndex << " unset.\n";
5632 ColoredPrintf(COLOR_RED, msg.GetString().c_str());
5635 } else if (shard_index < 0 || shard_index >= total_shards) {
5636 const Message msg = Message()
5637 << "Invalid environment variables: we require 0 <= "
5638 << kTestShardIndex << " < " << kTestTotalShards
5639 << ", but you have " << kTestShardIndex << "=" << shard_index
5640 << ", " << kTestTotalShards << "=" << total_shards << ".\n";
5641 ColoredPrintf(COLOR_RED, msg.GetString().c_str());
5646 return total_shards > 1;
5649 // Parses the environment variable var as an Int32. If it is unset,
5650 // returns default_val. If it is not an Int32, prints an error
5652 Int32 Int32FromEnvOrDie(const char* var, Int32 default_val) {
5653 const char* str_val = posix::GetEnv(var);
5654 if (str_val == NULL) {
5659 if (!ParseInt32(Message() << "The value of environment variable " << var,
5660 str_val, &result)) {
5666 // Given the total number of shards, the shard index, and the test id,
5667 // returns true iff the test should be run on this shard. The test id is
5668 // some arbitrary but unique non-negative integer assigned to each test
5669 // method. Assumes that 0 <= shard_index < total_shards.
5670 bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) {
5671 return (test_id % total_shards) == shard_index;
5674 // Compares the name of each test with the user-specified filter to
5675 // decide whether the test should be run, then records the result in
5676 // each TestCase and TestInfo object.
5677 // If shard_tests == true, further filters tests based on sharding
5678 // variables in the environment - see
5679 // http://code.google.com/p/googletest/wiki/GoogleTestAdvancedGuide.
5680 // Returns the number of tests that should run.
5681 int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) {
5682 const Int32 total_shards = shard_tests == HONOR_SHARDING_PROTOCOL ?
5683 Int32FromEnvOrDie(kTestTotalShards, -1) : -1;
5684 const Int32 shard_index = shard_tests == HONOR_SHARDING_PROTOCOL ?
5685 Int32FromEnvOrDie(kTestShardIndex, -1) : -1;
5687 // num_runnable_tests are the number of tests that will
5688 // run across all shards (i.e., match filter and are not disabled).
5689 // num_selected_tests are the number of tests to be run on
5691 int num_runnable_tests = 0;
5692 int num_selected_tests = 0;
5693 for (size_t i = 0; i < test_cases_.size(); i++) {
5694 TestCase* const test_case = test_cases_[i];
5695 const String &test_case_name = test_case->name();
5696 test_case->set_should_run(false);
5698 for (size_t j = 0; j < test_case->test_info_list().size(); j++) {
5699 TestInfo* const test_info = test_case->test_info_list()[j];
5700 const String test_name(test_info->name());
5701 // A test is disabled if test case name or test name matches
5702 // kDisableTestFilter.
5703 const bool is_disabled =
5704 internal::UnitTestOptions::MatchesFilter(test_case_name,
5705 kDisableTestFilter) ||
5706 internal::UnitTestOptions::MatchesFilter(test_name,
5707 kDisableTestFilter);
5708 test_info->is_disabled_ = is_disabled;
5710 const bool matches_filter =
5711 internal::UnitTestOptions::FilterMatchesTest(test_case_name,
5713 test_info->matches_filter_ = matches_filter;
5715 const bool is_runnable =
5716 (GTEST_FLAG(also_run_disabled_tests) || !is_disabled) &&
5719 const bool is_selected = is_runnable &&
5720 (shard_tests == IGNORE_SHARDING_PROTOCOL ||
5721 ShouldRunTestOnShard(total_shards, shard_index,
5722 num_runnable_tests));
5724 num_runnable_tests += is_runnable;
5725 num_selected_tests += is_selected;
5727 test_info->should_run_ = is_selected;
5728 test_case->set_should_run(test_case->should_run() || is_selected);
5731 return num_selected_tests;
5734 // Prints the names of the tests matching the user-specified filter flag.
5735 void UnitTestImpl::ListTestsMatchingFilter() {
5736 for (size_t i = 0; i < test_cases_.size(); i++) {
5737 const TestCase* const test_case = test_cases_[i];
5738 bool printed_test_case_name = false;
5740 for (size_t j = 0; j < test_case->test_info_list().size(); j++) {
5741 const TestInfo* const test_info =
5742 test_case->test_info_list()[j];
5743 if (test_info->matches_filter_) {
5744 if (!printed_test_case_name) {
5745 printed_test_case_name = true;
5746 printf("%s.\n", test_case->name());
5748 printf(" %s\n", test_info->name());
5755 // Sets the OS stack trace getter.
5757 // Does nothing if the input and the current OS stack trace getter are
5758 // the same; otherwise, deletes the old getter and makes the input the
5760 void UnitTestImpl::set_os_stack_trace_getter(
5761 OsStackTraceGetterInterface* getter) {
5762 if (os_stack_trace_getter_ != getter) {
5763 delete os_stack_trace_getter_;
5764 os_stack_trace_getter_ = getter;
5768 // Returns the current OS stack trace getter if it is not NULL;
5769 // otherwise, creates an OsStackTraceGetter, makes it the current
5770 // getter, and returns it.
5771 OsStackTraceGetterInterface* UnitTestImpl::os_stack_trace_getter() {
5772 if (os_stack_trace_getter_ == NULL) {
5773 os_stack_trace_getter_ = new OsStackTraceGetter;
5776 return os_stack_trace_getter_;
5779 // Returns the TestResult for the test that's currently running, or
5780 // the TestResult for the ad hoc test if no test is running.
5781 TestResult* UnitTestImpl::current_test_result() {
5782 return current_test_info_ ?
5783 &(current_test_info_->result_) : &ad_hoc_test_result_;
5786 // Shuffles all test cases, and the tests within each test case,
5787 // making sure that death tests are still run first.
5788 void UnitTestImpl::ShuffleTests() {
5789 // Shuffles the death test cases.
5790 ShuffleRange(random(), 0, last_death_test_case_ + 1, &test_case_indices_);
5792 // Shuffles the non-death test cases.
5793 ShuffleRange(random(), last_death_test_case_ + 1,
5794 static_cast<int>(test_cases_.size()), &test_case_indices_);
5796 // Shuffles the tests inside each test case.
5797 for (size_t i = 0; i < test_cases_.size(); i++) {
5798 test_cases_[i]->ShuffleTests(random());
5802 // Restores the test cases and tests to their order before the first shuffle.
5803 void UnitTestImpl::UnshuffleTests() {
5804 for (size_t i = 0; i < test_cases_.size(); i++) {
5805 // Unshuffles the tests in each test case.
5806 test_cases_[i]->UnshuffleTests();
5807 // Resets the index of each test case.
5808 test_case_indices_[i] = static_cast<int>(i);
5812 // Returns the current OS stack trace as a String.
5814 // The maximum number of stack frames to be included is specified by
5815 // the gtest_stack_trace_depth flag. The skip_count parameter
5816 // specifies the number of top frames to be skipped, which doesn't
5817 // count against the number of frames to be included.
5819 // For example, if Foo() calls Bar(), which in turn calls
5820 // GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in
5821 // the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.
5822 String GetCurrentOsStackTraceExceptTop(UnitTest* /*unit_test*/,
5824 // We pass skip_count + 1 to skip this wrapper function in addition
5825 // to what the user really wants to skip.
5826 return GetUnitTestImpl()->CurrentOsStackTraceExceptTop(skip_count + 1);
5829 // Used by the GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_ macro to
5830 // suppress unreachable code warnings.
5832 class ClassUniqueToAlwaysTrue {};
5835 bool IsTrue(bool condition) { return condition; }
5838 #if GTEST_HAS_EXCEPTIONS
5839 // This condition is always false so AlwaysTrue() never actually throws,
5840 // but it makes the compiler think that it may throw.
5842 throw ClassUniqueToAlwaysTrue();
5843 #endif // GTEST_HAS_EXCEPTIONS
5847 // If *pstr starts with the given prefix, modifies *pstr to be right
5848 // past the prefix and returns true; otherwise leaves *pstr unchanged
5849 // and returns false. None of pstr, *pstr, and prefix can be NULL.
5850 bool SkipPrefix(const char* prefix, const char** pstr) {
5851 const size_t prefix_len = strlen(prefix);
5852 if (strncmp(*pstr, prefix, prefix_len) == 0) {
5853 *pstr += prefix_len;
5859 // Parses a string as a command line flag. The string should have
5860 // the format "--flag=value". When def_optional is true, the "=value"
5861 // part can be omitted.
5863 // Returns the value of the flag, or NULL if the parsing failed.
5864 const char* ParseFlagValue(const char* str,
5866 bool def_optional) {
5867 // str and flag must not be NULL.
5868 if (str == NULL || flag == NULL) return NULL;
5870 // The flag must start with "--" followed by GTEST_FLAG_PREFIX_.
5871 const String flag_str = String::Format("--%s%s", GTEST_FLAG_PREFIX_, flag);
5872 const size_t flag_len = flag_str.length();
5873 if (strncmp(str, flag_str.c_str(), flag_len) != 0) return NULL;
5875 // Skips the flag name.
5876 const char* flag_end = str + flag_len;
5878 // When def_optional is true, it's OK to not have a "=value" part.
5879 if (def_optional && (flag_end[0] == '\0')) {
5883 // If def_optional is true and there are more characters after the
5884 // flag name, or if def_optional is false, there must be a '=' after
5886 if (flag_end[0] != '=') return NULL;
5888 // Returns the string after "=".
5889 return flag_end + 1;
5892 // Parses a string for a bool flag, in the form of either
5893 // "--flag=value" or "--flag".
5895 // In the former case, the value is taken as true as long as it does
5896 // not start with '0', 'f', or 'F'.
5898 // In the latter case, the value is taken as true.
5900 // On success, stores the value of the flag in *value, and returns
5901 // true. On failure, returns false without changing *value.
5902 bool ParseBoolFlag(const char* str, const char* flag, bool* value) {
5903 // Gets the value of the flag as a string.
5904 const char* const value_str = ParseFlagValue(str, flag, true);
5906 // Aborts if the parsing failed.
5907 if (value_str == NULL) return false;
5909 // Converts the string value to a bool.
5910 *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F');
5914 // Parses a string for an Int32 flag, in the form of
5917 // On success, stores the value of the flag in *value, and returns
5918 // true. On failure, returns false without changing *value.
5919 bool ParseInt32Flag(const char* str, const char* flag, Int32* value) {
5920 // Gets the value of the flag as a string.
5921 const char* const value_str = ParseFlagValue(str, flag, false);
5923 // Aborts if the parsing failed.
5924 if (value_str == NULL) return false;
5926 // Sets *value to the value of the flag.
5927 return ParseInt32(Message() << "The value of flag --" << flag,
5931 // Parses a string for a string flag, in the form of
5934 // On success, stores the value of the flag in *value, and returns
5935 // true. On failure, returns false without changing *value.
5936 bool ParseStringFlag(const char* str, const char* flag, String* value) {
5937 // Gets the value of the flag as a string.
5938 const char* const value_str = ParseFlagValue(str, flag, false);
5940 // Aborts if the parsing failed.
5941 if (value_str == NULL) return false;
5943 // Sets *value to the value of the flag.
5948 // Determines whether a string has a prefix that Google Test uses for its
5949 // flags, i.e., starts with GTEST_FLAG_PREFIX_ or GTEST_FLAG_PREFIX_DASH_.
5950 // If Google Test detects that a command line flag has its prefix but is not
5951 // recognized, it will print its help message. Flags starting with
5952 // GTEST_INTERNAL_PREFIX_ followed by "internal_" are considered Google Test
5953 // internal flags and do not trigger the help message.
5954 static bool HasGoogleTestFlagPrefix(const char* str) {
5955 return (SkipPrefix("--", &str) ||
5956 SkipPrefix("-", &str) ||
5957 SkipPrefix("/", &str)) &&
5958 !SkipPrefix(GTEST_FLAG_PREFIX_ "internal_", &str) &&
5959 (SkipPrefix(GTEST_FLAG_PREFIX_, &str) ||
5960 SkipPrefix(GTEST_FLAG_PREFIX_DASH_, &str));
5963 // Prints a string containing code-encoded text. The following escape
5964 // sequences can be used in the string to control the text color:
5966 // @@ prints a single '@' character.
5967 // @R changes the color to red.
5968 // @G changes the color to green.
5969 // @Y changes the color to yellow.
5970 // @D changes to the default terminal text color.
5972 // TODO(wan@google.com): Write tests for this once we add stdout
5973 // capturing to Google Test.
5974 static void PrintColorEncoded(const char* str) {
5975 GTestColor color = COLOR_DEFAULT; // The current color.
5977 // Conceptually, we split the string into segments divided by escape
5978 // sequences. Then we print one segment at a time. At the end of
5979 // each iteration, the str pointer advances to the beginning of the
5982 const char* p = strchr(str, '@');
5984 ColoredPrintf(color, "%s", str);
5988 ColoredPrintf(color, "%s", String(str, p - str).c_str());
5990 const char ch = p[1];
5993 ColoredPrintf(color, "@");
5994 } else if (ch == 'D') {
5995 color = COLOR_DEFAULT;
5996 } else if (ch == 'R') {
5998 } else if (ch == 'G') {
5999 color = COLOR_GREEN;
6000 } else if (ch == 'Y') {
6001 color = COLOR_YELLOW;
6008 static const char kColorEncodedHelpMessage[] =
6009 "This program contains tests written using " GTEST_NAME_ ". You can use the\n"
6010 "following command line flags to control its behavior:\n"
6013 " @G--" GTEST_FLAG_PREFIX_ "list_tests@D\n"
6014 " List the names of all tests instead of running them. The name of\n"
6015 " TEST(Foo, Bar) is \"Foo.Bar\".\n"
6016 " @G--" GTEST_FLAG_PREFIX_ "filter=@YPOSTIVE_PATTERNS"
6017 "[@G-@YNEGATIVE_PATTERNS]@D\n"
6018 " Run only the tests whose name matches one of the positive patterns but\n"
6019 " none of the negative patterns. '?' matches any single character; '*'\n"
6020 " matches any substring; ':' separates two patterns.\n"
6021 " @G--" GTEST_FLAG_PREFIX_ "also_run_disabled_tests@D\n"
6022 " Run all disabled tests too.\n"
6025 " @G--" GTEST_FLAG_PREFIX_ "repeat=@Y[COUNT]@D\n"
6026 " Run the tests repeatedly; use a negative count to repeat forever.\n"
6027 " @G--" GTEST_FLAG_PREFIX_ "shuffle@D\n"
6028 " Randomize tests' orders on every iteration.\n"
6029 " @G--" GTEST_FLAG_PREFIX_ "random_seed=@Y[NUMBER]@D\n"
6030 " Random number seed to use for shuffling test orders (between 1 and\n"
6031 " 99999, or 0 to use a seed based on the current time).\n"
6034 " @G--" GTEST_FLAG_PREFIX_ "color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\n"
6035 " Enable/disable colored output. The default is @Gauto@D.\n"
6036 " -@G-" GTEST_FLAG_PREFIX_ "print_time=0@D\n"
6037 " Don't print the elapsed time of each test.\n"
6038 " @G--" GTEST_FLAG_PREFIX_ "output=xml@Y[@G:@YDIRECTORY_PATH@G"
6039 GTEST_PATH_SEP_ "@Y|@G:@YFILE_PATH]@D\n"
6040 " Generate an XML report in the given directory or with the given file\n"
6041 " name. @YFILE_PATH@D defaults to @Gtest_details.xml@D.\n"
6042 #if GTEST_CAN_STREAM_RESULTS_
6043 " @G--" GTEST_FLAG_PREFIX_ "stream_result_to=@YHOST@G:@YPORT@D\n"
6044 " Stream test results to the given server.\n"
6045 #endif // GTEST_CAN_STREAM_RESULTS_
6047 "Assertion Behavior:\n"
6048 #if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
6049 " @G--" GTEST_FLAG_PREFIX_ "death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n"
6050 " Set the default death test style.\n"
6051 #endif // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
6052 " @G--" GTEST_FLAG_PREFIX_ "break_on_failure@D\n"
6053 " Turn assertion failures into debugger break-points.\n"
6054 " @G--" GTEST_FLAG_PREFIX_ "throw_on_failure@D\n"
6055 " Turn assertion failures into C++ exceptions.\n"
6056 " @G--" GTEST_FLAG_PREFIX_ "catch_exceptions=0@D\n"
6057 " Do not report exceptions as test failures. Instead, allow them\n"
6058 " to crash the program or throw a pop-up (on Windows).\n"
6060 "Except for @G--" GTEST_FLAG_PREFIX_ "list_tests@D, you can alternatively set "
6061 "the corresponding\n"
6062 "environment variable of a flag (all letters in upper-case). For example, to\n"
6063 "disable colored text output, you can either specify @G--" GTEST_FLAG_PREFIX_
6064 "color=no@D or set\n"
6065 "the @G" GTEST_FLAG_PREFIX_UPPER_ "COLOR@D environment variable to @Gno@D.\n"
6067 "For more information, please read the " GTEST_NAME_ " documentation at\n"
6068 "@G" GTEST_PROJECT_URL_ "@D. If you find a bug in " GTEST_NAME_ "\n"
6069 "(not one in your own code or tests), please report it to\n"
6070 "@G<" GTEST_DEV_EMAIL_ ">@D.\n";
6072 // Parses the command line for Google Test flags, without initializing
6073 // other parts of Google Test. The type parameter CharType can be
6074 // instantiated to either char or wchar_t.
6075 template <typename CharType>
6076 void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) {
6077 for (int i = 1; i < *argc; i++) {
6078 const String arg_string = StreamableToString(argv[i]);
6079 const char* const arg = arg_string.c_str();
6081 using internal::ParseBoolFlag;
6082 using internal::ParseInt32Flag;
6083 using internal::ParseStringFlag;
6085 // Do we see a Google Test flag?
6086 if (ParseBoolFlag(arg, kAlsoRunDisabledTestsFlag,
6087 >EST_FLAG(also_run_disabled_tests)) ||
6088 ParseBoolFlag(arg, kBreakOnFailureFlag,
6089 >EST_FLAG(break_on_failure)) ||
6090 ParseBoolFlag(arg, kCatchExceptionsFlag,
6091 >EST_FLAG(catch_exceptions)) ||
6092 ParseStringFlag(arg, kColorFlag, >EST_FLAG(color)) ||
6093 ParseStringFlag(arg, kDeathTestStyleFlag,
6094 >EST_FLAG(death_test_style)) ||
6095 ParseBoolFlag(arg, kDeathTestUseFork,
6096 >EST_FLAG(death_test_use_fork)) ||
6097 ParseStringFlag(arg, kFilterFlag, >EST_FLAG(filter)) ||
6098 ParseStringFlag(arg, kInternalRunDeathTestFlag,
6099 >EST_FLAG(internal_run_death_test)) ||
6100 ParseBoolFlag(arg, kListTestsFlag, >EST_FLAG(list_tests)) ||
6101 ParseStringFlag(arg, kOutputFlag, >EST_FLAG(output)) ||
6102 ParseBoolFlag(arg, kPrintTimeFlag, >EST_FLAG(print_time)) ||
6103 ParseInt32Flag(arg, kRandomSeedFlag, >EST_FLAG(random_seed)) ||
6104 ParseInt32Flag(arg, kRepeatFlag, >EST_FLAG(repeat)) ||
6105 ParseBoolFlag(arg, kShuffleFlag, >EST_FLAG(shuffle)) ||
6106 ParseInt32Flag(arg, kStackTraceDepthFlag,
6107 >EST_FLAG(stack_trace_depth)) ||
6108 ParseStringFlag(arg, kStreamResultToFlag,
6109 >EST_FLAG(stream_result_to)) ||
6110 ParseBoolFlag(arg, kThrowOnFailureFlag,
6111 >EST_FLAG(throw_on_failure))
6113 // Yes. Shift the remainder of the argv list left by one. Note
6114 // that argv has (*argc + 1) elements, the last one always being
6115 // NULL. The following loop moves the trailing NULL element as
6117 for (int j = i; j != *argc; j++) {
6118 argv[j] = argv[j + 1];
6121 // Decrements the argument count.
6124 // We also need to decrement the iterator as we just removed
6127 } else if (arg_string == "--help" || arg_string == "-h" ||
6128 arg_string == "-?" || arg_string == "/?" ||
6129 HasGoogleTestFlagPrefix(arg)) {
6130 // Both help flag and unrecognized Google Test flags (excluding
6131 // internal ones) trigger help display.
6137 // We print the help here instead of in RUN_ALL_TESTS(), as the
6138 // latter may not be called at all if the user is using Google
6139 // Test with another testing framework.
6140 PrintColorEncoded(kColorEncodedHelpMessage);
6144 // Parses the command line for Google Test flags, without initializing
6145 // other parts of Google Test.
6146 void ParseGoogleTestFlagsOnly(int* argc, char** argv) {
6147 ParseGoogleTestFlagsOnlyImpl(argc, argv);
6149 void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv) {
6150 ParseGoogleTestFlagsOnlyImpl(argc, argv);
6153 // The internal implementation of InitGoogleTest().
6155 // The type parameter CharType can be instantiated to either char or
6157 template <typename CharType>
6158 void InitGoogleTestImpl(int* argc, CharType** argv) {
6159 g_init_gtest_count++;
6161 // We don't want to run the initialization code twice.
6162 if (g_init_gtest_count != 1) return;
6164 if (*argc <= 0) return;
6166 internal::g_executable_path = internal::StreamableToString(argv[0]);
6168 #if GTEST_HAS_DEATH_TEST
6171 for (int i = 0; i != *argc; i++) {
6172 g_argvs.push_back(StreamableToString(argv[i]));
6175 #endif // GTEST_HAS_DEATH_TEST
6177 ParseGoogleTestFlagsOnly(argc, argv);
6178 GetUnitTestImpl()->PostFlagParsingInit();
6181 } // namespace internal
6183 // Initializes Google Test. This must be called before calling
6184 // RUN_ALL_TESTS(). In particular, it parses a command line for the
6185 // flags that Google Test recognizes. Whenever a Google Test flag is
6186 // seen, it is removed from argv, and *argc is decremented.
6188 // No value is returned. Instead, the Google Test flag variables are
6191 // Calling the function for the second time has no user-visible effect.
6192 void InitGoogleTest(int* argc, char** argv) {
6193 internal::InitGoogleTestImpl(argc, argv);
6196 // This overloaded version can be used in Windows programs compiled in
6198 void InitGoogleTest(int* argc, wchar_t** argv) {
6199 internal::InitGoogleTestImpl(argc, argv);
6202 } // namespace testing
6203 // Copyright 2005, Google Inc.
6204 // All rights reserved.
6206 // Redistribution and use in source and binary forms, with or without
6207 // modification, are permitted provided that the following conditions are
6210 // * Redistributions of source code must retain the above copyright
6211 // notice, this list of conditions and the following disclaimer.
6212 // * Redistributions in binary form must reproduce the above
6213 // copyright notice, this list of conditions and the following disclaimer
6214 // in the documentation and/or other materials provided with the
6216 // * Neither the name of Google Inc. nor the names of its
6217 // contributors may be used to endorse or promote products derived from
6218 // this software without specific prior written permission.
6220 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
6221 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
6222 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
6223 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
6224 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
6225 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
6226 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
6227 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
6228 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
6229 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
6230 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
6232 // Author: wan@google.com (Zhanyong Wan), vladl@google.com (Vlad Losev)
6234 // This file implements death tests.
6237 #if GTEST_HAS_DEATH_TEST
6240 # include <crt_externs.h>
6241 # endif // GTEST_OS_MAC
6245 # include <limits.h>
6246 # include <stdarg.h>
6248 # if GTEST_OS_WINDOWS
6249 # include <windows.h>
6251 # include <sys/mman.h>
6252 # include <sys/wait.h>
6253 # endif // GTEST_OS_WINDOWS
6255 #endif // GTEST_HAS_DEATH_TEST
6258 // Indicates that this translation unit is part of Google Test's
6259 // implementation. It must come before gtest-internal-inl.h is
6260 // included, or there will be a compiler error. This trick is to
6261 // prevent a user from accidentally including gtest-internal-inl.h in
6263 #define GTEST_IMPLEMENTATION_ 1
6264 #undef GTEST_IMPLEMENTATION_
6270 // The default death test style.
6271 static const char kDefaultDeathTestStyle[] = "fast";
6273 GTEST_DEFINE_string_(
6275 internal::StringFromGTestEnv("death_test_style", kDefaultDeathTestStyle),
6276 "Indicates how to run a death test in a forked child process: "
6277 "\"threadsafe\" (child process re-executes the test binary "
6278 "from the beginning, running only the specific death test) or "
6279 "\"fast\" (child process runs the death test immediately "
6283 death_test_use_fork,
6284 internal::BoolFromGTestEnv("death_test_use_fork", false),
6285 "Instructs to use fork()/_exit() instead of clone() in death tests. "
6286 "Ignored and always uses fork() on POSIX systems where clone() is not "
6287 "implemented. Useful when running under valgrind or similar tools if "
6288 "those do not support clone(). Valgrind 3.3.1 will just fail if "
6289 "it sees an unsupported combination of clone() flags. "
6290 "It is not recommended to use this flag w/o valgrind though it will "
6291 "work in 99% of the cases. Once valgrind is fixed, this flag will "
6292 "most likely be removed.");
6294 namespace internal {
6295 GTEST_DEFINE_string_(
6296 internal_run_death_test, "",
6297 "Indicates the file, line number, temporal index of "
6298 "the single death test to run, and a file descriptor to "
6299 "which a success code may be sent, all separated by "
6300 "colons. This flag is specified if and only if the current "
6301 "process is a sub-process launched for running a thread-safe "
6302 "death test. FOR INTERNAL USE ONLY.");
6303 } // namespace internal
6305 #if GTEST_HAS_DEATH_TEST
6307 // ExitedWithCode constructor.
6308 ExitedWithCode::ExitedWithCode(int exit_code) : exit_code_(exit_code) {
6311 // ExitedWithCode function-call operator.
6312 bool ExitedWithCode::operator()(int exit_status) const {
6313 # if GTEST_OS_WINDOWS
6315 return exit_status == exit_code_;
6319 return WIFEXITED(exit_status) && WEXITSTATUS(exit_status) == exit_code_;
6321 # endif // GTEST_OS_WINDOWS
6324 # if !GTEST_OS_WINDOWS
6325 // KilledBySignal constructor.
6326 KilledBySignal::KilledBySignal(int signum) : signum_(signum) {
6329 // KilledBySignal function-call operator.
6330 bool KilledBySignal::operator()(int exit_status) const {
6331 return WIFSIGNALED(exit_status) && WTERMSIG(exit_status) == signum_;
6333 # endif // !GTEST_OS_WINDOWS
6335 namespace internal {
6337 // Utilities needed for death tests.
6339 // Generates a textual description of a given exit code, in the format
6340 // specified by wait(2).
6341 static String ExitSummary(int exit_code) {
6344 # if GTEST_OS_WINDOWS
6346 m << "Exited with exit status " << exit_code;
6350 if (WIFEXITED(exit_code)) {
6351 m << "Exited with exit status " << WEXITSTATUS(exit_code);
6352 } else if (WIFSIGNALED(exit_code)) {
6353 m << "Terminated by signal " << WTERMSIG(exit_code);
6356 if (WCOREDUMP(exit_code)) {
6357 m << " (core dumped)";
6360 # endif // GTEST_OS_WINDOWS
6362 return m.GetString();
6365 // Returns true if exit_status describes a process that was terminated
6366 // by a signal, or exited normally with a nonzero exit code.
6367 bool ExitedUnsuccessfully(int exit_status) {
6368 return !ExitedWithCode(0)(exit_status);
6371 # if !GTEST_OS_WINDOWS
6372 // Generates a textual failure message when a death test finds more than
6373 // one thread running, or cannot determine the number of threads, prior
6374 // to executing the given statement. It is the responsibility of the
6375 // caller not to pass a thread_count of 1.
6376 static String DeathTestThreadWarning(size_t thread_count) {
6378 msg << "Death tests use fork(), which is unsafe particularly"
6379 << " in a threaded context. For this test, " << GTEST_NAME_ << " ";
6380 if (thread_count == 0)
6381 msg << "couldn't detect the number of threads.";
6383 msg << "detected " << thread_count << " threads.";
6384 return msg.GetString();
6386 # endif // !GTEST_OS_WINDOWS
6388 // Flag characters for reporting a death test that did not die.
6389 static const char kDeathTestLived = 'L';
6390 static const char kDeathTestReturned = 'R';
6391 static const char kDeathTestThrew = 'T';
6392 static const char kDeathTestInternalError = 'I';
6394 // An enumeration describing all of the possible ways that a death test can
6395 // conclude. DIED means that the process died while executing the test
6396 // code; LIVED means that process lived beyond the end of the test code;
6397 // RETURNED means that the test statement attempted to execute a return
6398 // statement, which is not allowed; THREW means that the test statement
6399 // returned control by throwing an exception. IN_PROGRESS means the test
6400 // has not yet concluded.
6401 // TODO(vladl@google.com): Unify names and possibly values for
6402 // AbortReason, DeathTestOutcome, and flag characters above.
6403 enum DeathTestOutcome { IN_PROGRESS, DIED, LIVED, RETURNED, THREW };
6405 // Routine for aborting the program which is safe to call from an
6406 // exec-style death test child process, in which case the error
6407 // message is propagated back to the parent process. Otherwise, the
6408 // message is simply printed to stderr. In either case, the program
6409 // then exits with status 1.
6410 void DeathTestAbort(const String& message) {
6411 // On a POSIX system, this function may be called from a threadsafe-style
6412 // death test child process, which operates on a very small stack. Use
6413 // the heap for any additional non-minuscule memory requirements.
6414 const InternalRunDeathTestFlag* const flag =
6415 GetUnitTestImpl()->internal_run_death_test_flag();
6417 FILE* parent = posix::FDOpen(flag->write_fd(), "w");
6418 fputc(kDeathTestInternalError, parent);
6419 fprintf(parent, "%s", message.c_str());
6423 fprintf(stderr, "%s", message.c_str());
6429 // A replacement for CHECK that calls DeathTestAbort if the assertion
6431 # define GTEST_DEATH_TEST_CHECK_(expression) \
6433 if (!::testing::internal::IsTrue(expression)) { \
6434 DeathTestAbort(::testing::internal::String::Format( \
6435 "CHECK failed: File %s, line %d: %s", \
6436 __FILE__, __LINE__, #expression)); \
6438 } while (::testing::internal::AlwaysFalse())
6440 // This macro is similar to GTEST_DEATH_TEST_CHECK_, but it is meant for
6441 // evaluating any system call that fulfills two conditions: it must return
6442 // -1 on failure, and set errno to EINTR when it is interrupted and
6443 // should be tried again. The macro expands to a loop that repeatedly
6444 // evaluates the expression as long as it evaluates to -1 and sets
6445 // errno to EINTR. If the expression evaluates to -1 but errno is
6446 // something other than EINTR, DeathTestAbort is called.
6447 # define GTEST_DEATH_TEST_CHECK_SYSCALL_(expression) \
6451 gtest_retval = (expression); \
6452 } while (gtest_retval == -1 && errno == EINTR); \
6453 if (gtest_retval == -1) { \
6454 DeathTestAbort(::testing::internal::String::Format( \
6455 "CHECK failed: File %s, line %d: %s != -1", \
6456 __FILE__, __LINE__, #expression)); \
6458 } while (::testing::internal::AlwaysFalse())
6460 // Returns the message describing the last system error in errno.
6461 String GetLastErrnoDescription() {
6462 return String(errno == 0 ? "" : posix::StrError(errno));
6465 // This is called from a death test parent process to read a failure
6466 // message from the death test child process and log it with the FATAL
6467 // severity. On Windows, the message is read from a pipe handle. On other
6468 // platforms, it is read from a file descriptor.
6469 static void FailFromInternalError(int fd) {
6475 while ((num_read = posix::Read(fd, buffer, 255)) > 0) {
6476 buffer[num_read] = '\0';
6479 } while (num_read == -1 && errno == EINTR);
6481 if (num_read == 0) {
6482 GTEST_LOG_(FATAL) << error.GetString();
6484 const int last_error = errno;
6485 GTEST_LOG_(FATAL) << "Error while reading death test internal: "
6486 << GetLastErrnoDescription() << " [" << last_error << "]";
6490 // Death test constructor. Increments the running death test count
6491 // for the current test.
6492 DeathTest::DeathTest() {
6493 TestInfo* const info = GetUnitTestImpl()->current_test_info();
6495 DeathTestAbort("Cannot run a death test outside of a TEST or "
6496 "TEST_F construct");
6500 // Creates and returns a death test by dispatching to the current
6501 // death test factory.
6502 bool DeathTest::Create(const char* statement, const RE* regex,
6503 const char* file, int line, DeathTest** test) {
6504 return GetUnitTestImpl()->death_test_factory()->Create(
6505 statement, regex, file, line, test);
6508 const char* DeathTest::LastMessage() {
6509 return last_death_test_message_.c_str();
6512 void DeathTest::set_last_death_test_message(const String& message) {
6513 last_death_test_message_ = message;
6516 String DeathTest::last_death_test_message_;
6518 // Provides cross platform implementation for some death functionality.
6519 class DeathTestImpl : public DeathTest {
6521 DeathTestImpl(const char* a_statement, const RE* a_regex)
6522 : statement_(a_statement),
6526 outcome_(IN_PROGRESS),
6530 // read_fd_ is expected to be closed and cleared by a derived class.
6531 ~DeathTestImpl() { GTEST_DEATH_TEST_CHECK_(read_fd_ == -1); }
6533 void Abort(AbortReason reason);
6534 virtual bool Passed(bool status_ok);
6536 const char* statement() const { return statement_; }
6537 const RE* regex() const { return regex_; }
6538 bool spawned() const { return spawned_; }
6539 void set_spawned(bool is_spawned) { spawned_ = is_spawned; }
6540 int status() const { return status_; }
6541 void set_status(int a_status) { status_ = a_status; }
6542 DeathTestOutcome outcome() const { return outcome_; }
6543 void set_outcome(DeathTestOutcome an_outcome) { outcome_ = an_outcome; }
6544 int read_fd() const { return read_fd_; }
6545 void set_read_fd(int fd) { read_fd_ = fd; }
6546 int write_fd() const { return write_fd_; }
6547 void set_write_fd(int fd) { write_fd_ = fd; }
6549 // Called in the parent process only. Reads the result code of the death
6550 // test child process via a pipe, interprets it to set the outcome_
6551 // member, and closes read_fd_. Outputs diagnostics and terminates in
6552 // case of unexpected codes.
6553 void ReadAndInterpretStatusByte();
6556 // The textual content of the code this object is testing. This class
6557 // doesn't own this string and should not attempt to delete it.
6558 const char* const statement_;
6559 // The regular expression which test output must match. DeathTestImpl
6560 // doesn't own this object and should not attempt to delete it.
6561 const RE* const regex_;
6562 // True if the death test child process has been successfully spawned.
6564 // The exit status of the child process.
6566 // How the death test concluded.
6567 DeathTestOutcome outcome_;
6568 // Descriptor to the read end of the pipe to the child process. It is
6569 // always -1 in the child process. The child keeps its write end of the
6570 // pipe in write_fd_.
6572 // Descriptor to the child's write end of the pipe to the parent process.
6573 // It is always -1 in the parent process. The parent keeps its end of the
6574 // pipe in read_fd_.
6578 // Called in the parent process only. Reads the result code of the death
6579 // test child process via a pipe, interprets it to set the outcome_
6580 // member, and closes read_fd_. Outputs diagnostics and terminates in
6581 // case of unexpected codes.
6582 void DeathTestImpl::ReadAndInterpretStatusByte() {
6586 // The read() here blocks until data is available (signifying the
6587 // failure of the death test) or until the pipe is closed (signifying
6588 // its success), so it's okay to call this in the parent before
6589 // the child process has exited.
6591 bytes_read = posix::Read(read_fd(), &flag, 1);
6592 } while (bytes_read == -1 && errno == EINTR);
6594 if (bytes_read == 0) {
6596 } else if (bytes_read == 1) {
6598 case kDeathTestReturned:
6599 set_outcome(RETURNED);
6601 case kDeathTestThrew:
6604 case kDeathTestLived:
6607 case kDeathTestInternalError:
6608 FailFromInternalError(read_fd()); // Does not return.
6611 GTEST_LOG_(FATAL) << "Death test child process reported "
6612 << "unexpected status byte ("
6613 << static_cast<unsigned int>(flag) << ")";
6616 GTEST_LOG_(FATAL) << "Read from death test child process failed: "
6617 << GetLastErrnoDescription();
6619 GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Close(read_fd()));
6623 // Signals that the death test code which should have exited, didn't.
6624 // Should be called only in a death test child process.
6625 // Writes a status byte to the child's status file descriptor, then
6627 void DeathTestImpl::Abort(AbortReason reason) {
6628 // The parent process considers the death test to be a failure if
6629 // it finds any data in our pipe. So, here we write a single flag byte
6630 // to the pipe, then exit.
6631 const char status_ch =
6632 reason == TEST_DID_NOT_DIE ? kDeathTestLived :
6633 reason == TEST_THREW_EXCEPTION ? kDeathTestThrew : kDeathTestReturned;
6635 GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Write(write_fd(), &status_ch, 1));
6636 // We are leaking the descriptor here because on some platforms (i.e.,
6637 // when built as Windows DLL), destructors of global objects will still
6638 // run after calling _exit(). On such systems, write_fd_ will be
6639 // indirectly closed from the destructor of UnitTestImpl, causing double
6640 // close if it is also closed here. On debug configurations, double close
6641 // may assert. As there are no in-process buffers to flush here, we are
6642 // relying on the OS to close the descriptor after the process terminates
6643 // when the destructors are not run.
6644 _exit(1); // Exits w/o any normal exit hooks (we were supposed to crash)
6647 // Returns an indented copy of stderr output for a death test.
6648 // This makes distinguishing death test output lines from regular log lines
6650 static ::std::string FormatDeathTestOutput(const ::std::string& output) {
6652 for (size_t at = 0; ; ) {
6653 const size_t line_end = output.find('\n', at);
6654 ret += "[ DEATH ] ";
6655 if (line_end == ::std::string::npos) {
6656 ret += output.substr(at);
6659 ret += output.substr(at, line_end + 1 - at);
6665 // Assesses the success or failure of a death test, using both private
6666 // members which have previously been set, and one argument:
6668 // Private data members:
6669 // outcome: An enumeration describing how the death test
6670 // concluded: DIED, LIVED, THREW, or RETURNED. The death test
6671 // fails in the latter three cases.
6672 // status: The exit status of the child process. On *nix, it is in the
6673 // in the format specified by wait(2). On Windows, this is the
6674 // value supplied to the ExitProcess() API or a numeric code
6675 // of the exception that terminated the program.
6676 // regex: A regular expression object to be applied to
6677 // the test's captured standard error output; the death test
6678 // fails if it does not match.
6681 // status_ok: true if exit_status is acceptable in the context of
6682 // this particular death test, which fails if it is false
6684 // Returns true iff all of the above conditions are met. Otherwise, the
6685 // first failing condition, in the order given above, is the one that is
6686 // reported. Also sets the last death test message string.
6687 bool DeathTestImpl::Passed(bool status_ok) {
6691 const String error_message = GetCapturedStderr();
6693 bool success = false;
6696 buffer << "Death test: " << statement() << "\n";
6697 switch (outcome()) {
6699 buffer << " Result: failed to die.\n"
6700 << " Error msg:\n" << FormatDeathTestOutput(error_message);
6703 buffer << " Result: threw an exception.\n"
6704 << " Error msg:\n" << FormatDeathTestOutput(error_message);
6707 buffer << " Result: illegal return in test statement.\n"
6708 << " Error msg:\n" << FormatDeathTestOutput(error_message);
6712 const bool matched = RE::PartialMatch(error_message.c_str(), *regex());
6716 buffer << " Result: died but not with expected error.\n"
6717 << " Expected: " << regex()->pattern() << "\n"
6718 << "Actual msg:\n" << FormatDeathTestOutput(error_message);
6721 buffer << " Result: died but not with expected exit code:\n"
6722 << " " << ExitSummary(status()) << "\n"
6723 << "Actual msg:\n" << FormatDeathTestOutput(error_message);
6729 << "DeathTest::Passed somehow called before conclusion of test";
6732 DeathTest::set_last_death_test_message(buffer.GetString());
6736 # if GTEST_OS_WINDOWS
6737 // WindowsDeathTest implements death tests on Windows. Due to the
6738 // specifics of starting new processes on Windows, death tests there are
6739 // always threadsafe, and Google Test considers the
6740 // --gtest_death_test_style=fast setting to be equivalent to
6741 // --gtest_death_test_style=threadsafe there.
6743 // A few implementation notes: Like the Linux version, the Windows
6744 // implementation uses pipes for child-to-parent communication. But due to
6745 // the specifics of pipes on Windows, some extra steps are required:
6747 // 1. The parent creates a communication pipe and stores handles to both
6749 // 2. The parent starts the child and provides it with the information
6750 // necessary to acquire the handle to the write end of the pipe.
6751 // 3. The child acquires the write end of the pipe and signals the parent
6752 // using a Windows event.
6753 // 4. Now the parent can release the write end of the pipe on its side. If
6754 // this is done before step 3, the object's reference count goes down to
6755 // 0 and it is destroyed, preventing the child from acquiring it. The
6756 // parent now has to release it, or read operations on the read end of
6757 // the pipe will not return when the child terminates.
6758 // 5. The parent reads child's output through the pipe (outcome code and
6759 // any possible error messages) from the pipe, and its stderr and then
6760 // determines whether to fail the test.
6762 // Note: to distinguish Win32 API calls from the local method and function
6763 // calls, the former are explicitly resolved in the global namespace.
6765 class WindowsDeathTest : public DeathTestImpl {
6767 WindowsDeathTest(const char* a_statement,
6771 : DeathTestImpl(a_statement, a_regex), file_(file), line_(line) {}
6773 // All of these virtual functions are inherited from DeathTest.
6775 virtual TestRole AssumeRole();
6778 // The name of the file in which the death test is located.
6779 const char* const file_;
6780 // The line number on which the death test is located.
6782 // Handle to the write end of the pipe to the child process.
6783 AutoHandle write_handle_;
6784 // Child process handle.
6785 AutoHandle child_handle_;
6786 // Event the child process uses to signal the parent that it has
6787 // acquired the handle to the write end of the pipe. After seeing this
6788 // event the parent can release its own handles to make sure its
6789 // ReadFile() calls return when the child terminates.
6790 AutoHandle event_handle_;
6793 // Waits for the child in a death test to exit, returning its exit
6794 // status, or 0 if no child process exists. As a side effect, sets the
6795 // outcome data member.
6796 int WindowsDeathTest::Wait() {
6800 // Wait until the child either signals that it has acquired the write end
6801 // of the pipe or it dies.
6802 const HANDLE wait_handles[2] = { child_handle_.Get(), event_handle_.Get() };
6803 switch (::WaitForMultipleObjects(2,
6805 FALSE, // Waits for any of the handles.
6808 case WAIT_OBJECT_0 + 1:
6811 GTEST_DEATH_TEST_CHECK_(false); // Should not get here.
6814 // The child has acquired the write end of the pipe or exited.
6815 // We release the handle on our side and continue.
6816 write_handle_.Reset();
6817 event_handle_.Reset();
6819 ReadAndInterpretStatusByte();
6821 // Waits for the child process to exit if it haven't already. This
6822 // returns immediately if the child has already exited, regardless of
6823 // whether previous calls to WaitForMultipleObjects synchronized on this
6825 GTEST_DEATH_TEST_CHECK_(
6826 WAIT_OBJECT_0 == ::WaitForSingleObject(child_handle_.Get(),
6829 GTEST_DEATH_TEST_CHECK_(
6830 ::GetExitCodeProcess(child_handle_.Get(), &status_code) != FALSE);
6831 child_handle_.Reset();
6832 set_status(static_cast<int>(status_code));
6836 // The AssumeRole process for a Windows death test. It creates a child
6837 // process with the same executable as the current process to run the
6838 // death test. The child process is given the --gtest_filter and
6839 // --gtest_internal_run_death_test flags such that it knows to run the
6840 // current death test only.
6841 DeathTest::TestRole WindowsDeathTest::AssumeRole() {
6842 const UnitTestImpl* const impl = GetUnitTestImpl();
6843 const InternalRunDeathTestFlag* const flag =
6844 impl->internal_run_death_test_flag();
6845 const TestInfo* const info = impl->current_test_info();
6846 const int death_test_index = info->result()->death_test_count();
6849 // ParseInternalRunDeathTestFlag() has performed all the necessary
6851 set_write_fd(flag->write_fd());
6852 return EXECUTE_TEST;
6855 // WindowsDeathTest uses an anonymous pipe to communicate results of
6857 SECURITY_ATTRIBUTES handles_are_inheritable = {
6858 sizeof(SECURITY_ATTRIBUTES), NULL, TRUE };
6859 HANDLE read_handle, write_handle;
6860 GTEST_DEATH_TEST_CHECK_(
6861 ::CreatePipe(&read_handle, &write_handle, &handles_are_inheritable,
6862 0) // Default buffer size.
6864 set_read_fd(::_open_osfhandle(reinterpret_cast<intptr_t>(read_handle),
6866 write_handle_.Reset(write_handle);
6867 event_handle_.Reset(::CreateEvent(
6868 &handles_are_inheritable,
6869 TRUE, // The event will automatically reset to non-signaled state.
6870 FALSE, // The initial state is non-signalled.
6871 NULL)); // The even is unnamed.
6872 GTEST_DEATH_TEST_CHECK_(event_handle_.Get() != NULL);
6873 const String filter_flag = String::Format("--%s%s=%s.%s",
6874 GTEST_FLAG_PREFIX_, kFilterFlag,
6875 info->test_case_name(),
6877 const String internal_flag = String::Format(
6878 "--%s%s=%s|%d|%d|%u|%Iu|%Iu",
6880 kInternalRunDeathTestFlag,
6883 static_cast<unsigned int>(::GetCurrentProcessId()),
6884 // size_t has the same with as pointers on both 32-bit and 64-bit
6885 // Windows platforms.
6886 // See http://msdn.microsoft.com/en-us/library/tcxf1dw6.aspx.
6887 reinterpret_cast<size_t>(write_handle),
6888 reinterpret_cast<size_t>(event_handle_.Get()));
6890 char executable_path[_MAX_PATH + 1]; // NOLINT
6891 GTEST_DEATH_TEST_CHECK_(
6892 _MAX_PATH + 1 != ::GetModuleFileNameA(NULL,
6896 String command_line = String::Format("%s %s \"%s\"",
6897 ::GetCommandLineA(),
6898 filter_flag.c_str(),
6899 internal_flag.c_str());
6901 DeathTest::set_last_death_test_message("");
6904 // Flush the log buffers since the log streams are shared with the child.
6907 // The child process will share the standard handles with the parent.
6908 STARTUPINFOA startup_info;
6909 memset(&startup_info, 0, sizeof(STARTUPINFO));
6910 startup_info.dwFlags = STARTF_USESTDHANDLES;
6911 startup_info.hStdInput = ::GetStdHandle(STD_INPUT_HANDLE);
6912 startup_info.hStdOutput = ::GetStdHandle(STD_OUTPUT_HANDLE);
6913 startup_info.hStdError = ::GetStdHandle(STD_ERROR_HANDLE);
6915 PROCESS_INFORMATION process_info;
6916 GTEST_DEATH_TEST_CHECK_(::CreateProcessA(
6918 const_cast<char*>(command_line.c_str()),
6919 NULL, // Retuned process handle is not inheritable.
6920 NULL, // Retuned thread handle is not inheritable.
6921 TRUE, // Child inherits all inheritable handles (for write_handle_).
6922 0x0, // Default creation flags.
6923 NULL, // Inherit the parent's environment.
6924 UnitTest::GetInstance()->original_working_dir(),
6926 &process_info) != FALSE);
6927 child_handle_.Reset(process_info.hProcess);
6928 ::CloseHandle(process_info.hThread);
6930 return OVERSEE_TEST;
6932 # else // We are not on Windows.
6934 // ForkingDeathTest provides implementations for most of the abstract
6935 // methods of the DeathTest interface. Only the AssumeRole method is
6937 class ForkingDeathTest : public DeathTestImpl {
6939 ForkingDeathTest(const char* statement, const RE* regex);
6941 // All of these virtual functions are inherited from DeathTest.
6945 void set_child_pid(pid_t child_pid) { child_pid_ = child_pid; }
6948 // PID of child process during death test; 0 in the child process itself.
6952 // Constructs a ForkingDeathTest.
6953 ForkingDeathTest::ForkingDeathTest(const char* a_statement, const RE* a_regex)
6954 : DeathTestImpl(a_statement, a_regex),
6957 // Waits for the child in a death test to exit, returning its exit
6958 // status, or 0 if no child process exists. As a side effect, sets the
6959 // outcome data member.
6960 int ForkingDeathTest::Wait() {
6964 ReadAndInterpretStatusByte();
6967 GTEST_DEATH_TEST_CHECK_SYSCALL_(waitpid(child_pid_, &status_value, 0));
6968 set_status(status_value);
6969 return status_value;
6972 // A concrete death test class that forks, then immediately runs the test
6973 // in the child process.
6974 class NoExecDeathTest : public ForkingDeathTest {
6976 NoExecDeathTest(const char* a_statement, const RE* a_regex) :
6977 ForkingDeathTest(a_statement, a_regex) { }
6978 virtual TestRole AssumeRole();
6981 // The AssumeRole process for a fork-and-run death test. It implements a
6982 // straightforward fork, with a simple pipe to transmit the status byte.
6983 DeathTest::TestRole NoExecDeathTest::AssumeRole() {
6984 const size_t thread_count = GetThreadCount();
6985 if (thread_count != 1) {
6986 GTEST_LOG_(WARNING) << DeathTestThreadWarning(thread_count);
6990 GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
6992 DeathTest::set_last_death_test_message("");
6994 // When we fork the process below, the log file buffers are copied, but the
6995 // file descriptors are shared. We flush all log files here so that closing
6996 // the file descriptors in the child process doesn't throw off the
6997 // synchronization between descriptors and buffers in the parent process.
6998 // This is as close to the fork as possible to avoid a race condition in case
6999 // there are multiple threads running before the death test, and another
7000 // thread writes to the log file.
7003 const pid_t child_pid = fork();
7004 GTEST_DEATH_TEST_CHECK_(child_pid != -1);
7005 set_child_pid(child_pid);
7006 if (child_pid == 0) {
7007 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[0]));
7008 set_write_fd(pipe_fd[1]);
7009 // Redirects all logging to stderr in the child process to prevent
7010 // concurrent writes to the log files. We capture stderr in the parent
7011 // process and append the child process' output to a log.
7013 // Event forwarding to the listeners of event listener API mush be shut
7014 // down in death test subprocesses.
7015 GetUnitTestImpl()->listeners()->SuppressEventForwarding();
7016 return EXECUTE_TEST;
7018 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
7019 set_read_fd(pipe_fd[0]);
7021 return OVERSEE_TEST;
7025 // A concrete death test class that forks and re-executes the main
7026 // program from the beginning, with command-line flags set that cause
7027 // only this specific death test to be run.
7028 class ExecDeathTest : public ForkingDeathTest {
7030 ExecDeathTest(const char* a_statement, const RE* a_regex,
7031 const char* file, int line) :
7032 ForkingDeathTest(a_statement, a_regex), file_(file), line_(line) { }
7033 virtual TestRole AssumeRole();
7035 // The name of the file in which the death test is located.
7036 const char* const file_;
7037 // The line number on which the death test is located.
7041 // Utility class for accumulating command-line arguments.
7045 args_.push_back(NULL);
7049 for (std::vector<char*>::iterator i = args_.begin(); i != args_.end();
7054 void AddArgument(const char* argument) {
7055 args_.insert(args_.end() - 1, posix::StrDup(argument));
7058 template <typename Str>
7059 void AddArguments(const ::std::vector<Str>& arguments) {
7060 for (typename ::std::vector<Str>::const_iterator i = arguments.begin();
7061 i != arguments.end();
7063 args_.insert(args_.end() - 1, posix::StrDup(i->c_str()));
7066 char* const* Argv() {
7070 std::vector<char*> args_;
7073 // A struct that encompasses the arguments to the child process of a
7074 // threadsafe-style death test process.
7075 struct ExecDeathTestArgs {
7076 char* const* argv; // Command-line arguments for the child's call to exec
7077 int close_fd; // File descriptor to close; the read end of a pipe
7081 inline char** GetEnviron() {
7082 // When Google Test is built as a framework on MacOS X, the environ variable
7083 // is unavailable. Apple's documentation (man environ) recommends using
7084 // _NSGetEnviron() instead.
7085 return *_NSGetEnviron();
7088 // Some POSIX platforms expect you to declare environ. extern "C" makes
7089 // it reside in the global namespace.
7090 extern "C" char** environ;
7091 inline char** GetEnviron() { return environ; }
7092 # endif // GTEST_OS_MAC
7094 // The main function for a threadsafe-style death test child process.
7095 // This function is called in a clone()-ed process and thus must avoid
7096 // any potentially unsafe operations like malloc or libc functions.
7097 static int ExecDeathTestChildMain(void* child_arg) {
7098 ExecDeathTestArgs* const args = static_cast<ExecDeathTestArgs*>(child_arg);
7099 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(args->close_fd));
7101 // We need to execute the test program in the same environment where
7102 // it was originally invoked. Therefore we change to the original
7103 // working directory first.
7104 const char* const original_dir =
7105 UnitTest::GetInstance()->original_working_dir();
7106 // We can safely call chdir() as it's a direct system call.
7107 if (chdir(original_dir) != 0) {
7108 DeathTestAbort(String::Format("chdir(\"%s\") failed: %s",
7110 GetLastErrnoDescription().c_str()));
7111 return EXIT_FAILURE;
7114 // We can safely call execve() as it's a direct system call. We
7115 // cannot use execvp() as it's a libc function and thus potentially
7116 // unsafe. Since execve() doesn't search the PATH, the user must
7117 // invoke the test program via a valid path that contains at least
7118 // one path separator.
7119 execve(args->argv[0], args->argv, GetEnviron());
7120 DeathTestAbort(String::Format("execve(%s, ...) in %s failed: %s",
7123 GetLastErrnoDescription().c_str()));
7124 return EXIT_FAILURE;
7127 // Two utility routines that together determine the direction the stack
7129 // This could be accomplished more elegantly by a single recursive
7130 // function, but we want to guard against the unlikely possibility of
7131 // a smart compiler optimizing the recursion away.
7133 // GTEST_NO_INLINE_ is required to prevent GCC 4.6 from inlining
7134 // StackLowerThanAddress into StackGrowsDown, which then doesn't give
7136 bool StackLowerThanAddress(const void* ptr) GTEST_NO_INLINE_;
7137 bool StackLowerThanAddress(const void* ptr) {
7139 return &dummy < ptr;
7142 bool StackGrowsDown() {
7144 return StackLowerThanAddress(&dummy);
7147 // A threadsafe implementation of fork(2) for threadsafe-style death tests
7148 // that uses clone(2). It dies with an error message if anything goes
7150 static pid_t ExecDeathTestFork(char* const* argv, int close_fd) {
7151 ExecDeathTestArgs args = { argv, close_fd };
7152 pid_t child_pid = -1;
7154 # if GTEST_HAS_CLONE
7155 const bool use_fork = GTEST_FLAG(death_test_use_fork);
7158 static const bool stack_grows_down = StackGrowsDown();
7159 const size_t stack_size = getpagesize();
7160 // MMAP_ANONYMOUS is not defined on Mac, so we use MAP_ANON instead.
7161 void* const stack = mmap(NULL, stack_size, PROT_READ | PROT_WRITE,
7162 MAP_ANON | MAP_PRIVATE, -1, 0);
7163 GTEST_DEATH_TEST_CHECK_(stack != MAP_FAILED);
7164 void* const stack_top =
7165 static_cast<char*>(stack) + (stack_grows_down ? stack_size : 0);
7167 child_pid = clone(&ExecDeathTestChildMain, stack_top, SIGCHLD, &args);
7169 GTEST_DEATH_TEST_CHECK_(munmap(stack, stack_size) != -1);
7172 const bool use_fork = true;
7173 # endif // GTEST_HAS_CLONE
7175 if (use_fork && (child_pid = fork()) == 0) {
7176 ExecDeathTestChildMain(&args);
7180 GTEST_DEATH_TEST_CHECK_(child_pid != -1);
7184 // The AssumeRole process for a fork-and-exec death test. It re-executes the
7185 // main program from the beginning, setting the --gtest_filter
7186 // and --gtest_internal_run_death_test flags to cause only the current
7187 // death test to be re-run.
7188 DeathTest::TestRole ExecDeathTest::AssumeRole() {
7189 const UnitTestImpl* const impl = GetUnitTestImpl();
7190 const InternalRunDeathTestFlag* const flag =
7191 impl->internal_run_death_test_flag();
7192 const TestInfo* const info = impl->current_test_info();
7193 const int death_test_index = info->result()->death_test_count();
7196 set_write_fd(flag->write_fd());
7197 return EXECUTE_TEST;
7201 GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
7202 // Clear the close-on-exec flag on the write end of the pipe, lest
7203 // it be closed when the child process does an exec:
7204 GTEST_DEATH_TEST_CHECK_(fcntl(pipe_fd[1], F_SETFD, 0) != -1);
7206 const String filter_flag =
7207 String::Format("--%s%s=%s.%s",
7208 GTEST_FLAG_PREFIX_, kFilterFlag,
7209 info->test_case_name(), info->name());
7210 const String internal_flag =
7211 String::Format("--%s%s=%s|%d|%d|%d",
7212 GTEST_FLAG_PREFIX_, kInternalRunDeathTestFlag,
7213 file_, line_, death_test_index, pipe_fd[1]);
7215 args.AddArguments(GetArgvs());
7216 args.AddArgument(filter_flag.c_str());
7217 args.AddArgument(internal_flag.c_str());
7219 DeathTest::set_last_death_test_message("");
7222 // See the comment in NoExecDeathTest::AssumeRole for why the next line
7226 const pid_t child_pid = ExecDeathTestFork(args.Argv(), pipe_fd[0]);
7227 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
7228 set_child_pid(child_pid);
7229 set_read_fd(pipe_fd[0]);
7231 return OVERSEE_TEST;
7234 # endif // !GTEST_OS_WINDOWS
7236 // Creates a concrete DeathTest-derived class that depends on the
7237 // --gtest_death_test_style flag, and sets the pointer pointed to
7238 // by the "test" argument to its address. If the test should be
7239 // skipped, sets that pointer to NULL. Returns true, unless the
7240 // flag is set to an invalid value.
7241 bool DefaultDeathTestFactory::Create(const char* statement, const RE* regex,
7242 const char* file, int line,
7244 UnitTestImpl* const impl = GetUnitTestImpl();
7245 const InternalRunDeathTestFlag* const flag =
7246 impl->internal_run_death_test_flag();
7247 const int death_test_index = impl->current_test_info()
7248 ->increment_death_test_count();
7251 if (death_test_index > flag->index()) {
7252 DeathTest::set_last_death_test_message(String::Format(
7253 "Death test count (%d) somehow exceeded expected maximum (%d)",
7254 death_test_index, flag->index()));
7258 if (!(flag->file() == file && flag->line() == line &&
7259 flag->index() == death_test_index)) {
7265 # if GTEST_OS_WINDOWS
7267 if (GTEST_FLAG(death_test_style) == "threadsafe" ||
7268 GTEST_FLAG(death_test_style) == "fast") {
7269 *test = new WindowsDeathTest(statement, regex, file, line);
7274 if (GTEST_FLAG(death_test_style) == "threadsafe") {
7275 *test = new ExecDeathTest(statement, regex, file, line);
7276 } else if (GTEST_FLAG(death_test_style) == "fast") {
7277 *test = new NoExecDeathTest(statement, regex);
7280 # endif // GTEST_OS_WINDOWS
7282 else { // NOLINT - this is more readable than unbalanced brackets inside #if.
7283 DeathTest::set_last_death_test_message(String::Format(
7284 "Unknown death test style \"%s\" encountered",
7285 GTEST_FLAG(death_test_style).c_str()));
7292 // Splits a given string on a given delimiter, populating a given
7293 // vector with the fields. GTEST_HAS_DEATH_TEST implies that we have
7294 // ::std::string, so we can use it here.
7295 static void SplitString(const ::std::string& str, char delimiter,
7296 ::std::vector< ::std::string>* dest) {
7297 ::std::vector< ::std::string> parsed;
7298 ::std::string::size_type pos = 0;
7299 while (::testing::internal::AlwaysTrue()) {
7300 const ::std::string::size_type colon = str.find(delimiter, pos);
7301 if (colon == ::std::string::npos) {
7302 parsed.push_back(str.substr(pos));
7305 parsed.push_back(str.substr(pos, colon - pos));
7312 # if GTEST_OS_WINDOWS
7313 // Recreates the pipe and event handles from the provided parameters,
7314 // signals the event, and returns a file descriptor wrapped around the pipe
7315 // handle. This function is called in the child process only.
7316 int GetStatusFileDescriptor(unsigned int parent_process_id,
7317 size_t write_handle_as_size_t,
7318 size_t event_handle_as_size_t) {
7319 AutoHandle parent_process_handle(::OpenProcess(PROCESS_DUP_HANDLE,
7320 FALSE, // Non-inheritable.
7321 parent_process_id));
7322 if (parent_process_handle.Get() == INVALID_HANDLE_VALUE) {
7323 DeathTestAbort(String::Format("Unable to open parent process %u",
7324 parent_process_id));
7327 // TODO(vladl@google.com): Replace the following check with a
7328 // compile-time assertion when available.
7329 GTEST_CHECK_(sizeof(HANDLE) <= sizeof(size_t));
7331 const HANDLE write_handle =
7332 reinterpret_cast<HANDLE>(write_handle_as_size_t);
7333 HANDLE dup_write_handle;
7335 // The newly initialized handle is accessible only in in the parent
7336 // process. To obtain one accessible within the child, we need to use
7338 if (!::DuplicateHandle(parent_process_handle.Get(), write_handle,
7339 ::GetCurrentProcess(), &dup_write_handle,
7340 0x0, // Requested privileges ignored since
7341 // DUPLICATE_SAME_ACCESS is used.
7342 FALSE, // Request non-inheritable handler.
7343 DUPLICATE_SAME_ACCESS)) {
7344 DeathTestAbort(String::Format(
7345 "Unable to duplicate the pipe handle %Iu from the parent process %u",
7346 write_handle_as_size_t, parent_process_id));
7349 const HANDLE event_handle = reinterpret_cast<HANDLE>(event_handle_as_size_t);
7350 HANDLE dup_event_handle;
7352 if (!::DuplicateHandle(parent_process_handle.Get(), event_handle,
7353 ::GetCurrentProcess(), &dup_event_handle,
7356 DUPLICATE_SAME_ACCESS)) {
7357 DeathTestAbort(String::Format(
7358 "Unable to duplicate the event handle %Iu from the parent process %u",
7359 event_handle_as_size_t, parent_process_id));
7362 const int write_fd =
7363 ::_open_osfhandle(reinterpret_cast<intptr_t>(dup_write_handle), O_APPEND);
7364 if (write_fd == -1) {
7365 DeathTestAbort(String::Format(
7366 "Unable to convert pipe handle %Iu to a file descriptor",
7367 write_handle_as_size_t));
7370 // Signals the parent that the write end of the pipe has been acquired
7371 // so the parent can release its own write end.
7372 ::SetEvent(dup_event_handle);
7376 # endif // GTEST_OS_WINDOWS
7378 // Returns a newly created InternalRunDeathTestFlag object with fields
7379 // initialized from the GTEST_FLAG(internal_run_death_test) flag if
7380 // the flag is specified; otherwise returns NULL.
7381 InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() {
7382 if (GTEST_FLAG(internal_run_death_test) == "") return NULL;
7384 // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we
7388 ::std::vector< ::std::string> fields;
7389 SplitString(GTEST_FLAG(internal_run_death_test).c_str(), '|', &fields);
7392 # if GTEST_OS_WINDOWS
7394 unsigned int parent_process_id = 0;
7395 size_t write_handle_as_size_t = 0;
7396 size_t event_handle_as_size_t = 0;
7398 if (fields.size() != 6
7399 || !ParseNaturalNumber(fields[1], &line)
7400 || !ParseNaturalNumber(fields[2], &index)
7401 || !ParseNaturalNumber(fields[3], &parent_process_id)
7402 || !ParseNaturalNumber(fields[4], &write_handle_as_size_t)
7403 || !ParseNaturalNumber(fields[5], &event_handle_as_size_t)) {
7404 DeathTestAbort(String::Format(
7405 "Bad --gtest_internal_run_death_test flag: %s",
7406 GTEST_FLAG(internal_run_death_test).c_str()));
7408 write_fd = GetStatusFileDescriptor(parent_process_id,
7409 write_handle_as_size_t,
7410 event_handle_as_size_t);
7413 if (fields.size() != 4
7414 || !ParseNaturalNumber(fields[1], &line)
7415 || !ParseNaturalNumber(fields[2], &index)
7416 || !ParseNaturalNumber(fields[3], &write_fd)) {
7417 DeathTestAbort(String::Format(
7418 "Bad --gtest_internal_run_death_test flag: %s",
7419 GTEST_FLAG(internal_run_death_test).c_str()));
7422 # endif // GTEST_OS_WINDOWS
7424 return new InternalRunDeathTestFlag(fields[0], line, index, write_fd);
7427 } // namespace internal
7429 #endif // GTEST_HAS_DEATH_TEST
7431 } // namespace testing
7432 // Copyright 2008, Google Inc.
7433 // All rights reserved.
7435 // Redistribution and use in source and binary forms, with or without
7436 // modification, are permitted provided that the following conditions are
7439 // * Redistributions of source code must retain the above copyright
7440 // notice, this list of conditions and the following disclaimer.
7441 // * Redistributions in binary form must reproduce the above
7442 // copyright notice, this list of conditions and the following disclaimer
7443 // in the documentation and/or other materials provided with the
7445 // * Neither the name of Google Inc. nor the names of its
7446 // contributors may be used to endorse or promote products derived from
7447 // this software without specific prior written permission.
7449 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
7450 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
7451 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
7452 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
7453 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
7454 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
7455 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
7456 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
7457 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
7458 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
7459 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
7461 // Authors: keith.ray@gmail.com (Keith Ray)
7466 #if GTEST_OS_WINDOWS_MOBILE
7467 # include <windows.h>
7468 #elif GTEST_OS_WINDOWS
7469 # include <direct.h>
7471 #elif GTEST_OS_SYMBIAN || GTEST_OS_NACL
7472 // Symbian OpenC and NaCl have PATH_MAX in sys/syslimits.h
7473 # include <sys/syslimits.h>
7475 # include <limits.h>
7476 # include <climits> // Some Linux distributions define PATH_MAX here.
7477 #endif // GTEST_OS_WINDOWS_MOBILE
7479 #if GTEST_OS_WINDOWS
7480 # define GTEST_PATH_MAX_ _MAX_PATH
7481 #elif defined(PATH_MAX)
7482 # define GTEST_PATH_MAX_ PATH_MAX
7483 #elif defined(_XOPEN_PATH_MAX)
7484 # define GTEST_PATH_MAX_ _XOPEN_PATH_MAX
7486 # define GTEST_PATH_MAX_ _POSIX_PATH_MAX
7487 #endif // GTEST_OS_WINDOWS
7491 namespace internal {
7493 #if GTEST_OS_WINDOWS
7494 // On Windows, '\\' is the standard path separator, but many tools and the
7495 // Windows API also accept '/' as an alternate path separator. Unless otherwise
7496 // noted, a file path can contain either kind of path separators, or a mixture
7498 const char kPathSeparator = '\\';
7499 const char kAlternatePathSeparator = '/';
7500 const char kPathSeparatorString[] = "\\";
7501 const char kAlternatePathSeparatorString[] = "/";
7502 # if GTEST_OS_WINDOWS_MOBILE
7503 // Windows CE doesn't have a current directory. You should not use
7504 // the current directory in tests on Windows CE, but this at least
7505 // provides a reasonable fallback.
7506 const char kCurrentDirectoryString[] = "\\";
7507 // Windows CE doesn't define INVALID_FILE_ATTRIBUTES
7508 const DWORD kInvalidFileAttributes = 0xffffffff;
7510 const char kCurrentDirectoryString[] = ".\\";
7511 # endif // GTEST_OS_WINDOWS_MOBILE
7513 const char kPathSeparator = '/';
7514 const char kPathSeparatorString[] = "/";
7515 const char kCurrentDirectoryString[] = "./";
7516 #endif // GTEST_OS_WINDOWS
7518 // Returns whether the given character is a valid path separator.
7519 static bool IsPathSeparator(char c) {
7520 #if GTEST_HAS_ALT_PATH_SEP_
7521 return (c == kPathSeparator) || (c == kAlternatePathSeparator);
7523 return c == kPathSeparator;
7527 // Returns the current working directory, or "" if unsuccessful.
7528 FilePath FilePath::GetCurrentDir() {
7529 #if GTEST_OS_WINDOWS_MOBILE
7530 // Windows CE doesn't have a current directory, so we just return
7531 // something reasonable.
7532 return FilePath(kCurrentDirectoryString);
7533 #elif GTEST_OS_WINDOWS
7534 char cwd[GTEST_PATH_MAX_ + 1] = { '\0' };
7535 return FilePath(_getcwd(cwd, sizeof(cwd)) == NULL ? "" : cwd);
7537 char cwd[GTEST_PATH_MAX_ + 1] = { '\0' };
7538 return FilePath(getcwd(cwd, sizeof(cwd)) == NULL ? "" : cwd);
7539 #endif // GTEST_OS_WINDOWS_MOBILE
7542 // Returns a copy of the FilePath with the case-insensitive extension removed.
7543 // Example: FilePath("dir/file.exe").RemoveExtension("EXE") returns
7544 // FilePath("dir/file"). If a case-insensitive extension is not
7545 // found, returns a copy of the original FilePath.
7546 FilePath FilePath::RemoveExtension(const char* extension) const {
7547 String dot_extension(String::Format(".%s", extension));
7548 if (pathname_.EndsWithCaseInsensitive(dot_extension.c_str())) {
7549 return FilePath(String(pathname_.c_str(), pathname_.length() - 4));
7554 // Returns a pointer to the last occurence of a valid path separator in
7555 // the FilePath. On Windows, for example, both '/' and '\' are valid path
7556 // separators. Returns NULL if no path separator was found.
7557 const char* FilePath::FindLastPathSeparator() const {
7558 const char* const last_sep = strrchr(c_str(), kPathSeparator);
7559 #if GTEST_HAS_ALT_PATH_SEP_
7560 const char* const last_alt_sep = strrchr(c_str(), kAlternatePathSeparator);
7561 // Comparing two pointers of which only one is NULL is undefined.
7562 if (last_alt_sep != NULL &&
7563 (last_sep == NULL || last_alt_sep > last_sep)) {
7564 return last_alt_sep;
7570 // Returns a copy of the FilePath with the directory part removed.
7571 // Example: FilePath("path/to/file").RemoveDirectoryName() returns
7572 // FilePath("file"). If there is no directory part ("just_a_file"), it returns
7573 // the FilePath unmodified. If there is no file part ("just_a_dir/") it
7574 // returns an empty FilePath ("").
7575 // On Windows platform, '\' is the path separator, otherwise it is '/'.
7576 FilePath FilePath::RemoveDirectoryName() const {
7577 const char* const last_sep = FindLastPathSeparator();
7578 return last_sep ? FilePath(String(last_sep + 1)) : *this;
7581 // RemoveFileName returns the directory path with the filename removed.
7582 // Example: FilePath("path/to/file").RemoveFileName() returns "path/to/".
7583 // If the FilePath is "a_file" or "/a_file", RemoveFileName returns
7584 // FilePath("./") or, on Windows, FilePath(".\\"). If the filepath does
7585 // not have a file, like "just/a/dir/", it returns the FilePath unmodified.
7586 // On Windows platform, '\' is the path separator, otherwise it is '/'.
7587 FilePath FilePath::RemoveFileName() const {
7588 const char* const last_sep = FindLastPathSeparator();
7591 dir = String(c_str(), last_sep + 1 - c_str());
7593 dir = kCurrentDirectoryString;
7595 return FilePath(dir);
7598 // Helper functions for naming files in a directory for xml output.
7600 // Given directory = "dir", base_name = "test", number = 0,
7601 // extension = "xml", returns "dir/test.xml". If number is greater
7602 // than zero (e.g., 12), returns "dir/test_12.xml".
7603 // On Windows platform, uses \ as the separator rather than /.
7604 FilePath FilePath::MakeFileName(const FilePath& directory,
7605 const FilePath& base_name,
7607 const char* extension) {
7610 file = String::Format("%s.%s", base_name.c_str(), extension);
7612 file = String::Format("%s_%d.%s", base_name.c_str(), number, extension);
7614 return ConcatPaths(directory, FilePath(file));
7617 // Given directory = "dir", relative_path = "test.xml", returns "dir/test.xml".
7618 // On Windows, uses \ as the separator rather than /.
7619 FilePath FilePath::ConcatPaths(const FilePath& directory,
7620 const FilePath& relative_path) {
7621 if (directory.IsEmpty())
7622 return relative_path;
7623 const FilePath dir(directory.RemoveTrailingPathSeparator());
7624 return FilePath(String::Format("%s%c%s", dir.c_str(), kPathSeparator,
7625 relative_path.c_str()));
7628 // Returns true if pathname describes something findable in the file-system,
7629 // either a file, directory, or whatever.
7630 bool FilePath::FileOrDirectoryExists() const {
7631 #if GTEST_OS_WINDOWS_MOBILE
7632 LPCWSTR unicode = String::AnsiToUtf16(pathname_.c_str());
7633 const DWORD attributes = GetFileAttributes(unicode);
7635 return attributes != kInvalidFileAttributes;
7637 posix::StatStruct file_stat;
7638 return posix::Stat(pathname_.c_str(), &file_stat) == 0;
7639 #endif // GTEST_OS_WINDOWS_MOBILE
7642 // Returns true if pathname describes a directory in the file-system
7644 bool FilePath::DirectoryExists() const {
7645 bool result = false;
7646 #if GTEST_OS_WINDOWS
7647 // Don't strip off trailing separator if path is a root directory on
7648 // Windows (like "C:\\").
7649 const FilePath& path(IsRootDirectory() ? *this :
7650 RemoveTrailingPathSeparator());
7652 const FilePath& path(*this);
7655 #if GTEST_OS_WINDOWS_MOBILE
7656 LPCWSTR unicode = String::AnsiToUtf16(path.c_str());
7657 const DWORD attributes = GetFileAttributes(unicode);
7659 if ((attributes != kInvalidFileAttributes) &&
7660 (attributes & FILE_ATTRIBUTE_DIRECTORY)) {
7664 posix::StatStruct file_stat;
7665 result = posix::Stat(path.c_str(), &file_stat) == 0 &&
7666 posix::IsDir(file_stat);
7667 #endif // GTEST_OS_WINDOWS_MOBILE
7672 // Returns true if pathname describes a root directory. (Windows has one
7673 // root directory per disk drive.)
7674 bool FilePath::IsRootDirectory() const {
7675 #if GTEST_OS_WINDOWS
7676 // TODO(wan@google.com): on Windows a network share like
7677 // \\server\share can be a root directory, although it cannot be the
7678 // current directory. Handle this properly.
7679 return pathname_.length() == 3 && IsAbsolutePath();
7681 return pathname_.length() == 1 && IsPathSeparator(pathname_.c_str()[0]);
7685 // Returns true if pathname describes an absolute path.
7686 bool FilePath::IsAbsolutePath() const {
7687 const char* const name = pathname_.c_str();
7688 #if GTEST_OS_WINDOWS
7689 return pathname_.length() >= 3 &&
7690 ((name[0] >= 'a' && name[0] <= 'z') ||
7691 (name[0] >= 'A' && name[0] <= 'Z')) &&
7693 IsPathSeparator(name[2]);
7695 return IsPathSeparator(name[0]);
7699 // Returns a pathname for a file that does not currently exist. The pathname
7700 // will be directory/base_name.extension or
7701 // directory/base_name_<number>.extension if directory/base_name.extension
7702 // already exists. The number will be incremented until a pathname is found
7703 // that does not already exist.
7704 // Examples: 'dir/foo_test.xml' or 'dir/foo_test_1.xml'.
7705 // There could be a race condition if two or more processes are calling this
7706 // function at the same time -- they could both pick the same filename.
7707 FilePath FilePath::GenerateUniqueFileName(const FilePath& directory,
7708 const FilePath& base_name,
7709 const char* extension) {
7710 FilePath full_pathname;
7713 full_pathname.Set(MakeFileName(directory, base_name, number++, extension));
7714 } while (full_pathname.FileOrDirectoryExists());
7715 return full_pathname;
7718 // Returns true if FilePath ends with a path separator, which indicates that
7719 // it is intended to represent a directory. Returns false otherwise.
7720 // This does NOT check that a directory (or file) actually exists.
7721 bool FilePath::IsDirectory() const {
7722 return !pathname_.empty() &&
7723 IsPathSeparator(pathname_.c_str()[pathname_.length() - 1]);
7726 // Create directories so that path exists. Returns true if successful or if
7727 // the directories already exist; returns false if unable to create directories
7729 bool FilePath::CreateDirectoriesRecursively() const {
7730 if (!this->IsDirectory()) {
7734 if (pathname_.length() == 0 || this->DirectoryExists()) {
7738 const FilePath parent(this->RemoveTrailingPathSeparator().RemoveFileName());
7739 return parent.CreateDirectoriesRecursively() && this->CreateFolder();
7742 // Create the directory so that path exists. Returns true if successful or
7743 // if the directory already exists; returns false if unable to create the
7744 // directory for any reason, including if the parent directory does not
7745 // exist. Not named "CreateDirectory" because that's a macro on Windows.
7746 bool FilePath::CreateFolder() const {
7747 #if GTEST_OS_WINDOWS_MOBILE
7748 FilePath removed_sep(this->RemoveTrailingPathSeparator());
7749 LPCWSTR unicode = String::AnsiToUtf16(removed_sep.c_str());
7750 int result = CreateDirectory(unicode, NULL) ? 0 : -1;
7752 #elif GTEST_OS_WINDOWS
7753 int result = _mkdir(pathname_.c_str());
7755 int result = mkdir(pathname_.c_str(), 0777);
7756 #endif // GTEST_OS_WINDOWS_MOBILE
7759 return this->DirectoryExists(); // An error is OK if the directory exists.
7761 return true; // No error.
7764 // If input name has a trailing separator character, remove it and return the
7765 // name, otherwise return the name string unmodified.
7766 // On Windows platform, uses \ as the separator, other platforms use /.
7767 FilePath FilePath::RemoveTrailingPathSeparator() const {
7768 return IsDirectory()
7769 ? FilePath(String(pathname_.c_str(), pathname_.length() - 1))
7773 // Removes any redundant separators that might be in the pathname.
7774 // For example, "bar///foo" becomes "bar/foo". Does not eliminate other
7775 // redundancies that might be in a pathname involving "." or "..".
7776 // TODO(wan@google.com): handle Windows network shares (e.g. \\server\share).
7777 void FilePath::Normalize() {
7778 if (pathname_.c_str() == NULL) {
7782 const char* src = pathname_.c_str();
7783 char* const dest = new char[pathname_.length() + 1];
7784 char* dest_ptr = dest;
7785 memset(dest_ptr, 0, pathname_.length() + 1);
7787 while (*src != '\0') {
7789 if (!IsPathSeparator(*src)) {
7792 #if GTEST_HAS_ALT_PATH_SEP_
7793 if (*dest_ptr == kAlternatePathSeparator) {
7794 *dest_ptr = kPathSeparator;
7797 while (IsPathSeparator(*src))
7807 } // namespace internal
7808 } // namespace testing
7809 // Copyright 2008, Google Inc.
7810 // All rights reserved.
7812 // Redistribution and use in source and binary forms, with or without
7813 // modification, are permitted provided that the following conditions are
7816 // * Redistributions of source code must retain the above copyright
7817 // notice, this list of conditions and the following disclaimer.
7818 // * Redistributions in binary form must reproduce the above
7819 // copyright notice, this list of conditions and the following disclaimer
7820 // in the documentation and/or other materials provided with the
7822 // * Neither the name of Google Inc. nor the names of its
7823 // contributors may be used to endorse or promote products derived from
7824 // this software without specific prior written permission.
7826 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
7827 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
7828 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
7829 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
7830 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
7831 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
7832 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
7833 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
7834 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
7835 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
7836 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
7838 // Author: wan@google.com (Zhanyong Wan)
7846 #if GTEST_OS_WINDOWS_MOBILE
7847 # include <windows.h> // For TerminateProcess()
7848 #elif GTEST_OS_WINDOWS
7850 # include <sys/stat.h>
7852 # include <unistd.h>
7853 #endif // GTEST_OS_WINDOWS_MOBILE
7856 # include <mach/mach_init.h>
7857 # include <mach/task.h>
7858 # include <mach/vm_map.h>
7859 #endif // GTEST_OS_MAC
7862 // Indicates that this translation unit is part of Google Test's
7863 // implementation. It must come before gtest-internal-inl.h is
7864 // included, or there will be a compiler error. This trick is to
7865 // prevent a user from accidentally including gtest-internal-inl.h in
7867 #define GTEST_IMPLEMENTATION_ 1
7868 #undef GTEST_IMPLEMENTATION_
7871 namespace internal {
7873 #if defined(_MSC_VER) || defined(__BORLANDC__)
7874 // MSVC and C++Builder do not provide a definition of STDERR_FILENO.
7875 const int kStdOutFileno = 1;
7876 const int kStdErrFileno = 2;
7878 const int kStdOutFileno = STDOUT_FILENO;
7879 const int kStdErrFileno = STDERR_FILENO;
7884 // Returns the number of threads running in the process, or 0 to indicate that
7885 // we cannot detect it.
7886 size_t GetThreadCount() {
7887 const task_t task = mach_task_self();
7888 mach_msg_type_number_t thread_count;
7889 thread_act_array_t thread_list;
7890 const kern_return_t status = task_threads(task, &thread_list, &thread_count);
7891 if (status == KERN_SUCCESS) {
7892 // task_threads allocates resources in thread_list and we need to free them
7895 reinterpret_cast<vm_address_t>(thread_list),
7896 sizeof(thread_t) * thread_count);
7897 return static_cast<size_t>(thread_count);
7905 size_t GetThreadCount() {
7906 // There's no portable way to detect the number of threads, so we just
7907 // return 0 to indicate that we cannot detect it.
7911 #endif // GTEST_OS_MAC
7913 #if GTEST_USES_POSIX_RE
7915 // Implements RE. Currently only needed for death tests.
7919 // regfree'ing an invalid regex might crash because the content
7920 // of the regex is undefined. Since the regex's are essentially
7921 // the same, one cannot be valid (or invalid) without the other
7923 regfree(&partial_regex_);
7924 regfree(&full_regex_);
7926 free(const_cast<char*>(pattern_));
7929 // Returns true iff regular expression re matches the entire str.
7930 bool RE::FullMatch(const char* str, const RE& re) {
7931 if (!re.is_valid_) return false;
7934 return regexec(&re.full_regex_, str, 1, &match, 0) == 0;
7937 // Returns true iff regular expression re matches a substring of str
7938 // (including str itself).
7939 bool RE::PartialMatch(const char* str, const RE& re) {
7940 if (!re.is_valid_) return false;
7943 return regexec(&re.partial_regex_, str, 1, &match, 0) == 0;
7946 // Initializes an RE from its string representation.
7947 void RE::Init(const char* regex) {
7948 pattern_ = posix::StrDup(regex);
7950 // Reserves enough bytes to hold the regular expression used for a
7952 const size_t full_regex_len = strlen(regex) + 10;
7953 char* const full_pattern = new char[full_regex_len];
7955 snprintf(full_pattern, full_regex_len, "^(%s)$", regex);
7956 is_valid_ = regcomp(&full_regex_, full_pattern, REG_EXTENDED) == 0;
7957 // We want to call regcomp(&partial_regex_, ...) even if the
7958 // previous expression returns false. Otherwise partial_regex_ may
7959 // not be properly initialized can may cause trouble when it's
7962 // Some implementation of POSIX regex (e.g. on at least some
7963 // versions of Cygwin) doesn't accept the empty string as a valid
7964 // regex. We change it to an equivalent form "()" to be safe.
7966 const char* const partial_regex = (*regex == '\0') ? "()" : regex;
7967 is_valid_ = regcomp(&partial_regex_, partial_regex, REG_EXTENDED) == 0;
7969 EXPECT_TRUE(is_valid_)
7970 << "Regular expression \"" << regex
7971 << "\" is not a valid POSIX Extended regular expression.";
7973 delete[] full_pattern;
7976 #elif GTEST_USES_SIMPLE_RE
7978 // Returns true iff ch appears anywhere in str (excluding the
7979 // terminating '\0' character).
7980 bool IsInSet(char ch, const char* str) {
7981 return ch != '\0' && strchr(str, ch) != NULL;
7984 // Returns true iff ch belongs to the given classification. Unlike
7985 // similar functions in <ctype.h>, these aren't affected by the
7987 bool IsAsciiDigit(char ch) { return '0' <= ch && ch <= '9'; }
7988 bool IsAsciiPunct(char ch) {
7989 return IsInSet(ch, "^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~");
7991 bool IsRepeat(char ch) { return IsInSet(ch, "?*+"); }
7992 bool IsAsciiWhiteSpace(char ch) { return IsInSet(ch, " \f\n\r\t\v"); }
7993 bool IsAsciiWordChar(char ch) {
7994 return ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') ||
7995 ('0' <= ch && ch <= '9') || ch == '_';
7998 // Returns true iff "\\c" is a supported escape sequence.
7999 bool IsValidEscape(char c) {
8000 return (IsAsciiPunct(c) || IsInSet(c, "dDfnrsStvwW"));
8003 // Returns true iff the given atom (specified by escaped and pattern)
8004 // matches ch. The result is undefined if the atom is invalid.
8005 bool AtomMatchesChar(bool escaped, char pattern_char, char ch) {
8006 if (escaped) { // "\\p" where p is pattern_char.
8007 switch (pattern_char) {
8008 case 'd': return IsAsciiDigit(ch);
8009 case 'D': return !IsAsciiDigit(ch);
8010 case 'f': return ch == '\f';
8011 case 'n': return ch == '\n';
8012 case 'r': return ch == '\r';
8013 case 's': return IsAsciiWhiteSpace(ch);
8014 case 'S': return !IsAsciiWhiteSpace(ch);
8015 case 't': return ch == '\t';
8016 case 'v': return ch == '\v';
8017 case 'w': return IsAsciiWordChar(ch);
8018 case 'W': return !IsAsciiWordChar(ch);
8020 return IsAsciiPunct(pattern_char) && pattern_char == ch;
8023 return (pattern_char == '.' && ch != '\n') || pattern_char == ch;
8026 // Helper function used by ValidateRegex() to format error messages.
8027 String FormatRegexSyntaxError(const char* regex, int index) {
8028 return (Message() << "Syntax error at index " << index
8029 << " in simple regular expression \"" << regex << "\": ").GetString();
8032 // Generates non-fatal failures and returns false if regex is invalid;
8033 // otherwise returns true.
8034 bool ValidateRegex(const char* regex) {
8035 if (regex == NULL) {
8036 // TODO(wan@google.com): fix the source file location in the
8037 // assertion failures to match where the regex is used in user
8039 ADD_FAILURE() << "NULL is not a valid simple regular expression.";
8043 bool is_valid = true;
8045 // True iff ?, *, or + can follow the previous atom.
8046 bool prev_repeatable = false;
8047 for (int i = 0; regex[i]; i++) {
8048 if (regex[i] == '\\') { // An escape sequence
8050 if (regex[i] == '\0') {
8051 ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
8052 << "'\\' cannot appear at the end.";
8056 if (!IsValidEscape(regex[i])) {
8057 ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
8058 << "invalid escape sequence \"\\" << regex[i] << "\".";
8061 prev_repeatable = true;
8062 } else { // Not an escape sequence.
8063 const char ch = regex[i];
8065 if (ch == '^' && i > 0) {
8066 ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
8067 << "'^' can only appear at the beginning.";
8069 } else if (ch == '$' && regex[i + 1] != '\0') {
8070 ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
8071 << "'$' can only appear at the end.";
8073 } else if (IsInSet(ch, "()[]{}|")) {
8074 ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
8075 << "'" << ch << "' is unsupported.";
8077 } else if (IsRepeat(ch) && !prev_repeatable) {
8078 ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
8079 << "'" << ch << "' can only follow a repeatable token.";
8083 prev_repeatable = !IsInSet(ch, "^$?*+");
8090 // Matches a repeated regex atom followed by a valid simple regular
8091 // expression. The regex atom is defined as c if escaped is false,
8092 // or \c otherwise. repeat is the repetition meta character (?, *,
8093 // or +). The behavior is undefined if str contains too many
8094 // characters to be indexable by size_t, in which case the test will
8095 // probably time out anyway. We are fine with this limitation as
8096 // std::string has it too.
8097 bool MatchRepetitionAndRegexAtHead(
8098 bool escaped, char c, char repeat, const char* regex,
8100 const size_t min_count = (repeat == '+') ? 1 : 0;
8101 const size_t max_count = (repeat == '?') ? 1 :
8102 static_cast<size_t>(-1) - 1;
8103 // We cannot call numeric_limits::max() as it conflicts with the
8104 // max() macro on Windows.
8106 for (size_t i = 0; i <= max_count; ++i) {
8107 // We know that the atom matches each of the first i characters in str.
8108 if (i >= min_count && MatchRegexAtHead(regex, str + i)) {
8109 // We have enough matches at the head, and the tail matches too.
8110 // Since we only care about *whether* the pattern matches str
8111 // (as opposed to *how* it matches), there is no need to find a
8115 if (str[i] == '\0' || !AtomMatchesChar(escaped, c, str[i]))
8121 // Returns true iff regex matches a prefix of str. regex must be a
8122 // valid simple regular expression and not start with "^", or the
8123 // result is undefined.
8124 bool MatchRegexAtHead(const char* regex, const char* str) {
8125 if (*regex == '\0') // An empty regex matches a prefix of anything.
8128 // "$" only matches the end of a string. Note that regex being
8129 // valid guarantees that there's nothing after "$" in it.
8131 return *str == '\0';
8133 // Is the first thing in regex an escape sequence?
8134 const bool escaped = *regex == '\\';
8137 if (IsRepeat(regex[1])) {
8138 // MatchRepetitionAndRegexAtHead() calls MatchRegexAtHead(), so
8139 // here's an indirect recursion. It terminates as the regex gets
8140 // shorter in each recursion.
8141 return MatchRepetitionAndRegexAtHead(
8142 escaped, regex[0], regex[1], regex + 2, str);
8144 // regex isn't empty, isn't "$", and doesn't start with a
8145 // repetition. We match the first atom of regex with the first
8146 // character of str and recurse.
8147 return (*str != '\0') && AtomMatchesChar(escaped, *regex, *str) &&
8148 MatchRegexAtHead(regex + 1, str + 1);
8152 // Returns true iff regex matches any substring of str. regex must be
8153 // a valid simple regular expression, or the result is undefined.
8155 // The algorithm is recursive, but the recursion depth doesn't exceed
8156 // the regex length, so we won't need to worry about running out of
8157 // stack space normally. In rare cases the time complexity can be
8158 // exponential with respect to the regex length + the string length,
8159 // but usually it's must faster (often close to linear).
8160 bool MatchRegexAnywhere(const char* regex, const char* str) {
8161 if (regex == NULL || str == NULL)
8165 return MatchRegexAtHead(regex + 1, str);
8167 // A successful match can be anywhere in str.
8169 if (MatchRegexAtHead(regex, str))
8171 } while (*str++ != '\0');
8175 // Implements the RE class.
8178 free(const_cast<char*>(pattern_));
8179 free(const_cast<char*>(full_pattern_));
8182 // Returns true iff regular expression re matches the entire str.
8183 bool RE::FullMatch(const char* str, const RE& re) {
8184 return re.is_valid_ && MatchRegexAnywhere(re.full_pattern_, str);
8187 // Returns true iff regular expression re matches a substring of str
8188 // (including str itself).
8189 bool RE::PartialMatch(const char* str, const RE& re) {
8190 return re.is_valid_ && MatchRegexAnywhere(re.pattern_, str);
8193 // Initializes an RE from its string representation.
8194 void RE::Init(const char* regex) {
8195 pattern_ = full_pattern_ = NULL;
8196 if (regex != NULL) {
8197 pattern_ = posix::StrDup(regex);
8200 is_valid_ = ValidateRegex(regex);
8202 // No need to calculate the full pattern when the regex is invalid.
8206 const size_t len = strlen(regex);
8207 // Reserves enough bytes to hold the regular expression used for a
8208 // full match: we need space to prepend a '^', append a '$', and
8209 // terminate the string with '\0'.
8210 char* buffer = static_cast<char*>(malloc(len + 3));
8211 full_pattern_ = buffer;
8214 *buffer++ = '^'; // Makes sure full_pattern_ starts with '^'.
8216 // We don't use snprintf or strncpy, as they trigger a warning when
8217 // compiled with VC++ 8.0.
8218 memcpy(buffer, regex, len);
8221 if (len == 0 || regex[len - 1] != '$')
8222 *buffer++ = '$'; // Makes sure full_pattern_ ends with '$'.
8227 #endif // GTEST_USES_POSIX_RE
8229 const char kUnknownFile[] = "unknown file";
8231 // Formats a source file path and a line number as they would appear
8232 // in an error message from the compiler used to compile this code.
8233 GTEST_API_ ::std::string FormatFileLocation(const char* file, int line) {
8234 const char* const file_name = file == NULL ? kUnknownFile : file;
8237 return String::Format("%s:", file_name).c_str();
8240 return String::Format("%s(%d):", file_name, line).c_str();
8242 return String::Format("%s:%d:", file_name, line).c_str();
8246 // Formats a file location for compiler-independent XML output.
8247 // Although this function is not platform dependent, we put it next to
8248 // FormatFileLocation in order to contrast the two functions.
8249 // Note that FormatCompilerIndependentFileLocation() does NOT append colon
8250 // to the file location it produces, unlike FormatFileLocation().
8251 GTEST_API_ ::std::string FormatCompilerIndependentFileLocation(
8252 const char* file, int line) {
8253 const char* const file_name = file == NULL ? kUnknownFile : file;
8258 return String::Format("%s:%d", file_name, line).c_str();
8262 GTestLog::GTestLog(GTestLogSeverity severity, const char* file, int line)
8263 : severity_(severity) {
8264 const char* const marker =
8265 severity == GTEST_INFO ? "[ INFO ]" :
8266 severity == GTEST_WARNING ? "[WARNING]" :
8267 severity == GTEST_ERROR ? "[ ERROR ]" : "[ FATAL ]";
8268 GetStream() << ::std::endl << marker << " "
8269 << FormatFileLocation(file, line).c_str() << ": ";
8272 // Flushes the buffers and, if severity is GTEST_FATAL, aborts the program.
8273 GTestLog::~GTestLog() {
8274 GetStream() << ::std::endl;
8275 if (severity_ == GTEST_FATAL) {
8280 // Disable Microsoft deprecation warnings for POSIX functions called from
8281 // this class (creat, dup, dup2, and close)
8283 # pragma warning(push)
8284 # pragma warning(disable: 4996)
8287 #if GTEST_HAS_STREAM_REDIRECTION
8289 // Object that captures an output stream (stdout/stderr).
8290 class CapturedStream {
8292 // The ctor redirects the stream to a temporary file.
8293 CapturedStream(int fd) : fd_(fd), uncaptured_fd_(dup(fd)) {
8295 # if GTEST_OS_WINDOWS
8296 char temp_dir_path[MAX_PATH + 1] = { '\0' }; // NOLINT
8297 char temp_file_path[MAX_PATH + 1] = { '\0' }; // NOLINT
8299 ::GetTempPathA(sizeof(temp_dir_path), temp_dir_path);
8300 const UINT success = ::GetTempFileNameA(temp_dir_path,
8302 0, // Generate unique file name.
8304 GTEST_CHECK_(success != 0)
8305 << "Unable to create a temporary file in " << temp_dir_path;
8306 const int captured_fd = creat(temp_file_path, _S_IREAD | _S_IWRITE);
8307 GTEST_CHECK_(captured_fd != -1) << "Unable to open temporary file "
8309 filename_ = temp_file_path;
8311 // There's no guarantee that a test has write access to the
8312 // current directory, so we create the temporary file in the /tmp
8313 // directory instead.
8314 char name_template[] = "/tmp/captured_stream.XXXXXX";
8315 const int captured_fd = mkstemp(name_template);
8316 filename_ = name_template;
8317 # endif // GTEST_OS_WINDOWS
8319 dup2(captured_fd, fd_);
8324 remove(filename_.c_str());
8327 String GetCapturedString() {
8328 if (uncaptured_fd_ != -1) {
8329 // Restores the original stream.
8331 dup2(uncaptured_fd_, fd_);
8332 close(uncaptured_fd_);
8333 uncaptured_fd_ = -1;
8336 FILE* const file = posix::FOpen(filename_.c_str(), "r");
8337 const String content = ReadEntireFile(file);
8338 posix::FClose(file);
8343 // Reads the entire content of a file as a String.
8344 static String ReadEntireFile(FILE* file);
8346 // Returns the size (in bytes) of a file.
8347 static size_t GetFileSize(FILE* file);
8349 const int fd_; // A stream to capture.
8351 // Name of the temporary file holding the stderr output.
8352 ::std::string filename_;
8354 GTEST_DISALLOW_COPY_AND_ASSIGN_(CapturedStream);
8357 // Returns the size (in bytes) of a file.
8358 size_t CapturedStream::GetFileSize(FILE* file) {
8359 fseek(file, 0, SEEK_END);
8360 return static_cast<size_t>(ftell(file));
8363 // Reads the entire content of a file as a string.
8364 String CapturedStream::ReadEntireFile(FILE* file) {
8365 const size_t file_size = GetFileSize(file);
8366 char* const buffer = new char[file_size];
8368 size_t bytes_last_read = 0; // # of bytes read in the last fread()
8369 size_t bytes_read = 0; // # of bytes read so far
8371 fseek(file, 0, SEEK_SET);
8373 // Keeps reading the file until we cannot read further or the
8374 // pre-determined file size is reached.
8376 bytes_last_read = fread(buffer+bytes_read, 1, file_size-bytes_read, file);
8377 bytes_read += bytes_last_read;
8378 } while (bytes_last_read > 0 && bytes_read < file_size);
8380 const String content(buffer, bytes_read);
8387 # pragma warning(pop)
8390 static CapturedStream* g_captured_stderr = NULL;
8391 static CapturedStream* g_captured_stdout = NULL;
8393 // Starts capturing an output stream (stdout/stderr).
8394 void CaptureStream(int fd, const char* stream_name, CapturedStream** stream) {
8395 if (*stream != NULL) {
8396 GTEST_LOG_(FATAL) << "Only one " << stream_name
8397 << " capturer can exist at a time.";
8399 *stream = new CapturedStream(fd);
8402 // Stops capturing the output stream and returns the captured string.
8403 String GetCapturedStream(CapturedStream** captured_stream) {
8404 const String content = (*captured_stream)->GetCapturedString();
8406 delete *captured_stream;
8407 *captured_stream = NULL;
8412 // Starts capturing stdout.
8413 void CaptureStdout() {
8414 CaptureStream(kStdOutFileno, "stdout", &g_captured_stdout);
8417 // Starts capturing stderr.
8418 void CaptureStderr() {
8419 CaptureStream(kStdErrFileno, "stderr", &g_captured_stderr);
8422 // Stops capturing stdout and returns the captured string.
8423 String GetCapturedStdout() { return GetCapturedStream(&g_captured_stdout); }
8425 // Stops capturing stderr and returns the captured string.
8426 String GetCapturedStderr() { return GetCapturedStream(&g_captured_stderr); }
8428 #endif // GTEST_HAS_STREAM_REDIRECTION
8430 #if GTEST_HAS_DEATH_TEST
8432 // A copy of all command line arguments. Set by InitGoogleTest().
8433 ::std::vector<String> g_argvs;
8435 // Returns the command line as a vector of strings.
8436 const ::std::vector<String>& GetArgvs() { return g_argvs; }
8438 #endif // GTEST_HAS_DEATH_TEST
8440 #if GTEST_OS_WINDOWS_MOBILE
8444 TerminateProcess(GetCurrentProcess(), 1);
8446 } // namespace posix
8447 #endif // GTEST_OS_WINDOWS_MOBILE
8449 // Returns the name of the environment variable corresponding to the
8450 // given flag. For example, FlagToEnvVar("foo") will return
8451 // "GTEST_FOO" in the open-source version.
8452 static String FlagToEnvVar(const char* flag) {
8453 const String full_flag =
8454 (Message() << GTEST_FLAG_PREFIX_ << flag).GetString();
8457 for (size_t i = 0; i != full_flag.length(); i++) {
8458 env_var << ToUpper(full_flag.c_str()[i]);
8461 return env_var.GetString();
8464 // Parses 'str' for a 32-bit signed integer. If successful, writes
8465 // the result to *value and returns true; otherwise leaves *value
8466 // unchanged and returns false.
8467 bool ParseInt32(const Message& src_text, const char* str, Int32* value) {
8468 // Parses the environment variable as a decimal integer.
8470 const long long_value = strtol(str, &end, 10); // NOLINT
8472 // Has strtol() consumed all characters in the string?
8474 // No - an invalid character was encountered.
8476 msg << "WARNING: " << src_text
8477 << " is expected to be a 32-bit integer, but actually"
8478 << " has value \"" << str << "\".\n";
8479 printf("%s", msg.GetString().c_str());
8484 // Is the parsed value in the range of an Int32?
8485 const Int32 result = static_cast<Int32>(long_value);
8486 if (long_value == LONG_MAX || long_value == LONG_MIN ||
8487 // The parsed value overflows as a long. (strtol() returns
8488 // LONG_MAX or LONG_MIN when the input overflows.)
8489 result != long_value
8490 // The parsed value overflows as an Int32.
8493 msg << "WARNING: " << src_text
8494 << " is expected to be a 32-bit integer, but actually"
8495 << " has value " << str << ", which overflows.\n";
8496 printf("%s", msg.GetString().c_str());
8505 // Reads and returns the Boolean environment variable corresponding to
8506 // the given flag; if it's not set, returns default_value.
8508 // The value is considered true iff it's not "0".
8509 bool BoolFromGTestEnv(const char* flag, bool default_value) {
8510 const String env_var = FlagToEnvVar(flag);
8511 const char* const string_value = posix::GetEnv(env_var.c_str());
8512 return string_value == NULL ?
8513 default_value : strcmp(string_value, "0") != 0;
8516 // Reads and returns a 32-bit integer stored in the environment
8517 // variable corresponding to the given flag; if it isn't set or
8518 // doesn't represent a valid 32-bit integer, returns default_value.
8519 Int32 Int32FromGTestEnv(const char* flag, Int32 default_value) {
8520 const String env_var = FlagToEnvVar(flag);
8521 const char* const string_value = posix::GetEnv(env_var.c_str());
8522 if (string_value == NULL) {
8523 // The environment variable is not set.
8524 return default_value;
8527 Int32 result = default_value;
8528 if (!ParseInt32(Message() << "Environment variable " << env_var,
8529 string_value, &result)) {
8530 printf("The default value %s is used.\n",
8531 (Message() << default_value).GetString().c_str());
8533 return default_value;
8539 // Reads and returns the string environment variable corresponding to
8540 // the given flag; if it's not set, returns default_value.
8541 const char* StringFromGTestEnv(const char* flag, const char* default_value) {
8542 const String env_var = FlagToEnvVar(flag);
8543 const char* const value = posix::GetEnv(env_var.c_str());
8544 return value == NULL ? default_value : value;
8547 } // namespace internal
8548 } // namespace testing
8549 // Copyright 2007, Google Inc.
8550 // All rights reserved.
8552 // Redistribution and use in source and binary forms, with or without
8553 // modification, are permitted provided that the following conditions are
8556 // * Redistributions of source code must retain the above copyright
8557 // notice, this list of conditions and the following disclaimer.
8558 // * Redistributions in binary form must reproduce the above
8559 // copyright notice, this list of conditions and the following disclaimer
8560 // in the documentation and/or other materials provided with the
8562 // * Neither the name of Google Inc. nor the names of its
8563 // contributors may be used to endorse or promote products derived from
8564 // this software without specific prior written permission.
8566 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
8567 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
8568 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
8569 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
8570 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
8571 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
8572 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
8573 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
8574 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
8575 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
8576 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
8578 // Author: wan@google.com (Zhanyong Wan)
8580 // Google Test - The Google C++ Testing Framework
8582 // This file implements a universal value printer that can print a
8583 // value of any type T:
8585 // void ::testing::internal::UniversalPrinter<T>::Print(value, ostream_ptr);
8587 // It uses the << operator when possible, and prints the bytes in the
8588 // object otherwise. A user can override its behavior for a class
8589 // type Foo by defining either operator<<(::std::ostream&, const Foo&)
8590 // or void PrintTo(const Foo&, ::std::ostream*) in the namespace that
8595 #include <ostream> // NOLINT
8602 using ::std::ostream;
8604 #if GTEST_OS_WINDOWS_MOBILE // Windows CE does not define _snprintf_s.
8605 # define snprintf _snprintf
8606 #elif _MSC_VER >= 1400 // VC 8.0 and later deprecate snprintf and _snprintf.
8607 # define snprintf _snprintf_s
8609 # define snprintf _snprintf
8610 #endif // GTEST_OS_WINDOWS_MOBILE
8612 // Prints a segment of bytes in the given object.
8613 void PrintByteSegmentInObjectTo(const unsigned char* obj_bytes, size_t start,
8614 size_t count, ostream* os) {
8616 for (size_t i = 0; i != count; i++) {
8617 const size_t j = start + i;
8619 // Organizes the bytes into groups of 2 for easy parsing by
8626 snprintf(text, sizeof(text), "%02X", obj_bytes[j]);
8631 // Prints the bytes in the given value to the given ostream.
8632 void PrintBytesInObjectToImpl(const unsigned char* obj_bytes, size_t count,
8634 // Tells the user how big the object is.
8635 *os << count << "-byte object <";
8637 const size_t kThreshold = 132;
8638 const size_t kChunkSize = 64;
8639 // If the object size is bigger than kThreshold, we'll have to omit
8640 // some details by printing only the first and the last kChunkSize
8642 // TODO(wan): let the user control the threshold using a flag.
8643 if (count < kThreshold) {
8644 PrintByteSegmentInObjectTo(obj_bytes, 0, count, os);
8646 PrintByteSegmentInObjectTo(obj_bytes, 0, kChunkSize, os);
8648 // Rounds up to 2-byte boundary.
8649 const size_t resume_pos = (count - kChunkSize + 1)/2*2;
8650 PrintByteSegmentInObjectTo(obj_bytes, resume_pos, count - resume_pos, os);
8657 namespace internal2 {
8659 // Delegates to PrintBytesInObjectToImpl() to print the bytes in the
8660 // given object. The delegation simplifies the implementation, which
8661 // uses the << operator and thus is easier done outside of the
8662 // ::testing::internal namespace, which contains a << operator that
8663 // sometimes conflicts with the one in STL.
8664 void PrintBytesInObjectTo(const unsigned char* obj_bytes, size_t count,
8666 PrintBytesInObjectToImpl(obj_bytes, count, os);
8669 } // namespace internal2
8671 namespace internal {
8673 // Depending on the value of a char (or wchar_t), we print it in one
8674 // of three formats:
8675 // - as is if it's a printable ASCII (e.g. 'a', '2', ' '),
8676 // - as a hexidecimal escape sequence (e.g. '\x7F'), or
8677 // - as a special escape sequence (e.g. '\r', '\n').
8684 // Returns true if c is a printable ASCII character. We test the
8685 // value of c directly instead of calling isprint(), which is buggy on
8687 inline bool IsPrintableAscii(wchar_t c) {
8688 return 0x20 <= c && c <= 0x7E;
8691 // Prints a wide or narrow char c as a character literal without the
8692 // quotes, escaping it when necessary; returns how c was formatted.
8693 // The template argument UnsignedChar is the unsigned version of Char,
8694 // which is the type of c.
8695 template <typename UnsignedChar, typename Char>
8696 static CharFormat PrintAsCharLiteralTo(Char c, ostream* os) {
8697 switch (static_cast<wchar_t>(c)) {
8729 if (IsPrintableAscii(c)) {
8730 *os << static_cast<char>(c);
8733 *os << String::Format("\\x%X", static_cast<UnsignedChar>(c));
8737 return kSpecialEscape;
8740 // Prints a char c as if it's part of a string literal, escaping it when
8741 // necessary; returns how c was formatted.
8742 static CharFormat PrintAsWideStringLiteralTo(wchar_t c, ostream* os) {
8749 return kSpecialEscape;
8751 return PrintAsCharLiteralTo<wchar_t>(c, os);
8755 // Prints a char c as if it's part of a string literal, escaping it when
8756 // necessary; returns how c was formatted.
8757 static CharFormat PrintAsNarrowStringLiteralTo(char c, ostream* os) {
8758 return PrintAsWideStringLiteralTo(static_cast<unsigned char>(c), os);
8761 // Prints a wide or narrow character c and its code. '\0' is printed
8762 // as "'\\0'", other unprintable characters are also properly escaped
8763 // using the standard C++ escape sequence. The template argument
8764 // UnsignedChar is the unsigned version of Char, which is the type of c.
8765 template <typename UnsignedChar, typename Char>
8766 void PrintCharAndCodeTo(Char c, ostream* os) {
8767 // First, print c as a literal in the most readable form we can find.
8768 *os << ((sizeof(c) > 1) ? "L'" : "'");
8769 const CharFormat format = PrintAsCharLiteralTo<UnsignedChar>(c, os);
8772 // To aid user debugging, we also print c's code in decimal, unless
8773 // it's 0 (in which case c was printed as '\\0', making the code
8777 *os << " (" << String::Format("%d", c).c_str();
8779 // For more convenience, we print c's code again in hexidecimal,
8780 // unless c was already printed in the form '\x##' or the code is in
8782 if (format == kHexEscape || (1 <= c && c <= 9)) {
8785 *os << String::Format(", 0x%X",
8786 static_cast<UnsignedChar>(c)).c_str();
8791 void PrintTo(unsigned char c, ::std::ostream* os) {
8792 PrintCharAndCodeTo<unsigned char>(c, os);
8794 void PrintTo(signed char c, ::std::ostream* os) {
8795 PrintCharAndCodeTo<unsigned char>(c, os);
8798 // Prints a wchar_t as a symbol if it is printable or as its internal
8799 // code otherwise and also as its code. L'\0' is printed as "L'\\0'".
8800 void PrintTo(wchar_t wc, ostream* os) {
8801 PrintCharAndCodeTo<wchar_t>(wc, os);
8804 // Prints the given array of characters to the ostream.
8805 // The array starts at *begin, the length is len, it may include '\0' characters
8806 // and may not be null-terminated.
8807 static void PrintCharsAsStringTo(const char* begin, size_t len, ostream* os) {
8809 bool is_previous_hex = false;
8810 for (size_t index = 0; index < len; ++index) {
8811 const char cur = begin[index];
8812 if (is_previous_hex && IsXDigit(cur)) {
8813 // Previous character is of '\x..' form and this character can be
8814 // interpreted as another hexadecimal digit in its number. Break string to
8818 is_previous_hex = PrintAsNarrowStringLiteralTo(cur, os) == kHexEscape;
8823 // Prints a (const) char array of 'len' elements, starting at address 'begin'.
8824 void UniversalPrintArray(const char* begin, size_t len, ostream* os) {
8825 PrintCharsAsStringTo(begin, len, os);
8828 // Prints the given array of wide characters to the ostream.
8829 // The array starts at *begin, the length is len, it may include L'\0'
8830 // characters and may not be null-terminated.
8831 static void PrintWideCharsAsStringTo(const wchar_t* begin, size_t len,
8834 bool is_previous_hex = false;
8835 for (size_t index = 0; index < len; ++index) {
8836 const wchar_t cur = begin[index];
8837 if (is_previous_hex && isascii(cur) && IsXDigit(static_cast<char>(cur))) {
8838 // Previous character is of '\x..' form and this character can be
8839 // interpreted as another hexadecimal digit in its number. Break string to
8843 is_previous_hex = PrintAsWideStringLiteralTo(cur, os) == kHexEscape;
8848 // Prints the given C string to the ostream.
8849 void PrintTo(const char* s, ostream* os) {
8853 *os << ImplicitCast_<const void*>(s) << " pointing to ";
8854 PrintCharsAsStringTo(s, strlen(s), os);
8858 // MSVC compiler can be configured to define whar_t as a typedef
8859 // of unsigned short. Defining an overload for const wchar_t* in that case
8860 // would cause pointers to unsigned shorts be printed as wide strings,
8861 // possibly accessing more memory than intended and causing invalid
8862 // memory accesses. MSVC defines _NATIVE_WCHAR_T_DEFINED symbol when
8863 // wchar_t is implemented as a native type.
8864 #if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED)
8865 // Prints the given wide C string to the ostream.
8866 void PrintTo(const wchar_t* s, ostream* os) {
8870 *os << ImplicitCast_<const void*>(s) << " pointing to ";
8871 PrintWideCharsAsStringTo(s, wcslen(s), os);
8874 #endif // wchar_t is native
8876 // Prints a ::string object.
8877 #if GTEST_HAS_GLOBAL_STRING
8878 void PrintStringTo(const ::string& s, ostream* os) {
8879 PrintCharsAsStringTo(s.data(), s.size(), os);
8881 #endif // GTEST_HAS_GLOBAL_STRING
8883 void PrintStringTo(const ::std::string& s, ostream* os) {
8884 PrintCharsAsStringTo(s.data(), s.size(), os);
8887 // Prints a ::wstring object.
8888 #if GTEST_HAS_GLOBAL_WSTRING
8889 void PrintWideStringTo(const ::wstring& s, ostream* os) {
8890 PrintWideCharsAsStringTo(s.data(), s.size(), os);
8892 #endif // GTEST_HAS_GLOBAL_WSTRING
8894 #if GTEST_HAS_STD_WSTRING
8895 void PrintWideStringTo(const ::std::wstring& s, ostream* os) {
8896 PrintWideCharsAsStringTo(s.data(), s.size(), os);
8898 #endif // GTEST_HAS_STD_WSTRING
8900 } // namespace internal
8902 } // namespace testing
8903 // Copyright 2008, Google Inc.
8904 // All rights reserved.
8906 // Redistribution and use in source and binary forms, with or without
8907 // modification, are permitted provided that the following conditions are
8910 // * Redistributions of source code must retain the above copyright
8911 // notice, this list of conditions and the following disclaimer.
8912 // * Redistributions in binary form must reproduce the above
8913 // copyright notice, this list of conditions and the following disclaimer
8914 // in the documentation and/or other materials provided with the
8916 // * Neither the name of Google Inc. nor the names of its
8917 // contributors may be used to endorse or promote products derived from
8918 // this software without specific prior written permission.
8920 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
8921 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
8922 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
8923 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
8924 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
8925 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
8926 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
8927 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
8928 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
8929 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
8930 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
8932 // Author: mheule@google.com (Markus Heule)
8934 // The Google C++ Testing Framework (Google Test)
8937 // Indicates that this translation unit is part of Google Test's
8938 // implementation. It must come before gtest-internal-inl.h is
8939 // included, or there will be a compiler error. This trick is to
8940 // prevent a user from accidentally including gtest-internal-inl.h in
8942 #define GTEST_IMPLEMENTATION_ 1
8943 #undef GTEST_IMPLEMENTATION_
8947 using internal::GetUnitTestImpl;
8949 // Gets the summary of the failure message by omitting the stack trace
8951 internal::String TestPartResult::ExtractSummary(const char* message) {
8952 const char* const stack_trace = strstr(message, internal::kStackTraceMarker);
8953 return stack_trace == NULL ? internal::String(message) :
8954 internal::String(message, stack_trace - message);
8957 // Prints a TestPartResult object.
8958 std::ostream& operator<<(std::ostream& os, const TestPartResult& result) {
8960 << result.file_name() << ":" << result.line_number() << ": "
8961 << (result.type() == TestPartResult::kSuccess ? "Success" :
8962 result.type() == TestPartResult::kFatalFailure ? "Fatal failure" :
8963 "Non-fatal failure") << ":\n"
8964 << result.message() << std::endl;
8967 // Appends a TestPartResult to the array.
8968 void TestPartResultArray::Append(const TestPartResult& result) {
8969 array_.push_back(result);
8972 // Returns the TestPartResult at the given index (0-based).
8973 const TestPartResult& TestPartResultArray::GetTestPartResult(int index) const {
8974 if (index < 0 || index >= size()) {
8975 printf("\nInvalid index (%d) into TestPartResultArray.\n", index);
8976 internal::posix::Abort();
8979 return array_[index];
8982 // Returns the number of TestPartResult objects in the array.
8983 int TestPartResultArray::size() const {
8984 return static_cast<int>(array_.size());
8987 namespace internal {
8989 HasNewFatalFailureHelper::HasNewFatalFailureHelper()
8990 : has_new_fatal_failure_(false),
8991 original_reporter_(GetUnitTestImpl()->
8992 GetTestPartResultReporterForCurrentThread()) {
8993 GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(this);
8996 HasNewFatalFailureHelper::~HasNewFatalFailureHelper() {
8997 GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(
8998 original_reporter_);
9001 void HasNewFatalFailureHelper::ReportTestPartResult(
9002 const TestPartResult& result) {
9003 if (result.fatally_failed())
9004 has_new_fatal_failure_ = true;
9005 original_reporter_->ReportTestPartResult(result);
9008 } // namespace internal
9010 } // namespace testing
9011 // Copyright 2008 Google Inc.
9012 // All Rights Reserved.
9014 // Redistribution and use in source and binary forms, with or without
9015 // modification, are permitted provided that the following conditions are
9018 // * Redistributions of source code must retain the above copyright
9019 // notice, this list of conditions and the following disclaimer.
9020 // * Redistributions in binary form must reproduce the above
9021 // copyright notice, this list of conditions and the following disclaimer
9022 // in the documentation and/or other materials provided with the
9024 // * Neither the name of Google Inc. nor the names of its
9025 // contributors may be used to endorse or promote products derived from
9026 // this software without specific prior written permission.
9028 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
9029 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
9030 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
9031 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9032 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
9033 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9034 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
9035 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
9036 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
9037 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
9038 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
9040 // Author: wan@google.com (Zhanyong Wan)
9044 namespace internal {
9046 #if GTEST_HAS_TYPED_TEST_P
9048 // Skips to the first non-space char in str. Returns an empty string if str
9049 // contains only whitespace characters.
9050 static const char* SkipSpaces(const char* str) {
9051 while (IsSpace(*str))
9056 // Verifies that registered_tests match the test names in
9057 // defined_test_names_; returns registered_tests if successful, or
9058 // aborts the program otherwise.
9059 const char* TypedTestCasePState::VerifyRegisteredTestNames(
9060 const char* file, int line, const char* registered_tests) {
9061 typedef ::std::set<const char*>::const_iterator DefinedTestIter;
9064 // Skip initial whitespace in registered_tests since some
9065 // preprocessors prefix stringizied literals with whitespace.
9066 registered_tests = SkipSpaces(registered_tests);
9069 ::std::set<String> tests;
9070 for (const char* names = registered_tests; names != NULL;
9071 names = SkipComma(names)) {
9072 const String name = GetPrefixUntilComma(names);
9073 if (tests.count(name) != 0) {
9074 errors << "Test " << name << " is listed more than once.\n";
9079 for (DefinedTestIter it = defined_test_names_.begin();
9080 it != defined_test_names_.end();
9091 errors << "No test named " << name
9092 << " can be found in this test case.\n";
9096 for (DefinedTestIter it = defined_test_names_.begin();
9097 it != defined_test_names_.end();
9099 if (tests.count(*it) == 0) {
9100 errors << "You forgot to list test " << *it << ".\n";
9104 const String& errors_str = errors.GetString();
9105 if (errors_str != "") {
9106 fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(),
9107 errors_str.c_str());
9112 return registered_tests;
9115 #endif // GTEST_HAS_TYPED_TEST_P
9117 } // namespace internal
9118 } // namespace testing