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 "precomp.hpp"
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,
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_
322 // TODO(kenton@google.com): Use autoconf to detect availability of
324 #define GTEST_HAS_GETTIMEOFDAY_ 1
329 // Declares vsnprintf(). This header is not available on Windows.
331 #include <sys/mman.h>
332 #include <sys/time.h>
337 #elif GTEST_OS_SYMBIAN
338 #define GTEST_HAS_GETTIMEOFDAY_ 1
339 #include <sys/time.h> // NOLINT
342 #define GTEST_HAS_GETTIMEOFDAY_ 1
343 #include <sys/time.h> // NOLINT
345 // On z/OS we additionally need strings.h for strcasecmp.
346 #include <strings.h> // NOLINT
348 #elif GTEST_OS_WINDOWS_MOBILE // We are on Windows CE.
350 #include <windows.h> // NOLINT
352 #elif GTEST_OS_WINDOWS // We are on Windows proper.
354 #include <io.h> // NOLINT
355 #include <sys/timeb.h> // NOLINT
356 #include <sys/types.h> // NOLINT
357 #include <sys/stat.h> // NOLINT
359 #if GTEST_OS_WINDOWS_MINGW
360 // MinGW has gettimeofday() but not _ftime64().
361 // TODO(kenton@google.com): Use autoconf to detect availability of
363 // TODO(kenton@google.com): There are other ways to get the time on
364 // Windows, like GetTickCount() or GetSystemTimeAsFileTime(). MinGW
365 // supports these. consider using them instead.
366 #define GTEST_HAS_GETTIMEOFDAY_ 1
367 #include <sys/time.h> // NOLINT
368 #endif // GTEST_OS_WINDOWS_MINGW
370 // cpplint thinks that the header is already included, so we want to
372 #include <windows.h> // NOLINT
376 // Assume other platforms have gettimeofday().
377 // TODO(kenton@google.com): Use autoconf to detect availability of
379 #define GTEST_HAS_GETTIMEOFDAY_ 1
381 // cpplint thinks that the header is already included, so we want to
383 #include <sys/time.h> // NOLINT
384 #include <unistd.h> // NOLINT
386 #endif // GTEST_OS_LINUX
388 #if GTEST_HAS_EXCEPTIONS
392 // Indicates that this translation unit is part of Google Test's
393 // implementation. It must come before gtest-internal-inl.h is
394 // included, or there will be a compiler error. This trick is to
395 // prevent a user from accidentally including gtest-internal-inl.h in
397 #define GTEST_IMPLEMENTATION_ 1
398 // Copyright 2005, Google Inc.
399 // All rights reserved.
401 // Redistribution and use in source and binary forms, with or without
402 // modification, are permitted provided that the following conditions are
405 // * Redistributions of source code must retain the above copyright
406 // notice, this list of conditions and the following disclaimer.
407 // * Redistributions in binary form must reproduce the above
408 // copyright notice, this list of conditions and the following disclaimer
409 // in the documentation and/or other materials provided with the
411 // * Neither the name of Google Inc. nor the names of its
412 // contributors may be used to endorse or promote products derived from
413 // this software without specific prior written permission.
415 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
416 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
417 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
418 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
419 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
420 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
421 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
422 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
423 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
424 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
425 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
427 // Utility functions and classes used by the Google C++ testing framework.
429 // Author: wan@google.com (Zhanyong Wan)
431 // This file contains purely Google Test's internal implementation. Please
432 // DO NOT #INCLUDE IT IN A USER PROGRAM.
434 #ifndef GTEST_SRC_GTEST_INTERNAL_INL_H_
435 #define GTEST_SRC_GTEST_INTERNAL_INL_H_
437 // GTEST_IMPLEMENTATION_ is defined to 1 iff the current translation unit is
438 // part of Google Test's implementation; otherwise it's undefined.
439 #if !GTEST_IMPLEMENTATION_
440 // A user is trying to include this from his code - just say no.
441 #error "gtest-internal-inl.h is part of Google Test's internal implementation."
442 #error "It must not be included except by Google Test itself."
443 #endif // GTEST_IMPLEMENTATION_
447 #endif // !_WIN32_WCE
449 #include <stdlib.h> // For strtoll/_strtoul64/malloc/free.
450 #include <string.h> // For memmove.
458 #include <windows.h> // For DWORD.
459 #endif // GTEST_OS_WINDOWS
464 // Declares the flags.
466 // We don't want the users to modify this flag in the code, but want
467 // Google Test's own unit tests to be able to access it. Therefore we
468 // declare it here as opposed to in gtest.h.
469 GTEST_DECLARE_bool_(death_test_use_fork);
473 // The value of GetTestTypeId() as seen from within the Google Test
474 // library. This is solely for testing GetTestTypeId().
475 GTEST_API_ extern const TypeId kTestTypeIdInGoogleTest;
477 // Names of the flags (needed for parsing Google Test flags).
478 const char kAlsoRunDisabledTestsFlag[] = "also_run_disabled_tests";
479 const char kBreakOnFailureFlag[] = "break_on_failure";
480 const char kCatchExceptionsFlag[] = "catch_exceptions";
481 const char kColorFlag[] = "color";
482 const char kFilterFlag[] = "filter";
483 const char kListTestsFlag[] = "list_tests";
484 const char kOutputFlag[] = "output";
485 const char kPrintTimeFlag[] = "print_time";
486 const char kRandomSeedFlag[] = "random_seed";
487 const char kRepeatFlag[] = "repeat";
488 const char kShuffleFlag[] = "shuffle";
489 const char kStackTraceDepthFlag[] = "stack_trace_depth";
490 const char kThrowOnFailureFlag[] = "throw_on_failure";
492 // A valid random seed must be in [1, kMaxRandomSeed].
493 const int kMaxRandomSeed = 99999;
495 // g_help_flag is true iff the --help flag or an equivalent form is
496 // specified on the command line.
497 GTEST_API_ extern bool g_help_flag;
499 // Returns the current time in milliseconds.
500 GTEST_API_ TimeInMillis GetTimeInMillis();
502 // Returns true iff Google Test should use colors in the output.
503 GTEST_API_ bool ShouldUseColor(bool stdout_is_tty);
505 // Formats the given time in milliseconds as seconds.
506 GTEST_API_ std::string FormatTimeInMillisAsSeconds(TimeInMillis ms);
508 // Parses a string for an Int32 flag, in the form of "--flag=value".
510 // On success, stores the value of the flag in *value, and returns
511 // true. On failure, returns false without changing *value.
512 GTEST_API_ bool ParseInt32Flag(
513 const char* str, const char* flag, Int32* value);
515 // Returns a random seed in range [1, kMaxRandomSeed] based on the
516 // given --gtest_random_seed flag value.
517 inline int GetRandomSeedFromFlag(Int32 random_seed_flag) {
518 const unsigned int raw_seed = (random_seed_flag == 0) ?
519 static_cast<unsigned int>(GetTimeInMillis()) :
520 static_cast<unsigned int>(random_seed_flag);
522 // Normalizes the actual seed to range [1, kMaxRandomSeed] such that
523 // it's easy to type.
524 const int normalized_seed =
525 static_cast<int>((raw_seed - 1U) %
526 static_cast<unsigned int>(kMaxRandomSeed)) + 1;
527 return normalized_seed;
530 // Returns the first valid random seed after 'seed'. The behavior is
531 // undefined if 'seed' is invalid. The seed after kMaxRandomSeed is
532 // considered to be 1.
533 inline int GetNextRandomSeed(int seed) {
534 GTEST_CHECK_(1 <= seed && seed <= kMaxRandomSeed)
535 << "Invalid random seed " << seed << " - must be in [1, "
536 << kMaxRandomSeed << "].";
537 const int next_seed = seed + 1;
538 return (next_seed > kMaxRandomSeed) ? 1 : next_seed;
541 // This class saves the values of all Google Test flags in its c'tor, and
542 // restores them in its d'tor.
543 class GTestFlagSaver {
547 also_run_disabled_tests_ = GTEST_FLAG(also_run_disabled_tests);
548 break_on_failure_ = GTEST_FLAG(break_on_failure);
549 catch_exceptions_ = GTEST_FLAG(catch_exceptions);
550 color_ = GTEST_FLAG(color);
551 death_test_style_ = GTEST_FLAG(death_test_style);
552 death_test_use_fork_ = GTEST_FLAG(death_test_use_fork);
553 filter_ = GTEST_FLAG(filter);
554 internal_run_death_test_ = GTEST_FLAG(internal_run_death_test);
555 list_tests_ = GTEST_FLAG(list_tests);
556 output_ = GTEST_FLAG(output);
557 print_time_ = GTEST_FLAG(print_time);
558 random_seed_ = GTEST_FLAG(random_seed);
559 repeat_ = GTEST_FLAG(repeat);
560 shuffle_ = GTEST_FLAG(shuffle);
561 stack_trace_depth_ = GTEST_FLAG(stack_trace_depth);
562 throw_on_failure_ = GTEST_FLAG(throw_on_failure);
565 // The d'tor is not virtual. DO NOT INHERIT FROM THIS CLASS.
567 GTEST_FLAG(also_run_disabled_tests) = also_run_disabled_tests_;
568 GTEST_FLAG(break_on_failure) = break_on_failure_;
569 GTEST_FLAG(catch_exceptions) = catch_exceptions_;
570 GTEST_FLAG(color) = color_;
571 GTEST_FLAG(death_test_style) = death_test_style_;
572 GTEST_FLAG(death_test_use_fork) = death_test_use_fork_;
573 GTEST_FLAG(filter) = filter_;
574 GTEST_FLAG(internal_run_death_test) = internal_run_death_test_;
575 GTEST_FLAG(list_tests) = list_tests_;
576 GTEST_FLAG(output) = output_;
577 GTEST_FLAG(print_time) = print_time_;
578 GTEST_FLAG(random_seed) = random_seed_;
579 GTEST_FLAG(repeat) = repeat_;
580 GTEST_FLAG(shuffle) = shuffle_;
581 GTEST_FLAG(stack_trace_depth) = stack_trace_depth_;
582 GTEST_FLAG(throw_on_failure) = throw_on_failure_;
585 // Fields for saving the original values of flags.
586 bool also_run_disabled_tests_;
587 bool break_on_failure_;
588 bool catch_exceptions_;
590 String death_test_style_;
591 bool death_test_use_fork_;
593 String internal_run_death_test_;
598 internal::Int32 random_seed_;
599 internal::Int32 repeat_;
601 internal::Int32 stack_trace_depth_;
602 bool throw_on_failure_;
603 } GTEST_ATTRIBUTE_UNUSED_;
605 // Converts a Unicode code point to a narrow string in UTF-8 encoding.
606 // code_point parameter is of type UInt32 because wchar_t may not be
607 // wide enough to contain a code point.
608 // The output buffer str must containt at least 32 characters.
609 // The function returns the address of the output buffer.
610 // If the code_point is not a valid Unicode code point
611 // (i.e. outside of Unicode range U+0 to U+10FFFF) it will be output
612 // as '(Invalid Unicode 0xXXXXXXXX)'.
613 GTEST_API_ char* CodePointToUtf8(UInt32 code_point, char* str);
615 // Converts a wide string to a narrow string in UTF-8 encoding.
616 // The wide string is assumed to have the following encoding:
617 // UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS)
618 // UTF-32 if sizeof(wchar_t) == 4 (on Linux)
619 // Parameter str points to a null-terminated wide string.
620 // Parameter num_chars may additionally limit the number
621 // of wchar_t characters processed. -1 is used when the entire string
622 // should be processed.
623 // If the string contains code points that are not valid Unicode code points
624 // (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
625 // as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
626 // and contains invalid UTF-16 surrogate pairs, values in those pairs
627 // will be encoded as individual Unicode characters from Basic Normal Plane.
628 GTEST_API_ String WideStringToUtf8(const wchar_t* str, int num_chars);
630 // Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
631 // if the variable is present. If a file already exists at this location, this
632 // function will write over it. If the variable is present, but the file cannot
633 // be created, prints an error and exits.
634 void WriteToShardStatusFileIfNeeded();
636 // Checks whether sharding is enabled by examining the relevant
637 // environment variable values. If the variables are present,
638 // but inconsistent (e.g., shard_index >= total_shards), prints
639 // an error and exits. If in_subprocess_for_death_test, sharding is
640 // disabled because it must only be applied to the original test
641 // process. Otherwise, we could filter out death tests we intended to execute.
642 GTEST_API_ bool ShouldShard(const char* total_shards_str,
643 const char* shard_index_str,
644 bool in_subprocess_for_death_test);
646 // Parses the environment variable var as an Int32. If it is unset,
647 // returns default_val. If it is not an Int32, prints an error and
649 GTEST_API_ Int32 Int32FromEnvOrDie(const char* env_var, Int32 default_val);
651 // Given the total number of shards, the shard index, and the test id,
652 // returns true iff the test should be run on this shard. The test id is
653 // some arbitrary but unique non-negative integer assigned to each test
654 // method. Assumes that 0 <= shard_index < total_shards.
655 GTEST_API_ bool ShouldRunTestOnShard(
656 int total_shards, int shard_index, int test_id);
658 // STL container utilities.
660 // Returns the number of elements in the given container that satisfy
661 // the given predicate.
662 template <class Container, typename Predicate>
663 inline int CountIf(const Container& c, Predicate predicate) {
664 return static_cast<int>(std::count_if(c.begin(), c.end(), predicate));
667 // Applies a function/functor to each element in the container.
668 template <class Container, typename Functor>
669 void ForEach(const Container& c, Functor functor) {
670 std::for_each(c.begin(), c.end(), functor);
673 // Returns the i-th element of the vector, or default_value if i is not
674 // in range [0, v.size()).
675 template <typename E>
676 inline E GetElementOr(const std::vector<E>& v, int i, E default_value) {
677 return (i < 0 || i >= static_cast<int>(v.size())) ? default_value : v[i];
680 // Performs an in-place shuffle of a range of the vector's elements.
681 // 'begin' and 'end' are element indices as an STL-style range;
682 // i.e. [begin, end) are shuffled, where 'end' == size() means to
683 // shuffle to the end of the vector.
684 template <typename E>
685 void ShuffleRange(internal::Random* random, int begin, int end,
687 const int size = static_cast<int>(v->size());
688 GTEST_CHECK_(0 <= begin && begin <= size)
689 << "Invalid shuffle range start " << begin << ": must be in range [0, "
691 GTEST_CHECK_(begin <= end && end <= size)
692 << "Invalid shuffle range finish " << end << ": must be in range ["
693 << begin << ", " << size << "].";
695 // Fisher-Yates shuffle, from
696 // http://en.wikipedia.org/wiki/Fisher-Yates_shuffle
697 for (int range_width = end - begin; range_width >= 2; range_width--) {
698 const int last_in_range = begin + range_width - 1;
699 const int selected = begin + random->Generate(range_width);
700 std::swap((*v)[selected], (*v)[last_in_range]);
704 // Performs an in-place shuffle of the vector's elements.
705 template <typename E>
706 inline void Shuffle(internal::Random* random, std::vector<E>* v) {
707 ShuffleRange(random, 0, static_cast<int>(v->size()), v);
710 // A function for deleting an object. Handy for being used as a
712 template <typename T>
713 static void Delete(T* x) {
717 // A predicate that checks the key of a TestProperty against a known key.
719 // TestPropertyKeyIs is copyable.
720 class TestPropertyKeyIs {
724 // TestPropertyKeyIs has NO default constructor.
725 explicit TestPropertyKeyIs(const char* key)
728 // Returns true iff the test name of test property matches on key_.
729 bool operator()(const TestProperty& test_property) const {
730 return String(test_property.key()).Compare(key_) == 0;
739 TestInfoImpl(TestInfo* parent, const char* test_case_name,
740 const char* name, const char* test_case_comment,
741 const char* comment, TypeId fixture_class_id,
742 internal::TestFactoryBase* factory);
745 // Returns true if this test should run.
746 bool should_run() const { return should_run_; }
748 // Sets the should_run member.
749 void set_should_run(bool should) { should_run_ = should; }
751 // Returns true if this test is disabled. Disabled tests are not run.
752 bool is_disabled() const { return is_disabled_; }
754 // Sets the is_disabled member.
755 void set_is_disabled(bool is) { is_disabled_ = is; }
757 // Returns true if this test matches the filter specified by the user.
758 bool matches_filter() const { return matches_filter_; }
760 // Sets the matches_filter member.
761 void set_matches_filter(bool matches) { matches_filter_ = matches; }
763 // Returns the test case name.
764 const char* test_case_name() const { return test_case_name_.c_str(); }
766 // Returns the test name.
767 const char* name() const { return name_.c_str(); }
769 // Returns the test case comment.
770 const char* test_case_comment() const { return test_case_comment_.c_str(); }
772 // Returns the test comment.
773 const char* comment() const { return comment_.c_str(); }
775 // Returns the ID of the test fixture class.
776 TypeId fixture_class_id() const { return fixture_class_id_; }
778 // Returns the test result.
779 TestResult* result() { return &result_; }
780 const TestResult* result() const { return &result_; }
782 // Creates the test object, runs it, records its result, and then
786 // Clears the test result.
787 void ClearResult() { result_.Clear(); }
789 // Clears the test result in the given TestInfo object.
790 static void ClearTestResult(TestInfo * test_info) {
791 test_info->impl()->ClearResult();
795 // These fields are immutable properties of the test.
796 TestInfo* const parent_; // The owner of this object
797 const String test_case_name_; // Test case name
798 const String name_; // Test name
799 const String test_case_comment_; // Test case comment
800 const String comment_; // Test comment
801 const TypeId fixture_class_id_; // ID of the test fixture class
802 bool should_run_; // True iff this test should run
803 bool is_disabled_; // True iff this test is disabled
804 bool matches_filter_; // True if this test matches the
805 // user-specified filter.
806 internal::TestFactoryBase* const factory_; // The factory that creates
809 // This field is mutable and needs to be reset before running the
810 // test for the second time.
813 GTEST_DISALLOW_COPY_AND_ASSIGN_(TestInfoImpl);
816 // Class UnitTestOptions.
818 // This class contains functions for processing options the user
819 // specifies when running the tests. It has only static members.
821 // In most cases, the user can specify an option using either an
822 // environment variable or a command line flag. E.g. you can set the
823 // test filter using either GTEST_FILTER or --gtest_filter. If both
824 // the variable and the flag are present, the latter overrides the
826 class GTEST_API_ UnitTestOptions {
828 // Functions for processing the gtest_output flag.
830 // Returns the output format, or "" for normal printed output.
831 static String GetOutputFormat();
833 // Returns the absolute path of the requested output file, or the
834 // default (test_detail.xml in the original working directory) if
835 // none was explicitly specified.
836 static String GetAbsolutePathToOutputFile();
838 // Functions for processing the gtest_filter flag.
840 // Returns true iff the wildcard pattern matches the string. The
841 // first ':' or '\0' character in pattern marks the end of it.
843 // This recursive algorithm isn't very efficient, but is clear and
844 // works well enough for matching test names, which are short.
845 static bool PatternMatchesString(const char *pattern, const char *str);
847 // Returns true iff the user-specified filter matches the test case
848 // name and the test name.
849 static bool FilterMatchesTest(const String &test_case_name,
850 const String &test_name);
853 // Function for supporting the gtest_catch_exception flag.
855 // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
856 // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
857 // This function is useful as an __except condition.
858 static int GTestShouldProcessSEH(DWORD exception_code);
859 #endif // GTEST_OS_WINDOWS
861 // Returns true if "name" matches the ':' separated list of glob-style
862 // filters in "filter".
863 static bool MatchesFilter(const String& name, const char* filter);
866 // Returns the current application's name, removing directory path if that
867 // is present. Used by UnitTestOptions::GetOutputFile.
868 GTEST_API_ FilePath GetCurrentExecutableName();
870 // The role interface for getting the OS stack trace as a string.
871 class OsStackTraceGetterInterface {
873 OsStackTraceGetterInterface() {}
874 virtual ~OsStackTraceGetterInterface() {}
876 // Returns the current OS stack trace as a String. Parameters:
878 // max_depth - the maximum number of stack frames to be included
880 // skip_count - the number of top frames to be skipped; doesn't count
881 // against max_depth.
882 virtual String CurrentStackTrace(int max_depth, int skip_count) = 0;
884 // UponLeavingGTest() should be called immediately before Google Test calls
885 // user code. It saves some information about the current stack that
886 // CurrentStackTrace() will use to find and hide Google Test stack frames.
887 virtual void UponLeavingGTest() = 0;
890 GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetterInterface);
893 // A working implementation of the OsStackTraceGetterInterface interface.
894 class OsStackTraceGetter : public OsStackTraceGetterInterface {
896 OsStackTraceGetter() : caller_frame_(NULL) {}
897 virtual String CurrentStackTrace(int max_depth, int skip_count);
898 virtual void UponLeavingGTest();
900 // This string is inserted in place of stack frames that are part of
901 // Google Test's implementation.
902 static const char* const kElidedFramesMarker;
905 Mutex mutex_; // protects all internal state
907 // We save the stack frame below the frame that calls user code.
908 // We do this because the address of the frame immediately below
909 // the user code changes between the call to UponLeavingGTest()
910 // and any calls to CurrentStackTrace() from within the user code.
913 GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetter);
916 // Information about a Google Test trace point.
923 // This is the default global test part result reporter used in UnitTestImpl.
924 // This class should only be used by UnitTestImpl.
925 class DefaultGlobalTestPartResultReporter
926 : public TestPartResultReporterInterface {
928 explicit DefaultGlobalTestPartResultReporter(UnitTestImpl* unit_test);
929 // Implements the TestPartResultReporterInterface. Reports the test part
930 // result in the current test.
931 virtual void ReportTestPartResult(const TestPartResult& result);
934 UnitTestImpl* const unit_test_;
936 GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultGlobalTestPartResultReporter);
939 // This is the default per thread test part result reporter used in
940 // UnitTestImpl. This class should only be used by UnitTestImpl.
941 class DefaultPerThreadTestPartResultReporter
942 : public TestPartResultReporterInterface {
944 explicit DefaultPerThreadTestPartResultReporter(UnitTestImpl* unit_test);
945 // Implements the TestPartResultReporterInterface. The implementation just
946 // delegates to the current global test part result reporter of *unit_test_.
947 virtual void ReportTestPartResult(const TestPartResult& result);
950 UnitTestImpl* const unit_test_;
952 GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultPerThreadTestPartResultReporter);
955 // The private implementation of the UnitTest class. We don't protect
956 // the methods under a mutex, as this class is not accessible by a
957 // user and the UnitTest class that delegates work to this class does
959 class GTEST_API_ UnitTestImpl {
961 explicit UnitTestImpl(UnitTest* parent);
962 virtual ~UnitTestImpl();
964 // There are two different ways to register your own TestPartResultReporter.
965 // You can register your own repoter to listen either only for test results
966 // from the current thread or for results from all threads.
967 // By default, each per-thread test result repoter just passes a new
968 // TestPartResult to the global test result reporter, which registers the
969 // test part result for the currently running test.
971 // Returns the global test part result reporter.
972 TestPartResultReporterInterface* GetGlobalTestPartResultReporter();
974 // Sets the global test part result reporter.
975 void SetGlobalTestPartResultReporter(
976 TestPartResultReporterInterface* reporter);
978 // Returns the test part result reporter for the current thread.
979 TestPartResultReporterInterface* GetTestPartResultReporterForCurrentThread();
981 // Sets the test part result reporter for the current thread.
982 void SetTestPartResultReporterForCurrentThread(
983 TestPartResultReporterInterface* reporter);
985 // Gets the number of successful test cases.
986 int successful_test_case_count() const;
988 // Gets the number of failed test cases.
989 int failed_test_case_count() const;
991 // Gets the number of all test cases.
992 int total_test_case_count() const;
994 // Gets the number of all test cases that contain at least one test
996 int test_case_to_run_count() const;
998 // Gets the number of successful tests.
999 int successful_test_count() const;
1001 // Gets the number of failed tests.
1002 int failed_test_count() const;
1004 // Gets the number of disabled tests.
1005 int disabled_test_count() const;
1007 // Gets the number of all tests.
1008 int total_test_count() const;
1010 // Gets the number of tests that should run.
1011 int test_to_run_count() const;
1013 // Gets the elapsed time, in milliseconds.
1014 TimeInMillis elapsed_time() const { return elapsed_time_; }
1016 // Returns true iff the unit test passed (i.e. all test cases passed).
1017 bool Passed() const { return !Failed(); }
1019 // Returns true iff the unit test failed (i.e. some test case failed
1020 // or something outside of all tests failed).
1021 bool Failed() const {
1022 return failed_test_case_count() > 0 || ad_hoc_test_result()->Failed();
1025 // Gets the i-th test case among all the test cases. i can range from 0 to
1026 // total_test_case_count() - 1. If i is not in that range, returns NULL.
1027 const TestCase* GetTestCase(int i) const {
1028 const int index = GetElementOr(test_case_indices_, i, -1);
1029 return index < 0 ? NULL : test_cases_[i];
1032 // Gets the i-th test case among all the test cases. i can range from 0 to
1033 // total_test_case_count() - 1. If i is not in that range, returns NULL.
1034 TestCase* GetMutableTestCase(int i) {
1035 const int index = GetElementOr(test_case_indices_, i, -1);
1036 return index < 0 ? NULL : test_cases_[index];
1039 // Provides access to the event listener list.
1040 TestEventListeners* listeners() { return &listeners_; }
1042 // Returns the TestResult for the test that's currently running, or
1043 // the TestResult for the ad hoc test if no test is running.
1044 TestResult* current_test_result();
1046 // Returns the TestResult for the ad hoc test.
1047 const TestResult* ad_hoc_test_result() const { return &ad_hoc_test_result_; }
1049 // Sets the OS stack trace getter.
1051 // Does nothing if the input and the current OS stack trace getter
1052 // are the same; otherwise, deletes the old getter and makes the
1053 // input the current getter.
1054 void set_os_stack_trace_getter(OsStackTraceGetterInterface* getter);
1056 // Returns the current OS stack trace getter if it is not NULL;
1057 // otherwise, creates an OsStackTraceGetter, makes it the current
1058 // getter, and returns it.
1059 OsStackTraceGetterInterface* os_stack_trace_getter();
1061 // Returns the current OS stack trace as a String.
1063 // The maximum number of stack frames to be included is specified by
1064 // the gtest_stack_trace_depth flag. The skip_count parameter
1065 // specifies the number of top frames to be skipped, which doesn't
1066 // count against the number of frames to be included.
1068 // For example, if Foo() calls Bar(), which in turn calls
1069 // CurrentOsStackTraceExceptTop(1), Foo() will be included in the
1070 // trace but Bar() and CurrentOsStackTraceExceptTop() won't.
1071 String CurrentOsStackTraceExceptTop(int skip_count);
1073 // Finds and returns a TestCase with the given name. If one doesn't
1074 // exist, creates one and returns it.
1078 // test_case_name: name of the test case
1079 // set_up_tc: pointer to the function that sets up the test case
1080 // tear_down_tc: pointer to the function that tears down the test case
1081 TestCase* GetTestCase(const char* test_case_name,
1082 const char* comment,
1083 Test::SetUpTestCaseFunc set_up_tc,
1084 Test::TearDownTestCaseFunc tear_down_tc);
1086 // Adds a TestInfo to the unit test.
1090 // set_up_tc: pointer to the function that sets up the test case
1091 // tear_down_tc: pointer to the function that tears down the test case
1092 // test_info: the TestInfo object
1093 void AddTestInfo(Test::SetUpTestCaseFunc set_up_tc,
1094 Test::TearDownTestCaseFunc tear_down_tc,
1095 TestInfo * test_info) {
1096 // In order to support thread-safe death tests, we need to
1097 // remember the original working directory when the test program
1098 // was first invoked. We cannot do this in RUN_ALL_TESTS(), as
1099 // the user may have changed the current directory before calling
1100 // RUN_ALL_TESTS(). Therefore we capture the current directory in
1101 // AddTestInfo(), which is called to register a TEST or TEST_F
1102 // before main() is reached.
1103 if (original_working_dir_.IsEmpty()) {
1104 original_working_dir_.Set(FilePath::GetCurrentDir());
1105 GTEST_CHECK_(!original_working_dir_.IsEmpty())
1106 << "Failed to get the current working directory.";
1109 GetTestCase(test_info->test_case_name(),
1110 test_info->test_case_comment(),
1112 tear_down_tc)->AddTestInfo(test_info);
1115 #if GTEST_HAS_PARAM_TEST
1116 // Returns ParameterizedTestCaseRegistry object used to keep track of
1117 // value-parameterized tests and instantiate and register them.
1118 internal::ParameterizedTestCaseRegistry& parameterized_test_registry() {
1119 return parameterized_test_registry_;
1121 #endif // GTEST_HAS_PARAM_TEST
1123 // Sets the TestCase object for the test that's currently running.
1124 void set_current_test_case(TestCase* a_current_test_case) {
1125 current_test_case_ = a_current_test_case;
1128 // Sets the TestInfo object for the test that's currently running. If
1129 // current_test_info is NULL, the assertion results will be stored in
1130 // ad_hoc_test_result_.
1131 void set_current_test_info(TestInfo* a_current_test_info) {
1132 current_test_info_ = a_current_test_info;
1135 // Registers all parameterized tests defined using TEST_P and
1136 // INSTANTIATE_TEST_P, creating regular tests for each test/parameter
1137 // combination. This method can be called more then once; it has
1138 // guards protecting from registering the tests more then once.
1139 // If value-parameterized tests are disabled, RegisterParameterizedTests
1140 // is present but does nothing.
1141 void RegisterParameterizedTests();
1143 // Runs all tests in this UnitTest object, prints the result, and
1144 // returns 0 if all tests are successful, or 1 otherwise. If any
1145 // exception is thrown during a test on Windows, this test is
1146 // considered to be failed, but the rest of the tests will still be
1147 // run. (We disable exceptions on Linux and Mac OS X, so the issue
1148 // doesn't apply there.)
1151 // Clears the results of all tests, including the ad hoc test.
1152 void ClearResult() {
1153 ForEach(test_cases_, TestCase::ClearTestCaseResult);
1154 ad_hoc_test_result_.Clear();
1157 enum ReactionToSharding {
1158 HONOR_SHARDING_PROTOCOL,
1159 IGNORE_SHARDING_PROTOCOL
1162 // Matches the full name of each test against the user-specified
1163 // filter to decide whether the test should run, then records the
1164 // result in each TestCase and TestInfo object.
1165 // If shard_tests == HONOR_SHARDING_PROTOCOL, further filters tests
1166 // based on sharding variables in the environment.
1167 // Returns the number of tests that should run.
1168 int FilterTests(ReactionToSharding shard_tests);
1170 // Prints the names of the tests matching the user-specified filter flag.
1171 void ListTestsMatchingFilter();
1173 const TestCase* current_test_case() const { return current_test_case_; }
1174 TestInfo* current_test_info() { return current_test_info_; }
1175 const TestInfo* current_test_info() const { return current_test_info_; }
1177 // Returns the vector of environments that need to be set-up/torn-down
1178 // before/after the tests are run.
1179 std::vector<Environment*>& environments() { return environments_; }
1181 // Getters for the per-thread Google Test trace stack.
1182 std::vector<TraceInfo>& gtest_trace_stack() {
1183 return *(gtest_trace_stack_.pointer());
1185 const std::vector<TraceInfo>& gtest_trace_stack() const {
1186 return gtest_trace_stack_.get();
1189 #if GTEST_HAS_DEATH_TEST
1190 void InitDeathTestSubprocessControlInfo() {
1191 internal_run_death_test_flag_.reset(ParseInternalRunDeathTestFlag());
1193 // Returns a pointer to the parsed --gtest_internal_run_death_test
1194 // flag, or NULL if that flag was not specified.
1195 // This information is useful only in a death test child process.
1196 // Must not be called before a call to InitGoogleTest.
1197 const InternalRunDeathTestFlag* internal_run_death_test_flag() const {
1198 return internal_run_death_test_flag_.get();
1201 // Returns a pointer to the current death test factory.
1202 internal::DeathTestFactory* death_test_factory() {
1203 return death_test_factory_.get();
1206 void SuppressTestEventsIfInSubprocess();
1208 friend class ReplaceDeathTestFactory;
1209 #endif // GTEST_HAS_DEATH_TEST
1211 // Initializes the event listener performing XML output as specified by
1212 // UnitTestOptions. Must not be called before InitGoogleTest.
1213 void ConfigureXmlOutput();
1215 // Performs initialization dependent upon flag values obtained in
1216 // ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to
1217 // ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest
1218 // this function is also called from RunAllTests. Since this function can be
1219 // called more than once, it has to be idempotent.
1220 void PostFlagParsingInit();
1222 // Gets the random seed used at the start of the current test iteration.
1223 int random_seed() const { return random_seed_; }
1225 // Gets the random number generator.
1226 internal::Random* random() { return &random_; }
1228 // Shuffles all test cases, and the tests within each test case,
1229 // making sure that death tests are still run first.
1230 void ShuffleTests();
1232 // Restores the test cases and tests to their order before the first shuffle.
1233 void UnshuffleTests();
1236 friend class ::testing::UnitTest;
1238 // The UnitTest object that owns this implementation object.
1239 UnitTest* const parent_;
1241 // The working directory when the first TEST() or TEST_F() was
1243 internal::FilePath original_working_dir_;
1245 // The default test part result reporters.
1246 DefaultGlobalTestPartResultReporter default_global_test_part_result_reporter_;
1247 DefaultPerThreadTestPartResultReporter
1248 default_per_thread_test_part_result_reporter_;
1250 // Points to (but doesn't own) the global test part result reporter.
1251 TestPartResultReporterInterface* global_test_part_result_repoter_;
1253 // Protects read and write access to global_test_part_result_reporter_.
1254 internal::Mutex global_test_part_result_reporter_mutex_;
1256 // Points to (but doesn't own) the per-thread test part result reporter.
1257 internal::ThreadLocal<TestPartResultReporterInterface*>
1258 per_thread_test_part_result_reporter_;
1260 // The vector of environments that need to be set-up/torn-down
1261 // before/after the tests are run.
1262 std::vector<Environment*> environments_;
1264 // The vector of TestCases in their original order. It owns the
1265 // elements in the vector.
1266 std::vector<TestCase*> test_cases_;
1268 // Provides a level of indirection for the test case list to allow
1269 // easy shuffling and restoring the test case order. The i-th
1270 // element of this vector is the index of the i-th test case in the
1272 std::vector<int> test_case_indices_;
1274 #if GTEST_HAS_PARAM_TEST
1275 // ParameterizedTestRegistry object used to register value-parameterized
1277 internal::ParameterizedTestCaseRegistry parameterized_test_registry_;
1279 // Indicates whether RegisterParameterizedTests() has been called already.
1280 bool parameterized_tests_registered_;
1281 #endif // GTEST_HAS_PARAM_TEST
1283 // Index of the last death test case registered. Initially -1.
1284 int last_death_test_case_;
1286 // This points to the TestCase for the currently running test. It
1287 // changes as Google Test goes through one test case after another.
1288 // When no test is running, this is set to NULL and Google Test
1289 // stores assertion results in ad_hoc_test_result_. Initially NULL.
1290 TestCase* current_test_case_;
1292 // This points to the TestInfo for the currently running test. It
1293 // changes as Google Test goes through one test after another. When
1294 // no test is running, this is set to NULL and Google Test stores
1295 // assertion results in ad_hoc_test_result_. Initially NULL.
1296 TestInfo* current_test_info_;
1298 // Normally, a user only writes assertions inside a TEST or TEST_F,
1299 // or inside a function called by a TEST or TEST_F. Since Google
1300 // Test keeps track of which test is current running, it can
1301 // associate such an assertion with the test it belongs to.
1303 // If an assertion is encountered when no TEST or TEST_F is running,
1304 // Google Test attributes the assertion result to an imaginary "ad hoc"
1305 // test, and records the result in ad_hoc_test_result_.
1306 TestResult ad_hoc_test_result_;
1308 // The list of event listeners that can be used to track events inside
1310 TestEventListeners listeners_;
1312 // The OS stack trace getter. Will be deleted when the UnitTest
1313 // object is destructed. By default, an OsStackTraceGetter is used,
1314 // but the user can set this field to use a custom getter if that is
1316 OsStackTraceGetterInterface* os_stack_trace_getter_;
1318 // True iff PostFlagParsingInit() has been called.
1319 bool post_flag_parse_init_performed_;
1321 // The random number seed used at the beginning of the test run.
1324 // Our random number generator.
1325 internal::Random random_;
1327 // How long the test took to run, in milliseconds.
1328 TimeInMillis elapsed_time_;
1330 #if GTEST_HAS_DEATH_TEST
1331 // The decomposed components of the gtest_internal_run_death_test flag,
1332 // parsed when RUN_ALL_TESTS is called.
1333 internal::scoped_ptr<InternalRunDeathTestFlag> internal_run_death_test_flag_;
1334 internal::scoped_ptr<internal::DeathTestFactory> death_test_factory_;
1335 #endif // GTEST_HAS_DEATH_TEST
1337 // A per-thread stack of traces created by the SCOPED_TRACE() macro.
1338 internal::ThreadLocal<std::vector<TraceInfo> > gtest_trace_stack_;
1340 GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTestImpl);
1341 }; // class UnitTestImpl
1343 // Convenience function for accessing the global UnitTest
1344 // implementation object.
1345 inline UnitTestImpl* GetUnitTestImpl() {
1346 return UnitTest::GetInstance()->impl();
1349 // Internal helper functions for implementing the simple regular
1350 // expression matcher.
1351 GTEST_API_ bool IsInSet(char ch, const char* str);
1352 GTEST_API_ bool IsDigit(char ch);
1353 GTEST_API_ bool IsPunct(char ch);
1354 GTEST_API_ bool IsRepeat(char ch);
1355 GTEST_API_ bool IsWhiteSpace(char ch);
1356 GTEST_API_ bool IsWordChar(char ch);
1357 GTEST_API_ bool IsValidEscape(char ch);
1358 GTEST_API_ bool AtomMatchesChar(bool escaped, char pattern, char ch);
1359 GTEST_API_ bool ValidateRegex(const char* regex);
1360 GTEST_API_ bool MatchRegexAtHead(const char* regex, const char* str);
1361 GTEST_API_ bool MatchRepetitionAndRegexAtHead(
1362 bool escaped, char ch, char repeat, const char* regex, const char* str);
1363 GTEST_API_ bool MatchRegexAnywhere(const char* regex, const char* str);
1365 // Parses the command line for Google Test flags, without initializing
1366 // other parts of Google Test.
1367 GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, char** argv);
1368 GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv);
1370 #if GTEST_HAS_DEATH_TEST
1372 // Returns the message describing the last system error, regardless of the
1374 String GetLastErrnoDescription();
1376 #if GTEST_OS_WINDOWS
1377 // Provides leak-safe Windows kernel handle ownership.
1380 AutoHandle() : handle_(INVALID_HANDLE_VALUE) {}
1381 explicit AutoHandle(HANDLE handle) : handle_(handle) {}
1383 ~AutoHandle() { Reset(); }
1385 HANDLE Get() const { return handle_; }
1386 void Reset() { Reset(INVALID_HANDLE_VALUE); }
1387 void Reset(HANDLE handle) {
1388 if (handle != handle_) {
1389 if (handle_ != INVALID_HANDLE_VALUE)
1390 ::CloseHandle(handle_);
1398 GTEST_DISALLOW_COPY_AND_ASSIGN_(AutoHandle);
1400 #endif // GTEST_OS_WINDOWS
1402 // Attempts to parse a string into a positive integer pointed to by the
1403 // number parameter. Returns true if that is possible.
1404 // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we can use
1406 template <typename Integer>
1407 bool ParseNaturalNumber(const ::std::string& str, Integer* number) {
1408 // Fail fast if the given string does not begin with a digit;
1409 // this bypasses strtoXXX's "optional leading whitespace and plus
1410 // or minus sign" semantics, which are undesirable here.
1411 if (str.empty() || !isdigit(str[0])) {
1417 // BiggestConvertible is the largest integer type that system-provided
1418 // string-to-number conversion routines can return.
1419 #if GTEST_OS_WINDOWS && !defined(__GNUC__)
1420 // MSVC and C++ Builder define __int64 instead of the standard long long.
1421 typedef unsigned __int64 BiggestConvertible;
1422 const BiggestConvertible parsed = _strtoui64(str.c_str(), &end, 10);
1424 typedef unsigned long long BiggestConvertible; // NOLINT
1425 const BiggestConvertible parsed = strtoull(str.c_str(), &end, 10);
1426 #endif // GTEST_OS_WINDOWS && !defined(__GNUC__)
1427 const bool parse_success = *end == '\0' && errno == 0;
1429 // TODO(vladl@google.com): Convert this to compile time assertion when it is
1431 GTEST_CHECK_(sizeof(Integer) <= sizeof(parsed));
1433 const Integer result = static_cast<Integer>(parsed);
1434 if (parse_success && static_cast<BiggestConvertible>(result) == parsed) {
1440 #endif // GTEST_HAS_DEATH_TEST
1442 // TestResult contains some private methods that should be hidden from
1443 // Google Test user but are required for testing. This class allow our tests
1446 // This class is supplied only for the purpose of testing Google Test's own
1447 // constructs. Do not use it in user tests, either directly or indirectly.
1448 class TestResultAccessor {
1450 static void RecordProperty(TestResult* test_result,
1451 const TestProperty& property) {
1452 test_result->RecordProperty(property);
1455 static void ClearTestPartResults(TestResult* test_result) {
1456 test_result->ClearTestPartResults();
1459 static const std::vector<testing::TestPartResult>& test_part_results(
1460 const TestResult& test_result) {
1461 return test_result.test_part_results();
1465 } // namespace internal
1466 } // namespace testing
1468 #endif // GTEST_SRC_GTEST_INTERNAL_INL_H_
1469 #undef GTEST_IMPLEMENTATION_
1471 #if GTEST_OS_WINDOWS
1472 #define vsnprintf _vsnprintf
1473 #endif // GTEST_OS_WINDOWS
1477 using internal::CountIf;
1478 using internal::ForEach;
1479 using internal::GetElementOr;
1480 using internal::Shuffle;
1484 // A test whose test case name or test name matches this filter is
1485 // disabled and not run.
1486 static const char kDisableTestFilter[] = "DISABLED_*:*/DISABLED_*";
1488 // A test case whose name matches this filter is considered a death
1489 // test case and will be run before test cases whose name doesn't
1490 // match this filter.
1491 static const char kDeathTestCaseFilter[] = "*DeathTest:*DeathTest/*";
1493 // A test filter that matches everything.
1494 static const char kUniversalFilter[] = "*";
1496 // The default output file for XML output.
1497 static const char kDefaultOutputFile[] = "test_detail.xml";
1499 // The environment variable name for the test shard index.
1500 static const char kTestShardIndex[] = "GTEST_SHARD_INDEX";
1501 // The environment variable name for the total number of test shards.
1502 static const char kTestTotalShards[] = "GTEST_TOTAL_SHARDS";
1503 // The environment variable name for the test shard status file.
1504 static const char kTestShardStatusFile[] = "GTEST_SHARD_STATUS_FILE";
1506 namespace internal {
1508 // The text used in failure messages to indicate the start of the
1510 const char kStackTraceMarker[] = "\nStack trace:\n";
1512 // g_help_flag is true iff the --help flag or an equivalent form is
1513 // specified on the command line.
1514 bool g_help_flag = false;
1516 } // namespace internal
1519 also_run_disabled_tests,
1520 internal::BoolFromGTestEnv("also_run_disabled_tests", false),
1521 "Run disabled tests too, in addition to the tests normally being run.");
1525 internal::BoolFromGTestEnv("break_on_failure", false),
1526 "True iff a failed assertion should be a debugger break-point.");
1530 internal::BoolFromGTestEnv("catch_exceptions", false),
1531 "True iff " GTEST_NAME_
1532 " should catch exceptions and treat them as test failures.");
1534 GTEST_DEFINE_string_(
1536 internal::StringFromGTestEnv("color", "auto"),
1537 "Whether to use colors in the output. Valid values: yes, no, "
1538 "and auto. 'auto' means to use colors if the output is "
1539 "being sent to a terminal and the TERM environment variable "
1540 "is set to xterm, xterm-color, xterm-256color, linux or cygwin.");
1542 GTEST_DEFINE_string_(
1544 internal::StringFromGTestEnv("filter", kUniversalFilter),
1545 "A colon-separated list of glob (not regex) patterns "
1546 "for filtering the tests to run, optionally followed by a "
1547 "'-' and a : separated list of negative patterns (tests to "
1548 "exclude). A test is run if it matches one of the positive "
1549 "patterns and does not match any of the negative patterns.");
1551 GTEST_DEFINE_bool_(list_tests, false,
1552 "List all tests without running them.");
1554 GTEST_DEFINE_string_(
1556 internal::StringFromGTestEnv("output", ""),
1557 "A format (currently must be \"xml\"), optionally followed "
1558 "by a colon and an output file name or directory. A directory "
1559 "is indicated by a trailing pathname separator. "
1560 "Examples: \"xml:filename.xml\", \"xml::directoryname/\". "
1561 "If a directory is specified, output files will be created "
1562 "within that directory, with file-names based on the test "
1563 "executable's name and, if necessary, made unique by adding "
1568 internal::BoolFromGTestEnv("print_time", true),
1569 "True iff " GTEST_NAME_
1570 " should display elapsed time in text output.");
1572 GTEST_DEFINE_int32_(
1574 internal::Int32FromGTestEnv("random_seed", 0),
1575 "Random number seed to use when shuffling test orders. Must be in range "
1576 "[1, 99999], or 0 to use a seed based on the current time.");
1578 GTEST_DEFINE_int32_(
1580 internal::Int32FromGTestEnv("repeat", 1),
1581 "How many times to repeat each test. Specify a negative number "
1582 "for repeating forever. Useful for shaking out flaky tests.");
1585 show_internal_stack_frames, false,
1586 "True iff " GTEST_NAME_ " should include internal stack frames when "
1587 "printing test failure stack traces.");
1591 internal::BoolFromGTestEnv("shuffle", false),
1592 "True iff " GTEST_NAME_
1593 " should randomize tests' order on every run.");
1595 GTEST_DEFINE_int32_(
1597 internal::Int32FromGTestEnv("stack_trace_depth", kMaxStackTraceDepth),
1598 "The maximum number of stack frames to print when an "
1599 "assertion fails. The valid range is 0 through 100, inclusive.");
1603 internal::BoolFromGTestEnv("throw_on_failure", false),
1604 "When this flag is specified, a failed assertion will throw an exception "
1605 "if exceptions are enabled or exit the program with a non-zero code "
1608 namespace internal {
1610 // Generates a random number from [0, range), using a Linear
1611 // Congruential Generator (LCG). Crashes if 'range' is 0 or greater
1613 UInt32 Random::Generate(UInt32 range) {
1614 // These constants are the same as are used in glibc's rand(3).
1615 state_ = (1103515245U*state_ + 12345U) % kMaxRange;
1617 GTEST_CHECK_(range > 0)
1618 << "Cannot generate a number in the range [0, 0).";
1619 GTEST_CHECK_(range <= kMaxRange)
1620 << "Generation of a number in [0, " << range << ") was requested, "
1621 << "but this can only generate numbers in [0, " << kMaxRange << ").";
1623 // Converting via modulus introduces a bit of downward bias, but
1624 // it's simple, and a linear congruential generator isn't too good
1626 return state_ % range;
1629 // GTestIsInitialized() returns true iff the user has initialized
1630 // Google Test. Useful for catching the user mistake of not initializing
1631 // Google Test before calling RUN_ALL_TESTS().
1633 // A user must call testing::InitGoogleTest() to initialize Google
1634 // Test. g_init_gtest_count is set to the number of times
1635 // InitGoogleTest() has been called. We don't protect this variable
1636 // under a mutex as it is only accessed in the main thread.
1637 int g_init_gtest_count = 0;
1638 static bool GTestIsInitialized() { return g_init_gtest_count != 0; }
1640 // Iterates over a vector of TestCases, keeping a running sum of the
1641 // results of calling a given int-returning method on each.
1643 static int SumOverTestCaseList(const std::vector<TestCase*>& case_list,
1644 int (TestCase::*method)() const) {
1646 for (size_t i = 0; i < case_list.size(); i++) {
1647 sum += (case_list[i]->*method)();
1652 // Returns true iff the test case passed.
1653 static bool TestCasePassed(const TestCase* test_case) {
1654 return test_case->should_run() && test_case->Passed();
1657 // Returns true iff the test case failed.
1658 static bool TestCaseFailed(const TestCase* test_case) {
1659 return test_case->should_run() && test_case->Failed();
1662 // Returns true iff test_case contains at least one test that should
1664 static bool ShouldRunTestCase(const TestCase* test_case) {
1665 return test_case->should_run();
1668 // AssertHelper constructor.
1669 AssertHelper::AssertHelper(TestPartResult::Type type,
1672 const char* message)
1673 : data_(new AssertHelperData(type, file, line, message)) {
1676 AssertHelper::~AssertHelper() {
1680 // Message assignment, for assertion streaming support.
1681 void AssertHelper::operator=(const Message& message) const {
1682 UnitTest::GetInstance()->
1683 AddTestPartResult(data_->type, data_->file, data_->line,
1684 AppendUserMessage(data_->message, message),
1685 UnitTest::GetInstance()->impl()
1686 ->CurrentOsStackTraceExceptTop(1)
1687 // Skips the stack frame for this function itself.
1691 // Mutex for linked pointers.
1692 GTEST_DEFINE_STATIC_MUTEX_(g_linked_ptr_mutex);
1694 // Application pathname gotten in InitGoogleTest.
1695 String g_executable_path;
1697 // Returns the current application's name, removing directory path if that
1699 FilePath GetCurrentExecutableName() {
1702 #if GTEST_OS_WINDOWS
1703 result.Set(FilePath(g_executable_path).RemoveExtension("exe"));
1705 result.Set(FilePath(g_executable_path));
1706 #endif // GTEST_OS_WINDOWS
1708 return result.RemoveDirectoryName();
1711 // Functions for processing the gtest_output flag.
1713 // Returns the output format, or "" for normal printed output.
1714 String UnitTestOptions::GetOutputFormat() {
1715 const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
1716 if (gtest_output_flag == NULL) return String("");
1718 const char* const colon = strchr(gtest_output_flag, ':');
1719 return (colon == NULL) ?
1720 String(gtest_output_flag) :
1721 String(gtest_output_flag, colon - gtest_output_flag);
1724 // Returns the name of the requested output file, or the default if none
1725 // was explicitly specified.
1726 String UnitTestOptions::GetAbsolutePathToOutputFile() {
1727 const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
1728 if (gtest_output_flag == NULL)
1731 const char* const colon = strchr(gtest_output_flag, ':');
1733 return String(internal::FilePath::ConcatPaths(
1735 UnitTest::GetInstance()->original_working_dir()),
1736 internal::FilePath(kDefaultOutputFile)).ToString() );
1738 internal::FilePath output_name(colon + 1);
1739 if (!output_name.IsAbsolutePath())
1740 // TODO(wan@google.com): on Windows \some\path is not an absolute
1741 // path (as its meaning depends on the current drive), yet the
1742 // following logic for turning it into an absolute path is wrong.
1744 output_name = internal::FilePath::ConcatPaths(
1745 internal::FilePath(UnitTest::GetInstance()->original_working_dir()),
1746 internal::FilePath(colon + 1));
1748 if (!output_name.IsDirectory())
1749 return output_name.ToString();
1751 internal::FilePath result(internal::FilePath::GenerateUniqueFileName(
1752 output_name, internal::GetCurrentExecutableName(),
1753 GetOutputFormat().c_str()));
1754 return result.ToString();
1757 // Returns true iff the wildcard pattern matches the string. The
1758 // first ':' or '\0' character in pattern marks the end of it.
1760 // This recursive algorithm isn't very efficient, but is clear and
1761 // works well enough for matching test names, which are short.
1762 bool UnitTestOptions::PatternMatchesString(const char *pattern,
1766 case ':': // Either ':' or '\0' marks the end of the pattern.
1767 return *str == '\0';
1768 case '?': // Matches any single character.
1769 return *str != '\0' && PatternMatchesString(pattern + 1, str + 1);
1770 case '*': // Matches any string (possibly empty) of characters.
1771 return (*str != '\0' && PatternMatchesString(pattern, str + 1)) ||
1772 PatternMatchesString(pattern + 1, str);
1773 default: // Non-special character. Matches itself.
1774 return *pattern == *str &&
1775 PatternMatchesString(pattern + 1, str + 1);
1779 bool UnitTestOptions::MatchesFilter(const String& name, const char* filter) {
1780 const char *cur_pattern = filter;
1782 if (PatternMatchesString(cur_pattern, name.c_str())) {
1786 // Finds the next pattern in the filter.
1787 cur_pattern = strchr(cur_pattern, ':');
1789 // Returns if no more pattern can be found.
1790 if (cur_pattern == NULL) {
1794 // Skips the pattern separater (the ':' character).
1799 // TODO(keithray): move String function implementations to gtest-string.cc.
1801 // Returns true iff the user-specified filter matches the test case
1802 // name and the test name.
1803 bool UnitTestOptions::FilterMatchesTest(const String &test_case_name,
1804 const String &test_name) {
1805 const String& full_name = String::Format("%s.%s",
1806 test_case_name.c_str(),
1809 // Split --gtest_filter at '-', if there is one, to separate into
1810 // positive filter and negative filter portions
1811 const char* const p = GTEST_FLAG(filter).c_str();
1812 const char* const dash = strchr(p, '-');
1816 positive = GTEST_FLAG(filter).c_str(); // Whole string is a positive filter
1817 negative = String("");
1819 positive = String(p, dash - p); // Everything up to the dash
1820 negative = String(dash+1); // Everything after the dash
1821 if (positive.empty()) {
1822 // Treat '-test1' as the same as '*-test1'
1823 positive = kUniversalFilter;
1827 // A filter is a colon-separated list of patterns. It matches a
1828 // test if any pattern in it matches the test.
1829 return (MatchesFilter(full_name, positive.c_str()) &&
1830 !MatchesFilter(full_name, negative.c_str()));
1833 #if GTEST_OS_WINDOWS
1834 // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
1835 // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
1836 // This function is useful as an __except condition.
1837 int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) {
1838 // Google Test should handle an exception if:
1839 // 1. the user wants it to, AND
1840 // 2. this is not a breakpoint exception.
1841 return (GTEST_FLAG(catch_exceptions) &&
1842 exception_code != EXCEPTION_BREAKPOINT) ?
1843 EXCEPTION_EXECUTE_HANDLER :
1844 EXCEPTION_CONTINUE_SEARCH;
1846 #endif // GTEST_OS_WINDOWS
1848 } // namespace internal
1850 // The c'tor sets this object as the test part result reporter used by
1851 // Google Test. The 'result' parameter specifies where to report the
1852 // results. Intercepts only failures from the current thread.
1853 ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
1854 TestPartResultArray* result)
1855 : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD),
1860 // The c'tor sets this object as the test part result reporter used by
1861 // Google Test. The 'result' parameter specifies where to report the
1863 ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
1864 InterceptMode intercept_mode, TestPartResultArray* result)
1865 : intercept_mode_(intercept_mode),
1870 void ScopedFakeTestPartResultReporter::Init() {
1871 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
1872 if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
1873 old_reporter_ = impl->GetGlobalTestPartResultReporter();
1874 impl->SetGlobalTestPartResultReporter(this);
1876 old_reporter_ = impl->GetTestPartResultReporterForCurrentThread();
1877 impl->SetTestPartResultReporterForCurrentThread(this);
1881 // The d'tor restores the test part result reporter used by Google Test
1883 ScopedFakeTestPartResultReporter::~ScopedFakeTestPartResultReporter() {
1884 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
1885 if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
1886 impl->SetGlobalTestPartResultReporter(old_reporter_);
1888 impl->SetTestPartResultReporterForCurrentThread(old_reporter_);
1892 // Increments the test part result count and remembers the result.
1893 // This method is from the TestPartResultReporterInterface interface.
1894 void ScopedFakeTestPartResultReporter::ReportTestPartResult(
1895 const TestPartResult& result) {
1896 result_->Append(result);
1899 namespace internal {
1901 // Returns the type ID of ::testing::Test. We should always call this
1902 // instead of GetTypeId< ::testing::Test>() to get the type ID of
1903 // testing::Test. This is to work around a suspected linker bug when
1904 // using Google Test as a framework on Mac OS X. The bug causes
1905 // GetTypeId< ::testing::Test>() to return different values depending
1906 // on whether the call is from the Google Test framework itself or
1907 // from user test code. GetTestTypeId() is guaranteed to always
1908 // return the same value, as it always calls GetTypeId<>() from the
1909 // gtest.cc, which is within the Google Test framework.
1910 TypeId GetTestTypeId() {
1911 return GetTypeId<Test>();
1914 // The value of GetTestTypeId() as seen from within the Google Test
1915 // library. This is solely for testing GetTestTypeId().
1916 extern const TypeId kTestTypeIdInGoogleTest = GetTestTypeId();
1918 // This predicate-formatter checks that 'results' contains a test part
1919 // failure of the given type and that the failure message contains the
1921 AssertionResult HasOneFailure(const char* /* results_expr */,
1922 const char* /* type_expr */,
1923 const char* /* substr_expr */,
1924 const TestPartResultArray& results,
1925 TestPartResult::Type type,
1926 const char* substr) {
1927 const String expected(type == TestPartResult::kFatalFailure ?
1929 "1 non-fatal failure");
1931 if (results.size() != 1) {
1932 msg << "Expected: " << expected << "\n"
1933 << " Actual: " << results.size() << " failures";
1934 for (int i = 0; i < results.size(); i++) {
1935 msg << "\n" << results.GetTestPartResult(i);
1937 return AssertionFailure(msg);
1940 const TestPartResult& r = results.GetTestPartResult(0);
1941 if (r.type() != type) {
1942 msg << "Expected: " << expected << "\n"
1945 return AssertionFailure(msg);
1948 if (strstr(r.message(), substr) == NULL) {
1949 msg << "Expected: " << expected << " containing \""
1953 return AssertionFailure(msg);
1956 return AssertionSuccess();
1959 // The constructor of SingleFailureChecker remembers where to look up
1960 // test part results, what type of failure we expect, and what
1961 // substring the failure message should contain.
1962 SingleFailureChecker:: SingleFailureChecker(
1963 const TestPartResultArray* results,
1964 TestPartResult::Type type,
1966 : results_(results),
1970 // The destructor of SingleFailureChecker verifies that the given
1971 // TestPartResultArray contains exactly one failure that has the given
1972 // type and contains the given substring. If that's not the case, a
1973 // non-fatal failure will be generated.
1974 SingleFailureChecker::~SingleFailureChecker() {
1975 EXPECT_PRED_FORMAT3(HasOneFailure, *results_, type_, substr_.c_str());
1978 DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter(
1979 UnitTestImpl* unit_test) : unit_test_(unit_test) {}
1981 void DefaultGlobalTestPartResultReporter::ReportTestPartResult(
1982 const TestPartResult& result) {
1983 unit_test_->current_test_result()->AddTestPartResult(result);
1984 unit_test_->listeners()->repeater()->OnTestPartResult(result);
1987 DefaultPerThreadTestPartResultReporter::DefaultPerThreadTestPartResultReporter(
1988 UnitTestImpl* unit_test) : unit_test_(unit_test) {}
1990 void DefaultPerThreadTestPartResultReporter::ReportTestPartResult(
1991 const TestPartResult& result) {
1992 unit_test_->GetGlobalTestPartResultReporter()->ReportTestPartResult(result);
1995 // Returns the global test part result reporter.
1996 TestPartResultReporterInterface*
1997 UnitTestImpl::GetGlobalTestPartResultReporter() {
1998 internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
1999 return global_test_part_result_repoter_;
2002 // Sets the global test part result reporter.
2003 void UnitTestImpl::SetGlobalTestPartResultReporter(
2004 TestPartResultReporterInterface* reporter) {
2005 internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
2006 global_test_part_result_repoter_ = reporter;
2009 // Returns the test part result reporter for the current thread.
2010 TestPartResultReporterInterface*
2011 UnitTestImpl::GetTestPartResultReporterForCurrentThread() {
2012 return per_thread_test_part_result_reporter_.get();
2015 // Sets the test part result reporter for the current thread.
2016 void UnitTestImpl::SetTestPartResultReporterForCurrentThread(
2017 TestPartResultReporterInterface* reporter) {
2018 per_thread_test_part_result_reporter_.set(reporter);
2021 // Gets the number of successful test cases.
2022 int UnitTestImpl::successful_test_case_count() const {
2023 return CountIf(test_cases_, TestCasePassed);
2026 // Gets the number of failed test cases.
2027 int UnitTestImpl::failed_test_case_count() const {
2028 return CountIf(test_cases_, TestCaseFailed);
2031 // Gets the number of all test cases.
2032 int UnitTestImpl::total_test_case_count() const {
2033 return static_cast<int>(test_cases_.size());
2036 // Gets the number of all test cases that contain at least one test
2038 int UnitTestImpl::test_case_to_run_count() const {
2039 return CountIf(test_cases_, ShouldRunTestCase);
2042 // Gets the number of successful tests.
2043 int UnitTestImpl::successful_test_count() const {
2044 return SumOverTestCaseList(test_cases_, &TestCase::successful_test_count);
2047 // Gets the number of failed tests.
2048 int UnitTestImpl::failed_test_count() const {
2049 return SumOverTestCaseList(test_cases_, &TestCase::failed_test_count);
2052 // Gets the number of disabled tests.
2053 int UnitTestImpl::disabled_test_count() const {
2054 return SumOverTestCaseList(test_cases_, &TestCase::disabled_test_count);
2057 // Gets the number of all tests.
2058 int UnitTestImpl::total_test_count() const {
2059 return SumOverTestCaseList(test_cases_, &TestCase::total_test_count);
2062 // Gets the number of tests that should run.
2063 int UnitTestImpl::test_to_run_count() const {
2064 return SumOverTestCaseList(test_cases_, &TestCase::test_to_run_count);
2067 // Returns the current OS stack trace as a String.
2069 // The maximum number of stack frames to be included is specified by
2070 // the gtest_stack_trace_depth flag. The skip_count parameter
2071 // specifies the number of top frames to be skipped, which doesn't
2072 // count against the number of frames to be included.
2074 // For example, if Foo() calls Bar(), which in turn calls
2075 // CurrentOsStackTraceExceptTop(1), Foo() will be included in the
2076 // trace but Bar() and CurrentOsStackTraceExceptTop() won't.
2077 String UnitTestImpl::CurrentOsStackTraceExceptTop(int skip_count) {
2082 // Returns the current time in milliseconds.
2083 TimeInMillis GetTimeInMillis() {
2084 #if GTEST_OS_WINDOWS_MOBILE || defined(__BORLANDC__)
2085 // Difference between 1970-01-01 and 1601-01-01 in milliseconds.
2086 // http://analogous.blogspot.com/2005/04/epoch.html
2087 const TimeInMillis kJavaEpochToWinFileTimeDelta =
2088 static_cast<TimeInMillis>(116444736UL) * 100000UL;
2089 const DWORD kTenthMicrosInMilliSecond = 10000;
2091 SYSTEMTIME now_systime;
2092 FILETIME now_filetime;
2093 ULARGE_INTEGER now_int64;
2094 // TODO(kenton@google.com): Shouldn't this just use
2095 // GetSystemTimeAsFileTime()?
2096 GetSystemTime(&now_systime);
2097 if (SystemTimeToFileTime(&now_systime, &now_filetime)) {
2098 now_int64.LowPart = now_filetime.dwLowDateTime;
2099 now_int64.HighPart = now_filetime.dwHighDateTime;
2100 now_int64.QuadPart = (now_int64.QuadPart / kTenthMicrosInMilliSecond) -
2101 kJavaEpochToWinFileTimeDelta;
2102 return now_int64.QuadPart;
2105 #elif GTEST_OS_WINDOWS && !GTEST_HAS_GETTIMEOFDAY_
2108 // MSVC 8 deprecates _ftime64(), so we want to suppress warning 4996
2109 // (deprecated function) there.
2110 // TODO(kenton@google.com): Use GetTickCount()? Or use
2111 // SystemTimeToFileTime()
2112 #pragma warning(push) // Saves the current warning state.
2113 #pragma warning(disable:4996) // Temporarily disables warning 4996.
2115 #pragma warning(pop) // Restores the warning state.
2119 return static_cast<TimeInMillis>(now.time) * 1000 + now.millitm;
2120 #elif GTEST_HAS_GETTIMEOFDAY_
2122 gettimeofday(&now, NULL);
2123 return static_cast<TimeInMillis>(now.tv_sec) * 1000 + now.tv_usec / 1000;
2125 #error "Don't know how to get the current time on your system."
2133 // Returns the input enclosed in double quotes if it's not NULL;
2134 // otherwise returns "(null)". For example, "\"Hello\"" is returned
2135 // for input "Hello".
2137 // This is useful for printing a C string in the syntax of a literal.
2139 // Known issue: escape sequences are not handled yet.
2140 String String::ShowCStringQuoted(const char* c_str) {
2141 return c_str ? String::Format("\"%s\"", c_str) : String("(null)");
2144 // Copies at most length characters from str into a newly-allocated
2145 // piece of memory of size length+1. The memory is allocated with new[].
2146 // A terminating null byte is written to the memory, and a pointer to it
2147 // is returned. If str is NULL, NULL is returned.
2148 static char* CloneString(const char* str, size_t length) {
2152 char* const clone = new char[length + 1];
2153 posix::StrNCpy(clone, str, length);
2154 clone[length] = '\0';
2159 // Clones a 0-terminated C string, allocating memory using new. The
2160 // caller is responsible for deleting[] the return value. Returns the
2161 // cloned string, or NULL if the input is NULL.
2162 const char * String::CloneCString(const char* c_str) {
2163 return (c_str == NULL) ?
2164 NULL : CloneString(c_str, strlen(c_str));
2167 #if GTEST_OS_WINDOWS_MOBILE
2168 // Creates a UTF-16 wide string from the given ANSI string, allocating
2169 // memory using new. The caller is responsible for deleting the return
2170 // value using delete[]. Returns the wide string, or NULL if the
2172 LPCWSTR String::AnsiToUtf16(const char* ansi) {
2173 if (!ansi) return NULL;
2174 const int length = strlen(ansi);
2175 const int unicode_length =
2176 MultiByteToWideChar(CP_ACP, 0, ansi, length,
2178 WCHAR* unicode = new WCHAR[unicode_length + 1];
2179 MultiByteToWideChar(CP_ACP, 0, ansi, length,
2180 unicode, unicode_length);
2181 unicode[unicode_length] = 0;
2185 // Creates an ANSI string from the given wide string, allocating
2186 // memory using new. The caller is responsible for deleting the return
2187 // value using delete[]. Returns the ANSI string, or NULL if the
2189 const char* String::Utf16ToAnsi(LPCWSTR utf16_str) {
2190 if (!utf16_str) return NULL;
2191 const int ansi_length =
2192 WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
2193 NULL, 0, NULL, NULL);
2194 char* ansi = new char[ansi_length + 1];
2195 WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
2196 ansi, ansi_length, NULL, NULL);
2197 ansi[ansi_length] = 0;
2201 #endif // GTEST_OS_WINDOWS_MOBILE
2203 // Compares two C strings. Returns true iff they have the same content.
2205 // Unlike strcmp(), this function can handle NULL argument(s). A NULL
2206 // C string is considered different to any non-NULL C string,
2207 // including the empty string.
2208 bool String::CStringEquals(const char * lhs, const char * rhs) {
2209 if ( lhs == NULL ) return rhs == NULL;
2211 if ( rhs == NULL ) return false;
2213 return strcmp(lhs, rhs) == 0;
2216 #if GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
2218 // Converts an array of wide chars to a narrow string using the UTF-8
2219 // encoding, and streams the result to the given Message object.
2220 static void StreamWideCharsToMessage(const wchar_t* wstr, size_t length,
2222 // TODO(wan): consider allowing a testing::String object to
2223 // contain '\0'. This will make it behave more like std::string,
2224 // and will allow ToUtf8String() to return the correct encoding
2225 // for '\0' s.t. we can get rid of the conditional here (and in
2226 // several other places).
2227 for (size_t i = 0; i != length; ) { // NOLINT
2228 if (wstr[i] != L'\0') {
2229 *msg << WideStringToUtf8(wstr + i, static_cast<int>(length - i));
2230 while (i != length && wstr[i] != L'\0')
2239 #endif // GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
2241 } // namespace internal
2243 #if GTEST_HAS_STD_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 ::std::wstring& wstr) {
2247 internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
2250 #endif // GTEST_HAS_STD_WSTRING
2252 #if GTEST_HAS_GLOBAL_WSTRING
2253 // Converts the given wide string to a narrow string using the UTF-8
2254 // encoding, and streams the result to this Message object.
2255 Message& Message::operator <<(const ::wstring& wstr) {
2256 internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
2259 #endif // GTEST_HAS_GLOBAL_WSTRING
2261 namespace internal {
2263 // Formats a value to be used in a failure message.
2265 // For a char value, we print it as a C++ char literal and as an
2266 // unsigned integer (both in decimal and in hexadecimal).
2267 String FormatForFailureMessage(char ch) {
2268 const unsigned int ch_as_uint = ch;
2269 // A String object cannot contain '\0', so we print "\\0" when ch is
2271 return String::Format("'%s' (%u, 0x%X)",
2272 ch ? String::Format("%c", ch).c_str() : "\\0",
2273 ch_as_uint, ch_as_uint);
2276 // For a wchar_t value, we print it as a C++ wchar_t literal and as an
2277 // unsigned integer (both in decimal and in hexidecimal).
2278 String FormatForFailureMessage(wchar_t wchar) {
2279 // The C++ standard doesn't specify the exact size of the wchar_t
2280 // type. It just says that it shall have the same size as another
2281 // integral type, called its underlying type.
2283 // Therefore, in order to print a wchar_t value in the numeric form,
2284 // we first convert it to the largest integral type (UInt64) and
2285 // then print the converted value.
2287 // We use streaming to print the value as "%llu" doesn't work
2288 // correctly with MSVC 7.1.
2289 const UInt64 wchar_as_uint64 = wchar;
2291 // A String object cannot contain '\0', so we print "\\0" when wchar is
2293 char buffer[32]; // CodePointToUtf8 requires a buffer that big.
2295 << (wchar ? CodePointToUtf8(static_cast<UInt32>(wchar), buffer) : "\\0")
2296 << "' (" << wchar_as_uint64 << ", 0x" << ::std::setbase(16)
2297 << wchar_as_uint64 << ")";
2298 return msg.GetString();
2301 } // namespace internal
2303 // AssertionResult constructors.
2304 // Used in EXPECT_TRUE/FALSE(assertion_result).
2305 AssertionResult::AssertionResult(const AssertionResult& other)
2306 : success_(other.success_),
2307 message_(other.message_.get() != NULL ?
2308 new internal::String(*other.message_) :
2309 static_cast<internal::String*>(NULL)) {
2312 // Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE.
2313 AssertionResult AssertionResult::operator!() const {
2314 AssertionResult negation(!success_);
2315 if (message_.get() != NULL)
2316 negation << *message_;
2320 // Makes a successful assertion result.
2321 AssertionResult AssertionSuccess() {
2322 return AssertionResult(true);
2325 // Makes a failed assertion result.
2326 AssertionResult AssertionFailure() {
2327 return AssertionResult(false);
2330 // Makes a failed assertion result with the given failure message.
2331 // Deprecated; use AssertionFailure() << message.
2332 AssertionResult AssertionFailure(const Message& message) {
2333 return AssertionFailure() << message;
2336 namespace internal {
2338 // Constructs and returns the message for an equality assertion
2339 // (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure.
2341 // The first four parameters are the expressions used in the assertion
2342 // and their values, as strings. For example, for ASSERT_EQ(foo, bar)
2343 // where foo is 5 and bar is 6, we have:
2345 // expected_expression: "foo"
2346 // actual_expression: "bar"
2347 // expected_value: "5"
2348 // actual_value: "6"
2350 // The ignoring_case parameter is true iff the assertion is a
2351 // *_STRCASEEQ*. When it's true, the string " (ignoring case)" will
2352 // be inserted into the message.
2353 AssertionResult EqFailure(const char* expected_expression,
2354 const char* actual_expression,
2355 const String& expected_value,
2356 const String& actual_value,
2357 bool ignoring_case) {
2359 msg << "Value of: " << actual_expression;
2360 if (actual_value != actual_expression) {
2361 msg << "\n Actual: " << actual_value;
2364 msg << "\nExpected: " << expected_expression;
2365 if (ignoring_case) {
2366 msg << " (ignoring case)";
2368 if (expected_value != expected_expression) {
2369 msg << "\nWhich is: " << expected_value;
2372 return AssertionFailure(msg);
2375 // Constructs a failure message for Boolean assertions such as EXPECT_TRUE.
2376 String GetBoolAssertionFailureMessage(const AssertionResult& assertion_result,
2377 const char* expression_text,
2378 const char* actual_predicate_value,
2379 const char* expected_predicate_value) {
2380 const char* actual_message = assertion_result.message();
2382 msg << "Value of: " << expression_text
2383 << "\n Actual: " << actual_predicate_value;
2384 if (actual_message[0] != '\0')
2385 msg << " (" << actual_message << ")";
2386 msg << "\nExpected: " << expected_predicate_value;
2387 return msg.GetString();
2390 // Helper function for implementing ASSERT_NEAR.
2391 AssertionResult DoubleNearPredFormat(const char* expr1,
2393 const char* abs_error_expr,
2397 const double diff = fabs(val1 - val2);
2398 if (diff <= abs_error) return AssertionSuccess();
2400 // TODO(wan): do not print the value of an expression if it's
2401 // already a literal.
2403 msg << "The difference between " << expr1 << " and " << expr2
2404 << " is " << diff << ", which exceeds " << abs_error_expr << ", where\n"
2405 << expr1 << " evaluates to " << val1 << ",\n"
2406 << expr2 << " evaluates to " << val2 << ", and\n"
2407 << abs_error_expr << " evaluates to " << abs_error << ".";
2408 return AssertionFailure(msg);
2412 // Helper template for implementing FloatLE() and DoubleLE().
2413 template <typename RawType>
2414 AssertionResult FloatingPointLE(const char* expr1,
2418 // Returns success if val1 is less than val2,
2420 return AssertionSuccess();
2423 // or if val1 is almost equal to val2.
2424 const FloatingPoint<RawType> lhs(val1), rhs(val2);
2425 if (lhs.AlmostEquals(rhs)) {
2426 return AssertionSuccess();
2429 // Note that the above two checks will both fail if either val1 or
2430 // val2 is NaN, as the IEEE floating-point standard requires that
2431 // any predicate involving a NaN must return false.
2434 val1_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
2438 val2_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
2442 msg << "Expected: (" << expr1 << ") <= (" << expr2 << ")\n"
2443 << " Actual: " << StrStreamToString(&val1_ss) << " vs "
2444 << StrStreamToString(&val2_ss);
2446 return AssertionFailure(msg);
2449 } // namespace internal
2451 // Asserts that val1 is less than, or almost equal to, val2. Fails
2452 // otherwise. In particular, it fails if either val1 or val2 is NaN.
2453 AssertionResult FloatLE(const char* expr1, const char* expr2,
2454 float val1, float val2) {
2455 return internal::FloatingPointLE<float>(expr1, expr2, val1, val2);
2458 // Asserts that val1 is less than, or almost equal to, val2. Fails
2459 // otherwise. In particular, it fails if either val1 or val2 is NaN.
2460 AssertionResult DoubleLE(const char* expr1, const char* expr2,
2461 double val1, double val2) {
2462 return internal::FloatingPointLE<double>(expr1, expr2, val1, val2);
2465 namespace internal {
2467 // The helper function for {ASSERT|EXPECT}_EQ with int or enum
2469 AssertionResult CmpHelperEQ(const char* expected_expression,
2470 const char* actual_expression,
2471 BiggestInt expected,
2472 BiggestInt actual) {
2473 if (expected == actual) {
2474 return AssertionSuccess();
2477 return EqFailure(expected_expression,
2479 FormatForComparisonFailureMessage(expected, actual),
2480 FormatForComparisonFailureMessage(actual, expected),
2484 // A macro for implementing the helper functions needed to implement
2485 // ASSERT_?? and EXPECT_?? with integer or enum arguments. It is here
2486 // just to avoid copy-and-paste of similar code.
2487 #define GTEST_IMPL_CMP_HELPER_(op_name, op)\
2488 AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \
2489 BiggestInt val1, BiggestInt val2) {\
2490 if (val1 op val2) {\
2491 return AssertionSuccess();\
2494 msg << "Expected: (" << expr1 << ") " #op " (" << expr2\
2495 << "), actual: " << FormatForComparisonFailureMessage(val1, val2)\
2496 << " vs " << FormatForComparisonFailureMessage(val2, val1);\
2497 return AssertionFailure(msg);\
2501 // Implements the helper function for {ASSERT|EXPECT}_NE with int or
2503 GTEST_IMPL_CMP_HELPER_(NE, !=)
2504 // Implements the helper function for {ASSERT|EXPECT}_LE with int or
2506 GTEST_IMPL_CMP_HELPER_(LE, <=)
2507 // Implements the helper function for {ASSERT|EXPECT}_LT with int or
2509 GTEST_IMPL_CMP_HELPER_(LT, < )
2510 // Implements the helper function for {ASSERT|EXPECT}_GE with int or
2512 GTEST_IMPL_CMP_HELPER_(GE, >=)
2513 // Implements the helper function for {ASSERT|EXPECT}_GT with int or
2515 GTEST_IMPL_CMP_HELPER_(GT, > )
2517 #undef GTEST_IMPL_CMP_HELPER_
2519 // The helper function for {ASSERT|EXPECT}_STREQ.
2520 AssertionResult CmpHelperSTREQ(const char* expected_expression,
2521 const char* actual_expression,
2522 const char* expected,
2523 const char* actual) {
2524 if (String::CStringEquals(expected, actual)) {
2525 return AssertionSuccess();
2528 return EqFailure(expected_expression,
2530 String::ShowCStringQuoted(expected),
2531 String::ShowCStringQuoted(actual),
2535 // The helper function for {ASSERT|EXPECT}_STRCASEEQ.
2536 AssertionResult CmpHelperSTRCASEEQ(const char* expected_expression,
2537 const char* actual_expression,
2538 const char* expected,
2539 const char* actual) {
2540 if (String::CaseInsensitiveCStringEquals(expected, actual)) {
2541 return AssertionSuccess();
2544 return EqFailure(expected_expression,
2546 String::ShowCStringQuoted(expected),
2547 String::ShowCStringQuoted(actual),
2551 // The helper function for {ASSERT|EXPECT}_STRNE.
2552 AssertionResult CmpHelperSTRNE(const char* s1_expression,
2553 const char* s2_expression,
2556 if (!String::CStringEquals(s1, s2)) {
2557 return AssertionSuccess();
2560 msg << "Expected: (" << s1_expression << ") != ("
2561 << s2_expression << "), actual: \""
2562 << s1 << "\" vs \"" << s2 << "\"";
2563 return AssertionFailure(msg);
2567 // The helper function for {ASSERT|EXPECT}_STRCASENE.
2568 AssertionResult CmpHelperSTRCASENE(const char* s1_expression,
2569 const char* s2_expression,
2572 if (!String::CaseInsensitiveCStringEquals(s1, s2)) {
2573 return AssertionSuccess();
2576 msg << "Expected: (" << s1_expression << ") != ("
2577 << s2_expression << ") (ignoring case), actual: \""
2578 << s1 << "\" vs \"" << s2 << "\"";
2579 return AssertionFailure(msg);
2583 } // namespace internal
2587 // Helper functions for implementing IsSubString() and IsNotSubstring().
2589 // This group of overloaded functions return true iff needle is a
2590 // substring of haystack. NULL is considered a substring of itself
2593 bool IsSubstringPred(const char* needle, const char* haystack) {
2594 if (needle == NULL || haystack == NULL)
2595 return needle == haystack;
2597 return strstr(haystack, needle) != NULL;
2600 bool IsSubstringPred(const wchar_t* needle, const wchar_t* haystack) {
2601 if (needle == NULL || haystack == NULL)
2602 return needle == haystack;
2604 return wcsstr(haystack, needle) != NULL;
2607 // StringType here can be either ::std::string or ::std::wstring.
2608 template <typename StringType>
2609 bool IsSubstringPred(const StringType& needle,
2610 const StringType& haystack) {
2611 return haystack.find(needle) != StringType::npos;
2614 // This function implements either IsSubstring() or IsNotSubstring(),
2615 // depending on the value of the expected_to_be_substring parameter.
2616 // StringType here can be const char*, const wchar_t*, ::std::string,
2617 // or ::std::wstring.
2618 template <typename StringType>
2619 AssertionResult IsSubstringImpl(
2620 bool expected_to_be_substring,
2621 const char* needle_expr, const char* haystack_expr,
2622 const StringType& needle, const StringType& haystack) {
2623 if (IsSubstringPred(needle, haystack) == expected_to_be_substring)
2624 return AssertionSuccess();
2626 const bool is_wide_string = sizeof(needle[0]) > 1;
2627 const char* const begin_string_quote = is_wide_string ? "L\"" : "\"";
2628 return AssertionFailure(
2630 << "Value of: " << needle_expr << "\n"
2631 << " Actual: " << begin_string_quote << needle << "\"\n"
2632 << "Expected: " << (expected_to_be_substring ? "" : "not ")
2633 << "a substring of " << haystack_expr << "\n"
2634 << "Which is: " << begin_string_quote << haystack << "\"");
2639 // IsSubstring() and IsNotSubstring() check whether needle is a
2640 // substring of haystack (NULL is considered a substring of itself
2641 // only), and return an appropriate error message when they fail.
2643 AssertionResult IsSubstring(
2644 const char* needle_expr, const char* haystack_expr,
2645 const char* needle, const char* haystack) {
2646 return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
2649 AssertionResult IsSubstring(
2650 const char* needle_expr, const char* haystack_expr,
2651 const wchar_t* needle, const wchar_t* haystack) {
2652 return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
2655 AssertionResult IsNotSubstring(
2656 const char* needle_expr, const char* haystack_expr,
2657 const char* needle, const char* haystack) {
2658 return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
2661 AssertionResult IsNotSubstring(
2662 const char* needle_expr, const char* haystack_expr,
2663 const wchar_t* needle, const wchar_t* haystack) {
2664 return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
2667 AssertionResult IsSubstring(
2668 const char* needle_expr, const char* haystack_expr,
2669 const ::std::string& needle, const ::std::string& haystack) {
2670 return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
2673 AssertionResult IsNotSubstring(
2674 const char* needle_expr, const char* haystack_expr,
2675 const ::std::string& needle, const ::std::string& haystack) {
2676 return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
2679 #if GTEST_HAS_STD_WSTRING
2680 AssertionResult IsSubstring(
2681 const char* needle_expr, const char* haystack_expr,
2682 const ::std::wstring& needle, const ::std::wstring& haystack) {
2683 return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
2686 AssertionResult IsNotSubstring(
2687 const char* needle_expr, const char* haystack_expr,
2688 const ::std::wstring& needle, const ::std::wstring& haystack) {
2689 return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
2691 #endif // GTEST_HAS_STD_WSTRING
2693 namespace internal {
2695 #if GTEST_OS_WINDOWS
2699 // Helper function for IsHRESULT{SuccessFailure} predicates
2700 AssertionResult HRESULTFailureHelper(const char* expr,
2701 const char* expected,
2702 long hr) { // NOLINT
2703 #if GTEST_OS_WINDOWS_MOBILE
2704 // Windows CE doesn't support FormatMessage.
2705 const char error_text[] = "";
2707 // Looks up the human-readable system message for the HRESULT code
2708 // and since we're not passing any params to FormatMessage, we don't
2709 // want inserts expanded.
2710 const DWORD kFlags = FORMAT_MESSAGE_FROM_SYSTEM |
2711 FORMAT_MESSAGE_IGNORE_INSERTS;
2712 const DWORD kBufSize = 4096; // String::Format can't exceed this length.
2713 // Gets the system's human readable message string for this HRESULT.
2714 char error_text[kBufSize] = { '\0' };
2715 DWORD message_length = ::FormatMessageA(kFlags,
2716 0, // no source, we're asking system
2718 0, // no line width restrictions
2719 error_text, // output buffer
2720 kBufSize, // buf size
2721 NULL); // no arguments for inserts
2722 // Trims tailing white space (FormatMessage leaves a trailing cr-lf)
2723 for (; message_length && isspace(error_text[message_length - 1]);
2725 error_text[message_length - 1] = '\0';
2727 #endif // GTEST_OS_WINDOWS_MOBILE
2729 const String error_hex(String::Format("0x%08X ", hr));
2731 msg << "Expected: " << expr << " " << expected << ".\n"
2732 << " Actual: " << error_hex << error_text << "\n";
2734 return ::testing::AssertionFailure(msg);
2739 AssertionResult IsHRESULTSuccess(const char* expr, long hr) { // NOLINT
2740 if (SUCCEEDED(hr)) {
2741 return AssertionSuccess();
2743 return HRESULTFailureHelper(expr, "succeeds", hr);
2746 AssertionResult IsHRESULTFailure(const char* expr, long hr) { // NOLINT
2748 return AssertionSuccess();
2750 return HRESULTFailureHelper(expr, "fails", hr);
2753 #endif // GTEST_OS_WINDOWS
2755 // Utility functions for encoding Unicode text (wide strings) in
2758 // A Unicode code-point can have upto 21 bits, and is encoded in UTF-8
2761 // Code-point length Encoding
2762 // 0 - 7 bits 0xxxxxxx
2763 // 8 - 11 bits 110xxxxx 10xxxxxx
2764 // 12 - 16 bits 1110xxxx 10xxxxxx 10xxxxxx
2765 // 17 - 21 bits 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
2767 // The maximum code-point a one-byte UTF-8 sequence can represent.
2768 const UInt32 kMaxCodePoint1 = (static_cast<UInt32>(1) << 7) - 1;
2770 // The maximum code-point a two-byte UTF-8 sequence can represent.
2771 const UInt32 kMaxCodePoint2 = (static_cast<UInt32>(1) << (5 + 6)) - 1;
2773 // The maximum code-point a three-byte UTF-8 sequence can represent.
2774 const UInt32 kMaxCodePoint3 = (static_cast<UInt32>(1) << (4 + 2*6)) - 1;
2776 // The maximum code-point a four-byte UTF-8 sequence can represent.
2777 const UInt32 kMaxCodePoint4 = (static_cast<UInt32>(1) << (3 + 3*6)) - 1;
2779 // Chops off the n lowest bits from a bit pattern. Returns the n
2780 // lowest bits. As a side effect, the original bit pattern will be
2781 // shifted to the right by n bits.
2782 inline UInt32 ChopLowBits(UInt32* bits, int n) {
2783 const UInt32 low_bits = *bits & ((static_cast<UInt32>(1) << n) - 1);
2788 // Converts a Unicode code point to a narrow string in UTF-8 encoding.
2789 // code_point parameter is of type UInt32 because wchar_t may not be
2790 // wide enough to contain a code point.
2791 // The output buffer str must containt at least 32 characters.
2792 // The function returns the address of the output buffer.
2793 // If the code_point is not a valid Unicode code point
2794 // (i.e. outside of Unicode range U+0 to U+10FFFF) it will be output
2795 // as '(Invalid Unicode 0xXXXXXXXX)'.
2796 char* CodePointToUtf8(UInt32 code_point, char* str) {
2797 if (code_point <= kMaxCodePoint1) {
2799 str[0] = static_cast<char>(code_point); // 0xxxxxxx
2800 } else if (code_point <= kMaxCodePoint2) {
2802 str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
2803 str[0] = static_cast<char>(0xC0 | code_point); // 110xxxxx
2804 } else if (code_point <= kMaxCodePoint3) {
2806 str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
2807 str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
2808 str[0] = static_cast<char>(0xE0 | code_point); // 1110xxxx
2809 } else if (code_point <= kMaxCodePoint4) {
2811 str[3] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
2812 str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
2813 str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
2814 str[0] = static_cast<char>(0xF0 | code_point); // 11110xxx
2816 // The longest string String::Format can produce when invoked
2817 // with these parameters is 28 character long (not including
2818 // the terminating nul character). We are asking for 32 character
2819 // buffer just in case. This is also enough for strncpy to
2820 // null-terminate the destination string.
2822 str, String::Format("(Invalid Unicode 0x%X)", code_point).c_str(), 32);
2823 str[31] = '\0'; // Makes sure no change in the format to strncpy leaves
2824 // the result unterminated.
2829 // The following two functions only make sense if the the system
2830 // uses UTF-16 for wide string encoding. All supported systems
2831 // with 16 bit wchar_t (Windows, Cygwin, Symbian OS) do use UTF-16.
2833 // Determines if the arguments constitute UTF-16 surrogate pair
2834 // and thus should be combined into a single Unicode code point
2835 // using CreateCodePointFromUtf16SurrogatePair.
2836 inline bool IsUtf16SurrogatePair(wchar_t first, wchar_t second) {
2837 return sizeof(wchar_t) == 2 &&
2838 (first & 0xFC00) == 0xD800 && (second & 0xFC00) == 0xDC00;
2841 // Creates a Unicode code point from UTF16 surrogate pair.
2842 inline UInt32 CreateCodePointFromUtf16SurrogatePair(wchar_t first,
2844 const UInt32 mask = (1 << 10) - 1;
2845 return (sizeof(wchar_t) == 2) ?
2846 (((first & mask) << 10) | (second & mask)) + 0x10000 :
2847 // This function should not be called when the condition is
2848 // false, but we provide a sensible default in case it is.
2849 static_cast<UInt32>(first);
2852 // Converts a wide string to a narrow string in UTF-8 encoding.
2853 // The wide string is assumed to have the following encoding:
2854 // UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS)
2855 // UTF-32 if sizeof(wchar_t) == 4 (on Linux)
2856 // Parameter str points to a null-terminated wide string.
2857 // Parameter num_chars may additionally limit the number
2858 // of wchar_t characters processed. -1 is used when the entire string
2859 // should be processed.
2860 // If the string contains code points that are not valid Unicode code points
2861 // (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
2862 // as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
2863 // and contains invalid UTF-16 surrogate pairs, values in those pairs
2864 // will be encoded as individual Unicode characters from Basic Normal Plane.
2865 String WideStringToUtf8(const wchar_t* str, int num_chars) {
2866 if (num_chars == -1)
2867 num_chars = static_cast<int>(wcslen(str));
2870 for (int i = 0; i < num_chars; ++i) {
2871 UInt32 unicode_code_point;
2873 if (str[i] == L'\0') {
2875 } else if (i + 1 < num_chars && IsUtf16SurrogatePair(str[i], str[i + 1])) {
2876 unicode_code_point = CreateCodePointFromUtf16SurrogatePair(str[i],
2880 unicode_code_point = static_cast<UInt32>(str[i]);
2883 char buffer[32]; // CodePointToUtf8 requires a buffer this big.
2884 stream << CodePointToUtf8(unicode_code_point, buffer);
2886 return StrStreamToString(&stream);
2889 // Converts a wide C string to a String using the UTF-8 encoding.
2890 // NULL will be converted to "(null)".
2891 String String::ShowWideCString(const wchar_t * wide_c_str) {
2892 if (wide_c_str == NULL) return String("(null)");
2894 return String(internal::WideStringToUtf8(wide_c_str, -1).c_str());
2897 // Similar to ShowWideCString(), except that this function encloses
2898 // the converted string in double quotes.
2899 String String::ShowWideCStringQuoted(const wchar_t* wide_c_str) {
2900 if (wide_c_str == NULL) return String("(null)");
2902 return String::Format("L\"%s\"",
2903 String::ShowWideCString(wide_c_str).c_str());
2906 // Compares two wide C strings. Returns true iff they have the same
2909 // Unlike wcscmp(), this function can handle NULL argument(s). A NULL
2910 // C string is considered different to any non-NULL C string,
2911 // including the empty string.
2912 bool String::WideCStringEquals(const wchar_t * lhs, const wchar_t * rhs) {
2913 if (lhs == NULL) return rhs == NULL;
2915 if (rhs == NULL) return false;
2917 return wcscmp(lhs, rhs) == 0;
2920 // Helper function for *_STREQ on wide strings.
2921 AssertionResult CmpHelperSTREQ(const char* expected_expression,
2922 const char* actual_expression,
2923 const wchar_t* expected,
2924 const wchar_t* actual) {
2925 if (String::WideCStringEquals(expected, actual)) {
2926 return AssertionSuccess();
2929 return EqFailure(expected_expression,
2931 String::ShowWideCStringQuoted(expected),
2932 String::ShowWideCStringQuoted(actual),
2936 // Helper function for *_STRNE on wide strings.
2937 AssertionResult CmpHelperSTRNE(const char* s1_expression,
2938 const char* s2_expression,
2940 const wchar_t* s2) {
2941 if (!String::WideCStringEquals(s1, s2)) {
2942 return AssertionSuccess();
2946 msg << "Expected: (" << s1_expression << ") != ("
2947 << s2_expression << "), actual: "
2948 << String::ShowWideCStringQuoted(s1)
2949 << " vs " << String::ShowWideCStringQuoted(s2);
2950 return AssertionFailure(msg);
2953 // Compares two C strings, ignoring case. Returns true iff they have
2954 // the same content.
2956 // Unlike strcasecmp(), this function can handle NULL argument(s). A
2957 // NULL C string is considered different to any non-NULL C string,
2958 // including the empty string.
2959 bool String::CaseInsensitiveCStringEquals(const char * lhs, const char * rhs) {
2964 return posix::StrCaseCmp(lhs, rhs) == 0;
2967 // Compares two wide C strings, ignoring case. Returns true iff they
2968 // have the same content.
2970 // Unlike wcscasecmp(), this function can handle NULL argument(s).
2971 // A NULL C string is considered different to any non-NULL wide C string,
2972 // including the empty string.
2973 // NB: The implementations on different platforms slightly differ.
2974 // On windows, this method uses _wcsicmp which compares according to LC_CTYPE
2975 // environment variable. On GNU platform this method uses wcscasecmp
2976 // which compares according to LC_CTYPE category of the current locale.
2977 // On MacOS X, it uses towlower, which also uses LC_CTYPE category of the
2979 bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs,
2980 const wchar_t* rhs) {
2981 if ( lhs == NULL ) return rhs == NULL;
2983 if ( rhs == NULL ) return false;
2985 #if GTEST_OS_WINDOWS
2986 return _wcsicmp(lhs, rhs) == 0;
2987 #elif GTEST_OS_LINUX
2988 return wcscasecmp(lhs, rhs) == 0;
2990 // Mac OS X and Cygwin don't define wcscasecmp. Other unknown OSes
2991 // may not define it either.
2994 left = towlower(*lhs++);
2995 right = towlower(*rhs++);
2996 } while (left && left == right);
2997 return left == right;
2998 #endif // OS selector
3001 // Compares this with another String.
3002 // Returns < 0 if this is less than rhs, 0 if this is equal to rhs, or > 0
3003 // if this is greater than rhs.
3004 int String::Compare(const String & rhs) const {
3005 const char* const lhs_c_str = c_str();
3006 const char* const rhs_c_str = rhs.c_str();
3008 if (lhs_c_str == NULL) {
3009 return rhs_c_str == NULL ? 0 : -1; // NULL < anything except NULL
3010 } else if (rhs_c_str == NULL) {
3014 const size_t shorter_str_len =
3015 length() <= rhs.length() ? length() : rhs.length();
3016 for (size_t i = 0; i != shorter_str_len; i++) {
3017 if (lhs_c_str[i] < rhs_c_str[i]) {
3019 } else if (lhs_c_str[i] > rhs_c_str[i]) {
3023 return (length() < rhs.length()) ? -1 :
3024 (length() > rhs.length()) ? 1 : 0;
3027 // Returns true iff this String ends with the given suffix. *Any*
3028 // String is considered to end with a NULL or empty suffix.
3029 bool String::EndsWith(const char* suffix) const {
3030 if (suffix == NULL || CStringEquals(suffix, "")) return true;
3032 if (c_str() == NULL) return false;
3034 const size_t this_len = strlen(c_str());
3035 const size_t suffix_len = strlen(suffix);
3036 return (this_len >= suffix_len) &&
3037 CStringEquals(c_str() + this_len - suffix_len, suffix);
3040 // Returns true iff this String ends with the given suffix, ignoring case.
3041 // Any String is considered to end with a NULL or empty suffix.
3042 bool String::EndsWithCaseInsensitive(const char* suffix) const {
3043 if (suffix == NULL || CStringEquals(suffix, "")) return true;
3045 if (c_str() == NULL) return false;
3047 const size_t this_len = strlen(c_str());
3048 const size_t suffix_len = strlen(suffix);
3049 return (this_len >= suffix_len) &&
3050 CaseInsensitiveCStringEquals(c_str() + this_len - suffix_len, suffix);
3053 // Formats a list of arguments to a String, using the same format
3054 // spec string as for printf.
3056 // We do not use the StringPrintf class as it is not universally
3059 // The result is limited to 4096 characters (including the tailing 0).
3060 // If 4096 characters are not enough to format the input, or if
3061 // there's an error, "<formatting error or buffer exceeded>" is
3063 String String::Format(const char * format, ...) {
3065 va_start(args, format);
3068 const int kBufferSize = sizeof(buffer)/sizeof(buffer[0]);
3070 // MSVC 8 deprecates vsnprintf(), so we want to suppress warning
3071 // 4996 (deprecated function) there.
3072 #ifdef _MSC_VER // We are using MSVC.
3073 #pragma warning(push) // Saves the current warning state.
3074 #pragma warning(disable:4996) // Temporarily disables warning 4996.
3075 const int size = vsnprintf(buffer, kBufferSize, format, args);
3076 #pragma warning(pop) // Restores the warning state.
3077 #else // We are not using MSVC.
3078 const int size = vsnprintf(buffer, kBufferSize, format, args);
3082 // vsnprintf()'s behavior is not portable. When the buffer is not
3083 // big enough, it returns a negative value in MSVC, and returns the
3084 // needed buffer size on Linux. When there is an output error, it
3085 // always returns a negative value. For simplicity, we lump the two
3086 // error cases together.
3087 if (size < 0 || size >= kBufferSize) {
3088 return String("<formatting error or buffer exceeded>");
3090 return String(buffer, size);
3094 // Converts the buffer in a StrStream to a String, converting NUL
3095 // bytes to "\\0" along the way.
3096 String StrStreamToString(StrStream* ss) {
3097 const ::std::string& str = ss->str();
3098 const char* const start = str.c_str();
3099 const char* const end = start + str.length();
3101 // We need to use a helper StrStream to do this transformation
3102 // because String doesn't support push_back().
3104 for (const char* ch = start; ch != end; ++ch) {
3106 helper << "\\0"; // Replaces NUL with "\\0";
3112 return String(helper.str().c_str());
3115 // Appends the user-supplied message to the Google-Test-generated message.
3116 String AppendUserMessage(const String& gtest_msg,
3117 const Message& user_msg) {
3118 // Appends the user message if it's non-empty.
3119 const String user_msg_string = user_msg.GetString();
3120 if (user_msg_string.empty()) {
3125 msg << gtest_msg << "\n" << user_msg_string;
3127 return msg.GetString();
3130 } // namespace internal
3134 // Creates an empty TestResult.
3135 TestResult::TestResult()
3136 : death_test_count_(0),
3141 TestResult::~TestResult() {
3144 // Returns the i-th test part result among all the results. i can
3145 // range from 0 to total_part_count() - 1. If i is not in that range,
3146 // aborts the program.
3147 const TestPartResult& TestResult::GetTestPartResult(int i) const {
3148 if (i < 0 || i >= total_part_count())
3149 internal::posix::Abort();
3150 return test_part_results_.at(i);
3153 // Returns the i-th test property. i can range from 0 to
3154 // test_property_count() - 1. If i is not in that range, aborts the
3156 const TestProperty& TestResult::GetTestProperty(int i) const {
3157 if (i < 0 || i >= test_property_count())
3158 internal::posix::Abort();
3159 return test_properties_.at(i);
3162 // Clears the test part results.
3163 void TestResult::ClearTestPartResults() {
3164 test_part_results_.clear();
3167 // Adds a test part result to the list.
3168 void TestResult::AddTestPartResult(const TestPartResult& test_part_result) {
3169 test_part_results_.push_back(test_part_result);
3172 // Adds a test property to the list. If a property with the same key as the
3173 // supplied property is already represented, the value of this test_property
3174 // replaces the old value for that key.
3175 void TestResult::RecordProperty(const TestProperty& test_property) {
3176 if (!ValidateTestProperty(test_property)) {
3179 internal::MutexLock lock(&test_properites_mutex_);
3180 const std::vector<TestProperty>::iterator property_with_matching_key =
3181 std::find_if(test_properties_.begin(), test_properties_.end(),
3182 internal::TestPropertyKeyIs(test_property.key()));
3183 if (property_with_matching_key == test_properties_.end()) {
3184 test_properties_.push_back(test_property);
3187 property_with_matching_key->SetValue(test_property.value());
3190 // Adds a failure if the key is a reserved attribute of Google Test
3191 // testcase tags. Returns true if the property is valid.
3192 bool TestResult::ValidateTestProperty(const TestProperty& test_property) {
3193 internal::String key(test_property.key());
3194 if (key == "name" || key == "status" || key == "time" || key == "classname") {
3196 << "Reserved key used in RecordProperty(): "
3198 << " ('name', 'status', 'time', and 'classname' are reserved by "
3199 << GTEST_NAME_ << ")";
3205 // Clears the object.
3206 void TestResult::Clear() {
3207 test_part_results_.clear();
3208 test_properties_.clear();
3209 death_test_count_ = 0;
3213 // Returns true iff the test failed.
3214 bool TestResult::Failed() const {
3215 for (int i = 0; i < total_part_count(); ++i) {
3216 if (GetTestPartResult(i).failed())
3222 // Returns true iff the test part fatally failed.
3223 static bool TestPartFatallyFailed(const TestPartResult& result) {
3224 return result.fatally_failed();
3227 // Returns true iff the test fatally failed.
3228 bool TestResult::HasFatalFailure() const {
3229 return CountIf(test_part_results_, TestPartFatallyFailed) > 0;
3232 // Returns true iff the test part non-fatally failed.
3233 static bool TestPartNonfatallyFailed(const TestPartResult& result) {
3234 return result.nonfatally_failed();
3237 // Returns true iff the test has a non-fatal failure.
3238 bool TestResult::HasNonfatalFailure() const {
3239 return CountIf(test_part_results_, TestPartNonfatallyFailed) > 0;
3242 // Gets the number of all test parts. This is the sum of the number
3243 // of successful test parts and the number of failed test parts.
3244 int TestResult::total_part_count() const {
3245 return static_cast<int>(test_part_results_.size());
3248 // Returns the number of the test properties.
3249 int TestResult::test_property_count() const {
3250 return static_cast<int>(test_properties_.size());
3255 // Creates a Test object.
3257 // The c'tor saves the values of all Google Test flags.
3259 : gtest_flag_saver_(new internal::GTestFlagSaver) {
3262 // The d'tor restores the values of all Google Test flags.
3264 delete gtest_flag_saver_;
3267 // Sets up the test fixture.
3269 // A sub-class may override this.
3270 void Test::SetUp() {
3273 // Tears down the test fixture.
3275 // A sub-class may override this.
3276 void Test::TearDown() {
3279 // Allows user supplied key value pairs to be recorded for later output.
3280 void Test::RecordProperty(const char* key, const char* value) {
3281 UnitTest::GetInstance()->RecordPropertyForCurrentTest(key, value);
3284 // Allows user supplied key value pairs to be recorded for later output.
3285 void Test::RecordProperty(const char* key, int value) {
3286 Message value_message;
3287 value_message << value;
3288 RecordProperty(key, value_message.GetString().c_str());
3291 namespace internal {
3293 void ReportFailureInUnknownLocation(TestPartResult::Type result_type,
3294 const String& message) {
3295 // This function is a friend of UnitTest and as such has access to
3296 // AddTestPartResult.
3297 UnitTest::GetInstance()->AddTestPartResult(
3299 NULL, // No info about the source file where the exception occurred.
3300 -1, // We have no info on which line caused the exception.
3302 String()); // No stack trace, either.
3305 } // namespace internal
3307 #if GTEST_OS_WINDOWS
3308 // We are on Windows.
3310 // Adds an "exception thrown" fatal failure to the current test.
3311 static void AddExceptionThrownFailure(DWORD exception_code,
3312 const char* location) {
3314 message << "Exception thrown with code 0x" << std::setbase(16) <<
3315 exception_code << std::setbase(10) << " in " << location << ".";
3317 internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure,
3318 message.GetString());
3321 #endif // GTEST_OS_WINDOWS
3323 // Google Test requires all tests in the same test case to use the same test
3324 // fixture class. This function checks if the current test has the
3325 // same fixture class as the first test in the current test case. If
3326 // yes, it returns true; otherwise it generates a Google Test failure and
3328 bool Test::HasSameFixtureClass() {
3329 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
3330 const TestCase* const test_case = impl->current_test_case();
3332 // Info about the first test in the current test case.
3333 const internal::TestInfoImpl* const first_test_info =
3334 test_case->test_info_list()[0]->impl();
3335 const internal::TypeId first_fixture_id = first_test_info->fixture_class_id();
3336 const char* const first_test_name = first_test_info->name();
3338 // Info about the current test.
3339 const internal::TestInfoImpl* const this_test_info =
3340 impl->current_test_info()->impl();
3341 const internal::TypeId this_fixture_id = this_test_info->fixture_class_id();
3342 const char* const this_test_name = this_test_info->name();
3344 if (this_fixture_id != first_fixture_id) {
3345 // Is the first test defined using TEST?
3346 const bool first_is_TEST = first_fixture_id == internal::GetTestTypeId();
3347 // Is this test defined using TEST?
3348 const bool this_is_TEST = this_fixture_id == internal::GetTestTypeId();
3350 if (first_is_TEST || this_is_TEST) {
3351 // The user mixed TEST and TEST_F in this test case - we'll tell
3352 // him/her how to fix it.
3354 // Gets the name of the TEST and the name of the TEST_F. Note
3355 // that first_is_TEST and this_is_TEST cannot both be true, as
3356 // the fixture IDs are different for the two tests.
3357 const char* const TEST_name =
3358 first_is_TEST ? first_test_name : this_test_name;
3359 const char* const TEST_F_name =
3360 first_is_TEST ? this_test_name : first_test_name;
3363 << "All tests in the same test case must use the same test fixture\n"
3364 << "class, so mixing TEST_F and TEST in the same test case is\n"
3365 << "illegal. In test case " << this_test_info->test_case_name()
3367 << "test " << TEST_F_name << " is defined using TEST_F but\n"
3368 << "test " << TEST_name << " is defined using TEST. You probably\n"
3369 << "want to change the TEST to TEST_F or move it to another test\n"
3372 // The user defined two fixture classes with the same name in
3373 // two namespaces - we'll tell him/her how to fix it.
3375 << "All tests in the same test case must use the same test fixture\n"
3376 << "class. However, in test case "
3377 << this_test_info->test_case_name() << ",\n"
3378 << "you defined test " << first_test_name
3379 << " and test " << this_test_name << "\n"
3380 << "using two different test fixture classes. This can happen if\n"
3381 << "the two classes are from different namespaces or translation\n"
3382 << "units and have the same name. You should probably rename one\n"
3383 << "of the classes to put the tests into different test cases.";
3391 // Runs the test and updates the test result.
3393 if (!HasSameFixtureClass()) return;
3395 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
3397 // Catch SEH-style exceptions.
3398 impl->os_stack_trace_getter()->UponLeavingGTest();
3401 } __except(internal::UnitTestOptions::GTestShouldProcessSEH(
3402 GetExceptionCode())) {
3403 AddExceptionThrownFailure(GetExceptionCode(), "SetUp()");
3406 // We will run the test only if SetUp() had no fatal failure.
3407 if (!HasFatalFailure()) {
3408 impl->os_stack_trace_getter()->UponLeavingGTest();
3411 } __except(internal::UnitTestOptions::GTestShouldProcessSEH(
3412 GetExceptionCode())) {
3413 AddExceptionThrownFailure(GetExceptionCode(), "the test body");
3417 // However, we want to clean up as much as possible. Hence we will
3418 // always call TearDown(), even if SetUp() or the test body has
3420 impl->os_stack_trace_getter()->UponLeavingGTest();
3423 } __except(internal::UnitTestOptions::GTestShouldProcessSEH(
3424 GetExceptionCode())) {
3425 AddExceptionThrownFailure(GetExceptionCode(), "TearDown()");
3428 #else // We are on a compiler or platform that doesn't support SEH.
3429 impl->os_stack_trace_getter()->UponLeavingGTest();
3432 // We will run the test only if SetUp() was successful.
3433 if (!HasFatalFailure()) {
3434 impl->os_stack_trace_getter()->UponLeavingGTest();
3438 // However, we want to clean up as much as possible. Hence we will
3439 // always call TearDown(), even if SetUp() or the test body has
3441 impl->os_stack_trace_getter()->UponLeavingGTest();
3443 #endif // GTEST_HAS_SEH
3447 // Returns true iff the current test has a fatal failure.
3448 bool Test::HasFatalFailure() {
3449 return internal::GetUnitTestImpl()->current_test_result()->HasFatalFailure();
3452 // Returns true iff the current test has a non-fatal failure.
3453 bool Test::HasNonfatalFailure() {
3454 return internal::GetUnitTestImpl()->current_test_result()->
3455 HasNonfatalFailure();
3460 // Constructs a TestInfo object. It assumes ownership of the test factory
3461 // object via impl_.
3462 TestInfo::TestInfo(const char* a_test_case_name,
3464 const char* a_test_case_comment,
3465 const char* a_comment,
3466 internal::TypeId fixture_class_id,
3467 internal::TestFactoryBase* factory) {
3468 impl_ = new internal::TestInfoImpl(this, a_test_case_name, a_name,
3469 a_test_case_comment, a_comment,
3470 fixture_class_id, factory);
3473 // Destructs a TestInfo object.
3474 TestInfo::~TestInfo() {
3478 namespace internal {
3480 // Creates a new TestInfo object and registers it with Google Test;
3481 // returns the created object.
3485 // test_case_name: name of the test case
3486 // name: name of the test
3487 // test_case_comment: a comment on the test case that will be included in
3489 // comment: a comment on the test that will be included in the
3491 // fixture_class_id: ID of the test fixture class
3492 // set_up_tc: pointer to the function that sets up the test case
3493 // tear_down_tc: pointer to the function that tears down the test case
3494 // factory: pointer to the factory that creates a test object.
3495 // The newly created TestInfo instance will assume
3496 // ownership of the factory object.
3497 TestInfo* MakeAndRegisterTestInfo(
3498 const char* test_case_name, const char* name,
3499 const char* test_case_comment, const char* comment,
3500 TypeId fixture_class_id,
3501 SetUpTestCaseFunc set_up_tc,
3502 TearDownTestCaseFunc tear_down_tc,
3503 TestFactoryBase* factory) {
3504 TestInfo* const test_info =
3505 new TestInfo(test_case_name, name, test_case_comment, comment,
3506 fixture_class_id, factory);
3507 GetUnitTestImpl()->AddTestInfo(set_up_tc, tear_down_tc, test_info);
3511 #if GTEST_HAS_PARAM_TEST
3512 void ReportInvalidTestCaseType(const char* test_case_name,
3513 const char* file, int line) {
3516 << "Attempted redefinition of test case " << test_case_name << ".\n"
3517 << "All tests in the same test case must use the same test fixture\n"
3518 << "class. However, in test case " << test_case_name << ", you tried\n"
3519 << "to define a test using a fixture class different from the one\n"
3520 << "used earlier. This can happen if the two fixture classes are\n"
3521 << "from different namespaces and have the same name. You should\n"
3522 << "probably rename one of the classes to put the tests into different\n"
3525 fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(),
3526 errors.GetString().c_str());
3528 #endif // GTEST_HAS_PARAM_TEST
3530 } // namespace internal
3532 // Returns the test case name.
3533 const char* TestInfo::test_case_name() const {
3534 return impl_->test_case_name();
3537 // Returns the test name.
3538 const char* TestInfo::name() const {
3539 return impl_->name();
3542 // Returns the test case comment.
3543 const char* TestInfo::test_case_comment() const {
3544 return impl_->test_case_comment();
3547 // Returns the test comment.
3548 const char* TestInfo::comment() const {
3549 return impl_->comment();
3552 // Returns true if this test should run.
3553 bool TestInfo::should_run() const { return impl_->should_run(); }
3555 // Returns true if this test matches the user-specified filter.
3556 bool TestInfo::matches_filter() const { return impl_->matches_filter(); }
3558 // Returns the result of the test.
3559 const TestResult* TestInfo::result() const { return impl_->result(); }
3561 // Increments the number of death tests encountered in this test so
3563 int TestInfo::increment_death_test_count() {
3564 return impl_->result()->increment_death_test_count();
3569 // A predicate that checks the test name of a TestInfo against a known
3572 // This is used for implementation of the TestCase class only. We put
3573 // it in the anonymous namespace to prevent polluting the outer
3576 // TestNameIs is copyable.
3581 // TestNameIs has NO default constructor.
3582 explicit TestNameIs(const char* name)
3585 // Returns true iff the test name of test_info matches name_.
3586 bool operator()(const TestInfo * test_info) const {
3587 return test_info && internal::String(test_info->name()).Compare(name_) == 0;
3591 internal::String name_;
3596 namespace internal {
3598 // This method expands all parameterized tests registered with macros TEST_P
3599 // and INSTANTIATE_TEST_CASE_P into regular tests and registers those.
3600 // This will be done just once during the program runtime.
3601 void UnitTestImpl::RegisterParameterizedTests() {
3602 #if GTEST_HAS_PARAM_TEST
3603 if (!parameterized_tests_registered_) {
3604 parameterized_test_registry_.RegisterTests();
3605 parameterized_tests_registered_ = true;
3610 // Creates the test object, runs it, records its result, and then
3612 void TestInfoImpl::Run() {
3613 if (!should_run_) return;
3615 // Tells UnitTest where to store test result.
3616 UnitTestImpl* const impl = internal::GetUnitTestImpl();
3617 impl->set_current_test_info(parent_);
3619 TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
3621 // Notifies the unit test event listeners that a test is about to start.
3622 repeater->OnTestStart(*parent_);
3624 const TimeInMillis start = GetTimeInMillis();
3626 impl->os_stack_trace_getter()->UponLeavingGTest();
3628 // Catch SEH-style exceptions.
3632 // Creates the test object.
3633 test = factory_->CreateTest();
3634 } __except(internal::UnitTestOptions::GTestShouldProcessSEH(
3635 GetExceptionCode())) {
3636 AddExceptionThrownFailure(GetExceptionCode(),
3637 "the test fixture's constructor");
3640 #else // We are on a compiler or platform that doesn't support SEH.
3642 // TODO(wan): If test->Run() throws, test won't be deleted. This is
3643 // not a problem now as we don't use exceptions. If we were to
3644 // enable exceptions, we should revise the following to be
3647 // Creates the test object.
3648 Test* test = factory_->CreateTest();
3649 #endif // GTEST_HAS_SEH
3651 // Runs the test only if the constructor of the test fixture didn't
3652 // generate a fatal failure.
3653 if (!Test::HasFatalFailure()) {
3657 // Deletes the test object.
3658 impl->os_stack_trace_getter()->UponLeavingGTest();
3662 result_.set_elapsed_time(GetTimeInMillis() - start);
3664 // Notifies the unit test event listener that a test has just finished.
3665 repeater->OnTestEnd(*parent_);
3667 // Tells UnitTest to stop associating assertion results to this
3669 impl->set_current_test_info(NULL);
3672 } // namespace internal
3676 // Gets the number of successful tests in this test case.
3677 int TestCase::successful_test_count() const {
3678 return CountIf(test_info_list_, TestPassed);
3681 // Gets the number of failed tests in this test case.
3682 int TestCase::failed_test_count() const {
3683 return CountIf(test_info_list_, TestFailed);
3686 int TestCase::disabled_test_count() const {
3687 return CountIf(test_info_list_, TestDisabled);
3690 // Get the number of tests in this test case that should run.
3691 int TestCase::test_to_run_count() const {
3692 return CountIf(test_info_list_, ShouldRunTest);
3695 // Gets the number of all tests.
3696 int TestCase::total_test_count() const {
3697 return static_cast<int>(test_info_list_.size());
3700 // Creates a TestCase with the given name.
3704 // name: name of the test case
3705 // set_up_tc: pointer to the function that sets up the test case
3706 // tear_down_tc: pointer to the function that tears down the test case
3707 TestCase::TestCase(const char* a_name, const char* a_comment,
3708 Test::SetUpTestCaseFunc set_up_tc,
3709 Test::TearDownTestCaseFunc tear_down_tc)
3711 comment_(a_comment),
3712 set_up_tc_(set_up_tc),
3713 tear_down_tc_(tear_down_tc),
3718 // Destructor of TestCase.
3719 TestCase::~TestCase() {
3720 // Deletes every Test in the collection.
3721 ForEach(test_info_list_, internal::Delete<TestInfo>);
3724 // Returns the i-th test among all the tests. i can range from 0 to
3725 // total_test_count() - 1. If i is not in that range, returns NULL.
3726 const TestInfo* TestCase::GetTestInfo(int i) const {
3727 const int index = GetElementOr(test_indices_, i, -1);
3728 return index < 0 ? NULL : test_info_list_[index];
3731 // Returns the i-th test among all the tests. i can range from 0 to
3732 // total_test_count() - 1. If i is not in that range, returns NULL.
3733 TestInfo* TestCase::GetMutableTestInfo(int i) {
3734 const int index = GetElementOr(test_indices_, i, -1);
3735 return index < 0 ? NULL : test_info_list_[index];
3738 // Adds a test to this test case. Will delete the test upon
3739 // destruction of the TestCase object.
3740 void TestCase::AddTestInfo(TestInfo * test_info) {
3741 test_info_list_.push_back(test_info);
3742 test_indices_.push_back(static_cast<int>(test_indices_.size()));
3745 // Runs every test in this TestCase.
3746 void TestCase::Run() {
3747 if (!should_run_) return;
3749 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
3750 impl->set_current_test_case(this);
3752 TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
3754 repeater->OnTestCaseStart(*this);
3755 impl->os_stack_trace_getter()->UponLeavingGTest();
3758 const internal::TimeInMillis start = internal::GetTimeInMillis();
3759 for (int i = 0; i < total_test_count(); i++) {
3760 GetMutableTestInfo(i)->impl()->Run();
3762 elapsed_time_ = internal::GetTimeInMillis() - start;
3764 impl->os_stack_trace_getter()->UponLeavingGTest();
3766 repeater->OnTestCaseEnd(*this);
3767 impl->set_current_test_case(NULL);
3770 // Clears the results of all tests in this test case.
3771 void TestCase::ClearResult() {
3772 ForEach(test_info_list_, internal::TestInfoImpl::ClearTestResult);
3775 // Returns true iff test passed.
3776 bool TestCase::TestPassed(const TestInfo * test_info) {
3777 const internal::TestInfoImpl* const impl = test_info->impl();
3778 return impl->should_run() && impl->result()->Passed();
3781 // Returns true iff test failed.
3782 bool TestCase::TestFailed(const TestInfo * test_info) {
3783 const internal::TestInfoImpl* const impl = test_info->impl();
3784 return impl->should_run() && impl->result()->Failed();
3787 // Returns true iff test is disabled.
3788 bool TestCase::TestDisabled(const TestInfo * test_info) {
3789 return test_info->impl()->is_disabled();
3792 // Returns true if the given test should run.
3793 bool TestCase::ShouldRunTest(const TestInfo *test_info) {
3794 return test_info->impl()->should_run();
3797 // Shuffles the tests in this test case.
3798 void TestCase::ShuffleTests(internal::Random* random) {
3799 Shuffle(random, &test_indices_);
3802 // Restores the test order to before the first shuffle.
3803 void TestCase::UnshuffleTests() {
3804 for (size_t i = 0; i < test_indices_.size(); i++) {
3805 test_indices_[i] = static_cast<int>(i);
3809 // Formats a countable noun. Depending on its quantity, either the
3810 // singular form or the plural form is used. e.g.
3812 // FormatCountableNoun(1, "formula", "formuli") returns "1 formula".
3813 // FormatCountableNoun(5, "book", "books") returns "5 books".
3814 static internal::String FormatCountableNoun(int count,
3815 const char * singular_form,
3816 const char * plural_form) {
3817 return internal::String::Format("%d %s", count,
3818 count == 1 ? singular_form : plural_form);
3821 // Formats the count of tests.
3822 static internal::String FormatTestCount(int test_count) {
3823 return FormatCountableNoun(test_count, "test", "tests");
3826 // Formats the count of test cases.
3827 static internal::String FormatTestCaseCount(int test_case_count) {
3828 return FormatCountableNoun(test_case_count, "test case", "test cases");
3831 // Converts a TestPartResult::Type enum to human-friendly string
3832 // representation. Both kNonFatalFailure and kFatalFailure are translated
3833 // to "Failure", as the user usually doesn't care about the difference
3834 // between the two when viewing the test result.
3835 static const char * TestPartResultTypeToString(TestPartResult::Type type) {
3837 case TestPartResult::kSuccess:
3840 case TestPartResult::kNonFatalFailure:
3841 case TestPartResult::kFatalFailure:
3849 return "Unknown result type";
3852 // Prints a TestPartResult to a String.
3853 static internal::String PrintTestPartResultToString(
3854 const TestPartResult& test_part_result) {
3856 << internal::FormatFileLocation(test_part_result.file_name(),
3857 test_part_result.line_number())
3858 << " " << TestPartResultTypeToString(test_part_result.type())
3859 << test_part_result.message()).GetString();
3862 // Prints a TestPartResult.
3863 static void PrintTestPartResult(const TestPartResult& test_part_result) {
3864 const internal::String& result =
3865 PrintTestPartResultToString(test_part_result);
3866 printf("%s\n", result.c_str());
3868 // If the test program runs in Visual Studio or a debugger, the
3869 // following statements add the test part result message to the Output
3870 // window such that the user can double-click on it to jump to the
3871 // corresponding source code location; otherwise they do nothing.
3872 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
3873 // We don't call OutputDebugString*() on Windows Mobile, as printing
3874 // to stdout is done by OutputDebugString() there already - we don't
3875 // want the same message printed twice.
3876 ::OutputDebugStringA(result.c_str());
3877 ::OutputDebugStringA("\n");
3881 // class PrettyUnitTestResultPrinter
3883 namespace internal {
3892 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
3894 // Returns the character attribute for the given color.
3895 WORD GetColorAttribute(GTestColor color) {
3897 case COLOR_RED: return FOREGROUND_RED;
3898 case COLOR_GREEN: return FOREGROUND_GREEN;
3899 case COLOR_YELLOW: return FOREGROUND_RED | FOREGROUND_GREEN;
3906 // Returns the ANSI color code for the given color. COLOR_DEFAULT is
3907 // an invalid input.
3908 const char* GetAnsiColorCode(GTestColor color) {
3910 case COLOR_RED: return "1";
3911 case COLOR_GREEN: return "2";
3912 case COLOR_YELLOW: return "3";
3913 default: return NULL;
3917 #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
3919 // Returns true iff Google Test should use colors in the output.
3920 bool ShouldUseColor(bool stdout_is_tty) {
3921 const char* const gtest_color = GTEST_FLAG(color).c_str();
3923 if (String::CaseInsensitiveCStringEquals(gtest_color, "auto")) {
3924 #if GTEST_OS_WINDOWS
3925 // On Windows the TERM variable is usually not set, but the
3926 // console there does support colors.
3927 return stdout_is_tty;
3929 // On non-Windows platforms, we rely on the TERM variable.
3930 const char* const term = posix::GetEnv("TERM");
3931 const bool term_supports_color =
3932 String::CStringEquals(term, "xterm") ||
3933 String::CStringEquals(term, "xterm-color") ||
3934 String::CStringEquals(term, "xterm-256color") ||
3935 String::CStringEquals(term, "linux") ||
3936 String::CStringEquals(term, "cygwin");
3937 return stdout_is_tty && term_supports_color;
3938 #endif // GTEST_OS_WINDOWS
3941 return String::CaseInsensitiveCStringEquals(gtest_color, "yes") ||
3942 String::CaseInsensitiveCStringEquals(gtest_color, "true") ||
3943 String::CaseInsensitiveCStringEquals(gtest_color, "t") ||
3944 String::CStringEquals(gtest_color, "1");
3945 // We take "yes", "true", "t", and "1" as meaning "yes". If the
3946 // value is neither one of these nor "auto", we treat it as "no" to
3950 // Helpers for printing colored strings to stdout. Note that on Windows, we
3951 // cannot simply emit special characters and have the terminal change colors.
3952 // This routine must actually emit the characters rather than return a string
3953 // that would be colored when printed, as can be done on Linux.
3954 void ColoredPrintf(GTestColor color, const char* fmt, ...) {
3956 va_start(args, fmt);
3958 #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS
3959 const bool use_color = false;
3961 static const bool in_color_mode =
3962 ShouldUseColor(posix::IsATTY(posix::FileNo(stdout)) != 0);
3963 const bool use_color = in_color_mode && (color != COLOR_DEFAULT);
3964 #endif // GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS
3965 // The '!= 0' comparison is necessary to satisfy MSVC 7.1.
3973 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
3974 const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
3976 // Gets the current text color.
3977 CONSOLE_SCREEN_BUFFER_INFO buffer_info;
3978 GetConsoleScreenBufferInfo(stdout_handle, &buffer_info);
3979 const WORD old_color_attrs = buffer_info.wAttributes;
3981 // We need to flush the stream buffers into the console before each
3982 // SetConsoleTextAttribute call lest it affect the text that is already
3983 // printed but has not yet reached the console.
3985 SetConsoleTextAttribute(stdout_handle,
3986 GetColorAttribute(color) | FOREGROUND_INTENSITY);
3990 // Restores the text color.
3991 SetConsoleTextAttribute(stdout_handle, old_color_attrs);
3993 printf("\033[0;3%sm", GetAnsiColorCode(color));
3995 printf("\033[m"); // Resets the terminal to default.
3996 #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
4000 // This class implements the TestEventListener interface.
4002 // Class PrettyUnitTestResultPrinter is copyable.
4003 class PrettyUnitTestResultPrinter : public TestEventListener {
4005 PrettyUnitTestResultPrinter() {}
4006 static void PrintTestName(const char * test_case, const char * test) {
4007 printf("%s.%s", test_case, test);
4010 // The following methods override what's in the TestEventListener class.
4011 virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {}
4012 virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration);
4013 virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test);
4014 virtual void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) {}
4015 virtual void OnTestCaseStart(const TestCase& test_case);
4016 virtual void OnTestStart(const TestInfo& test_info);
4017 virtual void OnTestPartResult(const TestPartResult& result);
4018 virtual void OnTestEnd(const TestInfo& test_info);
4019 virtual void OnTestCaseEnd(const TestCase& test_case);
4020 virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test);
4021 virtual void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) {}
4022 virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
4023 virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) {}
4026 static void PrintFailedTests(const UnitTest& unit_test);
4028 internal::String test_case_name_;
4031 // Fired before each iteration of tests starts.
4032 void PrettyUnitTestResultPrinter::OnTestIterationStart(
4033 const UnitTest& unit_test, int iteration) {
4034 if (GTEST_FLAG(repeat) != 1)
4035 printf("\nRepeating all tests (iteration %d) . . .\n\n", iteration + 1);
4037 const char* const filter = GTEST_FLAG(filter).c_str();
4039 // Prints the filter if it's not *. This reminds the user that some
4040 // tests may be skipped.
4041 if (!internal::String::CStringEquals(filter, kUniversalFilter)) {
4042 ColoredPrintf(COLOR_YELLOW,
4043 "Note: %s filter = %s\n", GTEST_NAME_, filter);
4046 if (internal::ShouldShard(kTestTotalShards, kTestShardIndex, false)) {
4047 ColoredPrintf(COLOR_YELLOW,
4048 "Note: This is test shard %s of %s.\n",
4049 internal::posix::GetEnv(kTestShardIndex),
4050 internal::posix::GetEnv(kTestTotalShards));
4053 if (GTEST_FLAG(shuffle)) {
4054 ColoredPrintf(COLOR_YELLOW,
4055 "Note: Randomizing tests' orders with a seed of %d .\n",
4056 unit_test.random_seed());
4059 ColoredPrintf(COLOR_GREEN, "[==========] ");
4060 printf("Running %s from %s.\n",
4061 FormatTestCount(unit_test.test_to_run_count()).c_str(),
4062 FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str());
4066 void PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart(
4067 const UnitTest& /*unit_test*/) {
4068 ColoredPrintf(COLOR_GREEN, "[----------] ");
4069 printf("Global test environment set-up.\n");
4073 void PrettyUnitTestResultPrinter::OnTestCaseStart(const TestCase& test_case) {
4074 test_case_name_ = test_case.name();
4075 const internal::String counts =
4076 FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
4077 ColoredPrintf(COLOR_GREEN, "[----------] ");
4078 printf("%s from %s", counts.c_str(), test_case_name_.c_str());
4079 if (test_case.comment()[0] == '\0') {
4082 printf(", where %s\n", test_case.comment());
4087 void PrettyUnitTestResultPrinter::OnTestStart(const TestInfo& test_info) {
4088 ColoredPrintf(COLOR_GREEN, "[ RUN ] ");
4089 PrintTestName(test_case_name_.c_str(), test_info.name());
4090 if (test_info.comment()[0] == '\0') {
4093 printf(", where %s\n", test_info.comment());
4098 // Called after an assertion failure.
4099 void PrettyUnitTestResultPrinter::OnTestPartResult(
4100 const TestPartResult& result) {
4101 // If the test part succeeded, we don't need to do anything.
4102 if (result.type() == TestPartResult::kSuccess)
4105 // Print failure message from the assertion (e.g. expected this and got that).
4106 PrintTestPartResult(result);
4110 void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) {
4111 if (test_info.result()->Passed()) {
4112 ColoredPrintf(COLOR_GREEN, "[ OK ] ");
4114 ColoredPrintf(COLOR_RED, "[ FAILED ] ");
4116 PrintTestName(test_case_name_.c_str(), test_info.name());
4117 if (GTEST_FLAG(print_time)) {
4118 printf(" (%s ms)\n", internal::StreamableToString(
4119 test_info.result()->elapsed_time()).c_str());
4126 void PrettyUnitTestResultPrinter::OnTestCaseEnd(const TestCase& test_case) {
4127 if (!GTEST_FLAG(print_time)) return;
4129 test_case_name_ = test_case.name();
4130 const internal::String counts =
4131 FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
4132 ColoredPrintf(COLOR_GREEN, "[----------] ");
4133 printf("%s from %s (%s ms total)\n\n",
4134 counts.c_str(), test_case_name_.c_str(),
4135 internal::StreamableToString(test_case.elapsed_time()).c_str());
4139 void PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart(
4140 const UnitTest& /*unit_test*/) {
4141 ColoredPrintf(COLOR_GREEN, "[----------] ");
4142 printf("Global test environment tear-down\n");
4146 // Internal helper for printing the list of failed tests.
4147 void PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest& unit_test) {
4148 const int failed_test_count = unit_test.failed_test_count();
4149 if (failed_test_count == 0) {
4153 for (int i = 0; i < unit_test.total_test_case_count(); ++i) {
4154 const TestCase& test_case = *unit_test.GetTestCase(i);
4155 if (!test_case.should_run() || (test_case.failed_test_count() == 0)) {
4158 for (int j = 0; j < test_case.total_test_count(); ++j) {
4159 const TestInfo& test_info = *test_case.GetTestInfo(j);
4160 if (!test_info.should_run() || test_info.result()->Passed()) {
4163 ColoredPrintf(COLOR_RED, "[ FAILED ] ");
4164 printf("%s.%s", test_case.name(), test_info.name());
4165 if (test_case.comment()[0] != '\0' ||
4166 test_info.comment()[0] != '\0') {
4167 printf(", where %s", test_case.comment());
4168 if (test_case.comment()[0] != '\0' &&
4169 test_info.comment()[0] != '\0') {
4173 printf("%s\n", test_info.comment());
4178 void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
4179 int /*iteration*/) {
4180 ColoredPrintf(COLOR_GREEN, "[==========] ");
4181 printf("%s from %s ran.",
4182 FormatTestCount(unit_test.test_to_run_count()).c_str(),
4183 FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str());
4184 if (GTEST_FLAG(print_time)) {
4185 printf(" (%s ms total)",
4186 internal::StreamableToString(unit_test.elapsed_time()).c_str());
4189 ColoredPrintf(COLOR_GREEN, "[ PASSED ] ");
4190 printf("%s.\n", FormatTestCount(unit_test.successful_test_count()).c_str());
4192 int num_failures = unit_test.failed_test_count();
4193 if (!unit_test.Passed()) {
4194 const int failed_test_count = unit_test.failed_test_count();
4195 ColoredPrintf(COLOR_RED, "[ FAILED ] ");
4196 printf("%s, listed below:\n", FormatTestCount(failed_test_count).c_str());
4197 PrintFailedTests(unit_test);
4198 printf("\n%2d FAILED %s\n", num_failures,
4199 num_failures == 1 ? "TEST" : "TESTS");
4202 int num_disabled = unit_test.disabled_test_count();
4203 if (num_disabled && !GTEST_FLAG(also_run_disabled_tests)) {
4204 if (!num_failures) {
4205 printf("\n"); // Add a spacer if no FAILURE banner is displayed.
4207 ColoredPrintf(COLOR_YELLOW,
4208 " YOU HAVE %d DISABLED %s\n\n",
4210 num_disabled == 1 ? "TEST" : "TESTS");
4212 // Ensure that Google Test output is printed before, e.g., heapchecker output.
4216 // End PrettyUnitTestResultPrinter
4218 // class TestEventRepeater
4220 // This class forwards events to other event listeners.
4221 class TestEventRepeater : public TestEventListener {
4223 TestEventRepeater() : forwarding_enabled_(true) {}
4224 virtual ~TestEventRepeater();
4225 void Append(TestEventListener *listener);
4226 TestEventListener* Release(TestEventListener* listener);
4228 // Controls whether events will be forwarded to listeners_. Set to false
4229 // in death test child processes.
4230 bool forwarding_enabled() const { return forwarding_enabled_; }
4231 void set_forwarding_enabled(bool enable) { forwarding_enabled_ = enable; }
4233 virtual void OnTestProgramStart(const UnitTest& unit_test);
4234 virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration);
4235 virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test);
4236 virtual void OnEnvironmentsSetUpEnd(const UnitTest& unit_test);
4237 virtual void OnTestCaseStart(const TestCase& test_case);
4238 virtual void OnTestStart(const TestInfo& test_info);
4239 virtual void OnTestPartResult(const TestPartResult& result);
4240 virtual void OnTestEnd(const TestInfo& test_info);
4241 virtual void OnTestCaseEnd(const TestCase& test_case);
4242 virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test);
4243 virtual void OnEnvironmentsTearDownEnd(const UnitTest& unit_test);
4244 virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
4245 virtual void OnTestProgramEnd(const UnitTest& unit_test);
4248 // Controls whether events will be forwarded to listeners_. Set to false
4249 // in death test child processes.
4250 bool forwarding_enabled_;
4251 // The list of listeners that receive events.
4252 std::vector<TestEventListener*> listeners_;
4254 GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventRepeater);
4257 TestEventRepeater::~TestEventRepeater() {
4258 ForEach(listeners_, Delete<TestEventListener>);
4261 void TestEventRepeater::Append(TestEventListener *listener) {
4262 listeners_.push_back(listener);
4265 // TODO(vladl@google.com): Factor the search functionality into Vector::Find.
4266 TestEventListener* TestEventRepeater::Release(TestEventListener *listener) {
4267 for (size_t i = 0; i < listeners_.size(); ++i) {
4268 if (listeners_[i] == listener) {
4269 listeners_.erase(listeners_.begin() + i);
4277 // Since most methods are very similar, use macros to reduce boilerplate.
4278 // This defines a member that forwards the call to all listeners.
4279 #define GTEST_REPEATER_METHOD_(Name, Type) \
4280 void TestEventRepeater::Name(const Type& parameter) { \
4281 if (forwarding_enabled_) { \
4282 for (size_t i = 0; i < listeners_.size(); i++) { \
4283 listeners_[i]->Name(parameter); \
4287 // This defines a member that forwards the call to all listeners in reverse
4289 #define GTEST_REVERSE_REPEATER_METHOD_(Name, Type) \
4290 void TestEventRepeater::Name(const Type& parameter) { \
4291 if (forwarding_enabled_) { \
4292 for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) { \
4293 listeners_[i]->Name(parameter); \
4298 GTEST_REPEATER_METHOD_(OnTestProgramStart, UnitTest)
4299 GTEST_REPEATER_METHOD_(OnEnvironmentsSetUpStart, UnitTest)
4300 GTEST_REPEATER_METHOD_(OnTestCaseStart, TestCase)
4301 GTEST_REPEATER_METHOD_(OnTestStart, TestInfo)
4302 GTEST_REPEATER_METHOD_(OnTestPartResult, TestPartResult)
4303 GTEST_REPEATER_METHOD_(OnEnvironmentsTearDownStart, UnitTest)
4304 GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsSetUpEnd, UnitTest)
4305 GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsTearDownEnd, UnitTest)
4306 GTEST_REVERSE_REPEATER_METHOD_(OnTestEnd, TestInfo)
4307 GTEST_REVERSE_REPEATER_METHOD_(OnTestCaseEnd, TestCase)
4308 GTEST_REVERSE_REPEATER_METHOD_(OnTestProgramEnd, UnitTest)
4310 #undef GTEST_REPEATER_METHOD_
4311 #undef GTEST_REVERSE_REPEATER_METHOD_
4313 void TestEventRepeater::OnTestIterationStart(const UnitTest& unit_test,
4315 if (forwarding_enabled_) {
4316 for (size_t i = 0; i < listeners_.size(); i++) {
4317 listeners_[i]->OnTestIterationStart(unit_test, iteration);
4322 void TestEventRepeater::OnTestIterationEnd(const UnitTest& unit_test,
4324 if (forwarding_enabled_) {
4325 for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) {
4326 listeners_[i]->OnTestIterationEnd(unit_test, iteration);
4331 // End TestEventRepeater
4333 // This class generates an XML output file.
4334 class XmlUnitTestResultPrinter : public EmptyTestEventListener {
4336 explicit XmlUnitTestResultPrinter(const char* output_file);
4338 virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
4341 // Is c a whitespace character that is normalized to a space character
4342 // when it appears in an XML attribute value?
4343 static bool IsNormalizableWhitespace(char c) {
4344 return c == 0x9 || c == 0xA || c == 0xD;
4347 // May c appear in a well-formed XML document?
4348 static bool IsValidXmlCharacter(char c) {
4349 return IsNormalizableWhitespace(c) || c >= 0x20;
4352 // Returns an XML-escaped copy of the input string str. If
4353 // is_attribute is true, the text is meant to appear as an attribute
4354 // value, and normalizable whitespace is preserved by replacing it
4355 // with character references.
4356 static String EscapeXml(const char* str, bool is_attribute);
4358 // Returns the given string with all characters invalid in XML removed.
4359 static String RemoveInvalidXmlCharacters(const char* str);
4361 // Convenience wrapper around EscapeXml when str is an attribute value.
4362 static String EscapeXmlAttribute(const char* str) {
4363 return EscapeXml(str, true);
4366 // Convenience wrapper around EscapeXml when str is not an attribute value.
4367 static String EscapeXmlText(const char* str) { return EscapeXml(str, false); }
4369 // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
4370 static void OutputXmlCDataSection(::std::ostream* stream, const char* data);
4372 // Streams an XML representation of a TestInfo object.
4373 static void OutputXmlTestInfo(::std::ostream* stream,
4374 const char* test_case_name,
4375 const TestInfo& test_info);
4377 // Prints an XML representation of a TestCase object
4378 static void PrintXmlTestCase(FILE* out, const TestCase& test_case);
4380 // Prints an XML summary of unit_test to output stream out.
4381 static void PrintXmlUnitTest(FILE* out, const UnitTest& unit_test);
4383 // Produces a string representing the test properties in a result as space
4384 // delimited XML attributes based on the property key="value" pairs.
4385 // When the String is not empty, it includes a space at the beginning,
4386 // to delimit this attribute from prior attributes.
4387 static String TestPropertiesAsXmlAttributes(const TestResult& result);
4390 const String output_file_;
4392 GTEST_DISALLOW_COPY_AND_ASSIGN_(XmlUnitTestResultPrinter);
4395 // Creates a new XmlUnitTestResultPrinter.
4396 XmlUnitTestResultPrinter::XmlUnitTestResultPrinter(const char* output_file)
4397 : output_file_(output_file) {
4398 if (output_file_.c_str() == NULL || output_file_.empty()) {
4399 fprintf(stderr, "XML output file may not be null\n");
4405 // Called after the unit test ends.
4406 void XmlUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
4407 int /*iteration*/) {
4408 FILE* xmlout = NULL;
4409 FilePath output_file(output_file_);
4410 FilePath output_dir(output_file.RemoveFileName());
4412 if (output_dir.CreateDirectoriesRecursively()) {
4413 xmlout = posix::FOpen(output_file_.c_str(), "w");
4415 if (xmlout == NULL) {
4416 // TODO(wan): report the reason of the failure.
4418 // We don't do it for now as:
4420 // 1. There is no urgent need for it.
4421 // 2. It's a bit involved to make the errno variable thread-safe on
4422 // all three operating systems (Linux, Windows, and Mac OS).
4423 // 3. To interpret the meaning of errno in a thread-safe way,
4424 // we need the strerror_r() function, which is not available on
4427 "Unable to open file \"%s\"\n",
4428 output_file_.c_str());
4432 PrintXmlUnitTest(xmlout, unit_test);
4436 // Returns an XML-escaped copy of the input string str. If is_attribute
4437 // is true, the text is meant to appear as an attribute value, and
4438 // normalizable whitespace is preserved by replacing it with character
4441 // Invalid XML characters in str, if any, are stripped from the output.
4442 // It is expected that most, if not all, of the text processed by this
4443 // module will consist of ordinary English text.
4444 // If this module is ever modified to produce version 1.1 XML output,
4445 // most invalid characters can be retained using character references.
4446 // TODO(wan): It might be nice to have a minimally invasive, human-readable
4447 // escaping scheme for invalid characters, rather than dropping them.
4448 String XmlUnitTestResultPrinter::EscapeXml(const char* str, bool is_attribute) {
4452 for (const char* src = str; *src; ++src) {
4476 if (IsValidXmlCharacter(*src)) {
4477 if (is_attribute && IsNormalizableWhitespace(*src))
4478 m << String::Format("&#x%02X;", unsigned(*src));
4487 return m.GetString();
4490 // Returns the given string with all characters invalid in XML removed.
4491 // Currently invalid characters are dropped from the string. An
4492 // alternative is to replace them with certain characters such as . or ?.
4493 String XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters(const char* str) {
4494 char* const output = new char[strlen(str) + 1];
4495 char* appender = output;
4496 for (char ch = *str; ch != '\0'; ch = *++str)
4497 if (IsValidXmlCharacter(ch))
4501 String ret_value(output);
4506 // The following routines generate an XML representation of a UnitTest
4509 // This is how Google Test concepts map to the DTD:
4511 // <testsuites name="AllTests"> <-- corresponds to a UnitTest object
4512 // <testsuite name="testcase-name"> <-- corresponds to a TestCase object
4513 // <testcase name="test-name"> <-- corresponds to a TestInfo object
4514 // <failure message="...">...</failure>
4515 // <failure message="...">...</failure>
4516 // <failure message="...">...</failure>
4517 // <-- individual assertion failures
4522 // Formats the given time in milliseconds as seconds.
4523 std::string FormatTimeInMillisAsSeconds(TimeInMillis ms) {
4524 ::std::stringstream ss;
4529 // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
4530 void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream,
4532 const char* segment = data;
4533 *stream << "<![CDATA[";
4535 const char* const next_segment = strstr(segment, "]]>");
4536 if (next_segment != NULL) {
4538 segment, static_cast<std::streamsize>(next_segment - segment));
4539 *stream << "]]>]]><![CDATA[";
4540 segment = next_segment + strlen("]]>");
4549 // Prints an XML representation of a TestInfo object.
4550 // TODO(wan): There is also value in printing properties with the plain printer.
4551 void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream,
4552 const char* test_case_name,
4553 const TestInfo& test_info) {
4554 const TestResult& result = *test_info.result();
4555 *stream << " <testcase name=\""
4556 << EscapeXmlAttribute(test_info.name()).c_str()
4558 << (test_info.should_run() ? "run" : "notrun")
4560 << FormatTimeInMillisAsSeconds(result.elapsed_time())
4561 << "\" classname=\"" << EscapeXmlAttribute(test_case_name).c_str()
4562 << "\"" << TestPropertiesAsXmlAttributes(result).c_str();
4565 for (int i = 0; i < result.total_part_count(); ++i) {
4566 const TestPartResult& part = result.GetTestPartResult(i);
4567 if (part.failed()) {
4568 if (++failures == 1)
4570 *stream << " <failure message=\""
4571 << EscapeXmlAttribute(part.summary()).c_str()
4573 const String message = RemoveInvalidXmlCharacters(String::Format(
4575 part.file_name(), part.line_number(),
4576 part.message()).c_str());
4577 OutputXmlCDataSection(stream, message.c_str());
4578 *stream << "</failure>\n";
4585 *stream << " </testcase>\n";
4588 // Prints an XML representation of a TestCase object
4589 void XmlUnitTestResultPrinter::PrintXmlTestCase(FILE* out,
4590 const TestCase& test_case) {
4592 " <testsuite name=\"%s\" tests=\"%d\" failures=\"%d\" "
4594 EscapeXmlAttribute(test_case.name()).c_str(),
4595 test_case.total_test_count(),
4596 test_case.failed_test_count(),
4597 test_case.disabled_test_count());
4599 "errors=\"0\" time=\"%s\">\n",
4600 FormatTimeInMillisAsSeconds(test_case.elapsed_time()).c_str());
4601 for (int i = 0; i < test_case.total_test_count(); ++i) {
4603 OutputXmlTestInfo(&stream, test_case.name(), *test_case.GetTestInfo(i));
4604 fprintf(out, "%s", StrStreamToString(&stream).c_str());
4606 fprintf(out, " </testsuite>\n");
4609 // Prints an XML summary of unit_test to output stream out.
4610 void XmlUnitTestResultPrinter::PrintXmlUnitTest(FILE* out,
4611 const UnitTest& unit_test) {
4612 fprintf(out, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
4614 "<testsuites tests=\"%d\" failures=\"%d\" disabled=\"%d\" "
4615 "errors=\"0\" time=\"%s\" ",
4616 unit_test.total_test_count(),
4617 unit_test.failed_test_count(),
4618 unit_test.disabled_test_count(),
4619 FormatTimeInMillisAsSeconds(unit_test.elapsed_time()).c_str());
4620 if (GTEST_FLAG(shuffle)) {
4621 fprintf(out, "random_seed=\"%d\" ", unit_test.random_seed());
4623 fprintf(out, "name=\"AllTests\">\n");
4624 for (int i = 0; i < unit_test.total_test_case_count(); ++i)
4625 PrintXmlTestCase(out, *unit_test.GetTestCase(i));
4626 fprintf(out, "</testsuites>\n");
4629 // Produces a string representing the test properties in a result as space
4630 // delimited XML attributes based on the property key="value" pairs.
4631 String XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes(
4632 const TestResult& result) {
4634 for (int i = 0; i < result.test_property_count(); ++i) {
4635 const TestProperty& property = result.GetTestProperty(i);
4636 attributes << " " << property.key() << "="
4637 << "\"" << EscapeXmlAttribute(property.value()) << "\"";
4639 return attributes.GetString();
4642 // End XmlUnitTestResultPrinter
4644 // Class ScopedTrace
4646 // Pushes the given source file location and message onto a per-thread
4647 // trace stack maintained by Google Test.
4648 // L < UnitTest::mutex_
4649 ScopedTrace::ScopedTrace(const char* file, int line, const Message& message) {
4653 trace.message = message.GetString();
4655 UnitTest::GetInstance()->PushGTestTrace(trace);
4658 // Pops the info pushed by the c'tor.
4659 // L < UnitTest::mutex_
4660 ScopedTrace::~ScopedTrace() {
4661 UnitTest::GetInstance()->PopGTestTrace();
4665 // class OsStackTraceGetter
4667 // Returns the current OS stack trace as a String. Parameters:
4669 // max_depth - the maximum number of stack frames to be included
4671 // skip_count - the number of top frames to be skipped; doesn't count
4672 // against max_depth.
4675 // We use "L < mutex_" to denote that the function may acquire mutex_.
4676 String OsStackTraceGetter::CurrentStackTrace(int, int) {
4681 void OsStackTraceGetter::UponLeavingGTest() {
4685 OsStackTraceGetter::kElidedFramesMarker =
4686 "... " GTEST_NAME_ " internal frames ...";
4688 } // namespace internal
4690 // class TestEventListeners
4692 TestEventListeners::TestEventListeners()
4693 : repeater_(new internal::TestEventRepeater()),
4694 default_result_printer_(NULL),
4695 default_xml_generator_(NULL) {
4698 TestEventListeners::~TestEventListeners() { delete repeater_; }
4700 // Returns the standard listener responsible for the default console
4701 // output. Can be removed from the listeners list to shut down default
4702 // console output. Note that removing this object from the listener list
4703 // with Release transfers its ownership to the user.
4704 void TestEventListeners::Append(TestEventListener* listener) {
4705 repeater_->Append(listener);
4708 // Removes the given event listener from the list and returns it. It then
4709 // becomes the caller's responsibility to delete the listener. Returns
4710 // NULL if the listener is not found in the list.
4711 TestEventListener* TestEventListeners::Release(TestEventListener* listener) {
4712 if (listener == default_result_printer_)
4713 default_result_printer_ = NULL;
4714 else if (listener == default_xml_generator_)
4715 default_xml_generator_ = NULL;
4716 return repeater_->Release(listener);
4719 // Returns repeater that broadcasts the TestEventListener events to all
4721 TestEventListener* TestEventListeners::repeater() { return repeater_; }
4723 // Sets the default_result_printer attribute to the provided listener.
4724 // The listener is also added to the listener list and previous
4725 // default_result_printer is removed from it and deleted. The listener can
4726 // also be NULL in which case it will not be added to the list. Does
4727 // nothing if the previous and the current listener objects are the same.
4728 void TestEventListeners::SetDefaultResultPrinter(TestEventListener* listener) {
4729 if (default_result_printer_ != listener) {
4730 // It is an error to pass this method a listener that is already in the
4732 delete Release(default_result_printer_);
4733 default_result_printer_ = listener;
4734 if (listener != NULL)
4739 // Sets the default_xml_generator attribute to the provided listener. The
4740 // listener is also added to the listener list and previous
4741 // default_xml_generator is removed from it and deleted. The listener can
4742 // also be NULL in which case it will not be added to the list. Does
4743 // nothing if the previous and the current listener objects are the same.
4744 void TestEventListeners::SetDefaultXmlGenerator(TestEventListener* listener) {
4745 if (default_xml_generator_ != listener) {
4746 // It is an error to pass this method a listener that is already in the
4748 delete Release(default_xml_generator_);
4749 default_xml_generator_ = listener;
4750 if (listener != NULL)
4755 // Controls whether events will be forwarded by the repeater to the
4756 // listeners in the list.
4757 bool TestEventListeners::EventForwardingEnabled() const {
4758 return repeater_->forwarding_enabled();
4761 void TestEventListeners::SuppressEventForwarding() {
4762 repeater_->set_forwarding_enabled(false);
4767 // Gets the singleton UnitTest object. The first time this method is
4768 // called, a UnitTest object is constructed and returned. Consecutive
4769 // calls will return the same object.
4771 // We don't protect this under mutex_ as a user is not supposed to
4772 // call this before main() starts, from which point on the return
4773 // value will never change.
4774 UnitTest * UnitTest::GetInstance() {
4775 // When compiled with MSVC 7.1 in optimized mode, destroying the
4776 // UnitTest object upon exiting the program messes up the exit code,
4777 // causing successful tests to appear failed. We have to use a
4778 // different implementation in this case to bypass the compiler bug.
4779 // This implementation makes the compiler happy, at the cost of
4780 // leaking the UnitTest object.
4782 // CodeGear C++Builder insists on a public destructor for the
4783 // default implementation. Use this implementation to keep good OO
4784 // design with private destructor.
4786 #if (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)
4787 static UnitTest* const instance = new UnitTest;
4790 static UnitTest instance;
4792 #endif // (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)
4795 // Gets the number of successful test cases.
4796 int UnitTest::successful_test_case_count() const {
4797 return impl()->successful_test_case_count();
4800 // Gets the number of failed test cases.
4801 int UnitTest::failed_test_case_count() const {
4802 return impl()->failed_test_case_count();
4805 // Gets the number of all test cases.
4806 int UnitTest::total_test_case_count() const {
4807 return impl()->total_test_case_count();
4810 // Gets the number of all test cases that contain at least one test
4812 int UnitTest::test_case_to_run_count() const {
4813 return impl()->test_case_to_run_count();
4816 // Gets the number of successful tests.
4817 int UnitTest::successful_test_count() const {
4818 return impl()->successful_test_count();
4821 // Gets the number of failed tests.
4822 int UnitTest::failed_test_count() const { return impl()->failed_test_count(); }
4824 // Gets the number of disabled tests.
4825 int UnitTest::disabled_test_count() const {
4826 return impl()->disabled_test_count();
4829 // Gets the number of all tests.
4830 int UnitTest::total_test_count() const { return impl()->total_test_count(); }
4832 // Gets the number of tests that should run.
4833 int UnitTest::test_to_run_count() const { return impl()->test_to_run_count(); }
4835 // Gets the elapsed time, in milliseconds.
4836 internal::TimeInMillis UnitTest::elapsed_time() const {
4837 return impl()->elapsed_time();
4840 // Returns true iff the unit test passed (i.e. all test cases passed).
4841 bool UnitTest::Passed() const { return impl()->Passed(); }
4843 // Returns true iff the unit test failed (i.e. some test case failed
4844 // or something outside of all tests failed).
4845 bool UnitTest::Failed() const { return impl()->Failed(); }
4847 // Gets the i-th test case among all the test cases. i can range from 0 to
4848 // total_test_case_count() - 1. If i is not in that range, returns NULL.
4849 const TestCase* UnitTest::GetTestCase(int i) const {
4850 return impl()->GetTestCase(i);
4853 // Gets the i-th test case among all the test cases. i can range from 0 to
4854 // total_test_case_count() - 1. If i is not in that range, returns NULL.
4855 TestCase* UnitTest::GetMutableTestCase(int i) {
4856 return impl()->GetMutableTestCase(i);
4859 // Returns the list of event listeners that can be used to track events
4860 // inside Google Test.
4861 TestEventListeners& UnitTest::listeners() {
4862 return *impl()->listeners();
4865 // Registers and returns a global test environment. When a test
4866 // program is run, all global test environments will be set-up in the
4867 // order they were registered. After all tests in the program have
4868 // finished, all global test environments will be torn-down in the
4869 // *reverse* order they were registered.
4871 // The UnitTest object takes ownership of the given environment.
4873 // We don't protect this under mutex_, as we only support calling it
4874 // from the main thread.
4875 Environment* UnitTest::AddEnvironment(Environment* env) {
4880 impl_->environments().push_back(env);
4884 #if GTEST_HAS_EXCEPTIONS
4885 // A failed Google Test assertion will throw an exception of this type
4886 // when exceptions are enabled. We derive it from std::runtime_error,
4887 // which is for errors presumably detectable only at run time. Since
4888 // std::runtime_error inherits from std::exception, many testing
4889 // frameworks know how to extract and print the message inside it.
4890 class GoogleTestFailureException : public ::std::runtime_error {
4892 explicit GoogleTestFailureException(const TestPartResult& failure)
4893 : ::std::runtime_error(PrintTestPartResultToString(failure).c_str()) {}
4897 // Adds a TestPartResult to the current TestResult object. All Google Test
4898 // assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) eventually call
4899 // this to report their results. The user code should use the
4900 // assertion macros instead of calling this directly.
4902 void UnitTest::AddTestPartResult(TestPartResult::Type result_type,
4903 const char* file_name,
4905 const internal::String& message,
4906 const internal::String& os_stack_trace) {
4910 internal::MutexLock lock(&mutex_);
4911 if (impl_->gtest_trace_stack().size() > 0) {
4912 msg << "\n" << GTEST_NAME_ << " trace:";
4914 for (int i = static_cast<int>(impl_->gtest_trace_stack().size());
4916 const internal::TraceInfo& trace = impl_->gtest_trace_stack()[i - 1];
4917 msg << "\n" << internal::FormatFileLocation(trace.file, trace.line)
4918 << " " << trace.message;
4922 if (os_stack_trace.c_str() != NULL && !os_stack_trace.empty()) {
4923 msg << internal::kStackTraceMarker << os_stack_trace;
4926 const TestPartResult result =
4927 TestPartResult(result_type, file_name, line_number,
4928 msg.GetString().c_str());
4929 impl_->GetTestPartResultReporterForCurrentThread()->
4930 ReportTestPartResult(result);
4932 if (result_type != TestPartResult::kSuccess) {
4933 // gtest_break_on_failure takes precedence over
4934 // gtest_throw_on_failure. This allows a user to set the latter
4935 // in the code (perhaps in order to use Google Test assertions
4936 // with another testing framework) and specify the former on the
4937 // command line for debugging.
4938 if (GTEST_FLAG(break_on_failure)) {
4939 #if GTEST_OS_WINDOWS
4940 // Using DebugBreak on Windows allows gtest to still break into a debugger
4941 // when a failure happens and both the --gtest_break_on_failure and
4942 // the --gtest_catch_exceptions flags are specified.
4945 *static_cast<int*>(NULL) = 1;
4946 #endif // GTEST_OS_WINDOWS
4947 } else if (GTEST_FLAG(throw_on_failure)) {
4948 #if GTEST_HAS_EXCEPTIONS
4949 throw GoogleTestFailureException(result);
4951 // We cannot call abort() as it generates a pop-up in debug mode
4952 // that cannot be suppressed in VC 7.1 or below.
4959 // Creates and adds a property to the current TestResult. If a property matching
4960 // the supplied value already exists, updates its value instead.
4961 void UnitTest::RecordPropertyForCurrentTest(const char* key,
4962 const char* value) {
4963 const TestProperty test_property(key, value);
4964 impl_->current_test_result()->RecordProperty(test_property);
4967 // Runs all tests in this UnitTest object and prints the result.
4968 // Returns 0 if successful, or 1 otherwise.
4970 // We don't protect this under mutex_, as we only support calling it
4971 // from the main thread.
4972 int UnitTest::Run() {
4974 // Catch SEH-style exceptions.
4976 const bool in_death_test_child_process =
4977 internal::GTEST_FLAG(internal_run_death_test).length() > 0;
4979 // Either the user wants Google Test to catch exceptions thrown by the
4980 // tests or this is executing in the context of death test child
4981 // process. In either case the user does not want to see pop-up dialogs
4982 // about crashes - they are expected..
4983 if (GTEST_FLAG(catch_exceptions) || in_death_test_child_process) {
4984 #if !GTEST_OS_WINDOWS_MOBILE
4985 // SetErrorMode doesn't exist on CE.
4986 SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT |
4987 SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);
4988 #endif // !GTEST_OS_WINDOWS_MOBILE
4990 #if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE
4991 // Death test children can be terminated with _abort(). On Windows,
4992 // _abort() can show a dialog with a warning message. This forces the
4993 // abort message to go to stderr instead.
4994 _set_error_mode(_OUT_TO_STDERR);
4997 #if _MSC_VER >= 1400 && !GTEST_OS_WINDOWS_MOBILE
4998 // In the debug version, Visual Studio pops up a separate dialog
4999 // offering a choice to debug the aborted program. We need to suppress
5000 // this dialog or it will pop up for every EXPECT/ASSERT_DEATH statement
5001 // executed. Google Test will notify the user of any unexpected
5002 // failure via stderr.
5004 // VC++ doesn't define _set_abort_behavior() prior to the version 8.0.
5005 // Users of prior VC versions shall suffer the agony and pain of
5006 // clicking through the countless debug dialogs.
5007 // TODO(vladl@google.com): find a way to suppress the abort dialog() in the
5008 // debug mode when compiled with VC 7.1 or lower.
5009 if (!GTEST_FLAG(break_on_failure))
5010 _set_abort_behavior(
5011 0x0, // Clear the following flags:
5012 _WRITE_ABORT_MSG | _CALL_REPORTFAULT); // pop-up window, core dump.
5017 return impl_->RunAllTests();
5018 } __except(internal::UnitTestOptions::GTestShouldProcessSEH(
5019 GetExceptionCode())) {
5020 printf("Exception thrown with code 0x%x.\nFAIL\n", GetExceptionCode());
5025 #else // We are on a compiler or platform that doesn't support SEH.
5027 return impl_->RunAllTests();
5028 #endif // GTEST_HAS_SEH
5031 // Returns the working directory when the first TEST() or TEST_F() was
5033 const char* UnitTest::original_working_dir() const {
5034 return impl_->original_working_dir_.c_str();
5037 // Returns the TestCase object for the test that's currently running,
5038 // or NULL if no test is running.
5040 const TestCase* UnitTest::current_test_case() const {
5041 internal::MutexLock lock(&mutex_);
5042 return impl_->current_test_case();
5045 // Returns the TestInfo object for the test that's currently running,
5046 // or NULL if no test is running.
5048 const TestInfo* UnitTest::current_test_info() const {
5049 internal::MutexLock lock(&mutex_);
5050 return impl_->current_test_info();
5053 // Returns the random seed used at the start of the current test run.
5054 int UnitTest::random_seed() const { return impl_->random_seed(); }
5056 #if GTEST_HAS_PARAM_TEST
5057 // Returns ParameterizedTestCaseRegistry object used to keep track of
5058 // value-parameterized tests and instantiate and register them.
5060 internal::ParameterizedTestCaseRegistry&
5061 UnitTest::parameterized_test_registry() {
5062 return impl_->parameterized_test_registry();
5064 #endif // GTEST_HAS_PARAM_TEST
5066 // Creates an empty UnitTest.
5067 UnitTest::UnitTest() {
5068 impl_ = new internal::UnitTestImpl(this);
5071 // Destructor of UnitTest.
5072 UnitTest::~UnitTest() {
5076 // Pushes a trace defined by SCOPED_TRACE() on to the per-thread
5077 // Google Test trace stack.
5079 void UnitTest::PushGTestTrace(const internal::TraceInfo& trace) {
5080 internal::MutexLock lock(&mutex_);
5081 impl_->gtest_trace_stack().push_back(trace);
5084 // Pops a trace from the per-thread Google Test trace stack.
5086 void UnitTest::PopGTestTrace() {
5087 internal::MutexLock lock(&mutex_);
5088 impl_->gtest_trace_stack().pop_back();
5091 namespace internal {
5093 UnitTestImpl::UnitTestImpl(UnitTest* parent)
5096 #pragma warning(push) // Saves the current warning state.
5097 #pragma warning(disable:4355) // Temporarily disables warning 4355
5098 // (using this in initializer).
5099 default_global_test_part_result_reporter_(this),
5100 default_per_thread_test_part_result_reporter_(this),
5101 #pragma warning(pop) // Restores the warning state again.
5103 default_global_test_part_result_reporter_(this),
5104 default_per_thread_test_part_result_reporter_(this),
5106 global_test_part_result_repoter_(
5107 &default_global_test_part_result_reporter_),
5108 per_thread_test_part_result_reporter_(
5109 &default_per_thread_test_part_result_reporter_),
5110 #if GTEST_HAS_PARAM_TEST
5111 parameterized_test_registry_(),
5112 parameterized_tests_registered_(false),
5113 #endif // GTEST_HAS_PARAM_TEST
5114 last_death_test_case_(-1),
5115 current_test_case_(NULL),
5116 current_test_info_(NULL),
5117 ad_hoc_test_result_(),
5118 os_stack_trace_getter_(NULL),
5119 post_flag_parse_init_performed_(false),
5120 random_seed_(0), // Will be overridden by the flag before first use.
5121 random_(0), // Will be reseeded before first use.
5122 #if GTEST_HAS_DEATH_TEST
5124 internal_run_death_test_flag_(NULL),
5125 death_test_factory_(new DefaultDeathTestFactory) {
5128 #endif // GTEST_HAS_DEATH_TEST
5129 listeners()->SetDefaultResultPrinter(new PrettyUnitTestResultPrinter);
5132 UnitTestImpl::~UnitTestImpl() {
5133 // Deletes every TestCase.
5134 ForEach(test_cases_, internal::Delete<TestCase>);
5136 // Deletes every Environment.
5137 ForEach(environments_, internal::Delete<Environment>);
5139 delete os_stack_trace_getter_;
5142 #if GTEST_HAS_DEATH_TEST
5143 // Disables event forwarding if the control is currently in a death test
5144 // subprocess. Must not be called before InitGoogleTest.
5145 void UnitTestImpl::SuppressTestEventsIfInSubprocess() {
5146 if (internal_run_death_test_flag_.get() != NULL)
5147 listeners()->SuppressEventForwarding();
5149 #endif // GTEST_HAS_DEATH_TEST
5151 // Initializes event listeners performing XML output as specified by
5152 // UnitTestOptions. Must not be called before InitGoogleTest.
5153 void UnitTestImpl::ConfigureXmlOutput() {
5154 const String& output_format = UnitTestOptions::GetOutputFormat();
5155 if (output_format == "xml") {
5156 listeners()->SetDefaultXmlGenerator(new XmlUnitTestResultPrinter(
5157 UnitTestOptions::GetAbsolutePathToOutputFile().c_str()));
5158 } else if (output_format != "") {
5159 printf("WARNING: unrecognized output format \"%s\" ignored.\n",
5160 output_format.c_str());
5165 // Performs initialization dependent upon flag values obtained in
5166 // ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to
5167 // ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest
5168 // this function is also called from RunAllTests. Since this function can be
5169 // called more than once, it has to be idempotent.
5170 void UnitTestImpl::PostFlagParsingInit() {
5171 // Ensures that this function does not execute more than once.
5172 if (!post_flag_parse_init_performed_) {
5173 post_flag_parse_init_performed_ = true;
5175 #if GTEST_HAS_DEATH_TEST
5176 InitDeathTestSubprocessControlInfo();
5177 SuppressTestEventsIfInSubprocess();
5178 #endif // GTEST_HAS_DEATH_TEST
5180 // Registers parameterized tests. This makes parameterized tests
5181 // available to the UnitTest reflection API without running
5183 RegisterParameterizedTests();
5185 // Configures listeners for XML output. This makes it possible for users
5186 // to shut down the default XML output before invoking RUN_ALL_TESTS.
5187 ConfigureXmlOutput();
5191 // A predicate that checks the name of a TestCase against a known
5194 // This is used for implementation of the UnitTest class only. We put
5195 // it in the anonymous namespace to prevent polluting the outer
5198 // TestCaseNameIs is copyable.
5199 class TestCaseNameIs {
5202 explicit TestCaseNameIs(const String& name)
5205 // Returns true iff the name of test_case matches name_.
5206 bool operator()(const TestCase* test_case) const {
5207 return test_case != NULL && strcmp(test_case->name(), name_.c_str()) == 0;
5214 // Finds and returns a TestCase with the given name. If one doesn't
5215 // exist, creates one and returns it. It's the CALLER'S
5216 // RESPONSIBILITY to ensure that this function is only called WHEN THE
5217 // TESTS ARE NOT SHUFFLED.
5221 // test_case_name: name of the test case
5222 // set_up_tc: pointer to the function that sets up the test case
5223 // tear_down_tc: pointer to the function that tears down the test case
5224 TestCase* UnitTestImpl::GetTestCase(const char* test_case_name,
5225 const char* comment,
5226 Test::SetUpTestCaseFunc set_up_tc,
5227 Test::TearDownTestCaseFunc tear_down_tc) {
5228 // Can we find a TestCase with the given name?
5229 const std::vector<TestCase*>::const_iterator test_case =
5230 std::find_if(test_cases_.begin(), test_cases_.end(),
5231 TestCaseNameIs(test_case_name));
5233 if (test_case != test_cases_.end())
5236 // No. Let's create one.
5237 TestCase* const new_test_case =
5238 new TestCase(test_case_name, comment, set_up_tc, tear_down_tc);
5240 // Is this a death test case?
5241 if (internal::UnitTestOptions::MatchesFilter(String(test_case_name),
5242 kDeathTestCaseFilter)) {
5243 // Yes. Inserts the test case after the last death test case
5244 // defined so far. This only works when the test cases haven't
5245 // been shuffled. Otherwise we may end up running a death test
5246 // after a non-death test.
5247 ++last_death_test_case_;
5248 test_cases_.insert(test_cases_.begin() + last_death_test_case_,
5251 // No. Appends to the end of the list.
5252 test_cases_.push_back(new_test_case);
5255 test_case_indices_.push_back(static_cast<int>(test_case_indices_.size()));
5256 return new_test_case;
5259 // Helpers for setting up / tearing down the given environment. They
5260 // are for use in the ForEach() function.
5261 static void SetUpEnvironment(Environment* env) { env->SetUp(); }
5262 static void TearDownEnvironment(Environment* env) { env->TearDown(); }
5264 // Runs all tests in this UnitTest object, prints the result, and
5265 // returns 0 if all tests are successful, or 1 otherwise. If any
5266 // exception is thrown during a test on Windows, this test is
5267 // considered to be failed, but the rest of the tests will still be
5268 // run. (We disable exceptions on Linux and Mac OS X, so the issue
5269 // doesn't apply there.)
5270 // When parameterized tests are enabled, it expands and registers
5271 // parameterized tests first in RegisterParameterizedTests().
5272 // All other functions called from RunAllTests() may safely assume that
5273 // parameterized tests are ready to be counted and run.
5274 int UnitTestImpl::RunAllTests() {
5275 // Makes sure InitGoogleTest() was called.
5276 if (!GTestIsInitialized()) {
5278 "\nThis test program did NOT call ::testing::InitGoogleTest "
5279 "before calling RUN_ALL_TESTS(). Please fix it.\n");
5283 // Do not run any test if the --help flag was specified.
5287 // Repeats the call to the post-flag parsing initialization in case the
5288 // user didn't call InitGoogleTest.
5289 PostFlagParsingInit();
5291 // Even if sharding is not on, test runners may want to use the
5292 // GTEST_SHARD_STATUS_FILE to query whether the test supports the sharding
5294 internal::WriteToShardStatusFileIfNeeded();
5296 // True iff we are in a subprocess for running a thread-safe-style
5298 bool in_subprocess_for_death_test = false;
5300 #if GTEST_HAS_DEATH_TEST
5301 in_subprocess_for_death_test = (internal_run_death_test_flag_.get() != NULL);
5302 #endif // GTEST_HAS_DEATH_TEST
5304 const bool should_shard = ShouldShard(kTestTotalShards, kTestShardIndex,
5305 in_subprocess_for_death_test);
5307 // Compares the full test names with the filter to decide which
5309 const bool has_tests_to_run = FilterTests(should_shard
5310 ? HONOR_SHARDING_PROTOCOL
5311 : IGNORE_SHARDING_PROTOCOL) > 0;
5313 // Lists the tests and exits if the --gtest_list_tests flag was specified.
5314 if (GTEST_FLAG(list_tests)) {
5315 // This must be called *after* FilterTests() has been called.
5316 ListTestsMatchingFilter();
5320 random_seed_ = GTEST_FLAG(shuffle) ?
5321 GetRandomSeedFromFlag(GTEST_FLAG(random_seed)) : 0;
5323 // True iff at least one test has failed.
5324 bool failed = false;
5326 TestEventListener* repeater = listeners()->repeater();
5328 repeater->OnTestProgramStart(*parent_);
5330 // How many times to repeat the tests? We don't want to repeat them
5331 // when we are inside the subprocess of a death test.
5332 const int repeat = in_subprocess_for_death_test ? 1 : GTEST_FLAG(repeat);
5333 // Repeats forever if the repeat count is negative.
5334 const bool forever = repeat < 0;
5335 for (int i = 0; forever || i != repeat; i++) {
5338 const TimeInMillis start = GetTimeInMillis();
5340 // Shuffles test cases and tests if requested.
5341 if (has_tests_to_run && GTEST_FLAG(shuffle)) {
5342 random()->Reseed(random_seed_);
5343 // This should be done before calling OnTestIterationStart(),
5344 // such that a test event listener can see the actual test order
5349 // Tells the unit test event listeners that the tests are about to start.
5350 repeater->OnTestIterationStart(*parent_, i);
5352 // Runs each test case if there is at least one test to run.
5353 if (has_tests_to_run) {
5354 // Sets up all environments beforehand.
5355 repeater->OnEnvironmentsSetUpStart(*parent_);
5356 ForEach(environments_, SetUpEnvironment);
5357 repeater->OnEnvironmentsSetUpEnd(*parent_);
5359 // Runs the tests only if there was no fatal failure during global
5361 if (!Test::HasFatalFailure()) {
5362 for (int test_index = 0; test_index < total_test_case_count();
5364 GetMutableTestCase(test_index)->Run();
5368 // Tears down all environments in reverse order afterwards.
5369 repeater->OnEnvironmentsTearDownStart(*parent_);
5370 std::for_each(environments_.rbegin(), environments_.rend(),
5371 TearDownEnvironment);
5372 repeater->OnEnvironmentsTearDownEnd(*parent_);
5375 elapsed_time_ = GetTimeInMillis() - start;
5377 // Tells the unit test event listener that the tests have just finished.
5378 repeater->OnTestIterationEnd(*parent_, i);
5380 // Gets the result and clears it.
5385 // Restores the original test order after the iteration. This
5386 // allows the user to quickly repro a failure that happens in the
5387 // N-th iteration without repeating the first (N - 1) iterations.
5388 // This is not enclosed in "if (GTEST_FLAG(shuffle)) { ... }", in
5389 // case the user somehow changes the value of the flag somewhere
5390 // (it's always safe to unshuffle the tests).
5393 if (GTEST_FLAG(shuffle)) {
5394 // Picks a new random seed for each iteration.
5395 random_seed_ = GetNextRandomSeed(random_seed_);
5399 repeater->OnTestProgramEnd(*parent_);
5401 // Returns 0 if all tests passed, or 1 other wise.
5402 return failed ? 1 : 0;
5405 // Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
5406 // if the variable is present. If a file already exists at this location, this
5407 // function will write over it. If the variable is present, but the file cannot
5408 // be created, prints an error and exits.
5409 void WriteToShardStatusFileIfNeeded() {
5410 const char* const test_shard_file = posix::GetEnv(kTestShardStatusFile);
5411 if (test_shard_file != NULL) {
5412 FILE* const file = posix::FOpen(test_shard_file, "w");
5414 ColoredPrintf(COLOR_RED,
5415 "Could not write to the test shard status file \"%s\" "
5416 "specified by the %s environment variable.\n",
5417 test_shard_file, kTestShardStatusFile);
5425 // Checks whether sharding is enabled by examining the relevant
5426 // environment variable values. If the variables are present,
5427 // but inconsistent (i.e., shard_index >= total_shards), prints
5428 // an error and exits. If in_subprocess_for_death_test, sharding is
5429 // disabled because it must only be applied to the original test
5430 // process. Otherwise, we could filter out death tests we intended to execute.
5431 bool ShouldShard(const char* total_shards_env,
5432 const char* shard_index_env,
5433 bool in_subprocess_for_death_test) {
5434 if (in_subprocess_for_death_test) {
5438 const Int32 total_shards = Int32FromEnvOrDie(total_shards_env, -1);
5439 const Int32 shard_index = Int32FromEnvOrDie(shard_index_env, -1);
5441 if (total_shards == -1 && shard_index == -1) {
5443 } else if (total_shards == -1 && shard_index != -1) {
5444 const Message msg = Message()
5445 << "Invalid environment variables: you have "
5446 << kTestShardIndex << " = " << shard_index
5447 << ", but have left " << kTestTotalShards << " unset.\n";
5448 ColoredPrintf(COLOR_RED, msg.GetString().c_str());
5451 } else if (total_shards != -1 && shard_index == -1) {
5452 const Message msg = Message()
5453 << "Invalid environment variables: you have "
5454 << kTestTotalShards << " = " << total_shards
5455 << ", but have left " << kTestShardIndex << " unset.\n";
5456 ColoredPrintf(COLOR_RED, msg.GetString().c_str());
5459 } else if (shard_index < 0 || shard_index >= total_shards) {
5460 const Message msg = Message()
5461 << "Invalid environment variables: we require 0 <= "
5462 << kTestShardIndex << " < " << kTestTotalShards
5463 << ", but you have " << kTestShardIndex << "=" << shard_index
5464 << ", " << kTestTotalShards << "=" << total_shards << ".\n";
5465 ColoredPrintf(COLOR_RED, msg.GetString().c_str());
5470 return total_shards > 1;
5473 // Parses the environment variable var as an Int32. If it is unset,
5474 // returns default_val. If it is not an Int32, prints an error
5476 Int32 Int32FromEnvOrDie(const char* const var, Int32 default_val) {
5477 const char* str_val = posix::GetEnv(var);
5478 if (str_val == NULL) {
5483 if (!ParseInt32(Message() << "The value of environment variable " << var,
5484 str_val, &result)) {
5490 // Given the total number of shards, the shard index, and the test id,
5491 // returns true iff the test should be run on this shard. The test id is
5492 // some arbitrary but unique non-negative integer assigned to each test
5493 // method. Assumes that 0 <= shard_index < total_shards.
5494 bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) {
5495 return (test_id % total_shards) == shard_index;
5498 // Compares the name of each test with the user-specified filter to
5499 // decide whether the test should be run, then records the result in
5500 // each TestCase and TestInfo object.
5501 // If shard_tests == true, further filters tests based on sharding
5502 // variables in the environment - see
5503 // http://code.google.com/p/googletest/wiki/GoogleTestAdvancedGuide.
5504 // Returns the number of tests that should run.
5505 int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) {
5506 const Int32 total_shards = shard_tests == HONOR_SHARDING_PROTOCOL ?
5507 Int32FromEnvOrDie(kTestTotalShards, -1) : -1;
5508 const Int32 shard_index = shard_tests == HONOR_SHARDING_PROTOCOL ?
5509 Int32FromEnvOrDie(kTestShardIndex, -1) : -1;
5511 // num_runnable_tests are the number of tests that will
5512 // run across all shards (i.e., match filter and are not disabled).
5513 // num_selected_tests are the number of tests to be run on
5515 int num_runnable_tests = 0;
5516 int num_selected_tests = 0;
5517 for (size_t i = 0; i < test_cases_.size(); i++) {
5518 TestCase* const test_case = test_cases_[i];
5519 const String &test_case_name = test_case->name();
5520 test_case->set_should_run(false);
5522 for (size_t j = 0; j < test_case->test_info_list().size(); j++) {
5523 TestInfo* const test_info = test_case->test_info_list()[j];
5524 const String test_name(test_info->name());
5525 // A test is disabled if test case name or test name matches
5526 // kDisableTestFilter.
5527 const bool is_disabled =
5528 internal::UnitTestOptions::MatchesFilter(test_case_name,
5529 kDisableTestFilter) ||
5530 internal::UnitTestOptions::MatchesFilter(test_name,
5531 kDisableTestFilter);
5532 test_info->impl()->set_is_disabled(is_disabled);
5534 const bool matches_filter =
5535 internal::UnitTestOptions::FilterMatchesTest(test_case_name,
5537 test_info->impl()->set_matches_filter(matches_filter);
5539 const bool is_runnable =
5540 (GTEST_FLAG(also_run_disabled_tests) || !is_disabled) &&
5543 const bool is_selected = is_runnable &&
5544 (shard_tests == IGNORE_SHARDING_PROTOCOL ||
5545 ShouldRunTestOnShard(total_shards, shard_index,
5546 num_runnable_tests));
5548 num_runnable_tests += is_runnable;
5549 num_selected_tests += is_selected;
5551 test_info->impl()->set_should_run(is_selected);
5552 test_case->set_should_run(test_case->should_run() || is_selected);
5555 return num_selected_tests;
5558 // Prints the names of the tests matching the user-specified filter flag.
5559 void UnitTestImpl::ListTestsMatchingFilter() {
5560 for (size_t i = 0; i < test_cases_.size(); i++) {
5561 const TestCase* const test_case = test_cases_[i];
5562 bool printed_test_case_name = false;
5564 for (size_t j = 0; j < test_case->test_info_list().size(); j++) {
5565 const TestInfo* const test_info =
5566 test_case->test_info_list()[j];
5567 if (test_info->matches_filter()) {
5568 if (!printed_test_case_name) {
5569 printed_test_case_name = true;
5570 printf("%s.\n", test_case->name());
5572 printf(" %s\n", test_info->name());
5579 // Sets the OS stack trace getter.
5581 // Does nothing if the input and the current OS stack trace getter are
5582 // the same; otherwise, deletes the old getter and makes the input the
5584 void UnitTestImpl::set_os_stack_trace_getter(
5585 OsStackTraceGetterInterface* getter) {
5586 if (os_stack_trace_getter_ != getter) {
5587 delete os_stack_trace_getter_;
5588 os_stack_trace_getter_ = getter;
5592 // Returns the current OS stack trace getter if it is not NULL;
5593 // otherwise, creates an OsStackTraceGetter, makes it the current
5594 // getter, and returns it.
5595 OsStackTraceGetterInterface* UnitTestImpl::os_stack_trace_getter() {
5596 if (os_stack_trace_getter_ == NULL) {
5597 os_stack_trace_getter_ = new OsStackTraceGetter;
5600 return os_stack_trace_getter_;
5603 // Returns the TestResult for the test that's currently running, or
5604 // the TestResult for the ad hoc test if no test is running.
5605 TestResult* UnitTestImpl::current_test_result() {
5606 return current_test_info_ ?
5607 current_test_info_->impl()->result() : &ad_hoc_test_result_;
5610 // Shuffles all test cases, and the tests within each test case,
5611 // making sure that death tests are still run first.
5612 void UnitTestImpl::ShuffleTests() {
5613 // Shuffles the death test cases.
5614 ShuffleRange(random(), 0, last_death_test_case_ + 1, &test_case_indices_);
5616 // Shuffles the non-death test cases.
5617 ShuffleRange(random(), last_death_test_case_ + 1,
5618 static_cast<int>(test_cases_.size()), &test_case_indices_);
5620 // Shuffles the tests inside each test case.
5621 for (size_t i = 0; i < test_cases_.size(); i++) {
5622 test_cases_[i]->ShuffleTests(random());
5626 // Restores the test cases and tests to their order before the first shuffle.
5627 void UnitTestImpl::UnshuffleTests() {
5628 for (size_t i = 0; i < test_cases_.size(); i++) {
5629 // Unshuffles the tests in each test case.
5630 test_cases_[i]->UnshuffleTests();
5631 // Resets the index of each test case.
5632 test_case_indices_[i] = static_cast<int>(i);
5636 // TestInfoImpl constructor. The new instance assumes ownership of the test
5638 TestInfoImpl::TestInfoImpl(TestInfo* parent,
5639 const char* a_test_case_name,
5641 const char* a_test_case_comment,
5642 const char* a_comment,
5643 TypeId a_fixture_class_id,
5644 internal::TestFactoryBase* factory) :
5646 test_case_name_(String(a_test_case_name)),
5647 name_(String(a_name)),
5648 test_case_comment_(String(a_test_case_comment)),
5649 comment_(String(a_comment)),
5650 fixture_class_id_(a_fixture_class_id),
5652 is_disabled_(false),
5653 matches_filter_(false),
5657 // TestInfoImpl destructor.
5658 TestInfoImpl::~TestInfoImpl() {
5662 // Returns the current OS stack trace as a String.
5664 // The maximum number of stack frames to be included is specified by
5665 // the gtest_stack_trace_depth flag. The skip_count parameter
5666 // specifies the number of top frames to be skipped, which doesn't
5667 // count against the number of frames to be included.
5669 // For example, if Foo() calls Bar(), which in turn calls
5670 // GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in
5671 // the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.
5672 String GetCurrentOsStackTraceExceptTop(UnitTest* /*unit_test*/,
5674 // We pass skip_count + 1 to skip this wrapper function in addition
5675 // to what the user really wants to skip.
5676 return GetUnitTestImpl()->CurrentOsStackTraceExceptTop(skip_count + 1);
5679 // Used by the GTEST_HIDE_UNREACHABLE_CODE_ macro to suppress unreachable
5682 class ClassUniqueToAlwaysTrue {};
5685 bool IsTrue(bool condition) { return condition; }
5688 #if GTEST_HAS_EXCEPTIONS
5689 // This condition is always false so AlwaysTrue() never actually throws,
5690 // but it makes the compiler think that it may throw.
5692 throw ClassUniqueToAlwaysTrue();
5693 #endif // GTEST_HAS_EXCEPTIONS
5697 // If *pstr starts with the given prefix, modifies *pstr to be right
5698 // past the prefix and returns true; otherwise leaves *pstr unchanged
5699 // and returns false. None of pstr, *pstr, and prefix can be NULL.
5700 bool SkipPrefix(const char* prefix, const char** pstr) {
5701 const size_t prefix_len = strlen(prefix);
5702 if (strncmp(*pstr, prefix, prefix_len) == 0) {
5703 *pstr += prefix_len;
5709 // Parses a string as a command line flag. The string should have
5710 // the format "--flag=value". When def_optional is true, the "=value"
5711 // part can be omitted.
5713 // Returns the value of the flag, or NULL if the parsing failed.
5714 const char* ParseFlagValue(const char* str,
5716 bool def_optional) {
5717 // str and flag must not be NULL.
5718 if (str == NULL || flag == NULL) return NULL;
5720 // The flag must start with "--" followed by GTEST_FLAG_PREFIX_.
5721 const String flag_str = String::Format("--%s%s", GTEST_FLAG_PREFIX_, flag);
5722 const size_t flag_len = flag_str.length();
5723 if (strncmp(str, flag_str.c_str(), flag_len) != 0) return NULL;
5725 // Skips the flag name.
5726 const char* flag_end = str + flag_len;
5728 // When def_optional is true, it's OK to not have a "=value" part.
5729 if (def_optional && (flag_end[0] == '\0')) {
5733 // If def_optional is true and there are more characters after the
5734 // flag name, or if def_optional is false, there must be a '=' after
5736 if (flag_end[0] != '=') return NULL;
5738 // Returns the string after "=".
5739 return flag_end + 1;
5742 // Parses a string for a bool flag, in the form of either
5743 // "--flag=value" or "--flag".
5745 // In the former case, the value is taken as true as long as it does
5746 // not start with '0', 'f', or 'F'.
5748 // In the latter case, the value is taken as true.
5750 // On success, stores the value of the flag in *value, and returns
5751 // true. On failure, returns false without changing *value.
5752 bool ParseBoolFlag(const char* str, const char* flag, bool* value) {
5753 // Gets the value of the flag as a string.
5754 const char* const value_str = ParseFlagValue(str, flag, true);
5756 // Aborts if the parsing failed.
5757 if (value_str == NULL) return false;
5759 // Converts the string value to a bool.
5760 *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F');
5764 // Parses a string for an Int32 flag, in the form of
5767 // On success, stores the value of the flag in *value, and returns
5768 // true. On failure, returns false without changing *value.
5769 bool ParseInt32Flag(const char* str, const char* flag, Int32* value) {
5770 // Gets the value of the flag as a string.
5771 const char* const value_str = ParseFlagValue(str, flag, false);
5773 // Aborts if the parsing failed.
5774 if (value_str == NULL) return false;
5776 // Sets *value to the value of the flag.
5777 return ParseInt32(Message() << "The value of flag --" << flag,
5781 // Parses a string for a string flag, in the form of
5784 // On success, stores the value of the flag in *value, and returns
5785 // true. On failure, returns false without changing *value.
5786 bool ParseStringFlag(const char* str, const char* flag, String* value) {
5787 // Gets the value of the flag as a string.
5788 const char* const value_str = ParseFlagValue(str, flag, false);
5790 // Aborts if the parsing failed.
5791 if (value_str == NULL) return false;
5793 // Sets *value to the value of the flag.
5798 // Determines whether a string has a prefix that Google Test uses for its
5799 // flags, i.e., starts with GTEST_FLAG_PREFIX_ or GTEST_FLAG_PREFIX_DASH_.
5800 // If Google Test detects that a command line flag has its prefix but is not
5801 // recognized, it will print its help message. Flags starting with
5802 // GTEST_INTERNAL_PREFIX_ followed by "internal_" are considered Google Test
5803 // internal flags and do not trigger the help message.
5804 static bool HasGoogleTestFlagPrefix(const char* str) {
5805 return (SkipPrefix("--", &str) ||
5806 SkipPrefix("-", &str) ||
5807 SkipPrefix("/", &str)) &&
5808 !SkipPrefix(GTEST_FLAG_PREFIX_ "internal_", &str) &&
5809 (SkipPrefix(GTEST_FLAG_PREFIX_, &str) ||
5810 SkipPrefix(GTEST_FLAG_PREFIX_DASH_, &str));
5813 // Prints a string containing code-encoded text. The following escape
5814 // sequences can be used in the string to control the text color:
5816 // @@ prints a single '@' character.
5817 // @R changes the color to red.
5818 // @G changes the color to green.
5819 // @Y changes the color to yellow.
5820 // @D changes to the default terminal text color.
5822 // TODO(wan@google.com): Write tests for this once we add stdout
5823 // capturing to Google Test.
5824 static void PrintColorEncoded(const char* str) {
5825 GTestColor color = COLOR_DEFAULT; // The current color.
5827 // Conceptually, we split the string into segments divided by escape
5828 // sequences. Then we print one segment at a time. At the end of
5829 // each iteration, the str pointer advances to the beginning of the
5832 const char* p = strchr(str, '@');
5834 ColoredPrintf(color, "%s", str);
5838 ColoredPrintf(color, "%s", String(str, p - str).c_str());
5840 const char ch = p[1];
5843 ColoredPrintf(color, "@");
5844 } else if (ch == 'D') {
5845 color = COLOR_DEFAULT;
5846 } else if (ch == 'R') {
5848 } else if (ch == 'G') {
5849 color = COLOR_GREEN;
5850 } else if (ch == 'Y') {
5851 color = COLOR_YELLOW;
5858 static const char kColorEncodedHelpMessage[] =
5859 "This program contains tests written using " GTEST_NAME_ ". You can use the\n"
5860 "following command line flags to control its behavior:\n"
5863 " @G--" GTEST_FLAG_PREFIX_ "list_tests@D\n"
5864 " List the names of all tests instead of running them. The name of\n"
5865 " TEST(Foo, Bar) is \"Foo.Bar\".\n"
5866 " @G--" GTEST_FLAG_PREFIX_ "filter=@YPOSTIVE_PATTERNS"
5867 "[@G-@YNEGATIVE_PATTERNS]@D\n"
5868 " Run only the tests whose name matches one of the positive patterns but\n"
5869 " none of the negative patterns. '?' matches any single character; '*'\n"
5870 " matches any substring; ':' separates two patterns.\n"
5871 " @G--" GTEST_FLAG_PREFIX_ "also_run_disabled_tests@D\n"
5872 " Run all disabled tests too.\n"
5875 " @G--" GTEST_FLAG_PREFIX_ "repeat=@Y[COUNT]@D\n"
5876 " Run the tests repeatedly; use a negative count to repeat forever.\n"
5877 " @G--" GTEST_FLAG_PREFIX_ "shuffle@D\n"
5878 " Randomize tests' orders on every iteration.\n"
5879 " @G--" GTEST_FLAG_PREFIX_ "random_seed=@Y[NUMBER]@D\n"
5880 " Random number seed to use for shuffling test orders (between 1 and\n"
5881 " 99999, or 0 to use a seed based on the current time).\n"
5884 " @G--" GTEST_FLAG_PREFIX_ "color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\n"
5885 " Enable/disable colored output. The default is @Gauto@D.\n"
5886 " -@G-" GTEST_FLAG_PREFIX_ "print_time=0@D\n"
5887 " Don't print the elapsed time of each test.\n"
5888 " @G--" GTEST_FLAG_PREFIX_ "output=xml@Y[@G:@YDIRECTORY_PATH@G"
5889 GTEST_PATH_SEP_ "@Y|@G:@YFILE_PATH]@D\n"
5890 " Generate an XML report in the given directory or with the given file\n"
5891 " name. @YFILE_PATH@D defaults to @Gtest_details.xml@D.\n"
5893 "Assertion Behavior:\n"
5894 #if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
5895 " @G--" GTEST_FLAG_PREFIX_ "death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n"
5896 " Set the default death test style.\n"
5897 #endif // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
5898 " @G--" GTEST_FLAG_PREFIX_ "break_on_failure@D\n"
5899 " Turn assertion failures into debugger break-points.\n"
5900 " @G--" GTEST_FLAG_PREFIX_ "throw_on_failure@D\n"
5901 " Turn assertion failures into C++ exceptions.\n"
5902 #if GTEST_OS_WINDOWS
5903 " @G--" GTEST_FLAG_PREFIX_ "catch_exceptions@D\n"
5904 " Suppress pop-ups caused by exceptions.\n"
5905 #endif // GTEST_OS_WINDOWS
5907 "Except for @G--" GTEST_FLAG_PREFIX_ "list_tests@D, you can alternatively set "
5908 "the corresponding\n"
5909 "environment variable of a flag (all letters in upper-case). For example, to\n"
5910 "disable colored text output, you can either specify @G--" GTEST_FLAG_PREFIX_
5911 "color=no@D or set\n"
5912 "the @G" GTEST_FLAG_PREFIX_UPPER_ "COLOR@D environment variable to @Gno@D.\n"
5914 "For more information, please read the " GTEST_NAME_ " documentation at\n"
5915 "@G" GTEST_PROJECT_URL_ "@D. If you find a bug in " GTEST_NAME_ "\n"
5916 "(not one in your own code or tests), please report it to\n"
5917 "@G<" GTEST_DEV_EMAIL_ ">@D.\n";
5919 // Parses the command line for Google Test flags, without initializing
5920 // other parts of Google Test. The type parameter CharType can be
5921 // instantiated to either char or wchar_t.
5922 template <typename CharType>
5923 void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) {
5924 for (int i = 1; i < *argc; i++) {
5925 const String arg_string = StreamableToString(argv[i]);
5926 const char* const arg = arg_string.c_str();
5928 using internal::ParseBoolFlag;
5929 using internal::ParseInt32Flag;
5930 using internal::ParseStringFlag;
5932 // Do we see a Google Test flag?
5933 if (ParseBoolFlag(arg, kAlsoRunDisabledTestsFlag,
5934 >EST_FLAG(also_run_disabled_tests)) ||
5935 ParseBoolFlag(arg, kBreakOnFailureFlag,
5936 >EST_FLAG(break_on_failure)) ||
5937 ParseBoolFlag(arg, kCatchExceptionsFlag,
5938 >EST_FLAG(catch_exceptions)) ||
5939 ParseStringFlag(arg, kColorFlag, >EST_FLAG(color)) ||
5940 ParseStringFlag(arg, kDeathTestStyleFlag,
5941 >EST_FLAG(death_test_style)) ||
5942 ParseBoolFlag(arg, kDeathTestUseFork,
5943 >EST_FLAG(death_test_use_fork)) ||
5944 ParseStringFlag(arg, kFilterFlag, >EST_FLAG(filter)) ||
5945 ParseStringFlag(arg, kInternalRunDeathTestFlag,
5946 >EST_FLAG(internal_run_death_test)) ||
5947 ParseBoolFlag(arg, kListTestsFlag, >EST_FLAG(list_tests)) ||
5948 ParseStringFlag(arg, kOutputFlag, >EST_FLAG(output)) ||
5949 ParseBoolFlag(arg, kPrintTimeFlag, >EST_FLAG(print_time)) ||
5950 ParseInt32Flag(arg, kRandomSeedFlag, >EST_FLAG(random_seed)) ||
5951 ParseInt32Flag(arg, kRepeatFlag, >EST_FLAG(repeat)) ||
5952 ParseBoolFlag(arg, kShuffleFlag, >EST_FLAG(shuffle)) ||
5953 ParseInt32Flag(arg, kStackTraceDepthFlag,
5954 >EST_FLAG(stack_trace_depth)) ||
5955 ParseBoolFlag(arg, kThrowOnFailureFlag, >EST_FLAG(throw_on_failure))
5957 // Yes. Shift the remainder of the argv list left by one. Note
5958 // that argv has (*argc + 1) elements, the last one always being
5959 // NULL. The following loop moves the trailing NULL element as
5961 for (int j = i; j != *argc; j++) {
5962 argv[j] = argv[j + 1];
5965 // Decrements the argument count.
5968 // We also need to decrement the iterator as we just removed
5971 } else if (arg_string == "--help" || arg_string == "-h" ||
5972 arg_string == "-?" || arg_string == "/?" ||
5973 HasGoogleTestFlagPrefix(arg)) {
5974 // Both help flag and unrecognized Google Test flags (excluding
5975 // internal ones) trigger help display.
5981 // We print the help here instead of in RUN_ALL_TESTS(), as the
5982 // latter may not be called at all if the user is using Google
5983 // Test with another testing framework.
5984 PrintColorEncoded(kColorEncodedHelpMessage);
5988 // Parses the command line for Google Test flags, without initializing
5989 // other parts of Google Test.
5990 void ParseGoogleTestFlagsOnly(int* argc, char** argv) {
5991 ParseGoogleTestFlagsOnlyImpl(argc, argv);
5993 void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv) {
5994 ParseGoogleTestFlagsOnlyImpl(argc, argv);
5997 // The internal implementation of InitGoogleTest().
5999 // The type parameter CharType can be instantiated to either char or
6001 template <typename CharType>
6002 void InitGoogleTestImpl(int* argc, CharType** argv) {
6003 g_init_gtest_count++;
6005 // We don't want to run the initialization code twice.
6006 if (g_init_gtest_count != 1) return;
6008 if (*argc <= 0) return;
6010 internal::g_executable_path = internal::StreamableToString(argv[0]);
6012 #if GTEST_HAS_DEATH_TEST
6014 for (int i = 0; i != *argc; i++) {
6015 g_argvs.push_back(StreamableToString(argv[i]));
6017 #endif // GTEST_HAS_DEATH_TEST
6019 ParseGoogleTestFlagsOnly(argc, argv);
6020 GetUnitTestImpl()->PostFlagParsingInit();
6023 } // namespace internal
6025 // Initializes Google Test. This must be called before calling
6026 // RUN_ALL_TESTS(). In particular, it parses a command line for the
6027 // flags that Google Test recognizes. Whenever a Google Test flag is
6028 // seen, it is removed from argv, and *argc is decremented.
6030 // No value is returned. Instead, the Google Test flag variables are
6033 // Calling the function for the second time has no user-visible effect.
6034 void InitGoogleTest(int* argc, char** argv) {
6035 internal::InitGoogleTestImpl(argc, argv);
6038 // This overloaded version can be used in Windows programs compiled in
6040 void InitGoogleTest(int* argc, wchar_t** argv) {
6041 internal::InitGoogleTestImpl(argc, argv);
6044 } // namespace testing
6045 // Copyright 2005, Google Inc.
6046 // All rights reserved.
6048 // Redistribution and use in source and binary forms, with or without
6049 // modification, are permitted provided that the following conditions are
6052 // * Redistributions of source code must retain the above copyright
6053 // notice, this list of conditions and the following disclaimer.
6054 // * Redistributions in binary form must reproduce the above
6055 // copyright notice, this list of conditions and the following disclaimer
6056 // in the documentation and/or other materials provided with the
6058 // * Neither the name of Google Inc. nor the names of its
6059 // contributors may be used to endorse or promote products derived from
6060 // this software without specific prior written permission.
6062 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
6063 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
6064 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
6065 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
6066 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
6067 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
6068 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
6069 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
6070 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
6071 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
6072 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
6074 // Author: wan@google.com (Zhanyong Wan), vladl@google.com (Vlad Losev)
6076 // This file implements death tests.
6079 #if GTEST_HAS_DEATH_TEST
6082 #include <crt_externs.h>
6083 #endif // GTEST_OS_MAC
6090 #if GTEST_OS_WINDOWS
6091 #include <windows.h>
6093 #include <sys/mman.h>
6094 #include <sys/wait.h>
6095 #endif // GTEST_OS_WINDOWS
6097 #endif // GTEST_HAS_DEATH_TEST
6100 // Indicates that this translation unit is part of Google Test's
6101 // implementation. It must come before gtest-internal-inl.h is
6102 // included, or there will be a compiler error. This trick is to
6103 // prevent a user from accidentally including gtest-internal-inl.h in
6105 #define GTEST_IMPLEMENTATION_ 1
6106 #undef GTEST_IMPLEMENTATION_
6112 // The default death test style.
6113 static const char kDefaultDeathTestStyle[] = "fast";
6115 GTEST_DEFINE_string_(
6117 internal::StringFromGTestEnv("death_test_style", kDefaultDeathTestStyle),
6118 "Indicates how to run a death test in a forked child process: "
6119 "\"threadsafe\" (child process re-executes the test binary "
6120 "from the beginning, running only the specific death test) or "
6121 "\"fast\" (child process runs the death test immediately "
6125 death_test_use_fork,
6126 internal::BoolFromGTestEnv("death_test_use_fork", false),
6127 "Instructs to use fork()/_exit() instead of clone() in death tests. "
6128 "Ignored and always uses fork() on POSIX systems where clone() is not "
6129 "implemented. Useful when running under valgrind or similar tools if "
6130 "those do not support clone(). Valgrind 3.3.1 will just fail if "
6131 "it sees an unsupported combination of clone() flags. "
6132 "It is not recommended to use this flag w/o valgrind though it will "
6133 "work in 99% of the cases. Once valgrind is fixed, this flag will "
6134 "most likely be removed.");
6136 namespace internal {
6137 GTEST_DEFINE_string_(
6138 internal_run_death_test, "",
6139 "Indicates the file, line number, temporal index of "
6140 "the single death test to run, and a file descriptor to "
6141 "which a success code may be sent, all separated by "
6142 "colons. This flag is specified if and only if the current "
6143 "process is a sub-process launched for running a thread-safe "
6144 "death test. FOR INTERNAL USE ONLY.");
6145 } // namespace internal
6147 #if GTEST_HAS_DEATH_TEST
6149 // ExitedWithCode constructor.
6150 ExitedWithCode::ExitedWithCode(int exit_code) : exit_code_(exit_code) {
6153 // ExitedWithCode function-call operator.
6154 bool ExitedWithCode::operator()(int exit_status) const {
6155 #if GTEST_OS_WINDOWS
6156 return exit_status == exit_code_;
6158 return WIFEXITED(exit_status) && WEXITSTATUS(exit_status) == exit_code_;
6159 #endif // GTEST_OS_WINDOWS
6162 #if !GTEST_OS_WINDOWS
6163 // KilledBySignal constructor.
6164 KilledBySignal::KilledBySignal(int signum) : signum_(signum) {
6167 // KilledBySignal function-call operator.
6168 bool KilledBySignal::operator()(int exit_status) const {
6169 return WIFSIGNALED(exit_status) && WTERMSIG(exit_status) == signum_;
6171 #endif // !GTEST_OS_WINDOWS
6173 namespace internal {
6175 // Utilities needed for death tests.
6177 // Generates a textual description of a given exit code, in the format
6178 // specified by wait(2).
6179 static String ExitSummary(int exit_code) {
6181 #if GTEST_OS_WINDOWS
6182 m << "Exited with exit status " << exit_code;
6184 if (WIFEXITED(exit_code)) {
6185 m << "Exited with exit status " << WEXITSTATUS(exit_code);
6186 } else if (WIFSIGNALED(exit_code)) {
6187 m << "Terminated by signal " << WTERMSIG(exit_code);
6190 if (WCOREDUMP(exit_code)) {
6191 m << " (core dumped)";
6194 #endif // GTEST_OS_WINDOWS
6195 return m.GetString();
6198 // Returns true if exit_status describes a process that was terminated
6199 // by a signal, or exited normally with a nonzero exit code.
6200 bool ExitedUnsuccessfully(int exit_status) {
6201 return !ExitedWithCode(0)(exit_status);
6204 #if !GTEST_OS_WINDOWS
6205 // Generates a textual failure message when a death test finds more than
6206 // one thread running, or cannot determine the number of threads, prior
6207 // to executing the given statement. It is the responsibility of the
6208 // caller not to pass a thread_count of 1.
6209 static String DeathTestThreadWarning(size_t thread_count) {
6211 msg << "Death tests use fork(), which is unsafe particularly"
6212 << " in a threaded context. For this test, " << GTEST_NAME_ << " ";
6213 if (thread_count == 0)
6214 msg << "couldn't detect the number of threads.";
6216 msg << "detected " << thread_count << " threads.";
6217 return msg.GetString();
6219 #endif // !GTEST_OS_WINDOWS
6221 // Flag characters for reporting a death test that did not die.
6222 static const char kDeathTestLived = 'L';
6223 static const char kDeathTestReturned = 'R';
6224 static const char kDeathTestInternalError = 'I';
6226 // An enumeration describing all of the possible ways that a death test
6227 // can conclude. DIED means that the process died while executing the
6228 // test code; LIVED means that process lived beyond the end of the test
6229 // code; and RETURNED means that the test statement attempted a "return,"
6230 // which is not allowed. IN_PROGRESS means the test has not yet
6232 enum DeathTestOutcome { IN_PROGRESS, DIED, LIVED, RETURNED };
6234 // Routine for aborting the program which is safe to call from an
6235 // exec-style death test child process, in which case the error
6236 // message is propagated back to the parent process. Otherwise, the
6237 // message is simply printed to stderr. In either case, the program
6238 // then exits with status 1.
6239 void DeathTestAbort(const String& message) {
6240 // On a POSIX system, this function may be called from a threadsafe-style
6241 // death test child process, which operates on a very small stack. Use
6242 // the heap for any additional non-minuscule memory requirements.
6243 const InternalRunDeathTestFlag* const flag =
6244 GetUnitTestImpl()->internal_run_death_test_flag();
6246 FILE* parent = posix::FDOpen(flag->write_fd(), "w");
6247 fputc(kDeathTestInternalError, parent);
6248 fprintf(parent, "%s", message.c_str());
6252 fprintf(stderr, "%s", message.c_str());
6258 // A replacement for CHECK that calls DeathTestAbort if the assertion
6260 #define GTEST_DEATH_TEST_CHECK_(expression) \
6262 if (!::testing::internal::IsTrue(expression)) { \
6263 DeathTestAbort(::testing::internal::String::Format( \
6264 "CHECK failed: File %s, line %d: %s", \
6265 __FILE__, __LINE__, #expression)); \
6267 } while (::testing::internal::AlwaysFalse())
6269 // This macro is similar to GTEST_DEATH_TEST_CHECK_, but it is meant for
6270 // evaluating any system call that fulfills two conditions: it must return
6271 // -1 on failure, and set errno to EINTR when it is interrupted and
6272 // should be tried again. The macro expands to a loop that repeatedly
6273 // evaluates the expression as long as it evaluates to -1 and sets
6274 // errno to EINTR. If the expression evaluates to -1 but errno is
6275 // something other than EINTR, DeathTestAbort is called.
6276 #define GTEST_DEATH_TEST_CHECK_SYSCALL_(expression) \
6280 gtest_retval = (expression); \
6281 } while (gtest_retval == -1 && errno == EINTR); \
6282 if (gtest_retval == -1) { \
6283 DeathTestAbort(::testing::internal::String::Format( \
6284 "CHECK failed: File %s, line %d: %s != -1", \
6285 __FILE__, __LINE__, #expression)); \
6287 } while (::testing::internal::AlwaysFalse())
6289 // Returns the message describing the last system error in errno.
6290 String GetLastErrnoDescription() {
6291 return String(errno == 0 ? "" : posix::StrError(errno));
6294 // This is called from a death test parent process to read a failure
6295 // message from the death test child process and log it with the FATAL
6296 // severity. On Windows, the message is read from a pipe handle. On other
6297 // platforms, it is read from a file descriptor.
6298 static void FailFromInternalError(int fd) {
6304 while ((num_read = posix::Read(fd, buffer, 255)) > 0) {
6305 buffer[num_read] = '\0';
6308 } while (num_read == -1 && errno == EINTR);
6310 if (num_read == 0) {
6311 GTEST_LOG_(FATAL) << error.GetString();
6313 const int last_error = errno;
6314 GTEST_LOG_(FATAL) << "Error while reading death test internal: "
6315 << GetLastErrnoDescription() << " [" << last_error << "]";
6319 // Death test constructor. Increments the running death test count
6320 // for the current test.
6321 DeathTest::DeathTest() {
6322 TestInfo* const info = GetUnitTestImpl()->current_test_info();
6324 DeathTestAbort("Cannot run a death test outside of a TEST or "
6325 "TEST_F construct");
6329 // Creates and returns a death test by dispatching to the current
6330 // death test factory.
6331 bool DeathTest::Create(const char* statement, const RE* regex,
6332 const char* file, int line, DeathTest** test) {
6333 return GetUnitTestImpl()->death_test_factory()->Create(
6334 statement, regex, file, line, test);
6337 const char* DeathTest::LastMessage() {
6338 return last_death_test_message_.c_str();
6341 void DeathTest::set_last_death_test_message(const String& message) {
6342 last_death_test_message_ = message;
6345 String DeathTest::last_death_test_message_;
6347 // Provides cross platform implementation for some death functionality.
6348 class DeathTestImpl : public DeathTest {
6350 DeathTestImpl(const char* a_statement, const RE* a_regex)
6351 : statement_(a_statement),
6355 outcome_(IN_PROGRESS),
6359 // read_fd_ is expected to be closed and cleared by a derived class.
6360 ~DeathTestImpl() { GTEST_DEATH_TEST_CHECK_(read_fd_ == -1); }
6362 void Abort(AbortReason reason);
6363 virtual bool Passed(bool status_ok);
6365 const char* statement() const { return statement_; }
6366 const RE* regex() const { return regex_; }
6367 bool spawned() const { return spawned_; }
6368 void set_spawned(bool is_spawned) { spawned_ = is_spawned; }
6369 int status() const { return status_; }
6370 void set_status(int a_status) { status_ = a_status; }
6371 DeathTestOutcome outcome() const { return outcome_; }
6372 void set_outcome(DeathTestOutcome an_outcome) { outcome_ = an_outcome; }
6373 int read_fd() const { return read_fd_; }
6374 void set_read_fd(int fd) { read_fd_ = fd; }
6375 int write_fd() const { return write_fd_; }
6376 void set_write_fd(int fd) { write_fd_ = fd; }
6378 // Called in the parent process only. Reads the result code of the death
6379 // test child process via a pipe, interprets it to set the outcome_
6380 // member, and closes read_fd_. Outputs diagnostics and terminates in
6381 // case of unexpected codes.
6382 void ReadAndInterpretStatusByte();
6385 // The textual content of the code this object is testing. This class
6386 // doesn't own this string and should not attempt to delete it.
6387 const char* const statement_;
6388 // The regular expression which test output must match. DeathTestImpl
6389 // doesn't own this object and should not attempt to delete it.
6390 const RE* const regex_;
6391 // True if the death test child process has been successfully spawned.
6393 // The exit status of the child process.
6395 // How the death test concluded.
6396 DeathTestOutcome outcome_;
6397 // Descriptor to the read end of the pipe to the child process. It is
6398 // always -1 in the child process. The child keeps its write end of the
6399 // pipe in write_fd_.
6401 // Descriptor to the child's write end of the pipe to the parent process.
6402 // It is always -1 in the parent process. The parent keeps its end of the
6403 // pipe in read_fd_.
6407 // Called in the parent process only. Reads the result code of the death
6408 // test child process via a pipe, interprets it to set the outcome_
6409 // member, and closes read_fd_. Outputs diagnostics and terminates in
6410 // case of unexpected codes.
6411 void DeathTestImpl::ReadAndInterpretStatusByte() {
6415 // The read() here blocks until data is available (signifying the
6416 // failure of the death test) or until the pipe is closed (signifying
6417 // its success), so it's okay to call this in the parent before
6418 // the child process has exited.
6420 bytes_read = posix::Read(read_fd(), &flag, 1);
6421 } while (bytes_read == -1 && errno == EINTR);
6423 if (bytes_read == 0) {
6425 } else if (bytes_read == 1) {
6427 case kDeathTestReturned:
6428 set_outcome(RETURNED);
6430 case kDeathTestLived:
6433 case kDeathTestInternalError:
6434 FailFromInternalError(read_fd()); // Does not return.
6437 GTEST_LOG_(FATAL) << "Death test child process reported "
6438 << "unexpected status byte ("
6439 << static_cast<unsigned int>(flag) << ")";
6442 GTEST_LOG_(FATAL) << "Read from death test child process failed: "
6443 << GetLastErrnoDescription();
6445 GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Close(read_fd()));
6449 // Signals that the death test code which should have exited, didn't.
6450 // Should be called only in a death test child process.
6451 // Writes a status byte to the child's status file descriptor, then
6453 void DeathTestImpl::Abort(AbortReason reason) {
6454 // The parent process considers the death test to be a failure if
6455 // it finds any data in our pipe. So, here we write a single flag byte
6456 // to the pipe, then exit.
6457 const char status_ch =
6458 reason == TEST_DID_NOT_DIE ? kDeathTestLived : kDeathTestReturned;
6459 GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Write(write_fd(), &status_ch, 1));
6460 GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Close(write_fd()));
6461 _exit(1); // Exits w/o any normal exit hooks (we were supposed to crash)
6464 // Assesses the success or failure of a death test, using both private
6465 // members which have previously been set, and one argument:
6467 // Private data members:
6468 // outcome: An enumeration describing how the death test
6469 // concluded: DIED, LIVED, or RETURNED. The death test fails
6470 // in the latter two cases.
6471 // status: The exit status of the child process. On *nix, it is in the
6472 // in the format specified by wait(2). On Windows, this is the
6473 // value supplied to the ExitProcess() API or a numeric code
6474 // of the exception that terminated the program.
6475 // regex: A regular expression object to be applied to
6476 // the test's captured standard error output; the death test
6477 // fails if it does not match.
6480 // status_ok: true if exit_status is acceptable in the context of
6481 // this particular death test, which fails if it is false
6483 // Returns true iff all of the above conditions are met. Otherwise, the
6484 // first failing condition, in the order given above, is the one that is
6485 // reported. Also sets the last death test message string.
6486 bool DeathTestImpl::Passed(bool status_ok) {
6490 const String error_message = GetCapturedStderr();
6492 bool success = false;
6495 buffer << "Death test: " << statement() << "\n";
6496 switch (outcome()) {
6498 buffer << " Result: failed to die.\n"
6499 << " Error msg: " << error_message;
6502 buffer << " Result: illegal return in test statement.\n"
6503 << " Error msg: " << error_message;
6507 const bool matched = RE::PartialMatch(error_message.c_str(), *regex());
6511 buffer << " Result: died but not with expected error.\n"
6512 << " Expected: " << regex()->pattern() << "\n"
6513 << "Actual msg: " << error_message;
6516 buffer << " Result: died but not with expected exit code:\n"
6517 << " " << ExitSummary(status()) << "\n";
6523 << "DeathTest::Passed somehow called before conclusion of test";
6526 DeathTest::set_last_death_test_message(buffer.GetString());
6530 #if GTEST_OS_WINDOWS
6531 // WindowsDeathTest implements death tests on Windows. Due to the
6532 // specifics of starting new processes on Windows, death tests there are
6533 // always threadsafe, and Google Test considers the
6534 // --gtest_death_test_style=fast setting to be equivalent to
6535 // --gtest_death_test_style=threadsafe there.
6537 // A few implementation notes: Like the Linux version, the Windows
6538 // implementation uses pipes for child-to-parent communication. But due to
6539 // the specifics of pipes on Windows, some extra steps are required:
6541 // 1. The parent creates a communication pipe and stores handles to both
6543 // 2. The parent starts the child and provides it with the information
6544 // necessary to acquire the handle to the write end of the pipe.
6545 // 3. The child acquires the write end of the pipe and signals the parent
6546 // using a Windows event.
6547 // 4. Now the parent can release the write end of the pipe on its side. If
6548 // this is done before step 3, the object's reference count goes down to
6549 // 0 and it is destroyed, preventing the child from acquiring it. The
6550 // parent now has to release it, or read operations on the read end of
6551 // the pipe will not return when the child terminates.
6552 // 5. The parent reads child's output through the pipe (outcome code and
6553 // any possible error messages) from the pipe, and its stderr and then
6554 // determines whether to fail the test.
6556 // Note: to distinguish Win32 API calls from the local method and function
6557 // calls, the former are explicitly resolved in the global namespace.
6559 class WindowsDeathTest : public DeathTestImpl {
6561 WindowsDeathTest(const char* statement,
6565 : DeathTestImpl(statement, regex), file_(file), line_(line) {}
6567 // All of these virtual functions are inherited from DeathTest.
6569 virtual TestRole AssumeRole();
6572 // The name of the file in which the death test is located.
6573 const char* const file_;
6574 // The line number on which the death test is located.
6576 // Handle to the write end of the pipe to the child process.
6577 AutoHandle write_handle_;
6578 // Child process handle.
6579 AutoHandle child_handle_;
6580 // Event the child process uses to signal the parent that it has
6581 // acquired the handle to the write end of the pipe. After seeing this
6582 // event the parent can release its own handles to make sure its
6583 // ReadFile() calls return when the child terminates.
6584 AutoHandle event_handle_;
6587 // Waits for the child in a death test to exit, returning its exit
6588 // status, or 0 if no child process exists. As a side effect, sets the
6589 // outcome data member.
6590 int WindowsDeathTest::Wait() {
6594 // Wait until the child either signals that it has acquired the write end
6595 // of the pipe or it dies.
6596 const HANDLE wait_handles[2] = { child_handle_.Get(), event_handle_.Get() };
6597 switch (::WaitForMultipleObjects(2,
6599 FALSE, // Waits for any of the handles.
6602 case WAIT_OBJECT_0 + 1:
6605 GTEST_DEATH_TEST_CHECK_(false); // Should not get here.
6608 // The child has acquired the write end of the pipe or exited.
6609 // We release the handle on our side and continue.
6610 write_handle_.Reset();
6611 event_handle_.Reset();
6613 ReadAndInterpretStatusByte();
6615 // Waits for the child process to exit if it haven't already. This
6616 // returns immediately if the child has already exited, regardless of
6617 // whether previous calls to WaitForMultipleObjects synchronized on this
6619 GTEST_DEATH_TEST_CHECK_(
6620 WAIT_OBJECT_0 == ::WaitForSingleObject(child_handle_.Get(),
6623 GTEST_DEATH_TEST_CHECK_(::GetExitCodeProcess(child_handle_.Get(), &status)
6625 child_handle_.Reset();
6626 set_status(static_cast<int>(status));
6627 return this->status();
6630 // The AssumeRole process for a Windows death test. It creates a child
6631 // process with the same executable as the current process to run the
6632 // death test. The child process is given the --gtest_filter and
6633 // --gtest_internal_run_death_test flags such that it knows to run the
6634 // current death test only.
6635 DeathTest::TestRole WindowsDeathTest::AssumeRole() {
6636 const UnitTestImpl* const impl = GetUnitTestImpl();
6637 const InternalRunDeathTestFlag* const flag =
6638 impl->internal_run_death_test_flag();
6639 const TestInfo* const info = impl->current_test_info();
6640 const int death_test_index = info->result()->death_test_count();
6643 // ParseInternalRunDeathTestFlag() has performed all the necessary
6645 set_write_fd(flag->write_fd());
6646 return EXECUTE_TEST;
6649 // WindowsDeathTest uses an anonymous pipe to communicate results of
6651 SECURITY_ATTRIBUTES handles_are_inheritable = {
6652 sizeof(SECURITY_ATTRIBUTES), NULL, TRUE };
6653 HANDLE read_handle, write_handle;
6654 GTEST_DEATH_TEST_CHECK_(
6655 ::CreatePipe(&read_handle, &write_handle, &handles_are_inheritable,
6656 0) // Default buffer size.
6658 set_read_fd(::_open_osfhandle(reinterpret_cast<intptr_t>(read_handle),
6660 write_handle_.Reset(write_handle);
6661 event_handle_.Reset(::CreateEvent(
6662 &handles_are_inheritable,
6663 TRUE, // The event will automatically reset to non-signaled state.
6664 FALSE, // The initial state is non-signalled.
6665 NULL)); // The even is unnamed.
6666 GTEST_DEATH_TEST_CHECK_(event_handle_.Get() != NULL);
6667 const String filter_flag = String::Format("--%s%s=%s.%s",
6668 GTEST_FLAG_PREFIX_, kFilterFlag,
6669 info->test_case_name(),
6671 const String internal_flag = String::Format(
6672 "--%s%s=%s|%d|%d|%u|%Iu|%Iu",
6674 kInternalRunDeathTestFlag,
6677 static_cast<unsigned int>(::GetCurrentProcessId()),
6678 // size_t has the same with as pointers on both 32-bit and 64-bit
6679 // Windows platforms.
6680 // See http://msdn.microsoft.com/en-us/library/tcxf1dw6.aspx.
6681 reinterpret_cast<size_t>(write_handle),
6682 reinterpret_cast<size_t>(event_handle_.Get()));
6684 char executable_path[_MAX_PATH + 1]; // NOLINT
6685 GTEST_DEATH_TEST_CHECK_(
6686 _MAX_PATH + 1 != ::GetModuleFileNameA(NULL,
6690 String command_line = String::Format("%s %s \"%s\"",
6691 ::GetCommandLineA(),
6692 filter_flag.c_str(),
6693 internal_flag.c_str());
6695 DeathTest::set_last_death_test_message("");
6698 // Flush the log buffers since the log streams are shared with the child.
6701 // The child process will share the standard handles with the parent.
6702 STARTUPINFOA startup_info;
6703 memset(&startup_info, 0, sizeof(STARTUPINFO));
6704 startup_info.dwFlags = STARTF_USESTDHANDLES;
6705 startup_info.hStdInput = ::GetStdHandle(STD_INPUT_HANDLE);
6706 startup_info.hStdOutput = ::GetStdHandle(STD_OUTPUT_HANDLE);
6707 startup_info.hStdError = ::GetStdHandle(STD_ERROR_HANDLE);
6709 PROCESS_INFORMATION process_info;
6710 GTEST_DEATH_TEST_CHECK_(::CreateProcessA(
6712 const_cast<char*>(command_line.c_str()),
6713 NULL, // Retuned process handle is not inheritable.
6714 NULL, // Retuned thread handle is not inheritable.
6715 TRUE, // Child inherits all inheritable handles (for write_handle_).
6716 0x0, // Default creation flags.
6717 NULL, // Inherit the parent's environment.
6718 UnitTest::GetInstance()->original_working_dir(),
6720 &process_info) != FALSE);
6721 child_handle_.Reset(process_info.hProcess);
6722 ::CloseHandle(process_info.hThread);
6724 return OVERSEE_TEST;
6726 #else // We are not on Windows.
6728 // ForkingDeathTest provides implementations for most of the abstract
6729 // methods of the DeathTest interface. Only the AssumeRole method is
6731 class ForkingDeathTest : public DeathTestImpl {
6733 ForkingDeathTest(const char* statement, const RE* regex);
6735 // All of these virtual functions are inherited from DeathTest.
6739 void set_child_pid(pid_t child_pid) { child_pid_ = child_pid; }
6742 // PID of child process during death test; 0 in the child process itself.
6746 // Constructs a ForkingDeathTest.
6747 ForkingDeathTest::ForkingDeathTest(const char* a_statement, const RE* a_regex)
6748 : DeathTestImpl(a_statement, a_regex),
6751 // Waits for the child in a death test to exit, returning its exit
6752 // status, or 0 if no child process exists. As a side effect, sets the
6753 // outcome data member.
6754 int ForkingDeathTest::Wait() {
6758 ReadAndInterpretStatusByte();
6761 GTEST_DEATH_TEST_CHECK_SYSCALL_(waitpid(child_pid_, &status_value, 0));
6762 set_status(status_value);
6763 return status_value;
6766 // A concrete death test class that forks, then immediately runs the test
6767 // in the child process.
6768 class NoExecDeathTest : public ForkingDeathTest {
6770 NoExecDeathTest(const char* a_statement, const RE* a_regex) :
6771 ForkingDeathTest(a_statement, a_regex) { }
6772 virtual TestRole AssumeRole();
6775 // The AssumeRole process for a fork-and-run death test. It implements a
6776 // straightforward fork, with a simple pipe to transmit the status byte.
6777 DeathTest::TestRole NoExecDeathTest::AssumeRole() {
6778 const size_t thread_count = GetThreadCount();
6779 if (thread_count != 1) {
6780 GTEST_LOG_(WARNING) << DeathTestThreadWarning(thread_count);
6784 GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
6786 DeathTest::set_last_death_test_message("");
6788 // When we fork the process below, the log file buffers are copied, but the
6789 // file descriptors are shared. We flush all log files here so that closing
6790 // the file descriptors in the child process doesn't throw off the
6791 // synchronization between descriptors and buffers in the parent process.
6792 // This is as close to the fork as possible to avoid a race condition in case
6793 // there are multiple threads running before the death test, and another
6794 // thread writes to the log file.
6797 const pid_t child_pid = fork();
6798 GTEST_DEATH_TEST_CHECK_(child_pid != -1);
6799 set_child_pid(child_pid);
6800 if (child_pid == 0) {
6801 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[0]));
6802 set_write_fd(pipe_fd[1]);
6803 // Redirects all logging to stderr in the child process to prevent
6804 // concurrent writes to the log files. We capture stderr in the parent
6805 // process and append the child process' output to a log.
6807 // Event forwarding to the listeners of event listener API mush be shut
6808 // down in death test subprocesses.
6809 GetUnitTestImpl()->listeners()->SuppressEventForwarding();
6810 return EXECUTE_TEST;
6812 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
6813 set_read_fd(pipe_fd[0]);
6815 return OVERSEE_TEST;
6819 // A concrete death test class that forks and re-executes the main
6820 // program from the beginning, with command-line flags set that cause
6821 // only this specific death test to be run.
6822 class ExecDeathTest : public ForkingDeathTest {
6824 ExecDeathTest(const char* a_statement, const RE* a_regex,
6825 const char* file, int line) :
6826 ForkingDeathTest(a_statement, a_regex), file_(file), line_(line) { }
6827 virtual TestRole AssumeRole();
6829 // The name of the file in which the death test is located.
6830 const char* const file_;
6831 // The line number on which the death test is located.
6835 // Utility class for accumulating command-line arguments.
6839 args_.push_back(NULL);
6843 for (std::vector<char*>::iterator i = args_.begin(); i != args_.end();
6848 void AddArgument(const char* argument) {
6849 args_.insert(args_.end() - 1, posix::StrDup(argument));
6852 template <typename Str>
6853 void AddArguments(const ::std::vector<Str>& arguments) {
6854 for (typename ::std::vector<Str>::const_iterator i = arguments.begin();
6855 i != arguments.end();
6857 args_.insert(args_.end() - 1, posix::StrDup(i->c_str()));
6860 char* const* Argv() {
6864 std::vector<char*> args_;
6867 // A struct that encompasses the arguments to the child process of a
6868 // threadsafe-style death test process.
6869 struct ExecDeathTestArgs {
6870 char* const* argv; // Command-line arguments for the child's call to exec
6871 int close_fd; // File descriptor to close; the read end of a pipe
6875 inline char** GetEnviron() {
6876 // When Google Test is built as a framework on MacOS X, the environ variable
6877 // is unavailable. Apple's documentation (man environ) recommends using
6878 // _NSGetEnviron() instead.
6879 return *_NSGetEnviron();
6882 // Some POSIX platforms expect you to declare environ. extern "C" makes
6883 // it reside in the global namespace.
6884 extern "C" char** environ;
6885 inline char** GetEnviron() { return environ; }
6886 #endif // GTEST_OS_MAC
6888 // The main function for a threadsafe-style death test child process.
6889 // This function is called in a clone()-ed process and thus must avoid
6890 // any potentially unsafe operations like malloc or libc functions.
6891 static int ExecDeathTestChildMain(void* child_arg) {
6892 ExecDeathTestArgs* const args = static_cast<ExecDeathTestArgs*>(child_arg);
6893 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(args->close_fd));
6895 // We need to execute the test program in the same environment where
6896 // it was originally invoked. Therefore we change to the original
6897 // working directory first.
6898 const char* const original_dir =
6899 UnitTest::GetInstance()->original_working_dir();
6900 // We can safely call chdir() as it's a direct system call.
6901 if (chdir(original_dir) != 0) {
6902 DeathTestAbort(String::Format("chdir(\"%s\") failed: %s",
6904 GetLastErrnoDescription().c_str()));
6905 return EXIT_FAILURE;
6908 // We can safely call execve() as it's a direct system call. We
6909 // cannot use execvp() as it's a libc function and thus potentially
6910 // unsafe. Since execve() doesn't search the PATH, the user must
6911 // invoke the test program via a valid path that contains at least
6912 // one path separator.
6913 execve(args->argv[0], args->argv, GetEnviron());
6914 DeathTestAbort(String::Format("execve(%s, ...) in %s failed: %s",
6917 GetLastErrnoDescription().c_str()));
6918 return EXIT_FAILURE;
6921 // Two utility routines that together determine the direction the stack
6923 // This could be accomplished more elegantly by a single recursive
6924 // function, but we want to guard against the unlikely possibility of
6925 // a smart compiler optimizing the recursion away.
6926 bool StackLowerThanAddress(const void* ptr) {
6928 return &dummy < ptr;
6931 bool StackGrowsDown() {
6933 return StackLowerThanAddress(&dummy);
6936 // A threadsafe implementation of fork(2) for threadsafe-style death tests
6937 // that uses clone(2). It dies with an error message if anything goes
6939 static pid_t ExecDeathTestFork(char* const* argv, int close_fd) {
6940 ExecDeathTestArgs args = { argv, close_fd };
6941 pid_t child_pid = -1;
6944 const bool use_fork = GTEST_FLAG(death_test_use_fork);
6947 static const bool stack_grows_down = StackGrowsDown();
6948 const size_t stack_size = getpagesize();
6949 // MMAP_ANONYMOUS is not defined on Mac, so we use MAP_ANON instead.
6950 void* const stack = mmap(NULL, stack_size, PROT_READ | PROT_WRITE,
6951 MAP_ANON | MAP_PRIVATE, -1, 0);
6952 GTEST_DEATH_TEST_CHECK_(stack != MAP_FAILED);
6953 void* const stack_top =
6954 static_cast<char*>(stack) + (stack_grows_down ? stack_size : 0);
6956 child_pid = clone(&ExecDeathTestChildMain, stack_top, SIGCHLD, &args);
6958 GTEST_DEATH_TEST_CHECK_(munmap(stack, stack_size) != -1);
6961 const bool use_fork = true;
6962 #endif // GTEST_HAS_CLONE
6964 if (use_fork && (child_pid = fork()) == 0) {
6965 ExecDeathTestChildMain(&args);
6969 GTEST_DEATH_TEST_CHECK_(child_pid != -1);
6973 // The AssumeRole process for a fork-and-exec death test. It re-executes the
6974 // main program from the beginning, setting the --gtest_filter
6975 // and --gtest_internal_run_death_test flags to cause only the current
6976 // death test to be re-run.
6977 DeathTest::TestRole ExecDeathTest::AssumeRole() {
6978 const UnitTestImpl* const impl = GetUnitTestImpl();
6979 const InternalRunDeathTestFlag* const flag =
6980 impl->internal_run_death_test_flag();
6981 const TestInfo* const info = impl->current_test_info();
6982 const int death_test_index = info->result()->death_test_count();
6985 set_write_fd(flag->write_fd());
6986 return EXECUTE_TEST;
6990 GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
6991 // Clear the close-on-exec flag on the write end of the pipe, lest
6992 // it be closed when the child process does an exec:
6993 GTEST_DEATH_TEST_CHECK_(fcntl(pipe_fd[1], F_SETFD, 0) != -1);
6995 const String filter_flag =
6996 String::Format("--%s%s=%s.%s",
6997 GTEST_FLAG_PREFIX_, kFilterFlag,
6998 info->test_case_name(), info->name());
6999 const String internal_flag =
7000 String::Format("--%s%s=%s|%d|%d|%d",
7001 GTEST_FLAG_PREFIX_, kInternalRunDeathTestFlag,
7002 file_, line_, death_test_index, pipe_fd[1]);
7004 args.AddArguments(GetArgvs());
7005 args.AddArgument(filter_flag.c_str());
7006 args.AddArgument(internal_flag.c_str());
7008 DeathTest::set_last_death_test_message("");
7011 // See the comment in NoExecDeathTest::AssumeRole for why the next line
7015 const pid_t child_pid = ExecDeathTestFork(args.Argv(), pipe_fd[0]);
7016 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
7017 set_child_pid(child_pid);
7018 set_read_fd(pipe_fd[0]);
7020 return OVERSEE_TEST;
7023 #endif // !GTEST_OS_WINDOWS
7025 // Creates a concrete DeathTest-derived class that depends on the
7026 // --gtest_death_test_style flag, and sets the pointer pointed to
7027 // by the "test" argument to its address. If the test should be
7028 // skipped, sets that pointer to NULL. Returns true, unless the
7029 // flag is set to an invalid value.
7030 bool DefaultDeathTestFactory::Create(const char* statement, const RE* regex,
7031 const char* file, int line,
7033 UnitTestImpl* const impl = GetUnitTestImpl();
7034 const InternalRunDeathTestFlag* const flag =
7035 impl->internal_run_death_test_flag();
7036 const int death_test_index = impl->current_test_info()
7037 ->increment_death_test_count();
7040 if (death_test_index > flag->index()) {
7041 DeathTest::set_last_death_test_message(String::Format(
7042 "Death test count (%d) somehow exceeded expected maximum (%d)",
7043 death_test_index, flag->index()));
7047 if (!(flag->file() == file && flag->line() == line &&
7048 flag->index() == death_test_index)) {
7054 #if GTEST_OS_WINDOWS
7055 if (GTEST_FLAG(death_test_style) == "threadsafe" ||
7056 GTEST_FLAG(death_test_style) == "fast") {
7057 *test = new WindowsDeathTest(statement, regex, file, line);
7060 if (GTEST_FLAG(death_test_style) == "threadsafe") {
7061 *test = new ExecDeathTest(statement, regex, file, line);
7062 } else if (GTEST_FLAG(death_test_style) == "fast") {
7063 *test = new NoExecDeathTest(statement, regex);
7065 #endif // GTEST_OS_WINDOWS
7066 else { // NOLINT - this is more readable than unbalanced brackets inside #if.
7067 DeathTest::set_last_death_test_message(String::Format(
7068 "Unknown death test style \"%s\" encountered",
7069 GTEST_FLAG(death_test_style).c_str()));
7076 // Splits a given string on a given delimiter, populating a given
7077 // vector with the fields. GTEST_HAS_DEATH_TEST implies that we have
7078 // ::std::string, so we can use it here.
7079 static void SplitString(const ::std::string& str, char delimiter,
7080 ::std::vector< ::std::string>* dest) {
7081 ::std::vector< ::std::string> parsed;
7082 ::std::string::size_type pos = 0;
7083 while (::testing::internal::AlwaysTrue()) {
7084 const ::std::string::size_type colon = str.find(delimiter, pos);
7085 if (colon == ::std::string::npos) {
7086 parsed.push_back(str.substr(pos));
7089 parsed.push_back(str.substr(pos, colon - pos));
7096 #if GTEST_OS_WINDOWS
7097 // Recreates the pipe and event handles from the provided parameters,
7098 // signals the event, and returns a file descriptor wrapped around the pipe
7099 // handle. This function is called in the child process only.
7100 int GetStatusFileDescriptor(unsigned int parent_process_id,
7101 size_t write_handle_as_size_t,
7102 size_t event_handle_as_size_t) {
7103 AutoHandle parent_process_handle(::OpenProcess(PROCESS_DUP_HANDLE,
7104 FALSE, // Non-inheritable.
7105 parent_process_id));
7106 if (parent_process_handle.Get() == INVALID_HANDLE_VALUE) {
7107 DeathTestAbort(String::Format("Unable to open parent process %u",
7108 parent_process_id));
7111 // TODO(vladl@google.com): Replace the following check with a
7112 // compile-time assertion when available.
7113 GTEST_CHECK_(sizeof(HANDLE) <= sizeof(size_t));
7115 const HANDLE write_handle =
7116 reinterpret_cast<HANDLE>(write_handle_as_size_t);
7117 HANDLE dup_write_handle;
7119 // The newly initialized handle is accessible only in in the parent
7120 // process. To obtain one accessible within the child, we need to use
7122 if (!::DuplicateHandle(parent_process_handle.Get(), write_handle,
7123 ::GetCurrentProcess(), &dup_write_handle,
7124 0x0, // Requested privileges ignored since
7125 // DUPLICATE_SAME_ACCESS is used.
7126 FALSE, // Request non-inheritable handler.
7127 DUPLICATE_SAME_ACCESS)) {
7128 DeathTestAbort(String::Format(
7129 "Unable to duplicate the pipe handle %Iu from the parent process %u",
7130 write_handle_as_size_t, parent_process_id));
7133 const HANDLE event_handle = reinterpret_cast<HANDLE>(event_handle_as_size_t);
7134 HANDLE dup_event_handle;
7136 if (!::DuplicateHandle(parent_process_handle.Get(), event_handle,
7137 ::GetCurrentProcess(), &dup_event_handle,
7140 DUPLICATE_SAME_ACCESS)) {
7141 DeathTestAbort(String::Format(
7142 "Unable to duplicate the event handle %Iu from the parent process %u",
7143 event_handle_as_size_t, parent_process_id));
7146 const int write_fd =
7147 ::_open_osfhandle(reinterpret_cast<intptr_t>(dup_write_handle), O_APPEND);
7148 if (write_fd == -1) {
7149 DeathTestAbort(String::Format(
7150 "Unable to convert pipe handle %Iu to a file descriptor",
7151 write_handle_as_size_t));
7154 // Signals the parent that the write end of the pipe has been acquired
7155 // so the parent can release its own write end.
7156 ::SetEvent(dup_event_handle);
7160 #endif // GTEST_OS_WINDOWS
7162 // Returns a newly created InternalRunDeathTestFlag object with fields
7163 // initialized from the GTEST_FLAG(internal_run_death_test) flag if
7164 // the flag is specified; otherwise returns NULL.
7165 InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() {
7166 if (GTEST_FLAG(internal_run_death_test) == "") return NULL;
7168 // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we
7172 ::std::vector< ::std::string> fields;
7173 SplitString(GTEST_FLAG(internal_run_death_test).c_str(), '|', &fields);
7176 #if GTEST_OS_WINDOWS
7177 unsigned int parent_process_id = 0;
7178 size_t write_handle_as_size_t = 0;
7179 size_t event_handle_as_size_t = 0;
7181 if (fields.size() != 6
7182 || !ParseNaturalNumber(fields[1], &line)
7183 || !ParseNaturalNumber(fields[2], &index)
7184 || !ParseNaturalNumber(fields[3], &parent_process_id)
7185 || !ParseNaturalNumber(fields[4], &write_handle_as_size_t)
7186 || !ParseNaturalNumber(fields[5], &event_handle_as_size_t)) {
7187 DeathTestAbort(String::Format(
7188 "Bad --gtest_internal_run_death_test flag: %s",
7189 GTEST_FLAG(internal_run_death_test).c_str()));
7191 write_fd = GetStatusFileDescriptor(parent_process_id,
7192 write_handle_as_size_t,
7193 event_handle_as_size_t);
7195 if (fields.size() != 4
7196 || !ParseNaturalNumber(fields[1], &line)
7197 || !ParseNaturalNumber(fields[2], &index)
7198 || !ParseNaturalNumber(fields[3], &write_fd)) {
7199 DeathTestAbort(String::Format(
7200 "Bad --gtest_internal_run_death_test flag: %s",
7201 GTEST_FLAG(internal_run_death_test).c_str()));
7203 #endif // GTEST_OS_WINDOWS
7204 return new InternalRunDeathTestFlag(fields[0], line, index, write_fd);
7207 } // namespace internal
7209 #endif // GTEST_HAS_DEATH_TEST
7211 } // namespace testing
7212 // Copyright 2008, Google Inc.
7213 // All rights reserved.
7215 // Redistribution and use in source and binary forms, with or without
7216 // modification, are permitted provided that the following conditions are
7219 // * Redistributions of source code must retain the above copyright
7220 // notice, this list of conditions and the following disclaimer.
7221 // * Redistributions in binary form must reproduce the above
7222 // copyright notice, this list of conditions and the following disclaimer
7223 // in the documentation and/or other materials provided with the
7225 // * Neither the name of Google Inc. nor the names of its
7226 // contributors may be used to endorse or promote products derived from
7227 // this software without specific prior written permission.
7229 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
7230 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
7231 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
7232 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
7233 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
7234 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
7235 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
7236 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
7237 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
7238 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
7239 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
7241 // Authors: keith.ray@gmail.com (Keith Ray)
7246 #if GTEST_OS_WINDOWS_MOBILE
7247 #include <windows.h>
7248 #elif GTEST_OS_WINDOWS
7251 #elif GTEST_OS_SYMBIAN
7252 // Symbian OpenC has PATH_MAX in sys/syslimits.h
7253 #include <sys/syslimits.h>
7256 #include <climits> // Some Linux distributions define PATH_MAX here.
7257 #endif // GTEST_OS_WINDOWS_MOBILE
7259 #if GTEST_OS_WINDOWS
7260 #define GTEST_PATH_MAX_ _MAX_PATH
7261 #elif defined(PATH_MAX)
7262 #define GTEST_PATH_MAX_ PATH_MAX
7263 #elif defined(_XOPEN_PATH_MAX)
7264 #define GTEST_PATH_MAX_ _XOPEN_PATH_MAX
7266 #define GTEST_PATH_MAX_ _POSIX_PATH_MAX
7267 #endif // GTEST_OS_WINDOWS
7271 namespace internal {
7273 #if GTEST_OS_WINDOWS
7274 // On Windows, '\\' is the standard path separator, but many tools and the
7275 // Windows API also accept '/' as an alternate path separator. Unless otherwise
7276 // noted, a file path can contain either kind of path separators, or a mixture
7278 const char kPathSeparator = '\\';
7279 const char kAlternatePathSeparator = '/';
7280 const char kPathSeparatorString[] = "\\";
7281 const char kAlternatePathSeparatorString[] = "/";
7282 #if GTEST_OS_WINDOWS_MOBILE
7283 // Windows CE doesn't have a current directory. You should not use
7284 // the current directory in tests on Windows CE, but this at least
7285 // provides a reasonable fallback.
7286 const char kCurrentDirectoryString[] = "\\";
7287 // Windows CE doesn't define INVALID_FILE_ATTRIBUTES
7288 const DWORD kInvalidFileAttributes = 0xffffffff;
7290 const char kCurrentDirectoryString[] = ".\\";
7291 #endif // GTEST_OS_WINDOWS_MOBILE
7293 const char kPathSeparator = '/';
7294 const char kPathSeparatorString[] = "/";
7295 const char kCurrentDirectoryString[] = "./";
7296 #endif // GTEST_OS_WINDOWS
7298 // Returns whether the given character is a valid path separator.
7299 static bool IsPathSeparator(char c) {
7300 #if GTEST_HAS_ALT_PATH_SEP_
7301 return (c == kPathSeparator) || (c == kAlternatePathSeparator);
7303 return c == kPathSeparator;
7307 // Returns the current working directory, or "" if unsuccessful.
7308 FilePath FilePath::GetCurrentDir() {
7309 #if GTEST_OS_WINDOWS_MOBILE
7310 // Windows CE doesn't have a current directory, so we just return
7311 // something reasonable.
7312 return FilePath(kCurrentDirectoryString);
7313 #elif GTEST_OS_WINDOWS
7314 char cwd[GTEST_PATH_MAX_ + 1] = { '\0' };
7315 return FilePath(_getcwd(cwd, sizeof(cwd)) == NULL ? "" : cwd);
7317 char cwd[GTEST_PATH_MAX_ + 1] = { '\0' };
7318 return FilePath(getcwd(cwd, sizeof(cwd)) == NULL ? "" : cwd);
7319 #endif // GTEST_OS_WINDOWS_MOBILE
7322 // Returns a copy of the FilePath with the case-insensitive extension removed.
7323 // Example: FilePath("dir/file.exe").RemoveExtension("EXE") returns
7324 // FilePath("dir/file"). If a case-insensitive extension is not
7325 // found, returns a copy of the original FilePath.
7326 FilePath FilePath::RemoveExtension(const char* extension) const {
7327 String dot_extension(String::Format(".%s", extension));
7328 if (pathname_.EndsWithCaseInsensitive(dot_extension.c_str())) {
7329 return FilePath(String(pathname_.c_str(), pathname_.length() - 4));
7334 // Returns a pointer to the last occurence of a valid path separator in
7335 // the FilePath. On Windows, for example, both '/' and '\' are valid path
7336 // separators. Returns NULL if no path separator was found.
7337 const char* FilePath::FindLastPathSeparator() const {
7338 const char* const last_sep = strrchr(c_str(), kPathSeparator);
7339 #if GTEST_HAS_ALT_PATH_SEP_
7340 const char* const last_alt_sep = strrchr(c_str(), kAlternatePathSeparator);
7341 // Comparing two pointers of which only one is NULL is undefined.
7342 if (last_alt_sep != NULL &&
7343 (last_sep == NULL || last_alt_sep > last_sep)) {
7344 return last_alt_sep;
7350 // Returns a copy of the FilePath with the directory part removed.
7351 // Example: FilePath("path/to/file").RemoveDirectoryName() returns
7352 // FilePath("file"). If there is no directory part ("just_a_file"), it returns
7353 // the FilePath unmodified. If there is no file part ("just_a_dir/") it
7354 // returns an empty FilePath ("").
7355 // On Windows platform, '\' is the path separator, otherwise it is '/'.
7356 FilePath FilePath::RemoveDirectoryName() const {
7357 const char* const last_sep = FindLastPathSeparator();
7358 return last_sep ? FilePath(String(last_sep + 1)) : *this;
7361 // RemoveFileName returns the directory path with the filename removed.
7362 // Example: FilePath("path/to/file").RemoveFileName() returns "path/to/".
7363 // If the FilePath is "a_file" or "/a_file", RemoveFileName returns
7364 // FilePath("./") or, on Windows, FilePath(".\\"). If the filepath does
7365 // not have a file, like "just/a/dir/", it returns the FilePath unmodified.
7366 // On Windows platform, '\' is the path separator, otherwise it is '/'.
7367 FilePath FilePath::RemoveFileName() const {
7368 const char* const last_sep = FindLastPathSeparator();
7371 dir = String(c_str(), last_sep + 1 - c_str());
7373 dir = kCurrentDirectoryString;
7375 return FilePath(dir);
7378 // Helper functions for naming files in a directory for xml output.
7380 // Given directory = "dir", base_name = "test", number = 0,
7381 // extension = "xml", returns "dir/test.xml". If number is greater
7382 // than zero (e.g., 12), returns "dir/test_12.xml".
7383 // On Windows platform, uses \ as the separator rather than /.
7384 FilePath FilePath::MakeFileName(const FilePath& directory,
7385 const FilePath& base_name,
7387 const char* extension) {
7390 file = String::Format("%s.%s", base_name.c_str(), extension);
7392 file = String::Format("%s_%d.%s", base_name.c_str(), number, extension);
7394 return ConcatPaths(directory, FilePath(file));
7397 // Given directory = "dir", relative_path = "test.xml", returns "dir/test.xml".
7398 // On Windows, uses \ as the separator rather than /.
7399 FilePath FilePath::ConcatPaths(const FilePath& directory,
7400 const FilePath& relative_path) {
7401 if (directory.IsEmpty())
7402 return relative_path;
7403 const FilePath dir(directory.RemoveTrailingPathSeparator());
7404 return FilePath(String::Format("%s%c%s", dir.c_str(), kPathSeparator,
7405 relative_path.c_str()));
7408 // Returns true if pathname describes something findable in the file-system,
7409 // either a file, directory, or whatever.
7410 bool FilePath::FileOrDirectoryExists() const {
7411 #if GTEST_OS_WINDOWS_MOBILE
7412 LPCWSTR unicode = String::AnsiToUtf16(pathname_.c_str());
7413 const DWORD attributes = GetFileAttributes(unicode);
7415 return attributes != kInvalidFileAttributes;
7417 posix::StatStruct file_stat;
7418 return posix::Stat(pathname_.c_str(), &file_stat) == 0;
7419 #endif // GTEST_OS_WINDOWS_MOBILE
7422 // Returns true if pathname describes a directory in the file-system
7424 bool FilePath::DirectoryExists() const {
7425 bool result = false;
7426 #if GTEST_OS_WINDOWS
7427 // Don't strip off trailing separator if path is a root directory on
7428 // Windows (like "C:\\").
7429 const FilePath& path(IsRootDirectory() ? *this :
7430 RemoveTrailingPathSeparator());
7432 const FilePath& path(*this);
7435 #if GTEST_OS_WINDOWS_MOBILE
7436 LPCWSTR unicode = String::AnsiToUtf16(path.c_str());
7437 const DWORD attributes = GetFileAttributes(unicode);
7439 if ((attributes != kInvalidFileAttributes) &&
7440 (attributes & FILE_ATTRIBUTE_DIRECTORY)) {
7444 posix::StatStruct file_stat;
7445 result = posix::Stat(path.c_str(), &file_stat) == 0 &&
7446 posix::IsDir(file_stat);
7447 #endif // GTEST_OS_WINDOWS_MOBILE
7452 // Returns true if pathname describes a root directory. (Windows has one
7453 // root directory per disk drive.)
7454 bool FilePath::IsRootDirectory() const {
7455 #if GTEST_OS_WINDOWS
7456 // TODO(wan@google.com): on Windows a network share like
7457 // \\server\share can be a root directory, although it cannot be the
7458 // current directory. Handle this properly.
7459 return pathname_.length() == 3 && IsAbsolutePath();
7461 return pathname_.length() == 1 && IsPathSeparator(pathname_.c_str()[0]);
7465 // Returns true if pathname describes an absolute path.
7466 bool FilePath::IsAbsolutePath() const {
7467 const char* const name = pathname_.c_str();
7468 #if GTEST_OS_WINDOWS
7469 return pathname_.length() >= 3 &&
7470 ((name[0] >= 'a' && name[0] <= 'z') ||
7471 (name[0] >= 'A' && name[0] <= 'Z')) &&
7473 IsPathSeparator(name[2]);
7475 return IsPathSeparator(name[0]);
7479 // Returns a pathname for a file that does not currently exist. The pathname
7480 // will be directory/base_name.extension or
7481 // directory/base_name_<number>.extension if directory/base_name.extension
7482 // already exists. The number will be incremented until a pathname is found
7483 // that does not already exist.
7484 // Examples: 'dir/foo_test.xml' or 'dir/foo_test_1.xml'.
7485 // There could be a race condition if two or more processes are calling this
7486 // function at the same time -- they could both pick the same filename.
7487 FilePath FilePath::GenerateUniqueFileName(const FilePath& directory,
7488 const FilePath& base_name,
7489 const char* extension) {
7490 FilePath full_pathname;
7493 full_pathname.Set(MakeFileName(directory, base_name, number++, extension));
7494 } while (full_pathname.FileOrDirectoryExists());
7495 return full_pathname;
7498 // Returns true if FilePath ends with a path separator, which indicates that
7499 // it is intended to represent a directory. Returns false otherwise.
7500 // This does NOT check that a directory (or file) actually exists.
7501 bool FilePath::IsDirectory() const {
7502 return !pathname_.empty() &&
7503 IsPathSeparator(pathname_.c_str()[pathname_.length() - 1]);
7506 // Create directories so that path exists. Returns true if successful or if
7507 // the directories already exist; returns false if unable to create directories
7509 bool FilePath::CreateDirectoriesRecursively() const {
7510 if (!this->IsDirectory()) {
7514 if (pathname_.length() == 0 || this->DirectoryExists()) {
7518 const FilePath parent(this->RemoveTrailingPathSeparator().RemoveFileName());
7519 return parent.CreateDirectoriesRecursively() && this->CreateFolder();
7522 // Create the directory so that path exists. Returns true if successful or
7523 // if the directory already exists; returns false if unable to create the
7524 // directory for any reason, including if the parent directory does not
7525 // exist. Not named "CreateDirectory" because that's a macro on Windows.
7526 bool FilePath::CreateFolder() const {
7527 #if GTEST_OS_WINDOWS_MOBILE
7528 FilePath removed_sep(this->RemoveTrailingPathSeparator());
7529 LPCWSTR unicode = String::AnsiToUtf16(removed_sep.c_str());
7530 int result = CreateDirectory(unicode, NULL) ? 0 : -1;
7532 #elif GTEST_OS_WINDOWS
7533 int result = _mkdir(pathname_.c_str());
7535 int result = mkdir(pathname_.c_str(), 0777);
7536 #endif // GTEST_OS_WINDOWS_MOBILE
7539 return this->DirectoryExists(); // An error is OK if the directory exists.
7541 return true; // No error.
7544 // If input name has a trailing separator character, remove it and return the
7545 // name, otherwise return the name string unmodified.
7546 // On Windows platform, uses \ as the separator, other platforms use /.
7547 FilePath FilePath::RemoveTrailingPathSeparator() const {
7548 return IsDirectory()
7549 ? FilePath(String(pathname_.c_str(), pathname_.length() - 1))
7553 // Removes any redundant separators that might be in the pathname.
7554 // For example, "bar///foo" becomes "bar/foo". Does not eliminate other
7555 // redundancies that might be in a pathname involving "." or "..".
7556 // TODO(wan@google.com): handle Windows network shares (e.g. \\server\share).
7557 void FilePath::Normalize() {
7558 if (pathname_.c_str() == NULL) {
7562 const char* src = pathname_.c_str();
7563 char* const dest = new char[pathname_.length() + 1];
7564 char* dest_ptr = dest;
7565 memset(dest_ptr, 0, pathname_.length() + 1);
7567 while (*src != '\0') {
7569 if (!IsPathSeparator(*src)) {
7572 #if GTEST_HAS_ALT_PATH_SEP_
7573 if (*dest_ptr == kAlternatePathSeparator) {
7574 *dest_ptr = kPathSeparator;
7577 while (IsPathSeparator(*src))
7587 } // namespace internal
7588 } // namespace testing
7589 // Copyright 2008, Google Inc.
7590 // All rights reserved.
7592 // Redistribution and use in source and binary forms, with or without
7593 // modification, are permitted provided that the following conditions are
7596 // * Redistributions of source code must retain the above copyright
7597 // notice, this list of conditions and the following disclaimer.
7598 // * Redistributions in binary form must reproduce the above
7599 // copyright notice, this list of conditions and the following disclaimer
7600 // in the documentation and/or other materials provided with the
7602 // * Neither the name of Google Inc. nor the names of its
7603 // contributors may be used to endorse or promote products derived from
7604 // this software without specific prior written permission.
7606 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
7607 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
7608 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
7609 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
7610 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
7611 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
7612 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
7613 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
7614 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
7615 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
7616 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
7618 // Author: wan@google.com (Zhanyong Wan)
7625 #if GTEST_OS_WINDOWS_MOBILE
7626 #include <windows.h> // For TerminateProcess()
7627 #elif GTEST_OS_WINDOWS
7629 #include <sys/stat.h>
7632 #endif // GTEST_OS_WINDOWS_MOBILE
7635 #include <mach/mach_init.h>
7636 #include <mach/task.h>
7637 #include <mach/vm_map.h>
7638 #endif // GTEST_OS_MAC
7641 // Indicates that this translation unit is part of Google Test's
7642 // implementation. It must come before gtest-internal-inl.h is
7643 // included, or there will be a compiler error. This trick is to
7644 // prevent a user from accidentally including gtest-internal-inl.h in
7646 #define GTEST_IMPLEMENTATION_ 1
7647 #undef GTEST_IMPLEMENTATION_
7650 namespace internal {
7652 #if defined(_MSC_VER) || defined(__BORLANDC__)
7653 // MSVC and C++Builder do not provide a definition of STDERR_FILENO.
7654 const int kStdOutFileno = 1;
7655 const int kStdErrFileno = 2;
7657 const int kStdOutFileno = STDOUT_FILENO;
7658 const int kStdErrFileno = STDERR_FILENO;
7663 // Returns the number of threads running in the process, or 0 to indicate that
7664 // we cannot detect it.
7665 size_t GetThreadCount() {
7666 const task_t task = mach_task_self();
7667 mach_msg_type_number_t thread_count;
7668 thread_act_array_t thread_list;
7669 const kern_return_t status = task_threads(task, &thread_list, &thread_count);
7670 if (status == KERN_SUCCESS) {
7671 // task_threads allocates resources in thread_list and we need to free them
7674 reinterpret_cast<vm_address_t>(thread_list),
7675 sizeof(thread_t) * thread_count);
7676 return static_cast<size_t>(thread_count);
7684 size_t GetThreadCount() {
7685 // There's no portable way to detect the number of threads, so we just
7686 // return 0 to indicate that we cannot detect it.
7690 #endif // GTEST_OS_MAC
7692 #if GTEST_USES_POSIX_RE
7694 // Implements RE. Currently only needed for death tests.
7698 // regfree'ing an invalid regex might crash because the content
7699 // of the regex is undefined. Since the regex's are essentially
7700 // the same, one cannot be valid (or invalid) without the other
7702 regfree(&partial_regex_);
7703 regfree(&full_regex_);
7705 free(const_cast<char*>(pattern_));
7708 // Returns true iff regular expression re matches the entire str.
7709 bool RE::FullMatch(const char* str, const RE& re) {
7710 if (!re.is_valid_) return false;
7713 return regexec(&re.full_regex_, str, 1, &match, 0) == 0;
7716 // Returns true iff regular expression re matches a substring of str
7717 // (including str itself).
7718 bool RE::PartialMatch(const char* str, const RE& re) {
7719 if (!re.is_valid_) return false;
7722 return regexec(&re.partial_regex_, str, 1, &match, 0) == 0;
7725 // Initializes an RE from its string representation.
7726 void RE::Init(const char* regex) {
7727 pattern_ = posix::StrDup(regex);
7729 // Reserves enough bytes to hold the regular expression used for a
7731 const size_t full_regex_len = strlen(regex) + 10;
7732 char* const full_pattern = new char[full_regex_len];
7734 snprintf(full_pattern, full_regex_len, "^(%s)$", regex);
7735 is_valid_ = regcomp(&full_regex_, full_pattern, REG_EXTENDED) == 0;
7736 // We want to call regcomp(&partial_regex_, ...) even if the
7737 // previous expression returns false. Otherwise partial_regex_ may
7738 // not be properly initialized can may cause trouble when it's
7741 // Some implementation of POSIX regex (e.g. on at least some
7742 // versions of Cygwin) doesn't accept the empty string as a valid
7743 // regex. We change it to an equivalent form "()" to be safe.
7745 const char* const partial_regex = (*regex == '\0') ? "()" : regex;
7746 is_valid_ = regcomp(&partial_regex_, partial_regex, REG_EXTENDED) == 0;
7748 EXPECT_TRUE(is_valid_)
7749 << "Regular expression \"" << regex
7750 << "\" is not a valid POSIX Extended regular expression.";
7752 delete[] full_pattern;
7755 #elif GTEST_USES_SIMPLE_RE
7757 // Returns true iff ch appears anywhere in str (excluding the
7758 // terminating '\0' character).
7759 bool IsInSet(char ch, const char* str) {
7760 return ch != '\0' && strchr(str, ch) != NULL;
7763 // Returns true iff ch belongs to the given classification. Unlike
7764 // similar functions in <ctype.h>, these aren't affected by the
7766 bool IsDigit(char ch) { return '0' <= ch && ch <= '9'; }
7767 bool IsPunct(char ch) {
7768 return IsInSet(ch, "^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~");
7770 bool IsRepeat(char ch) { return IsInSet(ch, "?*+"); }
7771 bool IsWhiteSpace(char ch) { return IsInSet(ch, " \f\n\r\t\v"); }
7772 bool IsWordChar(char ch) {
7773 return ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') ||
7774 ('0' <= ch && ch <= '9') || ch == '_';
7777 // Returns true iff "\\c" is a supported escape sequence.
7778 bool IsValidEscape(char c) {
7779 return (IsPunct(c) || IsInSet(c, "dDfnrsStvwW"));
7782 // Returns true iff the given atom (specified by escaped and pattern)
7783 // matches ch. The result is undefined if the atom is invalid.
7784 bool AtomMatchesChar(bool escaped, char pattern_char, char ch) {
7785 if (escaped) { // "\\p" where p is pattern_char.
7786 switch (pattern_char) {
7787 case 'd': return IsDigit(ch);
7788 case 'D': return !IsDigit(ch);
7789 case 'f': return ch == '\f';
7790 case 'n': return ch == '\n';
7791 case 'r': return ch == '\r';
7792 case 's': return IsWhiteSpace(ch);
7793 case 'S': return !IsWhiteSpace(ch);
7794 case 't': return ch == '\t';
7795 case 'v': return ch == '\v';
7796 case 'w': return IsWordChar(ch);
7797 case 'W': return !IsWordChar(ch);
7799 return IsPunct(pattern_char) && pattern_char == ch;
7802 return (pattern_char == '.' && ch != '\n') || pattern_char == ch;
7805 // Helper function used by ValidateRegex() to format error messages.
7806 String FormatRegexSyntaxError(const char* regex, int index) {
7807 return (Message() << "Syntax error at index " << index
7808 << " in simple regular expression \"" << regex << "\": ").GetString();
7811 // Generates non-fatal failures and returns false if regex is invalid;
7812 // otherwise returns true.
7813 bool ValidateRegex(const char* regex) {
7814 if (regex == NULL) {
7815 // TODO(wan@google.com): fix the source file location in the
7816 // assertion failures to match where the regex is used in user
7818 ADD_FAILURE() << "NULL is not a valid simple regular expression.";
7822 bool is_valid = true;
7824 // True iff ?, *, or + can follow the previous atom.
7825 bool prev_repeatable = false;
7826 for (int i = 0; regex[i]; i++) {
7827 if (regex[i] == '\\') { // An escape sequence
7829 if (regex[i] == '\0') {
7830 ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
7831 << "'\\' cannot appear at the end.";
7835 if (!IsValidEscape(regex[i])) {
7836 ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
7837 << "invalid escape sequence \"\\" << regex[i] << "\".";
7840 prev_repeatable = true;
7841 } else { // Not an escape sequence.
7842 const char ch = regex[i];
7844 if (ch == '^' && i > 0) {
7845 ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
7846 << "'^' can only appear at the beginning.";
7848 } else if (ch == '$' && regex[i + 1] != '\0') {
7849 ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
7850 << "'$' can only appear at the end.";
7852 } else if (IsInSet(ch, "()[]{}|")) {
7853 ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
7854 << "'" << ch << "' is unsupported.";
7856 } else if (IsRepeat(ch) && !prev_repeatable) {
7857 ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
7858 << "'" << ch << "' can only follow a repeatable token.";
7862 prev_repeatable = !IsInSet(ch, "^$?*+");
7869 // Matches a repeated regex atom followed by a valid simple regular
7870 // expression. The regex atom is defined as c if escaped is false,
7871 // or \c otherwise. repeat is the repetition meta character (?, *,
7872 // or +). The behavior is undefined if str contains too many
7873 // characters to be indexable by size_t, in which case the test will
7874 // probably time out anyway. We are fine with this limitation as
7875 // std::string has it too.
7876 bool MatchRepetitionAndRegexAtHead(
7877 bool escaped, char c, char repeat, const char* regex,
7879 const size_t min_count = (repeat == '+') ? 1 : 0;
7880 const size_t max_count = (repeat == '?') ? 1 :
7881 static_cast<size_t>(-1) - 1;
7882 // We cannot call numeric_limits::max() as it conflicts with the
7883 // max() macro on Windows.
7885 for (size_t i = 0; i <= max_count; ++i) {
7886 // We know that the atom matches each of the first i characters in str.
7887 if (i >= min_count && MatchRegexAtHead(regex, str + i)) {
7888 // We have enough matches at the head, and the tail matches too.
7889 // Since we only care about *whether* the pattern matches str
7890 // (as opposed to *how* it matches), there is no need to find a
7894 if (str[i] == '\0' || !AtomMatchesChar(escaped, c, str[i]))
7900 // Returns true iff regex matches a prefix of str. regex must be a
7901 // valid simple regular expression and not start with "^", or the
7902 // result is undefined.
7903 bool MatchRegexAtHead(const char* regex, const char* str) {
7904 if (*regex == '\0') // An empty regex matches a prefix of anything.
7907 // "$" only matches the end of a string. Note that regex being
7908 // valid guarantees that there's nothing after "$" in it.
7910 return *str == '\0';
7912 // Is the first thing in regex an escape sequence?
7913 const bool escaped = *regex == '\\';
7916 if (IsRepeat(regex[1])) {
7917 // MatchRepetitionAndRegexAtHead() calls MatchRegexAtHead(), so
7918 // here's an indirect recursion. It terminates as the regex gets
7919 // shorter in each recursion.
7920 return MatchRepetitionAndRegexAtHead(
7921 escaped, regex[0], regex[1], regex + 2, str);
7923 // regex isn't empty, isn't "$", and doesn't start with a
7924 // repetition. We match the first atom of regex with the first
7925 // character of str and recurse.
7926 return (*str != '\0') && AtomMatchesChar(escaped, *regex, *str) &&
7927 MatchRegexAtHead(regex + 1, str + 1);
7931 // Returns true iff regex matches any substring of str. regex must be
7932 // a valid simple regular expression, or the result is undefined.
7934 // The algorithm is recursive, but the recursion depth doesn't exceed
7935 // the regex length, so we won't need to worry about running out of
7936 // stack space normally. In rare cases the time complexity can be
7937 // exponential with respect to the regex length + the string length,
7938 // but usually it's must faster (often close to linear).
7939 bool MatchRegexAnywhere(const char* regex, const char* str) {
7940 if (regex == NULL || str == NULL)
7944 return MatchRegexAtHead(regex + 1, str);
7946 // A successful match can be anywhere in str.
7948 if (MatchRegexAtHead(regex, str))
7950 } while (*str++ != '\0');
7954 // Implements the RE class.
7957 free(const_cast<char*>(pattern_));
7958 free(const_cast<char*>(full_pattern_));
7961 // Returns true iff regular expression re matches the entire str.
7962 bool RE::FullMatch(const char* str, const RE& re) {
7963 return re.is_valid_ && MatchRegexAnywhere(re.full_pattern_, str);
7966 // Returns true iff regular expression re matches a substring of str
7967 // (including str itself).
7968 bool RE::PartialMatch(const char* str, const RE& re) {
7969 return re.is_valid_ && MatchRegexAnywhere(re.pattern_, str);
7972 // Initializes an RE from its string representation.
7973 void RE::Init(const char* regex) {
7974 pattern_ = full_pattern_ = NULL;
7975 if (regex != NULL) {
7976 pattern_ = posix::StrDup(regex);
7979 is_valid_ = ValidateRegex(regex);
7981 // No need to calculate the full pattern when the regex is invalid.
7985 const size_t len = strlen(regex);
7986 // Reserves enough bytes to hold the regular expression used for a
7987 // full match: we need space to prepend a '^', append a '$', and
7988 // terminate the string with '\0'.
7989 char* buffer = static_cast<char*>(malloc(len + 3));
7990 full_pattern_ = buffer;
7993 *buffer++ = '^'; // Makes sure full_pattern_ starts with '^'.
7995 // We don't use snprintf or strncpy, as they trigger a warning when
7996 // compiled with VC++ 8.0.
7997 memcpy(buffer, regex, len);
8000 if (len == 0 || regex[len - 1] != '$')
8001 *buffer++ = '$'; // Makes sure full_pattern_ ends with '$'.
8006 #endif // GTEST_USES_POSIX_RE
8009 GTestLog::GTestLog(GTestLogSeverity severity, const char* file, int line)
8010 : severity_(severity) {
8011 const char* const marker =
8012 severity == GTEST_INFO ? "[ INFO ]" :
8013 severity == GTEST_WARNING ? "[WARNING]" :
8014 severity == GTEST_ERROR ? "[ ERROR ]" : "[ FATAL ]";
8015 GetStream() << ::std::endl << marker << " "
8016 << FormatFileLocation(file, line).c_str() << ": ";
8019 // Flushes the buffers and, if severity is GTEST_FATAL, aborts the program.
8020 GTestLog::~GTestLog() {
8021 GetStream() << ::std::endl;
8022 if (severity_ == GTEST_FATAL) {
8027 // Disable Microsoft deprecation warnings for POSIX functions called from
8028 // this class (creat, dup, dup2, and close)
8030 #pragma warning(push)
8031 #pragma warning(disable: 4996)
8034 #if GTEST_HAS_STREAM_REDIRECTION_
8036 // Object that captures an output stream (stdout/stderr).
8037 class CapturedStream {
8039 // The ctor redirects the stream to a temporary file.
8040 CapturedStream(int fd) : fd_(fd), uncaptured_fd_(dup(fd)) {
8041 #if GTEST_OS_WINDOWS
8042 char temp_dir_path[MAX_PATH + 1] = { '\0' }; // NOLINT
8043 char temp_file_path[MAX_PATH + 1] = { '\0' }; // NOLINT
8045 ::GetTempPathA(sizeof(temp_dir_path), temp_dir_path);
8046 const UINT success = ::GetTempFileNameA(temp_dir_path,
8048 0, // Generate unique file name.
8050 GTEST_CHECK_(success != 0)
8051 << "Unable to create a temporary file in " << temp_dir_path;
8052 const int captured_fd = creat(temp_file_path, _S_IREAD | _S_IWRITE);
8053 GTEST_CHECK_(captured_fd != -1) << "Unable to open temporary file "
8055 filename_ = temp_file_path;
8057 // There's no guarantee that a test has write access to the
8058 // current directory, so we create the temporary file in the /tmp
8059 // directory instead.
8060 char name_template[] = "/tmp/captured_stream.XXXXXX";
8061 const int captured_fd = mkstemp(name_template);
8062 filename_ = name_template;
8063 #endif // GTEST_OS_WINDOWS
8065 dup2(captured_fd, fd_);
8070 remove(filename_.c_str());
8073 String GetCapturedString() {
8074 if (uncaptured_fd_ != -1) {
8075 // Restores the original stream.
8077 dup2(uncaptured_fd_, fd_);
8078 close(uncaptured_fd_);
8079 uncaptured_fd_ = -1;
8082 FILE* const file = posix::FOpen(filename_.c_str(), "r");
8083 const String content = ReadEntireFile(file);
8084 posix::FClose(file);
8089 // Reads the entire content of a file as a String.
8090 static String ReadEntireFile(FILE* file);
8092 // Returns the size (in bytes) of a file.
8093 static size_t GetFileSize(FILE* file);
8095 const int fd_; // A stream to capture.
8097 // Name of the temporary file holding the stderr output.
8098 ::std::string filename_;
8100 GTEST_DISALLOW_COPY_AND_ASSIGN_(CapturedStream);
8103 // Returns the size (in bytes) of a file.
8104 size_t CapturedStream::GetFileSize(FILE* file) {
8105 fseek(file, 0, SEEK_END);
8106 return static_cast<size_t>(ftell(file));
8109 // Reads the entire content of a file as a string.
8110 String CapturedStream::ReadEntireFile(FILE* file) {
8111 const size_t file_size = GetFileSize(file);
8112 char* const buffer = new char[file_size];
8114 size_t bytes_last_read = 0; // # of bytes read in the last fread()
8115 size_t bytes_read = 0; // # of bytes read so far
8117 fseek(file, 0, SEEK_SET);
8119 // Keeps reading the file until we cannot read further or the
8120 // pre-determined file size is reached.
8122 bytes_last_read = fread(buffer+bytes_read, 1, file_size-bytes_read, file);
8123 bytes_read += bytes_last_read;
8124 } while (bytes_last_read > 0 && bytes_read < file_size);
8126 const String content(buffer, bytes_read);
8133 #pragma warning(pop)
8136 static CapturedStream* g_captured_stderr = NULL;
8137 static CapturedStream* g_captured_stdout = NULL;
8139 // Starts capturing an output stream (stdout/stderr).
8140 void CaptureStream(int fd, const char* stream_name, CapturedStream** stream) {
8141 if (*stream != NULL) {
8142 GTEST_LOG_(FATAL) << "Only one " << stream_name
8143 << " capturer can exist at a time.";
8145 *stream = new CapturedStream(fd);
8148 // Stops capturing the output stream and returns the captured string.
8149 String GetCapturedStream(CapturedStream** captured_stream) {
8150 const String content = (*captured_stream)->GetCapturedString();
8152 delete *captured_stream;
8153 *captured_stream = NULL;
8158 // Starts capturing stdout.
8159 void CaptureStdout() {
8160 CaptureStream(kStdOutFileno, "stdout", &g_captured_stdout);
8163 // Starts capturing stderr.
8164 void CaptureStderr() {
8165 CaptureStream(kStdErrFileno, "stderr", &g_captured_stderr);
8168 // Stops capturing stdout and returns the captured string.
8169 String GetCapturedStdout() { return GetCapturedStream(&g_captured_stdout); }
8171 // Stops capturing stderr and returns the captured string.
8172 String GetCapturedStderr() { return GetCapturedStream(&g_captured_stderr); }
8174 #endif // GTEST_HAS_STREAM_REDIRECTION_
8176 #if GTEST_HAS_DEATH_TEST
8178 // A copy of all command line arguments. Set by InitGoogleTest().
8179 ::std::vector<String> g_argvs;
8181 // Returns the command line as a vector of strings.
8182 const ::std::vector<String>& GetArgvs() { return g_argvs; }
8184 #endif // GTEST_HAS_DEATH_TEST
8186 #if GTEST_OS_WINDOWS_MOBILE
8190 TerminateProcess(GetCurrentProcess(), 1);
8192 } // namespace posix
8193 #endif // GTEST_OS_WINDOWS_MOBILE
8195 // Returns the name of the environment variable corresponding to the
8196 // given flag. For example, FlagToEnvVar("foo") will return
8197 // "GTEST_FOO" in the open-source version.
8198 static String FlagToEnvVar(const char* flag) {
8199 const String full_flag =
8200 (Message() << GTEST_FLAG_PREFIX_ << flag).GetString();
8203 for (size_t i = 0; i != full_flag.length(); i++) {
8204 env_var << static_cast<char>(toupper(full_flag.c_str()[i]));
8207 return env_var.GetString();
8210 // Parses 'str' for a 32-bit signed integer. If successful, writes
8211 // the result to *value and returns true; otherwise leaves *value
8212 // unchanged and returns false.
8213 bool ParseInt32(const Message& src_text, const char* str, Int32* value) {
8214 // Parses the environment variable as a decimal integer.
8216 const long long_value = strtol(str, &end, 10); // NOLINT
8218 // Has strtol() consumed all characters in the string?
8220 // No - an invalid character was encountered.
8222 msg << "WARNING: " << src_text
8223 << " is expected to be a 32-bit integer, but actually"
8224 << " has value \"" << str << "\".\n";
8225 printf("%s", msg.GetString().c_str());
8230 // Is the parsed value in the range of an Int32?
8231 const Int32 result = static_cast<Int32>(long_value);
8232 if (long_value == LONG_MAX || long_value == LONG_MIN ||
8233 // The parsed value overflows as a long. (strtol() returns
8234 // LONG_MAX or LONG_MIN when the input overflows.)
8235 result != long_value
8236 // The parsed value overflows as an Int32.
8239 msg << "WARNING: " << src_text
8240 << " is expected to be a 32-bit integer, but actually"
8241 << " has value " << str << ", which overflows.\n";
8242 printf("%s", msg.GetString().c_str());
8251 // Reads and returns the Boolean environment variable corresponding to
8252 // the given flag; if it's not set, returns default_value.
8254 // The value is considered true iff it's not "0".
8255 bool BoolFromGTestEnv(const char* flag, bool default_value) {
8256 const String env_var = FlagToEnvVar(flag);
8257 const char* const string_value = posix::GetEnv(env_var.c_str());
8258 return string_value == NULL ?
8259 default_value : strcmp(string_value, "0") != 0;
8262 // Reads and returns a 32-bit integer stored in the environment
8263 // variable corresponding to the given flag; if it isn't set or
8264 // doesn't represent a valid 32-bit integer, returns default_value.
8265 Int32 Int32FromGTestEnv(const char* flag, Int32 default_value) {
8266 const String env_var = FlagToEnvVar(flag);
8267 const char* const string_value = posix::GetEnv(env_var.c_str());
8268 if (string_value == NULL) {
8269 // The environment variable is not set.
8270 return default_value;
8273 Int32 result = default_value;
8274 if (!ParseInt32(Message() << "Environment variable " << env_var,
8275 string_value, &result)) {
8276 printf("The default value %s is used.\n",
8277 (Message() << default_value).GetString().c_str());
8279 return default_value;
8285 // Reads and returns the string environment variable corresponding to
8286 // the given flag; if it's not set, returns default_value.
8287 const char* StringFromGTestEnv(const char* flag, const char* default_value) {
8288 const String env_var = FlagToEnvVar(flag);
8289 const char* const value = posix::GetEnv(env_var.c_str());
8290 return value == NULL ? default_value : value;
8293 } // namespace internal
8294 } // namespace testing
8295 // Copyright 2008, Google Inc.
8296 // All rights reserved.
8298 // Redistribution and use in source and binary forms, with or without
8299 // modification, are permitted provided that the following conditions are
8302 // * Redistributions of source code must retain the above copyright
8303 // notice, this list of conditions and the following disclaimer.
8304 // * Redistributions in binary form must reproduce the above
8305 // copyright notice, this list of conditions and the following disclaimer
8306 // in the documentation and/or other materials provided with the
8308 // * Neither the name of Google Inc. nor the names of its
8309 // contributors may be used to endorse or promote products derived from
8310 // this software without specific prior written permission.
8312 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
8313 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
8314 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
8315 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
8316 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
8317 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
8318 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
8319 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
8320 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
8321 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
8322 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
8324 // Author: mheule@google.com (Markus Heule)
8326 // The Google C++ Testing Framework (Google Test)
8329 // Indicates that this translation unit is part of Google Test's
8330 // implementation. It must come before gtest-internal-inl.h is
8331 // included, or there will be a compiler error. This trick is to
8332 // prevent a user from accidentally including gtest-internal-inl.h in
8334 #define GTEST_IMPLEMENTATION_ 1
8335 #undef GTEST_IMPLEMENTATION_
8339 using internal::GetUnitTestImpl;
8341 // Gets the summary of the failure message by omitting the stack trace
8343 internal::String TestPartResult::ExtractSummary(const char* message) {
8344 const char* const stack_trace = strstr(message, internal::kStackTraceMarker);
8345 return stack_trace == NULL ? internal::String(message) :
8346 internal::String(message, stack_trace - message);
8349 // Prints a TestPartResult object.
8350 std::ostream& operator<<(std::ostream& os, const TestPartResult& result) {
8352 << result.file_name() << ":" << result.line_number() << ": "
8353 << (result.type() == TestPartResult::kSuccess ? "Success" :
8354 result.type() == TestPartResult::kFatalFailure ? "Fatal failure" :
8355 "Non-fatal failure") << ":\n"
8356 << result.message() << std::endl;
8359 // Appends a TestPartResult to the array.
8360 void TestPartResultArray::Append(const TestPartResult& result) {
8361 array_.push_back(result);
8364 // Returns the TestPartResult at the given index (0-based).
8365 const TestPartResult& TestPartResultArray::GetTestPartResult(int index) const {
8366 if (index < 0 || index >= size()) {
8367 printf("\nInvalid index (%d) into TestPartResultArray.\n", index);
8368 internal::posix::Abort();
8371 return array_[index];
8374 // Returns the number of TestPartResult objects in the array.
8375 int TestPartResultArray::size() const {
8376 return static_cast<int>(array_.size());
8379 namespace internal {
8381 HasNewFatalFailureHelper::HasNewFatalFailureHelper()
8382 : has_new_fatal_failure_(false),
8383 original_reporter_(GetUnitTestImpl()->
8384 GetTestPartResultReporterForCurrentThread()) {
8385 GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(this);
8388 HasNewFatalFailureHelper::~HasNewFatalFailureHelper() {
8389 GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(
8390 original_reporter_);
8393 void HasNewFatalFailureHelper::ReportTestPartResult(
8394 const TestPartResult& result) {
8395 if (result.fatally_failed())
8396 has_new_fatal_failure_ = true;
8397 original_reporter_->ReportTestPartResult(result);
8400 } // namespace internal
8402 } // namespace testing
8403 // Copyright 2008 Google Inc.
8404 // All Rights Reserved.
8406 // Redistribution and use in source and binary forms, with or without
8407 // modification, are permitted provided that the following conditions are
8410 // * Redistributions of source code must retain the above copyright
8411 // notice, this list of conditions and the following disclaimer.
8412 // * Redistributions in binary form must reproduce the above
8413 // copyright notice, this list of conditions and the following disclaimer
8414 // in the documentation and/or other materials provided with the
8416 // * Neither the name of Google Inc. nor the names of its
8417 // contributors may be used to endorse or promote products derived from
8418 // this software without specific prior written permission.
8420 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
8421 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
8422 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
8423 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
8424 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
8425 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
8426 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
8427 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
8428 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
8429 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
8430 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
8432 // Author: wan@google.com (Zhanyong Wan)
8436 namespace internal {
8438 #if GTEST_HAS_TYPED_TEST_P
8440 // Skips to the first non-space char in str. Returns an empty string if str
8441 // contains only whitespace characters.
8442 static const char* SkipSpaces(const char* str) {
8443 while (isspace(*str))
8448 // Verifies that registered_tests match the test names in
8449 // defined_test_names_; returns registered_tests if successful, or
8450 // aborts the program otherwise.
8451 const char* TypedTestCasePState::VerifyRegisteredTestNames(
8452 const char* file, int line, const char* registered_tests) {
8453 typedef ::std::set<const char*>::const_iterator DefinedTestIter;
8456 // Skip initial whitespace in registered_tests since some
8457 // preprocessors prefix stringizied literals with whitespace.
8458 registered_tests = SkipSpaces(registered_tests);
8461 ::std::set<String> tests;
8462 for (const char* names = registered_tests; names != NULL;
8463 names = SkipComma(names)) {
8464 const String name = GetPrefixUntilComma(names);
8465 if (tests.count(name) != 0) {
8466 errors << "Test " << name << " is listed more than once.\n";
8471 for (DefinedTestIter it = defined_test_names_.begin();
8472 it != defined_test_names_.end();
8483 errors << "No test named " << name
8484 << " can be found in this test case.\n";
8488 for (DefinedTestIter it = defined_test_names_.begin();
8489 it != defined_test_names_.end();
8491 if (tests.count(*it) == 0) {
8492 errors << "You forgot to list test " << *it << ".\n";
8496 const String& errors_str = errors.GetString();
8497 if (errors_str != "") {
8498 fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(),
8499 errors_str.c_str());
8504 return registered_tests;
8507 #endif // GTEST_HAS_TYPED_TEST_P
8509 } // namespace internal
8510 } // namespace testing