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"
42 # pragma GCC diagnostic ignored "-Wmissing-declarations"
43 # pragma GCC diagnostic ignored "-Wmissing-field-initializers"
46 // The following lines pull in the real gtest *.cc files.
47 // Copyright 2005, Google Inc.
48 // All rights reserved.
50 // Redistribution and use in source and binary forms, with or without
51 // modification, are permitted provided that the following conditions are
54 // * Redistributions of source code must retain the above copyright
55 // notice, this list of conditions and the following disclaimer.
56 // * Redistributions in binary form must reproduce the above
57 // copyright notice, this list of conditions and the following disclaimer
58 // in the documentation and/or other materials provided with the
60 // * Neither the name of Google Inc. nor the names of its
61 // contributors may be used to endorse or promote products derived from
62 // this software without specific prior written permission.
64 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
65 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
66 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
67 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
68 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
69 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
70 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
71 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
72 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
73 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
74 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
76 // Author: wan@google.com (Zhanyong Wan)
78 // The Google C++ Testing Framework (Google Test)
80 // Copyright 2007, Google Inc.
81 // All rights reserved.
83 // Redistribution and use in source and binary forms, with or without
84 // modification, are permitted provided that the following conditions are
87 // * Redistributions of source code must retain the above copyright
88 // notice, this list of conditions and the following disclaimer.
89 // * Redistributions in binary form must reproduce the above
90 // copyright notice, this list of conditions and the following disclaimer
91 // in the documentation and/or other materials provided with the
93 // * Neither the name of Google Inc. nor the names of its
94 // contributors may be used to endorse or promote products derived from
95 // this software without specific prior written permission.
97 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
98 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
99 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
100 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
101 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
102 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
103 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
104 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
105 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
106 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
107 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
109 // Author: wan@google.com (Zhanyong Wan)
111 // Utilities for testing Google Test itself and code that uses Google Test
112 // (e.g. frameworks built on top of Google Test).
114 #ifndef GTEST_INCLUDE_GTEST_GTEST_SPI_H_
115 #define GTEST_INCLUDE_GTEST_GTEST_SPI_H_
120 // This helper class can be used to mock out Google Test failure reporting
121 // so that we can test Google Test or code that builds on Google Test.
123 // An object of this class appends a TestPartResult object to the
124 // TestPartResultArray object given in the constructor whenever a Google Test
125 // failure is reported. It can either intercept only failures that are
126 // generated in the same thread that created this object or it can intercept
127 // all generated failures. The scope of this mock object can be controlled with
128 // the second argument to the two arguments constructor.
129 class GTEST_API_ ScopedFakeTestPartResultReporter
130 : public TestPartResultReporterInterface {
132 // The two possible mocking modes of this object.
134 INTERCEPT_ONLY_CURRENT_THREAD, // Intercepts only thread local failures.
135 INTERCEPT_ALL_THREADS // Intercepts all failures.
138 // The c'tor sets this object as the test part result reporter used
139 // by Google Test. The 'result' parameter specifies where to report the
140 // results. This reporter will only catch failures generated in the current
141 // thread. DEPRECATED
142 explicit ScopedFakeTestPartResultReporter(TestPartResultArray* result);
144 // Same as above, but you can choose the interception scope of this object.
145 ScopedFakeTestPartResultReporter(InterceptMode intercept_mode,
146 TestPartResultArray* result);
148 // The d'tor restores the previous test part result reporter.
149 virtual ~ScopedFakeTestPartResultReporter();
151 // Appends the TestPartResult object to the TestPartResultArray
152 // received in the constructor.
154 // This method is from the TestPartResultReporterInterface
156 virtual void ReportTestPartResult(const TestPartResult& result);
160 const InterceptMode intercept_mode_;
161 TestPartResultReporterInterface* old_reporter_;
162 TestPartResultArray* const result_;
164 GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedFakeTestPartResultReporter);
169 // A helper class for implementing EXPECT_FATAL_FAILURE() and
170 // EXPECT_NONFATAL_FAILURE(). Its destructor verifies that the given
171 // TestPartResultArray contains exactly one failure that has the given
172 // type and contains the given substring. If that's not the case, a
173 // non-fatal failure will be generated.
174 class GTEST_API_ SingleFailureChecker {
176 // The constructor remembers the arguments.
177 SingleFailureChecker(const TestPartResultArray* results,
178 TestPartResult::Type type,
179 const string& substr);
180 ~SingleFailureChecker();
182 const TestPartResultArray* const results_;
183 const TestPartResult::Type type_;
184 const string substr_;
186 GTEST_DISALLOW_COPY_AND_ASSIGN_(SingleFailureChecker);
189 } // namespace internal
191 } // namespace testing
193 // A set of macros for testing Google Test assertions or code that's expected
194 // to generate Google Test fatal failures. It verifies that the given
195 // statement will cause exactly one fatal Google Test failure with 'substr'
196 // being part of the failure message.
198 // There are two different versions of this macro. EXPECT_FATAL_FAILURE only
199 // affects and considers failures generated in the current thread and
200 // EXPECT_FATAL_FAILURE_ON_ALL_THREADS does the same but for all threads.
202 // The verification of the assertion is done correctly even when the statement
203 // throws an exception or aborts the current function.
205 // Known restrictions:
206 // - 'statement' cannot reference local non-static variables or
207 // non-static members of the current object.
208 // - 'statement' cannot return a value.
209 // - You cannot stream a failure message to this macro.
211 // Note that even though the implementations of the following two
212 // macros are much alike, we cannot refactor them to use a common
213 // helper macro, due to some peculiarity in how the preprocessor
214 // works. The AcceptsMacroThatExpandsToUnprotectedComma test in
215 // gtest_unittest.cc will fail to compile if we do that.
216 #define EXPECT_FATAL_FAILURE(statement, substr) \
218 class GTestExpectFatalFailureHelper {\
220 static void Execute() { statement; }\
222 ::testing::TestPartResultArray gtest_failures;\
223 ::testing::internal::SingleFailureChecker gtest_checker(\
224 >est_failures, ::testing::TestPartResult::kFatalFailure, (substr));\
226 ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
227 ::testing::ScopedFakeTestPartResultReporter:: \
228 INTERCEPT_ONLY_CURRENT_THREAD, >est_failures);\
229 GTestExpectFatalFailureHelper::Execute();\
231 } while (::testing::internal::AlwaysFalse())
233 #define EXPECT_FATAL_FAILURE_ON_ALL_THREADS(statement, substr) \
235 class GTestExpectFatalFailureHelper {\
237 static void Execute() { statement; }\
239 ::testing::TestPartResultArray gtest_failures;\
240 ::testing::internal::SingleFailureChecker gtest_checker(\
241 >est_failures, ::testing::TestPartResult::kFatalFailure, (substr));\
243 ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
244 ::testing::ScopedFakeTestPartResultReporter:: \
245 INTERCEPT_ALL_THREADS, >est_failures);\
246 GTestExpectFatalFailureHelper::Execute();\
248 } while (::testing::internal::AlwaysFalse())
250 // A macro for testing Google Test assertions or code that's expected to
251 // generate Google Test non-fatal failures. It asserts that the given
252 // statement will cause exactly one non-fatal Google Test failure with 'substr'
253 // being part of the failure message.
255 // There are two different versions of this macro. EXPECT_NONFATAL_FAILURE only
256 // affects and considers failures generated in the current thread and
257 // EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS does the same but for all threads.
259 // 'statement' is allowed to reference local variables and members of
260 // the current object.
262 // The verification of the assertion is done correctly even when the statement
263 // throws an exception or aborts the current function.
265 // Known restrictions:
266 // - You cannot stream a failure message to this macro.
268 // Note that even though the implementations of the following two
269 // macros are much alike, we cannot refactor them to use a common
270 // helper macro, due to some peculiarity in how the preprocessor
271 // works. If we do that, the code won't compile when the user gives
272 // EXPECT_NONFATAL_FAILURE() a statement that contains a macro that
273 // expands to code containing an unprotected comma. The
274 // AcceptsMacroThatExpandsToUnprotectedComma test in gtest_unittest.cc
277 // For the same reason, we have to write
278 // if (::testing::internal::AlwaysTrue()) { statement; }
280 // GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement)
281 // to avoid an MSVC warning on unreachable code.
282 #define EXPECT_NONFATAL_FAILURE(statement, substr) \
284 ::testing::TestPartResultArray gtest_failures;\
285 ::testing::internal::SingleFailureChecker gtest_checker(\
286 >est_failures, ::testing::TestPartResult::kNonFatalFailure, \
289 ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
290 ::testing::ScopedFakeTestPartResultReporter:: \
291 INTERCEPT_ONLY_CURRENT_THREAD, >est_failures);\
292 if (::testing::internal::AlwaysTrue()) { statement; }\
294 } while (::testing::internal::AlwaysFalse())
296 #define EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(statement, substr) \
298 ::testing::TestPartResultArray gtest_failures;\
299 ::testing::internal::SingleFailureChecker gtest_checker(\
300 >est_failures, ::testing::TestPartResult::kNonFatalFailure, \
303 ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
304 ::testing::ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, \
306 if (::testing::internal::AlwaysTrue()) { statement; }\
308 } while (::testing::internal::AlwaysFalse())
310 #endif // GTEST_INCLUDE_GTEST_GTEST_SPI_H_
322 #include <ostream> // NOLINT
328 // TODO(kenton@google.com): Use autoconf to detect availability of
330 # define GTEST_HAS_GETTIMEOFDAY_ 1
332 # include <fcntl.h> // NOLINT
333 # include <limits.h> // NOLINT
334 # include <sched.h> // NOLINT
335 // Declares vsnprintf(). This header is not available on Windows.
336 # include <strings.h> // NOLINT
337 # include <sys/mman.h> // NOLINT
338 # include <sys/time.h> // NOLINT
339 # include <unistd.h> // NOLINT
342 #elif GTEST_OS_SYMBIAN
343 # define GTEST_HAS_GETTIMEOFDAY_ 1
344 # include <sys/time.h> // NOLINT
347 # define GTEST_HAS_GETTIMEOFDAY_ 1
348 # include <sys/time.h> // NOLINT
350 // On z/OS we additionally need strings.h for strcasecmp.
351 # include <strings.h> // NOLINT
353 #elif GTEST_OS_WINDOWS_MOBILE // We are on Windows CE.
355 # include <windows.h> // NOLINT
357 #elif GTEST_OS_WINDOWS // We are on Windows proper.
359 # include <io.h> // NOLINT
360 # include <sys/timeb.h> // NOLINT
361 # include <sys/types.h> // NOLINT
362 # include <sys/stat.h> // NOLINT
364 # if GTEST_OS_WINDOWS_MINGW
365 // MinGW has gettimeofday() but not _ftime64().
366 // TODO(kenton@google.com): Use autoconf to detect availability of
368 // TODO(kenton@google.com): There are other ways to get the time on
369 // Windows, like GetTickCount() or GetSystemTimeAsFileTime(). MinGW
370 // supports these. consider using them instead.
371 # define GTEST_HAS_GETTIMEOFDAY_ 1
372 # include <sys/time.h> // NOLINT
373 # endif // GTEST_OS_WINDOWS_MINGW
375 // cpplint thinks that the header is already included, so we want to
377 # include <windows.h> // NOLINT
381 // Assume other platforms have gettimeofday().
382 // TODO(kenton@google.com): Use autoconf to detect availability of
384 # define GTEST_HAS_GETTIMEOFDAY_ 1
386 // cpplint thinks that the header is already included, so we want to
388 # include <sys/time.h> // NOLINT
389 # include <unistd.h> // NOLINT
391 #endif // GTEST_OS_LINUX
393 #if GTEST_HAS_EXCEPTIONS
394 # include <stdexcept>
397 #if GTEST_CAN_STREAM_RESULTS_
398 # include <arpa/inet.h> // NOLINT
399 # include <netdb.h> // NOLINT
402 // Indicates that this translation unit is part of Google Test's
403 // implementation. It must come before gtest-internal-inl.h is
404 // included, or there will be a compiler error. This trick is to
405 // prevent a user from accidentally including gtest-internal-inl.h in
407 #define GTEST_IMPLEMENTATION_ 1
408 // Copyright 2005, Google Inc.
409 // All rights reserved.
411 // Redistribution and use in source and binary forms, with or without
412 // modification, are permitted provided that the following conditions are
415 // * Redistributions of source code must retain the above copyright
416 // notice, this list of conditions and the following disclaimer.
417 // * Redistributions in binary form must reproduce the above
418 // copyright notice, this list of conditions and the following disclaimer
419 // in the documentation and/or other materials provided with the
421 // * Neither the name of Google Inc. nor the names of its
422 // contributors may be used to endorse or promote products derived from
423 // this software without specific prior written permission.
425 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
426 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
427 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
428 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
429 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
430 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
431 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
432 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
433 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
434 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
435 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
437 // Utility functions and classes used by the Google C++ testing framework.
439 // Author: wan@google.com (Zhanyong Wan)
441 // This file contains purely Google Test's internal implementation. Please
442 // DO NOT #INCLUDE IT IN A USER PROGRAM.
444 #ifndef GTEST_SRC_GTEST_INTERNAL_INL_H_
445 #define GTEST_SRC_GTEST_INTERNAL_INL_H_
447 // GTEST_IMPLEMENTATION_ is defined to 1 iff the current translation unit is
448 // part of Google Test's implementation; otherwise it's undefined.
449 #if !GTEST_IMPLEMENTATION_
450 // A user is trying to include this from his code - just say no.
451 # error "gtest-internal-inl.h is part of Google Test's internal implementation."
452 # error "It must not be included except by Google Test itself."
453 #endif // GTEST_IMPLEMENTATION_
457 #endif // !_WIN32_WCE
459 #include <stdlib.h> // For strtoll/_strtoul64/malloc/free.
460 #include <string.h> // For memmove.
468 # include <windows.h> // NOLINT
469 #endif // GTEST_OS_WINDOWS
474 // Declares the flags.
476 // We don't want the users to modify this flag in the code, but want
477 // Google Test's own unit tests to be able to access it. Therefore we
478 // declare it here as opposed to in gtest.h.
479 GTEST_DECLARE_bool_(death_test_use_fork);
483 // The value of GetTestTypeId() as seen from within the Google Test
484 // library. This is solely for testing GetTestTypeId().
485 GTEST_API_ extern const TypeId kTestTypeIdInGoogleTest;
487 // Names of the flags (needed for parsing Google Test flags).
488 const char kAlsoRunDisabledTestsFlag[] = "also_run_disabled_tests";
489 const char kBreakOnFailureFlag[] = "break_on_failure";
490 const char kCatchExceptionsFlag[] = "catch_exceptions";
491 const char kColorFlag[] = "color";
492 const char kFilterFlag[] = "filter";
493 const char kListTestsFlag[] = "list_tests";
494 const char kOutputFlag[] = "output";
495 const char kPrintTimeFlag[] = "print_time";
496 const char kRandomSeedFlag[] = "random_seed";
497 const char kRepeatFlag[] = "repeat";
498 const char kShuffleFlag[] = "shuffle";
499 const char kStackTraceDepthFlag[] = "stack_trace_depth";
500 const char kStreamResultToFlag[] = "stream_result_to";
501 const char kThrowOnFailureFlag[] = "throw_on_failure";
503 // A valid random seed must be in [1, kMaxRandomSeed].
504 const int kMaxRandomSeed = 99999;
506 // g_help_flag is true iff the --help flag or an equivalent form is
507 // specified on the command line.
508 GTEST_API_ extern bool g_help_flag;
510 // Returns the current time in milliseconds.
511 GTEST_API_ TimeInMillis GetTimeInMillis();
513 // Returns true iff Google Test should use colors in the output.
514 GTEST_API_ bool ShouldUseColor(bool stdout_is_tty);
516 // Formats the given time in milliseconds as seconds.
517 GTEST_API_ std::string FormatTimeInMillisAsSeconds(TimeInMillis ms);
519 // Converts the given time in milliseconds to a date string in the ISO 8601
520 // format, without the timezone information. N.B.: due to the use the
521 // non-reentrant localtime() function, this function is not thread safe. Do
522 // not use it in any code that can be called from multiple threads.
523 GTEST_API_ std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms);
525 // Parses a string for an Int32 flag, in the form of "--flag=value".
527 // On success, stores the value of the flag in *value, and returns
528 // true. On failure, returns false without changing *value.
529 GTEST_API_ bool ParseInt32Flag(
530 const char* str, const char* flag, Int32* value);
532 // Returns a random seed in range [1, kMaxRandomSeed] based on the
533 // given --gtest_random_seed flag value.
534 inline int GetRandomSeedFromFlag(Int32 random_seed_flag) {
535 const unsigned int raw_seed = (random_seed_flag == 0) ?
536 static_cast<unsigned int>(GetTimeInMillis()) :
537 static_cast<unsigned int>(random_seed_flag);
539 // Normalizes the actual seed to range [1, kMaxRandomSeed] such that
540 // it's easy to type.
541 const int normalized_seed =
542 static_cast<int>((raw_seed - 1U) %
543 static_cast<unsigned int>(kMaxRandomSeed)) + 1;
544 return normalized_seed;
547 // Returns the first valid random seed after 'seed'. The behavior is
548 // undefined if 'seed' is invalid. The seed after kMaxRandomSeed is
549 // considered to be 1.
550 inline int GetNextRandomSeed(int seed) {
551 GTEST_CHECK_(1 <= seed && seed <= kMaxRandomSeed)
552 << "Invalid random seed " << seed << " - must be in [1, "
553 << kMaxRandomSeed << "].";
554 const int next_seed = seed + 1;
555 return (next_seed > kMaxRandomSeed) ? 1 : next_seed;
558 // This class saves the values of all Google Test flags in its c'tor, and
559 // restores them in its d'tor.
560 class GTestFlagSaver {
564 also_run_disabled_tests_ = GTEST_FLAG(also_run_disabled_tests);
565 break_on_failure_ = GTEST_FLAG(break_on_failure);
566 catch_exceptions_ = GTEST_FLAG(catch_exceptions);
567 color_ = GTEST_FLAG(color);
568 death_test_style_ = GTEST_FLAG(death_test_style);
569 death_test_use_fork_ = GTEST_FLAG(death_test_use_fork);
570 filter_ = GTEST_FLAG(filter);
571 internal_run_death_test_ = GTEST_FLAG(internal_run_death_test);
572 list_tests_ = GTEST_FLAG(list_tests);
573 output_ = GTEST_FLAG(output);
574 print_time_ = GTEST_FLAG(print_time);
575 random_seed_ = GTEST_FLAG(random_seed);
576 repeat_ = GTEST_FLAG(repeat);
577 shuffle_ = GTEST_FLAG(shuffle);
578 stack_trace_depth_ = GTEST_FLAG(stack_trace_depth);
579 stream_result_to_ = GTEST_FLAG(stream_result_to);
580 throw_on_failure_ = GTEST_FLAG(throw_on_failure);
583 // The d'tor is not virtual. DO NOT INHERIT FROM THIS CLASS.
585 GTEST_FLAG(also_run_disabled_tests) = also_run_disabled_tests_;
586 GTEST_FLAG(break_on_failure) = break_on_failure_;
587 GTEST_FLAG(catch_exceptions) = catch_exceptions_;
588 GTEST_FLAG(color) = color_;
589 GTEST_FLAG(death_test_style) = death_test_style_;
590 GTEST_FLAG(death_test_use_fork) = death_test_use_fork_;
591 GTEST_FLAG(filter) = filter_;
592 GTEST_FLAG(internal_run_death_test) = internal_run_death_test_;
593 GTEST_FLAG(list_tests) = list_tests_;
594 GTEST_FLAG(output) = output_;
595 GTEST_FLAG(print_time) = print_time_;
596 GTEST_FLAG(random_seed) = random_seed_;
597 GTEST_FLAG(repeat) = repeat_;
598 GTEST_FLAG(shuffle) = shuffle_;
599 GTEST_FLAG(stack_trace_depth) = stack_trace_depth_;
600 GTEST_FLAG(stream_result_to) = stream_result_to_;
601 GTEST_FLAG(throw_on_failure) = throw_on_failure_;
605 // Fields for saving the original values of flags.
606 bool also_run_disabled_tests_;
607 bool break_on_failure_;
608 bool catch_exceptions_;
610 String death_test_style_;
611 bool death_test_use_fork_;
613 String internal_run_death_test_;
618 internal::Int32 random_seed_;
619 internal::Int32 repeat_;
621 internal::Int32 stack_trace_depth_;
622 String stream_result_to_;
623 bool throw_on_failure_;
624 } GTEST_ATTRIBUTE_UNUSED_;
626 // Converts a Unicode code point to a narrow string in UTF-8 encoding.
627 // code_point parameter is of type UInt32 because wchar_t may not be
628 // wide enough to contain a code point.
629 // The output buffer str must containt at least 32 characters.
630 // The function returns the address of the output buffer.
631 // If the code_point is not a valid Unicode code point
632 // (i.e. outside of Unicode range U+0 to U+10FFFF) it will be output
633 // as '(Invalid Unicode 0xXXXXXXXX)'.
634 GTEST_API_ char* CodePointToUtf8(UInt32 code_point, char* str);
636 // Converts a wide string to a narrow string in UTF-8 encoding.
637 // The wide string is assumed to have the following encoding:
638 // UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS)
639 // UTF-32 if sizeof(wchar_t) == 4 (on Linux)
640 // Parameter str points to a null-terminated wide string.
641 // Parameter num_chars may additionally limit the number
642 // of wchar_t characters processed. -1 is used when the entire string
643 // should be processed.
644 // If the string contains code points that are not valid Unicode code points
645 // (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
646 // as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
647 // and contains invalid UTF-16 surrogate pairs, values in those pairs
648 // will be encoded as individual Unicode characters from Basic Normal Plane.
649 GTEST_API_ String WideStringToUtf8(const wchar_t* str, int num_chars);
651 // Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
652 // if the variable is present. If a file already exists at this location, this
653 // function will write over it. If the variable is present, but the file cannot
654 // be created, prints an error and exits.
655 void WriteToShardStatusFileIfNeeded();
657 // Checks whether sharding is enabled by examining the relevant
658 // environment variable values. If the variables are present,
659 // but inconsistent (e.g., shard_index >= total_shards), prints
660 // an error and exits. If in_subprocess_for_death_test, sharding is
661 // disabled because it must only be applied to the original test
662 // process. Otherwise, we could filter out death tests we intended to execute.
663 GTEST_API_ bool ShouldShard(const char* total_shards_str,
664 const char* shard_index_str,
665 bool in_subprocess_for_death_test);
667 // Parses the environment variable var as an Int32. If it is unset,
668 // returns default_val. If it is not an Int32, prints an error and
670 GTEST_API_ Int32 Int32FromEnvOrDie(const char* env_var, Int32 default_val);
672 // Given the total number of shards, the shard index, and the test id,
673 // returns true iff the test should be run on this shard. The test id is
674 // some arbitrary but unique non-negative integer assigned to each test
675 // method. Assumes that 0 <= shard_index < total_shards.
676 GTEST_API_ bool ShouldRunTestOnShard(
677 int total_shards, int shard_index, int test_id);
679 // STL container utilities.
681 // Returns the number of elements in the given container that satisfy
682 // the given predicate.
683 template <class Container, typename Predicate>
684 inline int CountIf(const Container& c, Predicate predicate) {
685 // Implemented as an explicit loop since std::count_if() in libCstd on
686 // Solaris has a non-standard signature.
688 for (typename Container::const_iterator it = c.begin(); it != c.end(); ++it) {
695 // Applies a function/functor to each element in the container.
696 template <class Container, typename Functor>
697 void ForEach(const Container& c, Functor functor) {
698 std::for_each(c.begin(), c.end(), functor);
701 // Returns the i-th element of the vector, or default_value if i is not
702 // in range [0, v.size()).
703 template <typename E>
704 inline E GetElementOr(const std::vector<E>& v, int i, E default_value) {
705 return (i < 0 || i >= static_cast<int>(v.size())) ? default_value : v[i];
708 // Performs an in-place shuffle of a range of the vector's elements.
709 // 'begin' and 'end' are element indices as an STL-style range;
710 // i.e. [begin, end) are shuffled, where 'end' == size() means to
711 // shuffle to the end of the vector.
712 template <typename E>
713 void ShuffleRange(internal::Random* random, int begin, int end,
715 const int size = static_cast<int>(v->size());
716 GTEST_CHECK_(0 <= begin && begin <= size)
717 << "Invalid shuffle range start " << begin << ": must be in range [0, "
719 GTEST_CHECK_(begin <= end && end <= size)
720 << "Invalid shuffle range finish " << end << ": must be in range ["
721 << begin << ", " << size << "].";
723 // Fisher-Yates shuffle, from
724 // http://en.wikipedia.org/wiki/Fisher-Yates_shuffle
725 for (int range_width = end - begin; range_width >= 2; range_width--) {
726 const int last_in_range = begin + range_width - 1;
727 const int selected = begin + random->Generate(range_width);
728 std::swap((*v)[selected], (*v)[last_in_range]);
732 // Performs an in-place shuffle of the vector's elements.
733 template <typename E>
734 inline void Shuffle(internal::Random* random, std::vector<E>* v) {
735 ShuffleRange(random, 0, static_cast<int>(v->size()), v);
738 // A function for deleting an object. Handy for being used as a
740 template <typename T>
741 static void Delete(T* x) {
745 // A predicate that checks the key of a TestProperty against a known key.
747 // TestPropertyKeyIs is copyable.
748 class TestPropertyKeyIs {
752 // TestPropertyKeyIs has NO default constructor.
753 explicit TestPropertyKeyIs(const char* key)
756 // Returns true iff the test name of test property matches on key_.
757 bool operator()(const TestProperty& test_property) const {
758 return String(test_property.key()).Compare(key_) == 0;
765 // Class UnitTestOptions.
767 // This class contains functions for processing options the user
768 // specifies when running the tests. It has only static members.
770 // In most cases, the user can specify an option using either an
771 // environment variable or a command line flag. E.g. you can set the
772 // test filter using either GTEST_FILTER or --gtest_filter. If both
773 // the variable and the flag are present, the latter overrides the
775 class GTEST_API_ UnitTestOptions {
777 // Functions for processing the gtest_output flag.
779 // Returns the output format, or "" for normal printed output.
780 static String GetOutputFormat();
782 // Returns the absolute path of the requested output file, or the
783 // default (test_detail.xml in the original working directory) if
784 // none was explicitly specified.
785 static String GetAbsolutePathToOutputFile();
787 // Functions for processing the gtest_filter flag.
789 // Returns true iff the wildcard pattern matches the string. The
790 // first ':' or '\0' character in pattern marks the end of it.
792 // This recursive algorithm isn't very efficient, but is clear and
793 // works well enough for matching test names, which are short.
794 static bool PatternMatchesString(const char *pattern, const char *str);
796 // Returns true iff the user-specified filter matches the test case
797 // name and the test name.
798 static bool FilterMatchesTest(const String &test_case_name,
799 const String &test_name);
802 // Function for supporting the gtest_catch_exception flag.
804 // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
805 // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
806 // This function is useful as an __except condition.
807 static int GTestShouldProcessSEH(DWORD exception_code);
808 #endif // GTEST_OS_WINDOWS
810 // Returns true if "name" matches the ':' separated list of glob-style
811 // filters in "filter".
812 static bool MatchesFilter(const String& name, const char* filter);
815 // Returns the current application's name, removing directory path if that
816 // is present. Used by UnitTestOptions::GetOutputFile.
817 GTEST_API_ FilePath GetCurrentExecutableName();
819 // The role interface for getting the OS stack trace as a string.
820 class OsStackTraceGetterInterface {
822 OsStackTraceGetterInterface() {}
823 virtual ~OsStackTraceGetterInterface() {}
825 // Returns the current OS stack trace as a String. Parameters:
827 // max_depth - the maximum number of stack frames to be included
829 // skip_count - the number of top frames to be skipped; doesn't count
830 // against max_depth.
831 virtual String CurrentStackTrace(int max_depth, int skip_count) = 0;
833 // UponLeavingGTest() should be called immediately before Google Test calls
834 // user code. It saves some information about the current stack that
835 // CurrentStackTrace() will use to find and hide Google Test stack frames.
836 virtual void UponLeavingGTest() = 0;
839 GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetterInterface);
842 // A working implementation of the OsStackTraceGetterInterface interface.
843 class OsStackTraceGetter : public OsStackTraceGetterInterface {
845 OsStackTraceGetter() : caller_frame_(NULL) {}
847 virtual String CurrentStackTrace(int max_depth, int skip_count)
848 GTEST_LOCK_EXCLUDED_(mutex_);
850 virtual void UponLeavingGTest() GTEST_LOCK_EXCLUDED_(mutex_);
852 // This string is inserted in place of stack frames that are part of
853 // Google Test's implementation.
854 static const char* const kElidedFramesMarker;
857 Mutex mutex_; // protects all internal state
859 // We save the stack frame below the frame that calls user code.
860 // We do this because the address of the frame immediately below
861 // the user code changes between the call to UponLeavingGTest()
862 // and any calls to CurrentStackTrace() from within the user code.
865 GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetter);
868 // Information about a Google Test trace point.
875 // This is the default global test part result reporter used in UnitTestImpl.
876 // This class should only be used by UnitTestImpl.
877 class DefaultGlobalTestPartResultReporter
878 : public TestPartResultReporterInterface {
880 explicit DefaultGlobalTestPartResultReporter(UnitTestImpl* unit_test);
881 // Implements the TestPartResultReporterInterface. Reports the test part
882 // result in the current test.
883 virtual void ReportTestPartResult(const TestPartResult& result);
886 UnitTestImpl* const unit_test_;
888 GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultGlobalTestPartResultReporter);
891 // This is the default per thread test part result reporter used in
892 // UnitTestImpl. This class should only be used by UnitTestImpl.
893 class DefaultPerThreadTestPartResultReporter
894 : public TestPartResultReporterInterface {
896 explicit DefaultPerThreadTestPartResultReporter(UnitTestImpl* unit_test);
897 // Implements the TestPartResultReporterInterface. The implementation just
898 // delegates to the current global test part result reporter of *unit_test_.
899 virtual void ReportTestPartResult(const TestPartResult& result);
902 UnitTestImpl* const unit_test_;
904 GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultPerThreadTestPartResultReporter);
907 // The private implementation of the UnitTest class. We don't protect
908 // the methods under a mutex, as this class is not accessible by a
909 // user and the UnitTest class that delegates work to this class does
911 class GTEST_API_ UnitTestImpl {
913 explicit UnitTestImpl(UnitTest* parent);
914 virtual ~UnitTestImpl();
916 // There are two different ways to register your own TestPartResultReporter.
917 // You can register your own repoter to listen either only for test results
918 // from the current thread or for results from all threads.
919 // By default, each per-thread test result repoter just passes a new
920 // TestPartResult to the global test result reporter, which registers the
921 // test part result for the currently running test.
923 // Returns the global test part result reporter.
924 TestPartResultReporterInterface* GetGlobalTestPartResultReporter();
926 // Sets the global test part result reporter.
927 void SetGlobalTestPartResultReporter(
928 TestPartResultReporterInterface* reporter);
930 // Returns the test part result reporter for the current thread.
931 TestPartResultReporterInterface* GetTestPartResultReporterForCurrentThread();
933 // Sets the test part result reporter for the current thread.
934 void SetTestPartResultReporterForCurrentThread(
935 TestPartResultReporterInterface* reporter);
937 // Gets the number of successful test cases.
938 int successful_test_case_count() const;
940 // Gets the number of failed test cases.
941 int failed_test_case_count() const;
943 // Gets the number of all test cases.
944 int total_test_case_count() const;
946 // Gets the number of all test cases that contain at least one test
948 int test_case_to_run_count() const;
950 // Gets the number of successful tests.
951 int successful_test_count() const;
953 // Gets the number of failed tests.
954 int failed_test_count() const;
956 // Gets the number of disabled tests.
957 int disabled_test_count() const;
959 // Gets the number of all tests.
960 int total_test_count() const;
962 // Gets the number of tests that should run.
963 int test_to_run_count() const;
965 // Gets the time of the test program start, in ms from the start of the
967 TimeInMillis start_timestamp() const { return start_timestamp_; }
969 // Gets the elapsed time, in milliseconds.
970 TimeInMillis elapsed_time() const { return elapsed_time_; }
972 // Returns true iff the unit test passed (i.e. all test cases passed).
973 bool Passed() const { return !Failed(); }
975 // Returns true iff the unit test failed (i.e. some test case failed
976 // or something outside of all tests failed).
977 bool Failed() const {
978 return failed_test_case_count() > 0 || ad_hoc_test_result()->Failed();
981 // Gets the i-th test case among all the test cases. i can range from 0 to
982 // total_test_case_count() - 1. If i is not in that range, returns NULL.
983 const TestCase* GetTestCase(int i) const {
984 const int index = GetElementOr(test_case_indices_, i, -1);
985 return index < 0 ? NULL : test_cases_[i];
988 // Gets the i-th test case among all the test cases. i can range from 0 to
989 // total_test_case_count() - 1. If i is not in that range, returns NULL.
990 TestCase* GetMutableTestCase(int i) {
991 const int index = GetElementOr(test_case_indices_, i, -1);
992 return index < 0 ? NULL : test_cases_[index];
995 // Provides access to the event listener list.
996 TestEventListeners* listeners() { return &listeners_; }
998 // Returns the TestResult for the test that's currently running, or
999 // the TestResult for the ad hoc test if no test is running.
1000 TestResult* current_test_result();
1002 // Returns the TestResult for the ad hoc test.
1003 const TestResult* ad_hoc_test_result() const { return &ad_hoc_test_result_; }
1005 // Sets the OS stack trace getter.
1007 // Does nothing if the input and the current OS stack trace getter
1008 // are the same; otherwise, deletes the old getter and makes the
1009 // input the current getter.
1010 void set_os_stack_trace_getter(OsStackTraceGetterInterface* getter);
1012 // Returns the current OS stack trace getter if it is not NULL;
1013 // otherwise, creates an OsStackTraceGetter, makes it the current
1014 // getter, and returns it.
1015 OsStackTraceGetterInterface* os_stack_trace_getter();
1017 // Returns the current OS stack trace as a String.
1019 // The maximum number of stack frames to be included is specified by
1020 // the gtest_stack_trace_depth flag. The skip_count parameter
1021 // specifies the number of top frames to be skipped, which doesn't
1022 // count against the number of frames to be included.
1024 // For example, if Foo() calls Bar(), which in turn calls
1025 // CurrentOsStackTraceExceptTop(1), Foo() will be included in the
1026 // trace but Bar() and CurrentOsStackTraceExceptTop() won't.
1027 String CurrentOsStackTraceExceptTop(int skip_count) GTEST_NO_INLINE_;
1029 // Finds and returns a TestCase with the given name. If one doesn't
1030 // exist, creates one and returns it.
1034 // test_case_name: name of the test case
1035 // type_param: the name of the test's type parameter, or NULL if
1036 // this is not a typed or a type-parameterized test.
1037 // set_up_tc: pointer to the function that sets up the test case
1038 // tear_down_tc: pointer to the function that tears down the test case
1039 TestCase* GetTestCase(const char* test_case_name,
1040 const char* type_param,
1041 Test::SetUpTestCaseFunc set_up_tc,
1042 Test::TearDownTestCaseFunc tear_down_tc);
1044 // Adds a TestInfo to the unit test.
1048 // set_up_tc: pointer to the function that sets up the test case
1049 // tear_down_tc: pointer to the function that tears down the test case
1050 // test_info: the TestInfo object
1051 void AddTestInfo(Test::SetUpTestCaseFunc set_up_tc,
1052 Test::TearDownTestCaseFunc tear_down_tc,
1053 TestInfo* test_info) {
1054 // In order to support thread-safe death tests, we need to
1055 // remember the original working directory when the test program
1056 // was first invoked. We cannot do this in RUN_ALL_TESTS(), as
1057 // the user may have changed the current directory before calling
1058 // RUN_ALL_TESTS(). Therefore we capture the current directory in
1059 // AddTestInfo(), which is called to register a TEST or TEST_F
1060 // before main() is reached.
1061 if (original_working_dir_.IsEmpty()) {
1062 original_working_dir_.Set(FilePath::GetCurrentDir());
1063 GTEST_CHECK_(!original_working_dir_.IsEmpty())
1064 << "Failed to get the current working directory.";
1067 GetTestCase(test_info->test_case_name(),
1068 test_info->type_param(),
1070 tear_down_tc)->AddTestInfo(test_info);
1073 #if GTEST_HAS_PARAM_TEST
1074 // Returns ParameterizedTestCaseRegistry object used to keep track of
1075 // value-parameterized tests and instantiate and register them.
1076 internal::ParameterizedTestCaseRegistry& parameterized_test_registry() {
1077 return parameterized_test_registry_;
1079 #endif // GTEST_HAS_PARAM_TEST
1081 // Sets the TestCase object for the test that's currently running.
1082 void set_current_test_case(TestCase* a_current_test_case) {
1083 current_test_case_ = a_current_test_case;
1086 // Sets the TestInfo object for the test that's currently running. If
1087 // current_test_info is NULL, the assertion results will be stored in
1088 // ad_hoc_test_result_.
1089 void set_current_test_info(TestInfo* a_current_test_info) {
1090 current_test_info_ = a_current_test_info;
1093 // Registers all parameterized tests defined using TEST_P and
1094 // INSTANTIATE_TEST_CASE_P, creating regular tests for each test/parameter
1095 // combination. This method can be called more then once; it has guards
1096 // protecting from registering the tests more then once. If
1097 // value-parameterized tests are disabled, RegisterParameterizedTests is
1098 // present but does nothing.
1099 void RegisterParameterizedTests();
1101 // Runs all tests in this UnitTest object, prints the result, and
1102 // returns true if all tests are successful. If any exception is
1103 // thrown during a test, this test is considered to be failed, but
1104 // the rest of the tests will still be run.
1107 // Clears the results of all tests, except the ad hoc tests.
1108 void ClearNonAdHocTestResult() {
1109 ForEach(test_cases_, TestCase::ClearTestCaseResult);
1112 // Clears the results of ad-hoc test assertions.
1113 void ClearAdHocTestResult() {
1114 ad_hoc_test_result_.Clear();
1117 enum ReactionToSharding {
1118 HONOR_SHARDING_PROTOCOL,
1119 IGNORE_SHARDING_PROTOCOL
1122 // Matches the full name of each test against the user-specified
1123 // filter to decide whether the test should run, then records the
1124 // result in each TestCase and TestInfo object.
1125 // If shard_tests == HONOR_SHARDING_PROTOCOL, further filters tests
1126 // based on sharding variables in the environment.
1127 // Returns the number of tests that should run.
1128 int FilterTests(ReactionToSharding shard_tests);
1130 // Prints the names of the tests matching the user-specified filter flag.
1131 void ListTestsMatchingFilter();
1133 const TestCase* current_test_case() const { return current_test_case_; }
1134 TestInfo* current_test_info() { return current_test_info_; }
1135 const TestInfo* current_test_info() const { return current_test_info_; }
1137 // Returns the vector of environments that need to be set-up/torn-down
1138 // before/after the tests are run.
1139 std::vector<Environment*>& environments() { return environments_; }
1141 // Getters for the per-thread Google Test trace stack.
1142 std::vector<TraceInfo>& gtest_trace_stack() {
1143 return *(gtest_trace_stack_.pointer());
1145 const std::vector<TraceInfo>& gtest_trace_stack() const {
1146 return gtest_trace_stack_.get();
1149 #if GTEST_HAS_DEATH_TEST
1150 void InitDeathTestSubprocessControlInfo() {
1151 internal_run_death_test_flag_.reset(ParseInternalRunDeathTestFlag());
1153 // Returns a pointer to the parsed --gtest_internal_run_death_test
1154 // flag, or NULL if that flag was not specified.
1155 // This information is useful only in a death test child process.
1156 // Must not be called before a call to InitGoogleTest.
1157 const InternalRunDeathTestFlag* internal_run_death_test_flag() const {
1158 return internal_run_death_test_flag_.get();
1161 // Returns a pointer to the current death test factory.
1162 internal::DeathTestFactory* death_test_factory() {
1163 return death_test_factory_.get();
1166 void SuppressTestEventsIfInSubprocess();
1168 friend class ReplaceDeathTestFactory;
1169 #endif // GTEST_HAS_DEATH_TEST
1171 // Initializes the event listener performing XML output as specified by
1172 // UnitTestOptions. Must not be called before InitGoogleTest.
1173 void ConfigureXmlOutput();
1175 #if GTEST_CAN_STREAM_RESULTS_
1176 // Initializes the event listener for streaming test results to a socket.
1177 // Must not be called before InitGoogleTest.
1178 void ConfigureStreamingOutput();
1181 // Performs initialization dependent upon flag values obtained in
1182 // ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to
1183 // ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest
1184 // this function is also called from RunAllTests. Since this function can be
1185 // called more than once, it has to be idempotent.
1186 void PostFlagParsingInit();
1188 // Gets the random seed used at the start of the current test iteration.
1189 int random_seed() const { return random_seed_; }
1191 // Gets the random number generator.
1192 internal::Random* random() { return &random_; }
1194 // Shuffles all test cases, and the tests within each test case,
1195 // making sure that death tests are still run first.
1196 void ShuffleTests();
1198 // Restores the test cases and tests to their order before the first shuffle.
1199 void UnshuffleTests();
1201 // Returns the value of GTEST_FLAG(catch_exceptions) at the moment
1202 // UnitTest::Run() starts.
1203 bool catch_exceptions() const { return catch_exceptions_; }
1206 friend class ::testing::UnitTest;
1208 // Used by UnitTest::Run() to capture the state of
1209 // GTEST_FLAG(catch_exceptions) at the moment it starts.
1210 void set_catch_exceptions(bool value) { catch_exceptions_ = value; }
1212 // The UnitTest object that owns this implementation object.
1213 UnitTest* const parent_;
1215 // The working directory when the first TEST() or TEST_F() was
1217 internal::FilePath original_working_dir_;
1219 // The default test part result reporters.
1220 DefaultGlobalTestPartResultReporter default_global_test_part_result_reporter_;
1221 DefaultPerThreadTestPartResultReporter
1222 default_per_thread_test_part_result_reporter_;
1224 // Points to (but doesn't own) the global test part result reporter.
1225 TestPartResultReporterInterface* global_test_part_result_repoter_;
1227 // Protects read and write access to global_test_part_result_reporter_.
1228 internal::Mutex global_test_part_result_reporter_mutex_;
1230 // Points to (but doesn't own) the per-thread test part result reporter.
1231 internal::ThreadLocal<TestPartResultReporterInterface*>
1232 per_thread_test_part_result_reporter_;
1234 // The vector of environments that need to be set-up/torn-down
1235 // before/after the tests are run.
1236 std::vector<Environment*> environments_;
1238 // The vector of TestCases in their original order. It owns the
1239 // elements in the vector.
1240 std::vector<TestCase*> test_cases_;
1242 // Provides a level of indirection for the test case list to allow
1243 // easy shuffling and restoring the test case order. The i-th
1244 // element of this vector is the index of the i-th test case in the
1246 std::vector<int> test_case_indices_;
1248 #if GTEST_HAS_PARAM_TEST
1249 // ParameterizedTestRegistry object used to register value-parameterized
1251 internal::ParameterizedTestCaseRegistry parameterized_test_registry_;
1253 // Indicates whether RegisterParameterizedTests() has been called already.
1254 bool parameterized_tests_registered_;
1255 #endif // GTEST_HAS_PARAM_TEST
1257 // Index of the last death test case registered. Initially -1.
1258 int last_death_test_case_;
1260 // This points to the TestCase for the currently running test. It
1261 // changes as Google Test goes through one test case after another.
1262 // When no test is running, this is set to NULL and Google Test
1263 // stores assertion results in ad_hoc_test_result_. Initially NULL.
1264 TestCase* current_test_case_;
1266 // This points to the TestInfo for the currently running test. It
1267 // changes as Google Test goes through one test after another. When
1268 // no test is running, this is set to NULL and Google Test stores
1269 // assertion results in ad_hoc_test_result_. Initially NULL.
1270 TestInfo* current_test_info_;
1272 // Normally, a user only writes assertions inside a TEST or TEST_F,
1273 // or inside a function called by a TEST or TEST_F. Since Google
1274 // Test keeps track of which test is current running, it can
1275 // associate such an assertion with the test it belongs to.
1277 // If an assertion is encountered when no TEST or TEST_F is running,
1278 // Google Test attributes the assertion result to an imaginary "ad hoc"
1279 // test, and records the result in ad_hoc_test_result_.
1280 TestResult ad_hoc_test_result_;
1282 // The list of event listeners that can be used to track events inside
1284 TestEventListeners listeners_;
1286 // The OS stack trace getter. Will be deleted when the UnitTest
1287 // object is destructed. By default, an OsStackTraceGetter is used,
1288 // but the user can set this field to use a custom getter if that is
1290 OsStackTraceGetterInterface* os_stack_trace_getter_;
1292 // True iff PostFlagParsingInit() has been called.
1293 bool post_flag_parse_init_performed_;
1295 // The random number seed used at the beginning of the test run.
1298 // Our random number generator.
1299 internal::Random random_;
1301 // The time of the test program start, in ms from the start of the
1303 TimeInMillis start_timestamp_;
1305 // How long the test took to run, in milliseconds.
1306 TimeInMillis elapsed_time_;
1308 #if GTEST_HAS_DEATH_TEST
1309 // The decomposed components of the gtest_internal_run_death_test flag,
1310 // parsed when RUN_ALL_TESTS is called.
1311 internal::scoped_ptr<InternalRunDeathTestFlag> internal_run_death_test_flag_;
1312 internal::scoped_ptr<internal::DeathTestFactory> death_test_factory_;
1313 #endif // GTEST_HAS_DEATH_TEST
1315 // A per-thread stack of traces created by the SCOPED_TRACE() macro.
1316 internal::ThreadLocal<std::vector<TraceInfo> > gtest_trace_stack_;
1318 // The value of GTEST_FLAG(catch_exceptions) at the moment RunAllTests()
1320 bool catch_exceptions_;
1322 GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTestImpl);
1323 }; // class UnitTestImpl
1325 // Convenience function for accessing the global UnitTest
1326 // implementation object.
1327 inline UnitTestImpl* GetUnitTestImpl() {
1328 return UnitTest::GetInstance()->impl();
1331 #if GTEST_USES_SIMPLE_RE
1333 // Internal helper functions for implementing the simple regular
1334 // expression matcher.
1335 GTEST_API_ bool IsInSet(char ch, const char* str);
1336 GTEST_API_ bool IsAsciiDigit(char ch);
1337 GTEST_API_ bool IsAsciiPunct(char ch);
1338 GTEST_API_ bool IsRepeat(char ch);
1339 GTEST_API_ bool IsAsciiWhiteSpace(char ch);
1340 GTEST_API_ bool IsAsciiWordChar(char ch);
1341 GTEST_API_ bool IsValidEscape(char ch);
1342 GTEST_API_ bool AtomMatchesChar(bool escaped, char pattern, char ch);
1343 GTEST_API_ bool ValidateRegex(const char* regex);
1344 GTEST_API_ bool MatchRegexAtHead(const char* regex, const char* str);
1345 GTEST_API_ bool MatchRepetitionAndRegexAtHead(
1346 bool escaped, char ch, char repeat, const char* regex, const char* str);
1347 GTEST_API_ bool MatchRegexAnywhere(const char* regex, const char* str);
1349 #endif // GTEST_USES_SIMPLE_RE
1351 // Parses the command line for Google Test flags, without initializing
1352 // other parts of Google Test.
1353 GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, char** argv);
1354 GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv);
1356 #if GTEST_HAS_DEATH_TEST
1358 // Returns the message describing the last system error, regardless of the
1360 GTEST_API_ String GetLastErrnoDescription();
1362 # if GTEST_OS_WINDOWS
1363 // Provides leak-safe Windows kernel handle ownership.
1366 AutoHandle() : handle_(INVALID_HANDLE_VALUE) {}
1367 explicit AutoHandle(HANDLE handle) : handle_(handle) {}
1369 ~AutoHandle() { Reset(); }
1371 HANDLE Get() const { return handle_; }
1372 void Reset() { Reset(INVALID_HANDLE_VALUE); }
1373 void Reset(HANDLE handle) {
1374 if (handle != handle_) {
1375 if (handle_ != INVALID_HANDLE_VALUE)
1376 ::CloseHandle(handle_);
1384 GTEST_DISALLOW_COPY_AND_ASSIGN_(AutoHandle);
1386 # endif // GTEST_OS_WINDOWS
1388 // Attempts to parse a string into a positive integer pointed to by the
1389 // number parameter. Returns true if that is possible.
1390 // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we can use
1392 template <typename Integer>
1393 bool ParseNaturalNumber(const ::std::string& str, Integer* number) {
1394 // Fail fast if the given string does not begin with a digit;
1395 // this bypasses strtoXXX's "optional leading whitespace and plus
1396 // or minus sign" semantics, which are undesirable here.
1397 if (str.empty() || !IsDigit(str[0])) {
1403 // BiggestConvertible is the largest integer type that system-provided
1404 // string-to-number conversion routines can return.
1406 # if GTEST_OS_WINDOWS && !defined(__GNUC__)
1408 // MSVC and C++ Builder define __int64 instead of the standard long long.
1409 typedef unsigned __int64 BiggestConvertible;
1410 const BiggestConvertible parsed = _strtoui64(str.c_str(), &end, 10);
1414 typedef unsigned long long BiggestConvertible; // NOLINT
1415 const BiggestConvertible parsed = strtoull(str.c_str(), &end, 10);
1417 # endif // GTEST_OS_WINDOWS && !defined(__GNUC__)
1419 const bool parse_success = *end == '\0' && errno == 0;
1421 // TODO(vladl@google.com): Convert this to compile time assertion when it is
1423 GTEST_CHECK_(sizeof(Integer) <= sizeof(parsed));
1425 const Integer result = static_cast<Integer>(parsed);
1426 if (parse_success && static_cast<BiggestConvertible>(result) == parsed) {
1432 #endif // GTEST_HAS_DEATH_TEST
1434 // TestResult contains some private methods that should be hidden from
1435 // Google Test user but are required for testing. This class allow our tests
1438 // This class is supplied only for the purpose of testing Google Test's own
1439 // constructs. Do not use it in user tests, either directly or indirectly.
1440 class TestResultAccessor {
1442 static void RecordProperty(TestResult* test_result,
1443 const TestProperty& property) {
1444 test_result->RecordProperty(property);
1447 static void ClearTestPartResults(TestResult* test_result) {
1448 test_result->ClearTestPartResults();
1451 static const std::vector<testing::TestPartResult>& test_part_results(
1452 const TestResult& test_result) {
1453 return test_result.test_part_results();
1457 } // namespace internal
1458 } // namespace testing
1460 #endif // GTEST_SRC_GTEST_INTERNAL_INL_H_
1461 #undef GTEST_IMPLEMENTATION_
1463 #if GTEST_OS_WINDOWS
1464 # define vsnprintf _vsnprintf
1465 #endif // GTEST_OS_WINDOWS
1469 using internal::CountIf;
1470 using internal::ForEach;
1471 using internal::GetElementOr;
1472 using internal::Shuffle;
1476 // A test whose test case name or test name matches this filter is
1477 // disabled and not run.
1478 static const char kDisableTestFilter[] = "DISABLED_*:*/DISABLED_*";
1480 // A test case whose name matches this filter is considered a death
1481 // test case and will be run before test cases whose name doesn't
1482 // match this filter.
1483 static const char kDeathTestCaseFilter[] = "*DeathTest:*DeathTest/*";
1485 // A test filter that matches everything.
1486 static const char kUniversalFilter[] = "*";
1488 // The default output file for XML output.
1489 static const char kDefaultOutputFile[] = "test_detail.xml";
1491 // The environment variable name for the test shard index.
1492 static const char kTestShardIndex[] = "GTEST_SHARD_INDEX";
1493 // The environment variable name for the total number of test shards.
1494 static const char kTestTotalShards[] = "GTEST_TOTAL_SHARDS";
1495 // The environment variable name for the test shard status file.
1496 static const char kTestShardStatusFile[] = "GTEST_SHARD_STATUS_FILE";
1498 namespace internal {
1500 // The text used in failure messages to indicate the start of the
1502 const char kStackTraceMarker[] = "\nStack trace:\n";
1504 // g_help_flag is true iff the --help flag or an equivalent form is
1505 // specified on the command line.
1506 bool g_help_flag = false;
1508 } // namespace internal
1511 also_run_disabled_tests,
1512 internal::BoolFromGTestEnv("also_run_disabled_tests", false),
1513 "Run disabled tests too, in addition to the tests normally being run.");
1517 internal::BoolFromGTestEnv("break_on_failure", false),
1518 "True iff a failed assertion should be a debugger break-point.");
1522 internal::BoolFromGTestEnv("catch_exceptions", true),
1523 "True iff " GTEST_NAME_
1524 " should catch exceptions and treat them as test failures.");
1526 GTEST_DEFINE_string_(
1528 internal::StringFromGTestEnv("color", "auto"),
1529 "Whether to use colors in the output. Valid values: yes, no, "
1530 "and auto. 'auto' means to use colors if the output is "
1531 "being sent to a terminal and the TERM environment variable "
1532 "is set to xterm, xterm-color, xterm-256color, linux or cygwin.");
1534 GTEST_DEFINE_string_(
1536 internal::StringFromGTestEnv("filter", kUniversalFilter),
1537 "A colon-separated list of glob (not regex) patterns "
1538 "for filtering the tests to run, optionally followed by a "
1539 "'-' and a : separated list of negative patterns (tests to "
1540 "exclude). A test is run if it matches one of the positive "
1541 "patterns and does not match any of the negative patterns.");
1543 GTEST_DEFINE_bool_(list_tests, false,
1544 "List all tests without running them.");
1546 GTEST_DEFINE_string_(
1548 internal::StringFromGTestEnv("output", ""),
1549 "A format (currently must be \"xml\"), optionally followed "
1550 "by a colon and an output file name or directory. A directory "
1551 "is indicated by a trailing pathname separator. "
1552 "Examples: \"xml:filename.xml\", \"xml::directoryname/\". "
1553 "If a directory is specified, output files will be created "
1554 "within that directory, with file-names based on the test "
1555 "executable's name and, if necessary, made unique by adding "
1560 internal::BoolFromGTestEnv("print_time", true),
1561 "True iff " GTEST_NAME_
1562 " should display elapsed time in text output.");
1564 GTEST_DEFINE_int32_(
1566 internal::Int32FromGTestEnv("random_seed", 0),
1567 "Random number seed to use when shuffling test orders. Must be in range "
1568 "[1, 99999], or 0 to use a seed based on the current time.");
1570 GTEST_DEFINE_int32_(
1572 internal::Int32FromGTestEnv("repeat", 1),
1573 "How many times to repeat each test. Specify a negative number "
1574 "for repeating forever. Useful for shaking out flaky tests.");
1577 show_internal_stack_frames, false,
1578 "True iff " GTEST_NAME_ " should include internal stack frames when "
1579 "printing test failure stack traces.");
1583 internal::BoolFromGTestEnv("shuffle", false),
1584 "True iff " GTEST_NAME_
1585 " should randomize tests' order on every run.");
1587 GTEST_DEFINE_int32_(
1589 internal::Int32FromGTestEnv("stack_trace_depth", kMaxStackTraceDepth),
1590 "The maximum number of stack frames to print when an "
1591 "assertion fails. The valid range is 0 through 100, inclusive.");
1593 GTEST_DEFINE_string_(
1595 internal::StringFromGTestEnv("stream_result_to", ""),
1596 "This flag specifies the host name and the port number on which to stream "
1597 "test results. Example: \"localhost:555\". The flag is effective only on "
1602 internal::BoolFromGTestEnv("throw_on_failure", false),
1603 "When this flag is specified, a failed assertion will throw an exception "
1604 "if exceptions are enabled or exit the program with a non-zero code "
1607 namespace internal {
1609 // Generates a random number from [0, range), using a Linear
1610 // Congruential Generator (LCG). Crashes if 'range' is 0 or greater
1612 UInt32 Random::Generate(UInt32 range) {
1613 // These constants are the same as are used in glibc's rand(3).
1614 state_ = (1103515245U*state_ + 12345U) % kMaxRange;
1616 GTEST_CHECK_(range > 0)
1617 << "Cannot generate a number in the range [0, 0).";
1618 GTEST_CHECK_(range <= kMaxRange)
1619 << "Generation of a number in [0, " << range << ") was requested, "
1620 << "but this can only generate numbers in [0, " << kMaxRange << ").";
1622 // Converting via modulus introduces a bit of downward bias, but
1623 // it's simple, and a linear congruential generator isn't too good
1625 return state_ % range;
1628 // GTestIsInitialized() returns true iff the user has initialized
1629 // Google Test. Useful for catching the user mistake of not initializing
1630 // Google Test before calling RUN_ALL_TESTS().
1632 // A user must call testing::InitGoogleTest() to initialize Google
1633 // Test. g_init_gtest_count is set to the number of times
1634 // InitGoogleTest() has been called. We don't protect this variable
1635 // under a mutex as it is only accessed in the main thread.
1636 GTEST_API_ int g_init_gtest_count = 0;
1637 static bool GTestIsInitialized() { return g_init_gtest_count != 0; }
1639 // Iterates over a vector of TestCases, keeping a running sum of the
1640 // results of calling a given int-returning method on each.
1642 static int SumOverTestCaseList(const std::vector<TestCase*>& case_list,
1643 int (TestCase::*method)() const) {
1645 for (size_t i = 0; i < case_list.size(); i++) {
1646 sum += (case_list[i]->*method)();
1651 // Returns true iff the test case passed.
1652 static bool TestCasePassed(const TestCase* test_case) {
1653 return test_case->should_run() && test_case->Passed();
1656 // Returns true iff the test case failed.
1657 static bool TestCaseFailed(const TestCase* test_case) {
1658 return test_case->should_run() && test_case->Failed();
1661 // Returns true iff test_case contains at least one test that should
1663 static bool ShouldRunTestCase(const TestCase* test_case) {
1664 return test_case->should_run();
1667 // AssertHelper constructor.
1668 AssertHelper::AssertHelper(TestPartResult::Type type,
1671 const char* message)
1672 : data_(new AssertHelperData(type, file, line, message)) {
1675 AssertHelper::~AssertHelper() {
1679 // Message assignment, for assertion streaming support.
1680 void AssertHelper::operator=(const Message& message) const {
1681 UnitTest::GetInstance()->
1682 AddTestPartResult(data_->type, data_->file, data_->line,
1683 AppendUserMessage(data_->message, message),
1684 UnitTest::GetInstance()->impl()
1685 ->CurrentOsStackTraceExceptTop(1)
1686 // Skips the stack frame for this function itself.
1690 // Mutex for linked pointers.
1691 GTEST_API_ GTEST_DEFINE_STATIC_MUTEX_(g_linked_ptr_mutex);
1693 // Application pathname gotten in InitGoogleTest.
1694 String g_executable_path;
1696 // Returns the current application's name, removing directory path if that
1698 FilePath GetCurrentExecutableName() {
1701 #if GTEST_OS_WINDOWS
1702 result.Set(FilePath(g_executable_path).RemoveExtension("exe"));
1704 result.Set(FilePath(g_executable_path));
1705 #endif // GTEST_OS_WINDOWS
1707 return result.RemoveDirectoryName();
1710 // Functions for processing the gtest_output flag.
1712 // Returns the output format, or "" for normal printed output.
1713 String UnitTestOptions::GetOutputFormat() {
1714 const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
1715 if (gtest_output_flag == NULL) return String("");
1717 const char* const colon = strchr(gtest_output_flag, ':');
1718 return (colon == NULL) ?
1719 String(gtest_output_flag) :
1720 String(gtest_output_flag, colon - gtest_output_flag);
1723 // Returns the name of the requested output file, or the default if none
1724 // was explicitly specified.
1725 String UnitTestOptions::GetAbsolutePathToOutputFile() {
1726 const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
1727 if (gtest_output_flag == NULL)
1730 const char* const colon = strchr(gtest_output_flag, ':');
1732 return String(internal::FilePath::ConcatPaths(
1734 UnitTest::GetInstance()->original_working_dir()),
1735 internal::FilePath(kDefaultOutputFile)).ToString() );
1737 internal::FilePath output_name(colon + 1);
1738 if (!output_name.IsAbsolutePath())
1739 // TODO(wan@google.com): on Windows \some\path is not an absolute
1740 // path (as its meaning depends on the current drive), yet the
1741 // following logic for turning it into an absolute path is wrong.
1743 output_name = internal::FilePath::ConcatPaths(
1744 internal::FilePath(UnitTest::GetInstance()->original_working_dir()),
1745 internal::FilePath(colon + 1));
1747 if (!output_name.IsDirectory())
1748 return output_name.ToString();
1750 internal::FilePath result(internal::FilePath::GenerateUniqueFileName(
1751 output_name, internal::GetCurrentExecutableName(),
1752 GetOutputFormat().c_str()));
1753 return result.ToString();
1756 // Returns true iff the wildcard pattern matches the string. The
1757 // first ':' or '\0' character in pattern marks the end of it.
1759 // This recursive algorithm isn't very efficient, but is clear and
1760 // works well enough for matching test names, which are short.
1761 bool UnitTestOptions::PatternMatchesString(const char *pattern,
1765 case ':': // Either ':' or '\0' marks the end of the pattern.
1766 return *str == '\0';
1767 case '?': // Matches any single character.
1768 return *str != '\0' && PatternMatchesString(pattern + 1, str + 1);
1769 case '*': // Matches any string (possibly empty) of characters.
1770 return (*str != '\0' && PatternMatchesString(pattern, str + 1)) ||
1771 PatternMatchesString(pattern + 1, str);
1772 default: // Non-special character. Matches itself.
1773 return *pattern == *str &&
1774 PatternMatchesString(pattern + 1, str + 1);
1778 bool UnitTestOptions::MatchesFilter(const String& name, const char* filter) {
1779 const char *cur_pattern = filter;
1781 if (PatternMatchesString(cur_pattern, name.c_str())) {
1785 // Finds the next pattern in the filter.
1786 cur_pattern = strchr(cur_pattern, ':');
1788 // Returns if no more pattern can be found.
1789 if (cur_pattern == NULL) {
1793 // Skips the pattern separater (the ':' character).
1798 // TODO(keithray): move String function implementations to gtest-string.cc.
1800 // Returns true iff the user-specified filter matches the test case
1801 // name and the test name.
1802 bool UnitTestOptions::FilterMatchesTest(const String &test_case_name,
1803 const String &test_name) {
1804 const String& full_name = String::Format("%s.%s",
1805 test_case_name.c_str(),
1808 // Split --gtest_filter at '-', if there is one, to separate into
1809 // positive filter and negative filter portions
1810 const char* const p = GTEST_FLAG(filter).c_str();
1811 const char* const dash = strchr(p, '-');
1815 positive = GTEST_FLAG(filter).c_str(); // Whole string is a positive filter
1816 negative = String("");
1818 positive = String(p, dash - p); // Everything up to the dash
1819 negative = String(dash+1); // Everything after the dash
1820 if (positive.empty()) {
1821 // Treat '-test1' as the same as '*-test1'
1822 positive = kUniversalFilter;
1826 // A filter is a colon-separated list of patterns. It matches a
1827 // test if any pattern in it matches the test.
1828 return (MatchesFilter(full_name, positive.c_str()) &&
1829 !MatchesFilter(full_name, negative.c_str()));
1833 // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
1834 // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
1835 // This function is useful as an __except condition.
1836 int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) {
1837 // Google Test should handle a SEH exception if:
1838 // 1. the user wants it to, AND
1839 // 2. this is not a breakpoint exception, AND
1840 // 3. this is not a C++ exception (VC++ implements them via SEH,
1843 // SEH exception code for C++ exceptions.
1844 // (see http://support.microsoft.com/kb/185294 for more information).
1845 const DWORD kCxxExceptionCode = 0xe06d7363;
1847 bool should_handle = true;
1849 if (!GTEST_FLAG(catch_exceptions))
1850 should_handle = false;
1851 else if (exception_code == EXCEPTION_BREAKPOINT)
1852 should_handle = false;
1853 else if (exception_code == kCxxExceptionCode)
1854 should_handle = false;
1856 return should_handle ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH;
1858 #endif // GTEST_HAS_SEH
1860 } // namespace internal
1862 // The c'tor sets this object as the test part result reporter used by
1863 // Google Test. The 'result' parameter specifies where to report the
1864 // results. Intercepts only failures from the current thread.
1865 ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
1866 TestPartResultArray* result)
1867 : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD),
1872 // The c'tor sets this object as the test part result reporter used by
1873 // Google Test. The 'result' parameter specifies where to report the
1875 ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
1876 InterceptMode intercept_mode, TestPartResultArray* result)
1877 : intercept_mode_(intercept_mode),
1882 void ScopedFakeTestPartResultReporter::Init() {
1883 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
1884 if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
1885 old_reporter_ = impl->GetGlobalTestPartResultReporter();
1886 impl->SetGlobalTestPartResultReporter(this);
1888 old_reporter_ = impl->GetTestPartResultReporterForCurrentThread();
1889 impl->SetTestPartResultReporterForCurrentThread(this);
1893 // The d'tor restores the test part result reporter used by Google Test
1895 ScopedFakeTestPartResultReporter::~ScopedFakeTestPartResultReporter() {
1896 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
1897 if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
1898 impl->SetGlobalTestPartResultReporter(old_reporter_);
1900 impl->SetTestPartResultReporterForCurrentThread(old_reporter_);
1904 // Increments the test part result count and remembers the result.
1905 // This method is from the TestPartResultReporterInterface interface.
1906 void ScopedFakeTestPartResultReporter::ReportTestPartResult(
1907 const TestPartResult& result) {
1908 result_->Append(result);
1911 namespace internal {
1913 // Returns the type ID of ::testing::Test. We should always call this
1914 // instead of GetTypeId< ::testing::Test>() to get the type ID of
1915 // testing::Test. This is to work around a suspected linker bug when
1916 // using Google Test as a framework on Mac OS X. The bug causes
1917 // GetTypeId< ::testing::Test>() to return different values depending
1918 // on whether the call is from the Google Test framework itself or
1919 // from user test code. GetTestTypeId() is guaranteed to always
1920 // return the same value, as it always calls GetTypeId<>() from the
1921 // gtest.cc, which is within the Google Test framework.
1922 TypeId GetTestTypeId() {
1923 return GetTypeId<Test>();
1926 // The value of GetTestTypeId() as seen from within the Google Test
1927 // library. This is solely for testing GetTestTypeId().
1928 extern const TypeId kTestTypeIdInGoogleTest = GetTestTypeId();
1930 // This predicate-formatter checks that 'results' contains a test part
1931 // failure of the given type and that the failure message contains the
1933 static AssertionResult HasOneFailure(const char* /* results_expr */,
1934 const char* /* type_expr */,
1935 const char* /* substr_expr */,
1936 const TestPartResultArray& results,
1937 TestPartResult::Type type,
1938 const string& substr) {
1939 const String expected(type == TestPartResult::kFatalFailure ?
1941 "1 non-fatal failure");
1943 if (results.size() != 1) {
1944 msg << "Expected: " << expected << "\n"
1945 << " Actual: " << results.size() << " failures";
1946 for (int i = 0; i < results.size(); i++) {
1947 msg << "\n" << results.GetTestPartResult(i);
1949 return AssertionFailure() << msg;
1952 const TestPartResult& r = results.GetTestPartResult(0);
1953 if (r.type() != type) {
1954 return AssertionFailure() << "Expected: " << expected << "\n"
1959 if (strstr(r.message(), substr.c_str()) == NULL) {
1960 return AssertionFailure() << "Expected: " << expected << " containing \""
1966 return AssertionSuccess();
1969 // The constructor of SingleFailureChecker remembers where to look up
1970 // test part results, what type of failure we expect, and what
1971 // substring the failure message should contain.
1972 SingleFailureChecker:: SingleFailureChecker(
1973 const TestPartResultArray* results,
1974 TestPartResult::Type type,
1975 const string& substr)
1976 : results_(results),
1980 // The destructor of SingleFailureChecker verifies that the given
1981 // TestPartResultArray contains exactly one failure that has the given
1982 // type and contains the given substring. If that's not the case, a
1983 // non-fatal failure will be generated.
1984 SingleFailureChecker::~SingleFailureChecker() {
1985 EXPECT_PRED_FORMAT3(HasOneFailure, *results_, type_, substr_);
1988 DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter(
1989 UnitTestImpl* unit_test) : unit_test_(unit_test) {}
1991 void DefaultGlobalTestPartResultReporter::ReportTestPartResult(
1992 const TestPartResult& result) {
1993 unit_test_->current_test_result()->AddTestPartResult(result);
1994 unit_test_->listeners()->repeater()->OnTestPartResult(result);
1997 DefaultPerThreadTestPartResultReporter::DefaultPerThreadTestPartResultReporter(
1998 UnitTestImpl* unit_test) : unit_test_(unit_test) {}
2000 void DefaultPerThreadTestPartResultReporter::ReportTestPartResult(
2001 const TestPartResult& result) {
2002 unit_test_->GetGlobalTestPartResultReporter()->ReportTestPartResult(result);
2005 // Returns the global test part result reporter.
2006 TestPartResultReporterInterface*
2007 UnitTestImpl::GetGlobalTestPartResultReporter() {
2008 internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
2009 return global_test_part_result_repoter_;
2012 // Sets the global test part result reporter.
2013 void UnitTestImpl::SetGlobalTestPartResultReporter(
2014 TestPartResultReporterInterface* reporter) {
2015 internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
2016 global_test_part_result_repoter_ = reporter;
2019 // Returns the test part result reporter for the current thread.
2020 TestPartResultReporterInterface*
2021 UnitTestImpl::GetTestPartResultReporterForCurrentThread() {
2022 return per_thread_test_part_result_reporter_.get();
2025 // Sets the test part result reporter for the current thread.
2026 void UnitTestImpl::SetTestPartResultReporterForCurrentThread(
2027 TestPartResultReporterInterface* reporter) {
2028 per_thread_test_part_result_reporter_.set(reporter);
2031 // Gets the number of successful test cases.
2032 int UnitTestImpl::successful_test_case_count() const {
2033 return CountIf(test_cases_, TestCasePassed);
2036 // Gets the number of failed test cases.
2037 int UnitTestImpl::failed_test_case_count() const {
2038 return CountIf(test_cases_, TestCaseFailed);
2041 // Gets the number of all test cases.
2042 int UnitTestImpl::total_test_case_count() const {
2043 return static_cast<int>(test_cases_.size());
2046 // Gets the number of all test cases that contain at least one test
2048 int UnitTestImpl::test_case_to_run_count() const {
2049 return CountIf(test_cases_, ShouldRunTestCase);
2052 // Gets the number of successful tests.
2053 int UnitTestImpl::successful_test_count() const {
2054 return SumOverTestCaseList(test_cases_, &TestCase::successful_test_count);
2057 // Gets the number of failed tests.
2058 int UnitTestImpl::failed_test_count() const {
2059 return SumOverTestCaseList(test_cases_, &TestCase::failed_test_count);
2062 // Gets the number of disabled tests.
2063 int UnitTestImpl::disabled_test_count() const {
2064 return SumOverTestCaseList(test_cases_, &TestCase::disabled_test_count);
2067 // Gets the number of all tests.
2068 int UnitTestImpl::total_test_count() const {
2069 return SumOverTestCaseList(test_cases_, &TestCase::total_test_count);
2072 // Gets the number of tests that should run.
2073 int UnitTestImpl::test_to_run_count() const {
2074 return SumOverTestCaseList(test_cases_, &TestCase::test_to_run_count);
2077 // Returns the current OS stack trace as a String.
2079 // The maximum number of stack frames to be included is specified by
2080 // the gtest_stack_trace_depth flag. The skip_count parameter
2081 // specifies the number of top frames to be skipped, which doesn't
2082 // count against the number of frames to be included.
2084 // For example, if Foo() calls Bar(), which in turn calls
2085 // CurrentOsStackTraceExceptTop(1), Foo() will be included in the
2086 // trace but Bar() and CurrentOsStackTraceExceptTop() won't.
2087 String UnitTestImpl::CurrentOsStackTraceExceptTop(int skip_count) {
2092 // Returns the current time in milliseconds.
2093 TimeInMillis GetTimeInMillis() {
2094 #if GTEST_OS_WINDOWS_MOBILE || defined(__BORLANDC__)
2095 // Difference between 1970-01-01 and 1601-01-01 in milliseconds.
2096 // http://analogous.blogspot.com/2005/04/epoch.html
2097 const TimeInMillis kJavaEpochToWinFileTimeDelta =
2098 static_cast<TimeInMillis>(116444736UL) * 100000UL;
2099 const DWORD kTenthMicrosInMilliSecond = 10000;
2101 SYSTEMTIME now_systime;
2102 FILETIME now_filetime;
2103 ULARGE_INTEGER now_int64;
2104 // TODO(kenton@google.com): Shouldn't this just use
2105 // GetSystemTimeAsFileTime()?
2106 GetSystemTime(&now_systime);
2107 if (SystemTimeToFileTime(&now_systime, &now_filetime)) {
2108 now_int64.LowPart = now_filetime.dwLowDateTime;
2109 now_int64.HighPart = now_filetime.dwHighDateTime;
2110 now_int64.QuadPart = (now_int64.QuadPart / kTenthMicrosInMilliSecond) -
2111 kJavaEpochToWinFileTimeDelta;
2112 return now_int64.QuadPart;
2115 #elif GTEST_OS_WINDOWS && !GTEST_HAS_GETTIMEOFDAY_
2120 // MSVC 8 deprecates _ftime64(), so we want to suppress warning 4996
2121 // (deprecated function) there.
2122 // TODO(kenton@google.com): Use GetTickCount()? Or use
2123 // SystemTimeToFileTime()
2124 # pragma warning(push) // Saves the current warning state.
2125 # pragma warning(disable:4996) // Temporarily disables warning 4996.
2127 # pragma warning(pop) // Restores the warning state.
2134 return static_cast<TimeInMillis>(now.time) * 1000 + now.millitm;
2135 #elif GTEST_HAS_GETTIMEOFDAY_
2137 gettimeofday(&now, NULL);
2138 return static_cast<TimeInMillis>(now.tv_sec) * 1000 + now.tv_usec / 1000;
2140 # error "Don't know how to get the current time on your system."
2148 // Copies at most length characters from str into a newly-allocated
2149 // piece of memory of size length+1. The memory is allocated with new[].
2150 // A terminating null byte is written to the memory, and a pointer to it
2151 // is returned. If str is NULL, NULL is returned.
2152 static char* CloneString(const char* str, size_t length) {
2156 char* const clone = new char[length + 1];
2157 posix::StrNCpy(clone, str, length);
2158 clone[length] = '\0';
2163 // Clones a 0-terminated C string, allocating memory using new. The
2164 // caller is responsible for deleting[] the return value. Returns the
2165 // cloned string, or NULL if the input is NULL.
2166 const char * String::CloneCString(const char* c_str) {
2167 return (c_str == NULL) ?
2168 NULL : CloneString(c_str, strlen(c_str));
2171 #if GTEST_OS_WINDOWS_MOBILE
2172 // Creates a UTF-16 wide string from the given ANSI string, allocating
2173 // memory using new. The caller is responsible for deleting the return
2174 // value using delete[]. Returns the wide string, or NULL if the
2176 LPCWSTR String::AnsiToUtf16(const char* ansi) {
2177 if (!ansi) return NULL;
2178 const int length = strlen(ansi);
2179 const int unicode_length =
2180 MultiByteToWideChar(CP_ACP, 0, ansi, length,
2182 WCHAR* unicode = new WCHAR[unicode_length + 1];
2183 MultiByteToWideChar(CP_ACP, 0, ansi, length,
2184 unicode, unicode_length);
2185 unicode[unicode_length] = 0;
2189 // Creates an ANSI string from the given wide string, allocating
2190 // memory using new. The caller is responsible for deleting the return
2191 // value using delete[]. Returns the ANSI string, or NULL if the
2193 const char* String::Utf16ToAnsi(LPCWSTR utf16_str) {
2194 if (!utf16_str) return NULL;
2195 const int ansi_length =
2196 WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
2197 NULL, 0, NULL, NULL);
2198 char* ansi = new char[ansi_length + 1];
2199 WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
2200 ansi, ansi_length, NULL, NULL);
2201 ansi[ansi_length] = 0;
2205 #endif // GTEST_OS_WINDOWS_MOBILE
2207 // Compares two C strings. Returns true iff they have the same content.
2209 // Unlike strcmp(), this function can handle NULL argument(s). A NULL
2210 // C string is considered different to any non-NULL C string,
2211 // including the empty string.
2212 bool String::CStringEquals(const char * lhs, const char * rhs) {
2213 if ( lhs == NULL ) return rhs == NULL;
2215 if ( rhs == NULL ) return false;
2217 return strcmp(lhs, rhs) == 0;
2220 #if GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
2222 // Converts an array of wide chars to a narrow string using the UTF-8
2223 // encoding, and streams the result to the given Message object.
2224 static void StreamWideCharsToMessage(const wchar_t* wstr, size_t length,
2226 // TODO(wan): consider allowing a testing::String object to
2227 // contain '\0'. This will make it behave more like std::string,
2228 // and will allow ToUtf8String() to return the correct encoding
2229 // for '\0' s.t. we can get rid of the conditional here (and in
2230 // several other places).
2231 for (size_t i = 0; i != length; ) { // NOLINT
2232 if (wstr[i] != L'\0') {
2233 *msg << WideStringToUtf8(wstr + i, static_cast<int>(length - i));
2234 while (i != length && wstr[i] != L'\0')
2243 #endif // GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
2245 } // namespace internal
2247 #if GTEST_HAS_STD_WSTRING
2248 // Converts the given wide string to a narrow string using the UTF-8
2249 // encoding, and streams the result to this Message object.
2250 Message& Message::operator <<(const ::std::wstring& wstr) {
2251 internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
2254 #endif // GTEST_HAS_STD_WSTRING
2256 #if GTEST_HAS_GLOBAL_WSTRING
2257 // Converts the given wide string to a narrow string using the UTF-8
2258 // encoding, and streams the result to this Message object.
2259 Message& Message::operator <<(const ::wstring& wstr) {
2260 internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
2263 #endif // GTEST_HAS_GLOBAL_WSTRING
2265 // AssertionResult constructors.
2266 // Used in EXPECT_TRUE/FALSE(assertion_result).
2267 AssertionResult::AssertionResult(const AssertionResult& other)
2268 : success_(other.success_),
2269 message_(other.message_.get() != NULL ?
2270 new ::std::string(*other.message_) :
2271 static_cast< ::std::string*>(NULL)) {
2274 // Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE.
2275 AssertionResult AssertionResult::operator!() const {
2276 AssertionResult negation(!success_);
2277 if (message_.get() != NULL)
2278 negation << *message_;
2282 // Makes a successful assertion result.
2283 AssertionResult AssertionSuccess() {
2284 return AssertionResult(true);
2287 // Makes a failed assertion result.
2288 AssertionResult AssertionFailure() {
2289 return AssertionResult(false);
2292 // Makes a failed assertion result with the given failure message.
2293 // Deprecated; use AssertionFailure() << message.
2294 AssertionResult AssertionFailure(const Message& message) {
2295 return AssertionFailure() << message;
2298 namespace internal {
2300 // Constructs and returns the message for an equality assertion
2301 // (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure.
2303 // The first four parameters are the expressions used in the assertion
2304 // and their values, as strings. For example, for ASSERT_EQ(foo, bar)
2305 // where foo is 5 and bar is 6, we have:
2307 // expected_expression: "foo"
2308 // actual_expression: "bar"
2309 // expected_value: "5"
2310 // actual_value: "6"
2312 // The ignoring_case parameter is true iff the assertion is a
2313 // *_STRCASEEQ*. When it's true, the string " (ignoring case)" will
2314 // be inserted into the message.
2315 AssertionResult EqFailure(const char* expected_expression,
2316 const char* actual_expression,
2317 const String& expected_value,
2318 const String& actual_value,
2319 bool ignoring_case) {
2321 msg << "Value of: " << actual_expression;
2322 if (actual_value != actual_expression) {
2323 msg << "\n Actual: " << actual_value;
2326 msg << "\nExpected: " << expected_expression;
2327 if (ignoring_case) {
2328 msg << " (ignoring case)";
2330 if (expected_value != expected_expression) {
2331 msg << "\nWhich is: " << expected_value;
2334 return AssertionFailure() << msg;
2337 // Constructs a failure message for Boolean assertions such as EXPECT_TRUE.
2338 String GetBoolAssertionFailureMessage(const AssertionResult& assertion_result,
2339 const char* expression_text,
2340 const char* actual_predicate_value,
2341 const char* expected_predicate_value) {
2342 const char* actual_message = assertion_result.message();
2344 msg << "Value of: " << expression_text
2345 << "\n Actual: " << actual_predicate_value;
2346 if (actual_message[0] != '\0')
2347 msg << " (" << actual_message << ")";
2348 msg << "\nExpected: " << expected_predicate_value;
2349 return msg.GetString();
2352 // Helper function for implementing ASSERT_NEAR.
2353 AssertionResult DoubleNearPredFormat(const char* expr1,
2355 const char* abs_error_expr,
2359 const double diff = fabs(val1 - val2);
2360 if (diff <= abs_error) return AssertionSuccess();
2362 // TODO(wan): do not print the value of an expression if it's
2363 // already a literal.
2364 return AssertionFailure()
2365 << "The difference between " << expr1 << " and " << expr2
2366 << " is " << diff << ", which exceeds " << abs_error_expr << ", where\n"
2367 << expr1 << " evaluates to " << val1 << ",\n"
2368 << expr2 << " evaluates to " << val2 << ", and\n"
2369 << abs_error_expr << " evaluates to " << abs_error << ".";
2373 // Helper template for implementing FloatLE() and DoubleLE().
2374 template <typename RawType>
2375 AssertionResult FloatingPointLE(const char* expr1,
2379 // Returns success if val1 is less than val2,
2381 return AssertionSuccess();
2384 // or if val1 is almost equal to val2.
2385 const FloatingPoint<RawType> lhs(val1), rhs(val2);
2386 if (lhs.AlmostEquals(rhs)) {
2387 return AssertionSuccess();
2390 // Note that the above two checks will both fail if either val1 or
2391 // val2 is NaN, as the IEEE floating-point standard requires that
2392 // any predicate involving a NaN must return false.
2394 ::std::stringstream val1_ss;
2395 val1_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
2398 ::std::stringstream val2_ss;
2399 val2_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
2402 return AssertionFailure()
2403 << "Expected: (" << expr1 << ") <= (" << expr2 << ")\n"
2404 << " Actual: " << StringStreamToString(&val1_ss) << " vs "
2405 << StringStreamToString(&val2_ss);
2408 } // namespace internal
2410 // Asserts that val1 is less than, or almost equal to, val2. Fails
2411 // otherwise. In particular, it fails if either val1 or val2 is NaN.
2412 AssertionResult FloatLE(const char* expr1, const char* expr2,
2413 float val1, float val2) {
2414 return internal::FloatingPointLE<float>(expr1, expr2, val1, val2);
2417 // Asserts that val1 is less than, or almost equal to, val2. Fails
2418 // otherwise. In particular, it fails if either val1 or val2 is NaN.
2419 AssertionResult DoubleLE(const char* expr1, const char* expr2,
2420 double val1, double val2) {
2421 return internal::FloatingPointLE<double>(expr1, expr2, val1, val2);
2424 namespace internal {
2426 // The helper function for {ASSERT|EXPECT}_EQ with int or enum
2428 AssertionResult CmpHelperEQ(const char* expected_expression,
2429 const char* actual_expression,
2430 BiggestInt expected,
2431 BiggestInt actual) {
2432 if (expected == actual) {
2433 return AssertionSuccess();
2436 return EqFailure(expected_expression,
2438 FormatForComparisonFailureMessage(expected, actual),
2439 FormatForComparisonFailureMessage(actual, expected),
2443 // A macro for implementing the helper functions needed to implement
2444 // ASSERT_?? and EXPECT_?? with integer or enum arguments. It is here
2445 // just to avoid copy-and-paste of similar code.
2446 #define GTEST_IMPL_CMP_HELPER_(op_name, op)\
2447 AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \
2448 BiggestInt val1, BiggestInt val2) {\
2449 if (val1 op val2) {\
2450 return AssertionSuccess();\
2452 return AssertionFailure() \
2453 << "Expected: (" << expr1 << ") " #op " (" << expr2\
2454 << "), actual: " << FormatForComparisonFailureMessage(val1, val2)\
2455 << " vs " << FormatForComparisonFailureMessage(val2, val1);\
2459 // Implements the helper function for {ASSERT|EXPECT}_NE with int or
2461 GTEST_IMPL_CMP_HELPER_(NE, !=)
2462 // Implements the helper function for {ASSERT|EXPECT}_LE with int or
2464 GTEST_IMPL_CMP_HELPER_(LE, <=)
2465 // Implements the helper function for {ASSERT|EXPECT}_LT with int or
2467 GTEST_IMPL_CMP_HELPER_(LT, < )
2468 // Implements the helper function for {ASSERT|EXPECT}_GE with int or
2470 GTEST_IMPL_CMP_HELPER_(GE, >=)
2471 // Implements the helper function for {ASSERT|EXPECT}_GT with int or
2473 GTEST_IMPL_CMP_HELPER_(GT, > )
2475 #undef GTEST_IMPL_CMP_HELPER_
2477 // The helper function for {ASSERT|EXPECT}_STREQ.
2478 AssertionResult CmpHelperSTREQ(const char* expected_expression,
2479 const char* actual_expression,
2480 const char* expected,
2481 const char* actual) {
2482 if (String::CStringEquals(expected, actual)) {
2483 return AssertionSuccess();
2486 return EqFailure(expected_expression,
2488 PrintToString(expected),
2489 PrintToString(actual),
2493 // The helper function for {ASSERT|EXPECT}_STRCASEEQ.
2494 AssertionResult CmpHelperSTRCASEEQ(const char* expected_expression,
2495 const char* actual_expression,
2496 const char* expected,
2497 const char* actual) {
2498 if (String::CaseInsensitiveCStringEquals(expected, actual)) {
2499 return AssertionSuccess();
2502 return EqFailure(expected_expression,
2504 PrintToString(expected),
2505 PrintToString(actual),
2509 // The helper function for {ASSERT|EXPECT}_STRNE.
2510 AssertionResult CmpHelperSTRNE(const char* s1_expression,
2511 const char* s2_expression,
2514 if (!String::CStringEquals(s1, s2)) {
2515 return AssertionSuccess();
2517 return AssertionFailure() << "Expected: (" << s1_expression << ") != ("
2518 << s2_expression << "), actual: \""
2519 << s1 << "\" vs \"" << s2 << "\"";
2523 // The helper function for {ASSERT|EXPECT}_STRCASENE.
2524 AssertionResult CmpHelperSTRCASENE(const char* s1_expression,
2525 const char* s2_expression,
2528 if (!String::CaseInsensitiveCStringEquals(s1, s2)) {
2529 return AssertionSuccess();
2531 return AssertionFailure()
2532 << "Expected: (" << s1_expression << ") != ("
2533 << s2_expression << ") (ignoring case), actual: \""
2534 << s1 << "\" vs \"" << s2 << "\"";
2538 } // namespace internal
2542 // Helper functions for implementing IsSubString() and IsNotSubstring().
2544 // This group of overloaded functions return true iff needle is a
2545 // substring of haystack. NULL is considered a substring of itself
2548 bool IsSubstringPred(const char* needle, const char* haystack) {
2549 if (needle == NULL || haystack == NULL)
2550 return needle == haystack;
2552 return strstr(haystack, needle) != NULL;
2555 bool IsSubstringPred(const wchar_t* needle, const wchar_t* haystack) {
2556 if (needle == NULL || haystack == NULL)
2557 return needle == haystack;
2559 return wcsstr(haystack, needle) != NULL;
2562 // StringType here can be either ::std::string or ::std::wstring.
2563 template <typename StringType>
2564 bool IsSubstringPred(const StringType& needle,
2565 const StringType& haystack) {
2566 return haystack.find(needle) != StringType::npos;
2569 // This function implements either IsSubstring() or IsNotSubstring(),
2570 // depending on the value of the expected_to_be_substring parameter.
2571 // StringType here can be const char*, const wchar_t*, ::std::string,
2572 // or ::std::wstring.
2573 template <typename StringType>
2574 AssertionResult IsSubstringImpl(
2575 bool expected_to_be_substring,
2576 const char* needle_expr, const char* haystack_expr,
2577 const StringType& needle, const StringType& haystack) {
2578 if (IsSubstringPred(needle, haystack) == expected_to_be_substring)
2579 return AssertionSuccess();
2581 const bool is_wide_string = sizeof(needle[0]) > 1;
2582 const char* const begin_string_quote = is_wide_string ? "L\"" : "\"";
2583 return AssertionFailure()
2584 << "Value of: " << needle_expr << "\n"
2585 << " Actual: " << begin_string_quote << needle << "\"\n"
2586 << "Expected: " << (expected_to_be_substring ? "" : "not ")
2587 << "a substring of " << haystack_expr << "\n"
2588 << "Which is: " << begin_string_quote << haystack << "\"";
2593 // IsSubstring() and IsNotSubstring() check whether needle is a
2594 // substring of haystack (NULL is considered a substring of itself
2595 // only), and return an appropriate error message when they fail.
2597 AssertionResult IsSubstring(
2598 const char* needle_expr, const char* haystack_expr,
2599 const char* needle, const char* haystack) {
2600 return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
2603 AssertionResult IsSubstring(
2604 const char* needle_expr, const char* haystack_expr,
2605 const wchar_t* needle, const wchar_t* haystack) {
2606 return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
2609 AssertionResult IsNotSubstring(
2610 const char* needle_expr, const char* haystack_expr,
2611 const char* needle, const char* haystack) {
2612 return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
2615 AssertionResult IsNotSubstring(
2616 const char* needle_expr, const char* haystack_expr,
2617 const wchar_t* needle, const wchar_t* haystack) {
2618 return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
2621 AssertionResult IsSubstring(
2622 const char* needle_expr, const char* haystack_expr,
2623 const ::std::string& needle, const ::std::string& haystack) {
2624 return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
2627 AssertionResult IsNotSubstring(
2628 const char* needle_expr, const char* haystack_expr,
2629 const ::std::string& needle, const ::std::string& haystack) {
2630 return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
2633 #if GTEST_HAS_STD_WSTRING
2634 AssertionResult IsSubstring(
2635 const char* needle_expr, const char* haystack_expr,
2636 const ::std::wstring& needle, const ::std::wstring& haystack) {
2637 return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
2640 AssertionResult IsNotSubstring(
2641 const char* needle_expr, const char* haystack_expr,
2642 const ::std::wstring& needle, const ::std::wstring& haystack) {
2643 return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
2645 #endif // GTEST_HAS_STD_WSTRING
2647 namespace internal {
2649 #if GTEST_OS_WINDOWS
2653 // Helper function for IsHRESULT{SuccessFailure} predicates
2654 AssertionResult HRESULTFailureHelper(const char* expr,
2655 const char* expected,
2656 long hr) { // NOLINT
2657 # if GTEST_OS_WINDOWS_MOBILE
2659 // Windows CE doesn't support FormatMessage.
2660 const char error_text[] = "";
2664 // Looks up the human-readable system message for the HRESULT code
2665 // and since we're not passing any params to FormatMessage, we don't
2666 // want inserts expanded.
2667 const DWORD kFlags = FORMAT_MESSAGE_FROM_SYSTEM |
2668 FORMAT_MESSAGE_IGNORE_INSERTS;
2669 const DWORD kBufSize = 4096; // String::Format can't exceed this length.
2670 // Gets the system's human readable message string for this HRESULT.
2671 char error_text[kBufSize] = { '\0' };
2672 DWORD message_length = ::FormatMessageA(kFlags,
2673 0, // no source, we're asking system
2675 0, // no line width restrictions
2676 error_text, // output buffer
2677 kBufSize, // buf size
2678 NULL); // no arguments for inserts
2679 // Trims tailing white space (FormatMessage leaves a trailing cr-lf)
2680 for (; message_length && IsSpace(error_text[message_length - 1]);
2682 error_text[message_length - 1] = '\0';
2685 # endif // GTEST_OS_WINDOWS_MOBILE
2687 const String error_hex(String::Format("0x%08X ", hr));
2688 return ::testing::AssertionFailure()
2689 << "Expected: " << expr << " " << expected << ".\n"
2690 << " Actual: " << error_hex << error_text << "\n";
2695 AssertionResult IsHRESULTSuccess(const char* expr, long hr) { // NOLINT
2696 if (SUCCEEDED(hr)) {
2697 return AssertionSuccess();
2699 return HRESULTFailureHelper(expr, "succeeds", hr);
2702 AssertionResult IsHRESULTFailure(const char* expr, long hr) { // NOLINT
2704 return AssertionSuccess();
2706 return HRESULTFailureHelper(expr, "fails", hr);
2709 #endif // GTEST_OS_WINDOWS
2711 // Utility functions for encoding Unicode text (wide strings) in
2714 // A Unicode code-point can have upto 21 bits, and is encoded in UTF-8
2717 // Code-point length Encoding
2718 // 0 - 7 bits 0xxxxxxx
2719 // 8 - 11 bits 110xxxxx 10xxxxxx
2720 // 12 - 16 bits 1110xxxx 10xxxxxx 10xxxxxx
2721 // 17 - 21 bits 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
2723 // The maximum code-point a one-byte UTF-8 sequence can represent.
2724 const UInt32 kMaxCodePoint1 = (static_cast<UInt32>(1) << 7) - 1;
2726 // The maximum code-point a two-byte UTF-8 sequence can represent.
2727 const UInt32 kMaxCodePoint2 = (static_cast<UInt32>(1) << (5 + 6)) - 1;
2729 // The maximum code-point a three-byte UTF-8 sequence can represent.
2730 const UInt32 kMaxCodePoint3 = (static_cast<UInt32>(1) << (4 + 2*6)) - 1;
2732 // The maximum code-point a four-byte UTF-8 sequence can represent.
2733 const UInt32 kMaxCodePoint4 = (static_cast<UInt32>(1) << (3 + 3*6)) - 1;
2735 // Chops off the n lowest bits from a bit pattern. Returns the n
2736 // lowest bits. As a side effect, the original bit pattern will be
2737 // shifted to the right by n bits.
2738 inline UInt32 ChopLowBits(UInt32* bits, int n) {
2739 const UInt32 low_bits = *bits & ((static_cast<UInt32>(1) << n) - 1);
2744 // Converts a Unicode code point to a narrow string in UTF-8 encoding.
2745 // code_point parameter is of type UInt32 because wchar_t may not be
2746 // wide enough to contain a code point.
2747 // The output buffer str must containt at least 32 characters.
2748 // The function returns the address of the output buffer.
2749 // If the code_point is not a valid Unicode code point
2750 // (i.e. outside of Unicode range U+0 to U+10FFFF) it will be output
2751 // as '(Invalid Unicode 0xXXXXXXXX)'.
2752 char* CodePointToUtf8(UInt32 code_point, char* str) {
2753 if (code_point <= kMaxCodePoint1) {
2755 str[0] = static_cast<char>(code_point); // 0xxxxxxx
2756 } else if (code_point <= kMaxCodePoint2) {
2758 str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
2759 str[0] = static_cast<char>(0xC0 | code_point); // 110xxxxx
2760 } else if (code_point <= kMaxCodePoint3) {
2762 str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
2763 str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
2764 str[0] = static_cast<char>(0xE0 | code_point); // 1110xxxx
2765 } else if (code_point <= kMaxCodePoint4) {
2767 str[3] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
2768 str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
2769 str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
2770 str[0] = static_cast<char>(0xF0 | code_point); // 11110xxx
2772 // The longest string String::Format can produce when invoked
2773 // with these parameters is 28 character long (not including
2774 // the terminating nul character). We are asking for 32 character
2775 // buffer just in case. This is also enough for strncpy to
2776 // null-terminate the destination string.
2778 str, String::Format("(Invalid Unicode 0x%X)", code_point).c_str(), 32);
2779 str[31] = '\0'; // Makes sure no change in the format to strncpy leaves
2780 // the result unterminated.
2785 // The following two functions only make sense if the the system
2786 // uses UTF-16 for wide string encoding. All supported systems
2787 // with 16 bit wchar_t (Windows, Cygwin, Symbian OS) do use UTF-16.
2789 // Determines if the arguments constitute UTF-16 surrogate pair
2790 // and thus should be combined into a single Unicode code point
2791 // using CreateCodePointFromUtf16SurrogatePair.
2792 inline bool IsUtf16SurrogatePair(wchar_t first, wchar_t second) {
2793 return sizeof(wchar_t) == 2 &&
2794 (first & 0xFC00) == 0xD800 && (second & 0xFC00) == 0xDC00;
2797 // Creates a Unicode code point from UTF16 surrogate pair.
2798 inline UInt32 CreateCodePointFromUtf16SurrogatePair(wchar_t first,
2800 const UInt32 mask = (1 << 10) - 1;
2801 return (sizeof(wchar_t) == 2) ?
2802 (((first & mask) << 10) | (second & mask)) + 0x10000 :
2803 // This function should not be called when the condition is
2804 // false, but we provide a sensible default in case it is.
2805 static_cast<UInt32>(first);
2808 // Converts a wide string to a narrow string in UTF-8 encoding.
2809 // The wide string is assumed to have the following encoding:
2810 // UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS)
2811 // UTF-32 if sizeof(wchar_t) == 4 (on Linux)
2812 // Parameter str points to a null-terminated wide string.
2813 // Parameter num_chars may additionally limit the number
2814 // of wchar_t characters processed. -1 is used when the entire string
2815 // should be processed.
2816 // If the string contains code points that are not valid Unicode code points
2817 // (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
2818 // as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
2819 // and contains invalid UTF-16 surrogate pairs, values in those pairs
2820 // will be encoded as individual Unicode characters from Basic Normal Plane.
2821 String WideStringToUtf8(const wchar_t* str, int num_chars) {
2822 if (num_chars == -1)
2823 num_chars = static_cast<int>(wcslen(str));
2825 ::std::stringstream stream;
2826 for (int i = 0; i < num_chars; ++i) {
2827 UInt32 unicode_code_point;
2829 if (str[i] == L'\0') {
2831 } else if (i + 1 < num_chars && IsUtf16SurrogatePair(str[i], str[i + 1])) {
2832 unicode_code_point = CreateCodePointFromUtf16SurrogatePair(str[i],
2836 unicode_code_point = static_cast<UInt32>(str[i]);
2839 char buffer[32]; // CodePointToUtf8 requires a buffer this big.
2840 stream << CodePointToUtf8(unicode_code_point, buffer);
2842 return StringStreamToString(&stream);
2845 // Converts a wide C string to a String using the UTF-8 encoding.
2846 // NULL will be converted to "(null)".
2847 String String::ShowWideCString(const wchar_t * wide_c_str) {
2848 if (wide_c_str == NULL) return String("(null)");
2850 return String(internal::WideStringToUtf8(wide_c_str, -1).c_str());
2853 // Compares two wide C strings. Returns true iff they have the same
2856 // Unlike wcscmp(), this function can handle NULL argument(s). A NULL
2857 // C string is considered different to any non-NULL C string,
2858 // including the empty string.
2859 bool String::WideCStringEquals(const wchar_t * lhs, const wchar_t * rhs) {
2860 if (lhs == NULL) return rhs == NULL;
2862 if (rhs == NULL) return false;
2864 return wcscmp(lhs, rhs) == 0;
2867 // Helper function for *_STREQ on wide strings.
2868 AssertionResult CmpHelperSTREQ(const char* expected_expression,
2869 const char* actual_expression,
2870 const wchar_t* expected,
2871 const wchar_t* actual) {
2872 if (String::WideCStringEquals(expected, actual)) {
2873 return AssertionSuccess();
2876 return EqFailure(expected_expression,
2878 PrintToString(expected),
2879 PrintToString(actual),
2883 // Helper function for *_STRNE on wide strings.
2884 AssertionResult CmpHelperSTRNE(const char* s1_expression,
2885 const char* s2_expression,
2887 const wchar_t* s2) {
2888 if (!String::WideCStringEquals(s1, s2)) {
2889 return AssertionSuccess();
2892 return AssertionFailure() << "Expected: (" << s1_expression << ") != ("
2893 << s2_expression << "), actual: "
2894 << PrintToString(s1)
2895 << " vs " << PrintToString(s2);
2898 // Compares two C strings, ignoring case. Returns true iff they have
2899 // the same content.
2901 // Unlike strcasecmp(), this function can handle NULL argument(s). A
2902 // NULL C string is considered different to any non-NULL C string,
2903 // including the empty string.
2904 bool String::CaseInsensitiveCStringEquals(const char * lhs, const char * rhs) {
2909 return posix::StrCaseCmp(lhs, rhs) == 0;
2912 // Compares two wide C strings, ignoring case. Returns true iff they
2913 // have the same content.
2915 // Unlike wcscasecmp(), this function can handle NULL argument(s).
2916 // A NULL C string is considered different to any non-NULL wide C string,
2917 // including the empty string.
2918 // NB: The implementations on different platforms slightly differ.
2919 // On windows, this method uses _wcsicmp which compares according to LC_CTYPE
2920 // environment variable. On GNU platform this method uses wcscasecmp
2921 // which compares according to LC_CTYPE category of the current locale.
2922 // On MacOS X, it uses towlower, which also uses LC_CTYPE category of the
2924 bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs,
2925 const wchar_t* rhs) {
2926 if (lhs == NULL) return rhs == NULL;
2928 if (rhs == NULL) return false;
2930 #if GTEST_OS_WINDOWS
2931 return _wcsicmp(lhs, rhs) == 0;
2932 #elif GTEST_OS_LINUX && !GTEST_OS_LINUX_ANDROID
2933 return wcscasecmp(lhs, rhs) == 0;
2935 // Android, Mac OS X and Cygwin don't define wcscasecmp.
2936 // Other unknown OSes may not define it either.
2939 left = towlower(*lhs++);
2940 right = towlower(*rhs++);
2941 } while (left && left == right);
2942 return left == right;
2943 #endif // OS selector
2946 // Compares this with another String.
2947 // Returns < 0 if this is less than rhs, 0 if this is equal to rhs, or > 0
2948 // if this is greater than rhs.
2949 int String::Compare(const String & rhs) const {
2950 const char* const lhs_c_str = c_str();
2951 const char* const rhs_c_str = rhs.c_str();
2953 if (lhs_c_str == NULL) {
2954 return rhs_c_str == NULL ? 0 : -1; // NULL < anything except NULL
2955 } else if (rhs_c_str == NULL) {
2959 const size_t shorter_str_len =
2960 length() <= rhs.length() ? length() : rhs.length();
2961 for (size_t i = 0; i != shorter_str_len; i++) {
2962 if (lhs_c_str[i] < rhs_c_str[i]) {
2964 } else if (lhs_c_str[i] > rhs_c_str[i]) {
2968 return (length() < rhs.length()) ? -1 :
2969 (length() > rhs.length()) ? 1 : 0;
2972 // Returns true iff this String ends with the given suffix. *Any*
2973 // String is considered to end with a NULL or empty suffix.
2974 bool String::EndsWith(const char* suffix) const {
2975 if (suffix == NULL || CStringEquals(suffix, "")) return true;
2977 if (c_str() == NULL) return false;
2979 const size_t this_len = strlen(c_str());
2980 const size_t suffix_len = strlen(suffix);
2981 return (this_len >= suffix_len) &&
2982 CStringEquals(c_str() + this_len - suffix_len, suffix);
2985 // Returns true iff this String ends with the given suffix, ignoring case.
2986 // Any String is considered to end with a NULL or empty suffix.
2987 bool String::EndsWithCaseInsensitive(const char* suffix) const {
2988 if (suffix == NULL || CStringEquals(suffix, "")) return true;
2990 if (c_str() == NULL) return false;
2992 const size_t this_len = strlen(c_str());
2993 const size_t suffix_len = strlen(suffix);
2994 return (this_len >= suffix_len) &&
2995 CaseInsensitiveCStringEquals(c_str() + this_len - suffix_len, suffix);
2998 // Formats a list of arguments to a String, using the same format
2999 // spec string as for printf.
3001 // We do not use the StringPrintf class as it is not universally
3004 // The result is limited to 4096 characters (including the tailing 0).
3005 // If 4096 characters are not enough to format the input, or if
3006 // there's an error, "<formatting error or buffer exceeded>" is
3008 String String::Format(const char * format, ...) {
3010 va_start(args, format);
3013 const int kBufferSize = sizeof(buffer)/sizeof(buffer[0]);
3015 // MSVC 8 deprecates vsnprintf(), so we want to suppress warning
3016 // 4996 (deprecated function) there.
3017 #ifdef _MSC_VER // We are using MSVC.
3018 # pragma warning(push) // Saves the current warning state.
3019 # pragma warning(disable:4996) // Temporarily disables warning 4996.
3021 const int size = vsnprintf(buffer, kBufferSize, format, args);
3023 # pragma warning(pop) // Restores the warning state.
3024 #else // We are not using MSVC.
3025 const int size = vsnprintf(buffer, kBufferSize, format, args);
3029 // vsnprintf()'s behavior is not portable. When the buffer is not
3030 // big enough, it returns a negative value in MSVC, and returns the
3031 // needed buffer size on Linux. When there is an output error, it
3032 // always returns a negative value. For simplicity, we lump the two
3033 // error cases together.
3034 if (size < 0 || size >= kBufferSize) {
3035 return String("<formatting error or buffer exceeded>");
3037 return String(buffer, size);
3041 // Converts the buffer in a stringstream to a String, converting NUL
3042 // bytes to "\\0" along the way.
3043 String StringStreamToString(::std::stringstream* ss) {
3044 const ::std::string& str = ss->str();
3045 const char* const start = str.c_str();
3046 const char* const end = start + str.length();
3048 // We need to use a helper stringstream to do this transformation
3049 // because String doesn't support push_back().
3050 ::std::stringstream helper;
3051 for (const char* ch = start; ch != end; ++ch) {
3053 helper << "\\0"; // Replaces NUL with "\\0";
3059 return String(helper.str().c_str());
3062 // Appends the user-supplied message to the Google-Test-generated message.
3063 String AppendUserMessage(const String& gtest_msg,
3064 const Message& user_msg) {
3065 // Appends the user message if it's non-empty.
3066 const String user_msg_string = user_msg.GetString();
3067 if (user_msg_string.empty()) {
3072 msg << gtest_msg << "\n" << user_msg_string;
3074 return msg.GetString();
3077 } // namespace internal
3081 // Creates an empty TestResult.
3082 TestResult::TestResult()
3083 : death_test_count_(0),
3088 TestResult::~TestResult() {
3091 // Returns the i-th test part result among all the results. i can
3092 // range from 0 to total_part_count() - 1. If i is not in that range,
3093 // aborts the program.
3094 const TestPartResult& TestResult::GetTestPartResult(int i) const {
3095 if (i < 0 || i >= total_part_count())
3096 internal::posix::Abort();
3097 return test_part_results_.at(i);
3100 // Returns the i-th test property. i can range from 0 to
3101 // test_property_count() - 1. If i is not in that range, aborts the
3103 const TestProperty& TestResult::GetTestProperty(int i) const {
3104 if (i < 0 || i >= test_property_count())
3105 internal::posix::Abort();
3106 return test_properties_.at(i);
3109 // Clears the test part results.
3110 void TestResult::ClearTestPartResults() {
3111 test_part_results_.clear();
3114 // Adds a test part result to the list.
3115 void TestResult::AddTestPartResult(const TestPartResult& test_part_result) {
3116 test_part_results_.push_back(test_part_result);
3119 // Adds a test property to the list. If a property with the same key as the
3120 // supplied property is already represented, the value of this test_property
3121 // replaces the old value for that key.
3122 void TestResult::RecordProperty(const TestProperty& test_property) {
3123 if (!ValidateTestProperty(test_property)) {
3126 internal::MutexLock lock(&test_properites_mutex_);
3127 const std::vector<TestProperty>::iterator property_with_matching_key =
3128 std::find_if(test_properties_.begin(), test_properties_.end(),
3129 internal::TestPropertyKeyIs(test_property.key()));
3130 if (property_with_matching_key == test_properties_.end()) {
3131 test_properties_.push_back(test_property);
3134 property_with_matching_key->SetValue(test_property.value());
3137 // Adds a failure if the key is a reserved attribute of Google Test
3138 // testcase tags. Returns true if the property is valid.
3139 bool TestResult::ValidateTestProperty(const TestProperty& test_property) {
3140 internal::String key(test_property.key());
3141 if (key == "name" || key == "status" || key == "time" || key == "classname") {
3143 << "Reserved key used in RecordProperty(): "
3145 << " ('name', 'status', 'time', and 'classname' are reserved by "
3146 << GTEST_NAME_ << ")";
3152 // Clears the object.
3153 void TestResult::Clear() {
3154 test_part_results_.clear();
3155 test_properties_.clear();
3156 death_test_count_ = 0;
3160 // Returns true iff the test failed.
3161 bool TestResult::Failed() const {
3162 for (int i = 0; i < total_part_count(); ++i) {
3163 if (GetTestPartResult(i).failed())
3169 // Returns true iff the test part fatally failed.
3170 static bool TestPartFatallyFailed(const TestPartResult& result) {
3171 return result.fatally_failed();
3174 // Returns true iff the test fatally failed.
3175 bool TestResult::HasFatalFailure() const {
3176 return CountIf(test_part_results_, TestPartFatallyFailed) > 0;
3179 // Returns true iff the test part non-fatally failed.
3180 static bool TestPartNonfatallyFailed(const TestPartResult& result) {
3181 return result.nonfatally_failed();
3184 // Returns true iff the test has a non-fatal failure.
3185 bool TestResult::HasNonfatalFailure() const {
3186 return CountIf(test_part_results_, TestPartNonfatallyFailed) > 0;
3189 // Gets the number of all test parts. This is the sum of the number
3190 // of successful test parts and the number of failed test parts.
3191 int TestResult::total_part_count() const {
3192 return static_cast<int>(test_part_results_.size());
3195 // Returns the number of the test properties.
3196 int TestResult::test_property_count() const {
3197 return static_cast<int>(test_properties_.size());
3202 // Creates a Test object.
3204 // The c'tor saves the values of all Google Test flags.
3206 : gtest_flag_saver_(new internal::GTestFlagSaver) {
3209 // The d'tor restores the values of all Google Test flags.
3211 delete gtest_flag_saver_;
3214 // Sets up the test fixture.
3216 // A sub-class may override this.
3217 void Test::SetUp() {
3220 // Tears down the test fixture.
3222 // A sub-class may override this.
3223 void Test::TearDown() {
3226 // Allows user supplied key value pairs to be recorded for later output.
3227 void Test::RecordProperty(const char* key, const char* value) {
3228 UnitTest::GetInstance()->RecordPropertyForCurrentTest(key, value);
3231 // Allows user supplied key value pairs to be recorded for later output.
3232 void Test::RecordProperty(const char* key, int value) {
3233 Message value_message;
3234 value_message << value;
3235 RecordProperty(key, value_message.GetString().c_str());
3238 namespace internal {
3240 void ReportFailureInUnknownLocation(TestPartResult::Type result_type,
3241 const String& message) {
3242 // This function is a friend of UnitTest and as such has access to
3243 // AddTestPartResult.
3244 UnitTest::GetInstance()->AddTestPartResult(
3246 NULL, // No info about the source file where the exception occurred.
3247 -1, // We have no info on which line caused the exception.
3249 String()); // No stack trace, either.
3252 } // namespace internal
3254 // Google Test requires all tests in the same test case to use the same test
3255 // fixture class. This function checks if the current test has the
3256 // same fixture class as the first test in the current test case. If
3257 // yes, it returns true; otherwise it generates a Google Test failure and
3259 bool Test::HasSameFixtureClass() {
3260 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
3261 const TestCase* const test_case = impl->current_test_case();
3263 // Info about the first test in the current test case.
3264 const TestInfo* const first_test_info = test_case->test_info_list()[0];
3265 const internal::TypeId first_fixture_id = first_test_info->fixture_class_id_;
3266 const char* const first_test_name = first_test_info->name();
3268 // Info about the current test.
3269 const TestInfo* const this_test_info = impl->current_test_info();
3270 const internal::TypeId this_fixture_id = this_test_info->fixture_class_id_;
3271 const char* const this_test_name = this_test_info->name();
3273 if (this_fixture_id != first_fixture_id) {
3274 // Is the first test defined using TEST?
3275 const bool first_is_TEST = first_fixture_id == internal::GetTestTypeId();
3276 // Is this test defined using TEST?
3277 const bool this_is_TEST = this_fixture_id == internal::GetTestTypeId();
3279 if (first_is_TEST || this_is_TEST) {
3280 // The user mixed TEST and TEST_F in this test case - we'll tell
3281 // him/her how to fix it.
3283 // Gets the name of the TEST and the name of the TEST_F. Note
3284 // that first_is_TEST and this_is_TEST cannot both be true, as
3285 // the fixture IDs are different for the two tests.
3286 const char* const TEST_name =
3287 first_is_TEST ? first_test_name : this_test_name;
3288 const char* const TEST_F_name =
3289 first_is_TEST ? this_test_name : first_test_name;
3292 << "All tests in the same test case must use the same test fixture\n"
3293 << "class, so mixing TEST_F and TEST in the same test case is\n"
3294 << "illegal. In test case " << this_test_info->test_case_name()
3296 << "test " << TEST_F_name << " is defined using TEST_F but\n"
3297 << "test " << TEST_name << " is defined using TEST. You probably\n"
3298 << "want to change the TEST to TEST_F or move it to another test\n"
3301 // The user defined two fixture classes with the same name in
3302 // two namespaces - we'll tell him/her how to fix it.
3304 << "All tests in the same test case must use the same test fixture\n"
3305 << "class. However, in test case "
3306 << this_test_info->test_case_name() << ",\n"
3307 << "you defined test " << first_test_name
3308 << " and test " << this_test_name << "\n"
3309 << "using two different test fixture classes. This can happen if\n"
3310 << "the two classes are from different namespaces or translation\n"
3311 << "units and have the same name. You should probably rename one\n"
3312 << "of the classes to put the tests into different test cases.";
3322 // Adds an "exception thrown" fatal failure to the current test. This
3323 // function returns its result via an output parameter pointer because VC++
3324 // prohibits creation of objects with destructors on stack in functions
3325 // using __try (see error C2712).
3326 static internal::String* FormatSehExceptionMessage(DWORD exception_code,
3327 const char* location) {
3329 message << "SEH exception with code 0x" << std::setbase(16) <<
3330 exception_code << std::setbase(10) << " thrown in " << location << ".";
3332 return new internal::String(message.GetString());
3335 #endif // GTEST_HAS_SEH
3337 #if GTEST_HAS_EXCEPTIONS
3339 // Adds an "exception thrown" fatal failure to the current test.
3340 static internal::String FormatCxxExceptionMessage(const char* description,
3341 const char* location) {
3343 if (description != NULL) {
3344 message << "C++ exception with description \"" << description << "\"";
3346 message << "Unknown C++ exception";
3348 message << " thrown in " << location << ".";
3350 return message.GetString();
3353 static internal::String PrintTestPartResultToString(
3354 const TestPartResult& test_part_result);
3356 // A failed Google Test assertion will throw an exception of this type when
3357 // GTEST_FLAG(throw_on_failure) is true (if exceptions are enabled). We
3358 // derive it from std::runtime_error, which is for errors presumably
3359 // detectable only at run time. Since std::runtime_error inherits from
3360 // std::exception, many testing frameworks know how to extract and print the
3361 // message inside it.
3362 class GoogleTestFailureException : public ::std::runtime_error {
3364 explicit GoogleTestFailureException(const TestPartResult& failure)
3365 : ::std::runtime_error(PrintTestPartResultToString(failure).c_str()) {}
3367 #endif // GTEST_HAS_EXCEPTIONS
3369 namespace internal {
3370 // We put these helper functions in the internal namespace as IBM's xlC
3371 // compiler rejects the code if they were declared static.
3373 // Runs the given method and handles SEH exceptions it throws, when
3374 // SEH is supported; returns the 0-value for type Result in case of an
3375 // SEH exception. (Microsoft compilers cannot handle SEH and C++
3376 // exceptions in the same function. Therefore, we provide a separate
3377 // wrapper function for handling SEH exceptions.)
3378 template <class T, typename Result>
3379 Result HandleSehExceptionsInMethodIfSupported(
3380 T* object, Result (T::*method)(), const char* location) {
3383 return (object->*method)();
3384 } __except (internal::UnitTestOptions::GTestShouldProcessSEH( // NOLINT
3385 GetExceptionCode())) {
3386 // We create the exception message on the heap because VC++ prohibits
3387 // creation of objects with destructors on stack in functions using __try
3388 // (see error C2712).
3389 internal::String* exception_message = FormatSehExceptionMessage(
3390 GetExceptionCode(), location);
3391 internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure,
3392 *exception_message);
3393 delete exception_message;
3394 return static_cast<Result>(0);
3398 return (object->*method)();
3399 #endif // GTEST_HAS_SEH
3402 // Runs the given method and catches and reports C++ and/or SEH-style
3403 // exceptions, if they are supported; returns the 0-value for type
3404 // Result in case of an SEH exception.
3405 template <class T, typename Result>
3406 Result HandleExceptionsInMethodIfSupported(
3407 T* object, Result (T::*method)(), const char* location) {
3408 // NOTE: The user code can affect the way in which Google Test handles
3409 // exceptions by setting GTEST_FLAG(catch_exceptions), but only before
3410 // RUN_ALL_TESTS() starts. It is technically possible to check the flag
3411 // after the exception is caught and either report or re-throw the
3412 // exception based on the flag's value:
3415 // // Perform the test method.
3417 // if (GTEST_FLAG(catch_exceptions))
3418 // // Report the exception as failure.
3420 // throw; // Re-throws the original exception.
3423 // However, the purpose of this flag is to allow the program to drop into
3424 // the debugger when the exception is thrown. On most platforms, once the
3425 // control enters the catch block, the exception origin information is
3426 // lost and the debugger will stop the program at the point of the
3427 // re-throw in this function -- instead of at the point of the original
3428 // throw statement in the code under test. For this reason, we perform
3429 // the check early, sacrificing the ability to affect Google Test's
3430 // exception handling in the method where the exception is thrown.
3431 if (internal::GetUnitTestImpl()->catch_exceptions()) {
3432 #if GTEST_HAS_EXCEPTIONS
3434 return HandleSehExceptionsInMethodIfSupported(object, method, location);
3435 } catch (const GoogleTestFailureException&) { // NOLINT
3436 // This exception doesn't originate in code under test. It makes no
3437 // sense to report it as a test failure.
3439 } catch (const std::exception& e) { // NOLINT
3440 internal::ReportFailureInUnknownLocation(
3441 TestPartResult::kFatalFailure,
3442 FormatCxxExceptionMessage(e.what(), location));
3443 } catch (...) { // NOLINT
3444 internal::ReportFailureInUnknownLocation(
3445 TestPartResult::kFatalFailure,
3446 FormatCxxExceptionMessage(NULL, location));
3448 return static_cast<Result>(0);
3450 return HandleSehExceptionsInMethodIfSupported(object, method, location);
3451 #endif // GTEST_HAS_EXCEPTIONS
3453 return (object->*method)();
3457 } // namespace internal
3459 // Runs the test and updates the test result.
3461 if (!HasSameFixtureClass()) return;
3463 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
3464 impl->os_stack_trace_getter()->UponLeavingGTest();
3465 internal::HandleExceptionsInMethodIfSupported(this, &Test::SetUp, "SetUp()");
3466 // We will run the test only if SetUp() was successful.
3467 if (!HasFatalFailure()) {
3468 impl->os_stack_trace_getter()->UponLeavingGTest();
3469 internal::HandleExceptionsInMethodIfSupported(
3470 this, &Test::TestBody, "the test body");
3473 // However, we want to clean up as much as possible. Hence we will
3474 // always call TearDown(), even if SetUp() or the test body has
3476 impl->os_stack_trace_getter()->UponLeavingGTest();
3477 internal::HandleExceptionsInMethodIfSupported(
3478 this, &Test::TearDown, "TearDown()");
3481 // Returns true iff the current test has a fatal failure.
3482 bool Test::HasFatalFailure() {
3483 return internal::GetUnitTestImpl()->current_test_result()->HasFatalFailure();
3486 // Returns true iff the current test has a non-fatal failure.
3487 bool Test::HasNonfatalFailure() {
3488 return internal::GetUnitTestImpl()->current_test_result()->
3489 HasNonfatalFailure();
3494 // Constructs a TestInfo object. It assumes ownership of the test factory
3496 // TODO(vladl@google.com): Make a_test_case_name and a_name const string&'s
3497 // to signify they cannot be NULLs.
3498 TestInfo::TestInfo(const char* a_test_case_name,
3500 const char* a_type_param,
3501 const char* a_value_param,
3502 internal::TypeId fixture_class_id,
3503 internal::TestFactoryBase* factory)
3504 : test_case_name_(a_test_case_name),
3506 type_param_(a_type_param ? new std::string(a_type_param) : NULL),
3507 value_param_(a_value_param ? new std::string(a_value_param) : NULL),
3508 fixture_class_id_(fixture_class_id),
3510 is_disabled_(false),
3511 matches_filter_(false),
3515 // Destructs a TestInfo object.
3516 TestInfo::~TestInfo() { delete factory_; }
3518 namespace internal {
3520 // Creates a new TestInfo object and registers it with Google Test;
3521 // returns the created object.
3525 // test_case_name: name of the test case
3526 // name: name of the test
3527 // type_param: the name of the test's type parameter, or NULL if
3528 // this is not a typed or a type-parameterized test.
3529 // value_param: text representation of the test's value parameter,
3530 // or NULL if this is not a value-parameterized test.
3531 // fixture_class_id: ID of the test fixture class
3532 // set_up_tc: pointer to the function that sets up the test case
3533 // tear_down_tc: pointer to the function that tears down the test case
3534 // factory: pointer to the factory that creates a test object.
3535 // The newly created TestInfo instance will assume
3536 // ownership of the factory object.
3537 TestInfo* MakeAndRegisterTestInfo(
3538 const char* test_case_name, const char* name,
3539 const char* type_param,
3540 const char* value_param,
3541 TypeId fixture_class_id,
3542 SetUpTestCaseFunc set_up_tc,
3543 TearDownTestCaseFunc tear_down_tc,
3544 TestFactoryBase* factory) {
3545 TestInfo* const test_info =
3546 new TestInfo(test_case_name, name, type_param, value_param,
3547 fixture_class_id, factory);
3548 GetUnitTestImpl()->AddTestInfo(set_up_tc, tear_down_tc, test_info);
3552 #if GTEST_HAS_PARAM_TEST
3553 void ReportInvalidTestCaseType(const char* test_case_name,
3554 const char* file, int line) {
3557 << "Attempted redefinition of test case " << test_case_name << ".\n"
3558 << "All tests in the same test case must use the same test fixture\n"
3559 << "class. However, in test case " << test_case_name << ", you tried\n"
3560 << "to define a test using a fixture class different from the one\n"
3561 << "used earlier. This can happen if the two fixture classes are\n"
3562 << "from different namespaces and have the same name. You should\n"
3563 << "probably rename one of the classes to put the tests into different\n"
3566 fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(),
3567 errors.GetString().c_str());
3569 #endif // GTEST_HAS_PARAM_TEST
3571 } // namespace internal
3575 // A predicate that checks the test name of a TestInfo against a known
3578 // This is used for implementation of the TestCase class only. We put
3579 // it in the anonymous namespace to prevent polluting the outer
3582 // TestNameIs is copyable.
3587 // TestNameIs has NO default constructor.
3588 explicit TestNameIs(const char* name)
3591 // Returns true iff the test name of test_info matches name_.
3592 bool operator()(const TestInfo * test_info) const {
3593 return test_info && internal::String(test_info->name()).Compare(name_) == 0;
3597 internal::String name_;
3602 namespace internal {
3604 // This method expands all parameterized tests registered with macros TEST_P
3605 // and INSTANTIATE_TEST_CASE_P into regular tests and registers those.
3606 // This will be done just once during the program runtime.
3607 void UnitTestImpl::RegisterParameterizedTests() {
3608 #if GTEST_HAS_PARAM_TEST
3609 if (!parameterized_tests_registered_) {
3610 parameterized_test_registry_.RegisterTests();
3611 parameterized_tests_registered_ = true;
3616 } // namespace internal
3618 // Creates the test object, runs it, records its result, and then
3620 void TestInfo::Run() {
3621 if (!should_run_) return;
3623 // Tells UnitTest where to store test result.
3624 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
3625 impl->set_current_test_info(this);
3627 TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
3629 // Notifies the unit test event listeners that a test is about to start.
3630 repeater->OnTestStart(*this);
3632 const TimeInMillis start = internal::GetTimeInMillis();
3634 impl->os_stack_trace_getter()->UponLeavingGTest();
3636 // Creates the test object.
3637 Test* const test = internal::HandleExceptionsInMethodIfSupported(
3638 factory_, &internal::TestFactoryBase::CreateTest,
3639 "the test fixture's constructor");
3641 // Runs the test only if the test object was created and its
3642 // constructor didn't generate a fatal failure.
3643 if ((test != NULL) && !Test::HasFatalFailure()) {
3644 // This doesn't throw as all user code that can throw are wrapped into
3645 // exception handling code.
3649 // Deletes the test object.
3650 impl->os_stack_trace_getter()->UponLeavingGTest();
3651 internal::HandleExceptionsInMethodIfSupported(
3652 test, &Test::DeleteSelf_, "the test fixture's destructor");
3654 result_.set_elapsed_time(internal::GetTimeInMillis() - start);
3656 // Notifies the unit test event listener that a test has just finished.
3657 repeater->OnTestEnd(*this);
3659 // Tells UnitTest to stop associating assertion results to this
3661 impl->set_current_test_info(NULL);
3666 // Gets the number of successful tests in this test case.
3667 int TestCase::successful_test_count() const {
3668 return CountIf(test_info_list_, TestPassed);
3671 // Gets the number of failed tests in this test case.
3672 int TestCase::failed_test_count() const {
3673 return CountIf(test_info_list_, TestFailed);
3676 int TestCase::disabled_test_count() const {
3677 return CountIf(test_info_list_, TestDisabled);
3680 // Get the number of tests in this test case that should run.
3681 int TestCase::test_to_run_count() const {
3682 return CountIf(test_info_list_, ShouldRunTest);
3685 // Gets the number of all tests.
3686 int TestCase::total_test_count() const {
3687 return static_cast<int>(test_info_list_.size());
3690 // Creates a TestCase with the given name.
3694 // name: name of the test case
3695 // a_type_param: the name of the test case's type parameter, or NULL if
3696 // this is not a typed or a type-parameterized test case.
3697 // set_up_tc: pointer to the function that sets up the test case
3698 // tear_down_tc: pointer to the function that tears down the test case
3699 TestCase::TestCase(const char* a_name, const char* a_type_param,
3700 Test::SetUpTestCaseFunc set_up_tc,
3701 Test::TearDownTestCaseFunc tear_down_tc)
3703 type_param_(a_type_param ? new std::string(a_type_param) : NULL),
3704 set_up_tc_(set_up_tc),
3705 tear_down_tc_(tear_down_tc),
3710 // Destructor of TestCase.
3711 TestCase::~TestCase() {
3712 // Deletes every Test in the collection.
3713 ForEach(test_info_list_, internal::Delete<TestInfo>);
3716 // Returns the i-th test among all the tests. i can range from 0 to
3717 // total_test_count() - 1. If i is not in that range, returns NULL.
3718 const TestInfo* TestCase::GetTestInfo(int i) const {
3719 const int index = GetElementOr(test_indices_, i, -1);
3720 return index < 0 ? NULL : test_info_list_[index];
3723 // Returns the i-th test among all the tests. i can range from 0 to
3724 // total_test_count() - 1. If i is not in that range, returns NULL.
3725 TestInfo* TestCase::GetMutableTestInfo(int i) {
3726 const int index = GetElementOr(test_indices_, i, -1);
3727 return index < 0 ? NULL : test_info_list_[index];
3730 // Adds a test to this test case. Will delete the test upon
3731 // destruction of the TestCase object.
3732 void TestCase::AddTestInfo(TestInfo * test_info) {
3733 test_info_list_.push_back(test_info);
3734 test_indices_.push_back(static_cast<int>(test_indices_.size()));
3737 // Runs every test in this TestCase.
3738 void TestCase::Run() {
3739 if (!should_run_) return;
3741 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
3742 impl->set_current_test_case(this);
3744 TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
3746 repeater->OnTestCaseStart(*this);
3747 impl->os_stack_trace_getter()->UponLeavingGTest();
3748 internal::HandleExceptionsInMethodIfSupported(
3749 this, &TestCase::RunSetUpTestCase, "SetUpTestCase()");
3751 const internal::TimeInMillis start = internal::GetTimeInMillis();
3752 for (int i = 0; i < total_test_count(); i++) {
3753 GetMutableTestInfo(i)->Run();
3755 elapsed_time_ = internal::GetTimeInMillis() - start;
3757 impl->os_stack_trace_getter()->UponLeavingGTest();
3758 internal::HandleExceptionsInMethodIfSupported(
3759 this, &TestCase::RunTearDownTestCase, "TearDownTestCase()");
3761 repeater->OnTestCaseEnd(*this);
3762 impl->set_current_test_case(NULL);
3765 // Clears the results of all tests in this test case.
3766 void TestCase::ClearResult() {
3767 ForEach(test_info_list_, TestInfo::ClearTestResult);
3770 // Shuffles the tests in this test case.
3771 void TestCase::ShuffleTests(internal::Random* random) {
3772 Shuffle(random, &test_indices_);
3775 // Restores the test order to before the first shuffle.
3776 void TestCase::UnshuffleTests() {
3777 for (size_t i = 0; i < test_indices_.size(); i++) {
3778 test_indices_[i] = static_cast<int>(i);
3782 // Formats a countable noun. Depending on its quantity, either the
3783 // singular form or the plural form is used. e.g.
3785 // FormatCountableNoun(1, "formula", "formuli") returns "1 formula".
3786 // FormatCountableNoun(5, "book", "books") returns "5 books".
3787 static internal::String FormatCountableNoun(int count,
3788 const char * singular_form,
3789 const char * plural_form) {
3790 return internal::String::Format("%d %s", count,
3791 count == 1 ? singular_form : plural_form);
3794 // Formats the count of tests.
3795 static internal::String FormatTestCount(int test_count) {
3796 return FormatCountableNoun(test_count, "test", "tests");
3799 // Formats the count of test cases.
3800 static internal::String FormatTestCaseCount(int test_case_count) {
3801 return FormatCountableNoun(test_case_count, "test case", "test cases");
3804 // Converts a TestPartResult::Type enum to human-friendly string
3805 // representation. Both kNonFatalFailure and kFatalFailure are translated
3806 // to "Failure", as the user usually doesn't care about the difference
3807 // between the two when viewing the test result.
3808 static const char * TestPartResultTypeToString(TestPartResult::Type type) {
3810 case TestPartResult::kSuccess:
3813 case TestPartResult::kNonFatalFailure:
3814 case TestPartResult::kFatalFailure:
3821 return "Unknown result type";
3825 // Prints a TestPartResult to a String.
3826 static internal::String PrintTestPartResultToString(
3827 const TestPartResult& test_part_result) {
3829 << internal::FormatFileLocation(test_part_result.file_name(),
3830 test_part_result.line_number())
3831 << " " << TestPartResultTypeToString(test_part_result.type())
3832 << test_part_result.message()).GetString();
3835 // Prints a TestPartResult.
3836 static void PrintTestPartResult(const TestPartResult& test_part_result) {
3837 const internal::String& result =
3838 PrintTestPartResultToString(test_part_result);
3839 printf("%s\n", result.c_str());
3841 // If the test program runs in Visual Studio or a debugger, the
3842 // following statements add the test part result message to the Output
3843 // window such that the user can double-click on it to jump to the
3844 // corresponding source code location; otherwise they do nothing.
3845 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
3846 // We don't call OutputDebugString*() on Windows Mobile, as printing
3847 // to stdout is done by OutputDebugString() there already - we don't
3848 // want the same message printed twice.
3849 ::OutputDebugStringA(result.c_str());
3850 ::OutputDebugStringA("\n");
3854 // class PrettyUnitTestResultPrinter
3856 namespace internal {
3865 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
3867 // Returns the character attribute for the given color.
3868 WORD GetColorAttribute(GTestColor color) {
3870 case COLOR_RED: return FOREGROUND_RED;
3871 case COLOR_GREEN: return FOREGROUND_GREEN;
3872 case COLOR_YELLOW: return FOREGROUND_RED | FOREGROUND_GREEN;
3879 // Returns the ANSI color code for the given color. COLOR_DEFAULT is
3880 // an invalid input.
3881 static const char* GetAnsiColorCode(GTestColor color) {
3883 case COLOR_RED: return "1";
3884 case COLOR_GREEN: return "2";
3885 case COLOR_YELLOW: return "3";
3886 default: return NULL;
3890 #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
3892 // Returns true iff Google Test should use colors in the output.
3893 bool ShouldUseColor(bool stdout_is_tty) {
3894 const char* const gtest_color = GTEST_FLAG(color).c_str();
3896 if (String::CaseInsensitiveCStringEquals(gtest_color, "auto")) {
3897 #if GTEST_OS_WINDOWS
3898 // On Windows the TERM variable is usually not set, but the
3899 // console there does support colors.
3900 return stdout_is_tty;
3902 // On non-Windows platforms, we rely on the TERM variable.
3903 const char* const term = posix::GetEnv("TERM");
3904 const bool term_supports_color =
3905 String::CStringEquals(term, "xterm") ||
3906 String::CStringEquals(term, "xterm-color") ||
3907 String::CStringEquals(term, "xterm-256color") ||
3908 String::CStringEquals(term, "screen") ||
3909 String::CStringEquals(term, "linux") ||
3910 String::CStringEquals(term, "cygwin");
3911 return stdout_is_tty && term_supports_color;
3912 #endif // GTEST_OS_WINDOWS
3915 return String::CaseInsensitiveCStringEquals(gtest_color, "yes") ||
3916 String::CaseInsensitiveCStringEquals(gtest_color, "true") ||
3917 String::CaseInsensitiveCStringEquals(gtest_color, "t") ||
3918 String::CStringEquals(gtest_color, "1");
3919 // We take "yes", "true", "t", and "1" as meaning "yes". If the
3920 // value is neither one of these nor "auto", we treat it as "no" to
3924 // Helpers for printing colored strings to stdout. Note that on Windows, we
3925 // cannot simply emit special characters and have the terminal change colors.
3926 // This routine must actually emit the characters rather than return a string
3927 // that would be colored when printed, as can be done on Linux.
3928 static void ColoredPrintf(GTestColor color, const char* fmt, ...) {
3930 va_start(args, fmt);
3932 #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS
3933 const bool use_color = false;
3935 static const bool in_color_mode =
3936 ShouldUseColor(posix::IsATTY(posix::FileNo(stdout)) != 0);
3937 const bool use_color = in_color_mode && (color != COLOR_DEFAULT);
3938 #endif // GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS
3939 // The '!= 0' comparison is necessary to satisfy MSVC 7.1.
3947 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
3948 const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
3950 // Gets the current text color.
3951 CONSOLE_SCREEN_BUFFER_INFO buffer_info;
3952 GetConsoleScreenBufferInfo(stdout_handle, &buffer_info);
3953 const WORD old_color_attrs = buffer_info.wAttributes;
3955 // We need to flush the stream buffers into the console before each
3956 // SetConsoleTextAttribute call lest it affect the text that is already
3957 // printed but has not yet reached the console.
3959 SetConsoleTextAttribute(stdout_handle,
3960 GetColorAttribute(color) | FOREGROUND_INTENSITY);
3964 // Restores the text color.
3965 SetConsoleTextAttribute(stdout_handle, old_color_attrs);
3967 printf("\033[0;3%sm", GetAnsiColorCode(color));
3969 printf("\033[m"); // Resets the terminal to default.
3970 #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
3974 static void PrintFullTestCommentIfPresent(const TestInfo& test_info) {
3975 const char* const type_param = test_info.type_param();
3976 const char* const value_param = test_info.value_param();
3978 if (type_param != NULL || value_param != NULL) {
3980 if (type_param != NULL) {
3981 printf("TypeParam = %s", type_param);
3982 if (value_param != NULL)
3985 if (value_param != NULL) {
3986 printf("GetParam() = %s", value_param);
3991 // This class implements the TestEventListener interface.
3993 // Class PrettyUnitTestResultPrinter is copyable.
3994 class PrettyUnitTestResultPrinter : public TestEventListener {
3996 PrettyUnitTestResultPrinter() {}
3997 static void PrintTestName(const char * test_case, const char * test) {
3998 printf("%s.%s", test_case, test);
4001 // The following methods override what's in the TestEventListener class.
4002 virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {}
4003 virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration);
4004 virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test);
4005 virtual void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) {}
4006 virtual void OnTestCaseStart(const TestCase& test_case);
4007 virtual void OnTestStart(const TestInfo& test_info);
4008 virtual void OnTestPartResult(const TestPartResult& result);
4009 virtual void OnTestEnd(const TestInfo& test_info);
4010 virtual void OnTestCaseEnd(const TestCase& test_case);
4011 virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test);
4012 virtual void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) {}
4013 virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
4014 virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) {}
4017 static void PrintFailedTests(const UnitTest& unit_test);
4020 // Fired before each iteration of tests starts.
4021 void PrettyUnitTestResultPrinter::OnTestIterationStart(
4022 const UnitTest& unit_test, int iteration) {
4023 if (GTEST_FLAG(repeat) != 1)
4024 printf("\nRepeating all tests (iteration %d) . . .\n\n", iteration + 1);
4026 const char* const filter = GTEST_FLAG(filter).c_str();
4028 // Prints the filter if it's not *. This reminds the user that some
4029 // tests may be skipped.
4030 if (!internal::String::CStringEquals(filter, kUniversalFilter)) {
4031 ColoredPrintf(COLOR_YELLOW,
4032 "Note: %s filter = %s\n", GTEST_NAME_, filter);
4035 if (internal::ShouldShard(kTestTotalShards, kTestShardIndex, false)) {
4036 const Int32 shard_index = Int32FromEnvOrDie(kTestShardIndex, -1);
4037 ColoredPrintf(COLOR_YELLOW,
4038 "Note: This is test shard %d of %s.\n",
4039 static_cast<int>(shard_index) + 1,
4040 internal::posix::GetEnv(kTestTotalShards));
4043 if (GTEST_FLAG(shuffle)) {
4044 ColoredPrintf(COLOR_YELLOW,
4045 "Note: Randomizing tests' orders with a seed of %d .\n",
4046 unit_test.random_seed());
4049 ColoredPrintf(COLOR_GREEN, "[==========] ");
4050 printf("Running %s from %s.\n",
4051 FormatTestCount(unit_test.test_to_run_count()).c_str(),
4052 FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str());
4056 void PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart(
4057 const UnitTest& /*unit_test*/) {
4058 ColoredPrintf(COLOR_GREEN, "[----------] ");
4059 printf("Global test environment set-up.\n");
4063 void PrettyUnitTestResultPrinter::OnTestCaseStart(const TestCase& test_case) {
4064 const internal::String counts =
4065 FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
4066 ColoredPrintf(COLOR_GREEN, "[----------] ");
4067 printf("%s from %s", counts.c_str(), test_case.name());
4068 if (test_case.type_param() == NULL) {
4071 printf(", where TypeParam = %s\n", test_case.type_param());
4076 void PrettyUnitTestResultPrinter::OnTestStart(const TestInfo& test_info) {
4077 ColoredPrintf(COLOR_GREEN, "[ RUN ] ");
4078 PrintTestName(test_info.test_case_name(), test_info.name());
4083 // Called after an assertion failure.
4084 void PrettyUnitTestResultPrinter::OnTestPartResult(
4085 const TestPartResult& result) {
4086 // If the test part succeeded, we don't need to do anything.
4087 if (result.type() == TestPartResult::kSuccess)
4090 // Print failure message from the assertion (e.g. expected this and got that).
4091 PrintTestPartResult(result);
4095 void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) {
4096 if (test_info.result()->Passed()) {
4097 ColoredPrintf(COLOR_GREEN, "[ OK ] ");
4099 ColoredPrintf(COLOR_RED, "[ FAILED ] ");
4101 PrintTestName(test_info.test_case_name(), test_info.name());
4102 if (test_info.result()->Failed())
4103 PrintFullTestCommentIfPresent(test_info);
4105 if (GTEST_FLAG(print_time)) {
4106 printf(" (%s ms)\n", internal::StreamableToString(
4107 test_info.result()->elapsed_time()).c_str());
4114 void PrettyUnitTestResultPrinter::OnTestCaseEnd(const TestCase& test_case) {
4115 if (!GTEST_FLAG(print_time)) return;
4117 const internal::String counts =
4118 FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
4119 ColoredPrintf(COLOR_GREEN, "[----------] ");
4120 printf("%s from %s (%s ms total)\n\n",
4121 counts.c_str(), test_case.name(),
4122 internal::StreamableToString(test_case.elapsed_time()).c_str());
4126 void PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart(
4127 const UnitTest& /*unit_test*/) {
4128 ColoredPrintf(COLOR_GREEN, "[----------] ");
4129 printf("Global test environment tear-down\n");
4133 // Internal helper for printing the list of failed tests.
4134 void PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest& unit_test) {
4135 const int failed_test_count = unit_test.failed_test_count();
4136 if (failed_test_count == 0) {
4140 for (int i = 0; i < unit_test.total_test_case_count(); ++i) {
4141 const TestCase& test_case = *unit_test.GetTestCase(i);
4142 if (!test_case.should_run() || (test_case.failed_test_count() == 0)) {
4145 for (int j = 0; j < test_case.total_test_count(); ++j) {
4146 const TestInfo& test_info = *test_case.GetTestInfo(j);
4147 if (!test_info.should_run() || test_info.result()->Passed()) {
4150 ColoredPrintf(COLOR_RED, "[ FAILED ] ");
4151 printf("%s.%s", test_case.name(), test_info.name());
4152 PrintFullTestCommentIfPresent(test_info);
4158 void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
4159 int /*iteration*/) {
4160 ColoredPrintf(COLOR_GREEN, "[==========] ");
4161 printf("%s from %s ran.",
4162 FormatTestCount(unit_test.test_to_run_count()).c_str(),
4163 FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str());
4164 if (GTEST_FLAG(print_time)) {
4165 printf(" (%s ms total)",
4166 internal::StreamableToString(unit_test.elapsed_time()).c_str());
4169 ColoredPrintf(COLOR_GREEN, "[ PASSED ] ");
4170 printf("%s.\n", FormatTestCount(unit_test.successful_test_count()).c_str());
4172 int num_failures = unit_test.failed_test_count();
4173 if (!unit_test.Passed()) {
4174 const int failed_test_count = unit_test.failed_test_count();
4175 ColoredPrintf(COLOR_RED, "[ FAILED ] ");
4176 printf("%s, listed below:\n", FormatTestCount(failed_test_count).c_str());
4177 PrintFailedTests(unit_test);
4178 printf("\n%2d FAILED %s\n", num_failures,
4179 num_failures == 1 ? "TEST" : "TESTS");
4182 int num_disabled = unit_test.disabled_test_count();
4183 if (num_disabled && !GTEST_FLAG(also_run_disabled_tests)) {
4184 if (!num_failures) {
4185 printf("\n"); // Add a spacer if no FAILURE banner is displayed.
4187 ColoredPrintf(COLOR_YELLOW,
4188 " YOU HAVE %d DISABLED %s\n\n",
4190 num_disabled == 1 ? "TEST" : "TESTS");
4192 // Ensure that Google Test output is printed before, e.g., heapchecker output.
4196 // End PrettyUnitTestResultPrinter
4198 // class TestEventRepeater
4200 // This class forwards events to other event listeners.
4201 class TestEventRepeater : public TestEventListener {
4203 TestEventRepeater() : forwarding_enabled_(true) {}
4204 virtual ~TestEventRepeater();
4205 void Append(TestEventListener *listener);
4206 TestEventListener* Release(TestEventListener* listener);
4208 // Controls whether events will be forwarded to listeners_. Set to false
4209 // in death test child processes.
4210 bool forwarding_enabled() const { return forwarding_enabled_; }
4211 void set_forwarding_enabled(bool enable) { forwarding_enabled_ = enable; }
4213 virtual void OnTestProgramStart(const UnitTest& unit_test);
4214 virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration);
4215 virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test);
4216 virtual void OnEnvironmentsSetUpEnd(const UnitTest& unit_test);
4217 virtual void OnTestCaseStart(const TestCase& test_case);
4218 virtual void OnTestStart(const TestInfo& test_info);
4219 virtual void OnTestPartResult(const TestPartResult& result);
4220 virtual void OnTestEnd(const TestInfo& test_info);
4221 virtual void OnTestCaseEnd(const TestCase& test_case);
4222 virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test);
4223 virtual void OnEnvironmentsTearDownEnd(const UnitTest& unit_test);
4224 virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
4225 virtual void OnTestProgramEnd(const UnitTest& unit_test);
4228 // Controls whether events will be forwarded to listeners_. Set to false
4229 // in death test child processes.
4230 bool forwarding_enabled_;
4231 // The list of listeners that receive events.
4232 std::vector<TestEventListener*> listeners_;
4234 GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventRepeater);
4237 TestEventRepeater::~TestEventRepeater() {
4238 ForEach(listeners_, Delete<TestEventListener>);
4241 void TestEventRepeater::Append(TestEventListener *listener) {
4242 listeners_.push_back(listener);
4245 // TODO(vladl@google.com): Factor the search functionality into Vector::Find.
4246 TestEventListener* TestEventRepeater::Release(TestEventListener *listener) {
4247 for (size_t i = 0; i < listeners_.size(); ++i) {
4248 if (listeners_[i] == listener) {
4249 listeners_.erase(listeners_.begin() + i);
4257 // Since most methods are very similar, use macros to reduce boilerplate.
4258 // This defines a member that forwards the call to all listeners.
4259 #define GTEST_REPEATER_METHOD_(Name, Type) \
4260 void TestEventRepeater::Name(const Type& parameter) { \
4261 if (forwarding_enabled_) { \
4262 for (size_t i = 0; i < listeners_.size(); i++) { \
4263 listeners_[i]->Name(parameter); \
4267 // This defines a member that forwards the call to all listeners in reverse
4269 #define GTEST_REVERSE_REPEATER_METHOD_(Name, Type) \
4270 void TestEventRepeater::Name(const Type& parameter) { \
4271 if (forwarding_enabled_) { \
4272 for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) { \
4273 listeners_[i]->Name(parameter); \
4278 GTEST_REPEATER_METHOD_(OnTestProgramStart, UnitTest)
4279 GTEST_REPEATER_METHOD_(OnEnvironmentsSetUpStart, UnitTest)
4280 GTEST_REPEATER_METHOD_(OnTestCaseStart, TestCase)
4281 GTEST_REPEATER_METHOD_(OnTestStart, TestInfo)
4282 GTEST_REPEATER_METHOD_(OnTestPartResult, TestPartResult)
4283 GTEST_REPEATER_METHOD_(OnEnvironmentsTearDownStart, UnitTest)
4284 GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsSetUpEnd, UnitTest)
4285 GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsTearDownEnd, UnitTest)
4286 GTEST_REVERSE_REPEATER_METHOD_(OnTestEnd, TestInfo)
4287 GTEST_REVERSE_REPEATER_METHOD_(OnTestCaseEnd, TestCase)
4288 GTEST_REVERSE_REPEATER_METHOD_(OnTestProgramEnd, UnitTest)
4290 #undef GTEST_REPEATER_METHOD_
4291 #undef GTEST_REVERSE_REPEATER_METHOD_
4293 void TestEventRepeater::OnTestIterationStart(const UnitTest& unit_test,
4295 if (forwarding_enabled_) {
4296 for (size_t i = 0; i < listeners_.size(); i++) {
4297 listeners_[i]->OnTestIterationStart(unit_test, iteration);
4302 void TestEventRepeater::OnTestIterationEnd(const UnitTest& unit_test,
4304 if (forwarding_enabled_) {
4305 for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) {
4306 listeners_[i]->OnTestIterationEnd(unit_test, iteration);
4311 // End TestEventRepeater
4313 // This class generates an XML output file.
4314 class XmlUnitTestResultPrinter : public EmptyTestEventListener {
4316 explicit XmlUnitTestResultPrinter(const char* output_file);
4318 virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
4321 // Is c a whitespace character that is normalized to a space character
4322 // when it appears in an XML attribute value?
4323 static bool IsNormalizableWhitespace(char c) {
4324 return c == 0x9 || c == 0xA || c == 0xD;
4327 // May c appear in a well-formed XML document?
4328 static bool IsValidXmlCharacter(char c) {
4329 return IsNormalizableWhitespace(c) || c >= 0x20;
4332 // Returns an XML-escaped copy of the input string str. If
4333 // is_attribute is true, the text is meant to appear as an attribute
4334 // value, and normalizable whitespace is preserved by replacing it
4335 // with character references.
4336 static String EscapeXml(const char* str, bool is_attribute);
4338 // Returns the given string with all characters invalid in XML removed.
4339 static string RemoveInvalidXmlCharacters(const string& str);
4341 // Convenience wrapper around EscapeXml when str is an attribute value.
4342 static String EscapeXmlAttribute(const char* str) {
4343 return EscapeXml(str, true);
4346 // Convenience wrapper around EscapeXml when str is not an attribute value.
4347 static String EscapeXmlText(const char* str) { return EscapeXml(str, false); }
4349 // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
4350 static void OutputXmlCDataSection(::std::ostream* stream, const char* data);
4352 // Streams an XML representation of a TestInfo object.
4353 static void OutputXmlTestInfo(::std::ostream* stream,
4354 const char* test_case_name,
4355 const TestInfo& test_info);
4357 // Prints an XML representation of a TestCase object
4358 static void PrintXmlTestCase(FILE* out, const TestCase& test_case);
4360 // Prints an XML summary of unit_test to output stream out.
4361 static void PrintXmlUnitTest(FILE* out, const UnitTest& unit_test);
4363 // Produces a string representing the test properties in a result as space
4364 // delimited XML attributes based on the property key="value" pairs.
4365 // When the String is not empty, it includes a space at the beginning,
4366 // to delimit this attribute from prior attributes.
4367 static String TestPropertiesAsXmlAttributes(const TestResult& result);
4370 const String output_file_;
4372 GTEST_DISALLOW_COPY_AND_ASSIGN_(XmlUnitTestResultPrinter);
4375 // Creates a new XmlUnitTestResultPrinter.
4376 XmlUnitTestResultPrinter::XmlUnitTestResultPrinter(const char* output_file)
4377 : output_file_(output_file) {
4378 if (output_file_.c_str() == NULL || output_file_.empty()) {
4379 fprintf(stderr, "XML output file may not be null\n");
4385 // Called after the unit test ends.
4386 void XmlUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
4387 int /*iteration*/) {
4388 FILE* xmlout = NULL;
4389 FilePath output_file(output_file_);
4390 FilePath output_dir(output_file.RemoveFileName());
4392 if (output_dir.CreateDirectoriesRecursively()) {
4393 xmlout = posix::FOpen(output_file_.c_str(), "w");
4395 if (xmlout == NULL) {
4396 // TODO(wan): report the reason of the failure.
4398 // We don't do it for now as:
4400 // 1. There is no urgent need for it.
4401 // 2. It's a bit involved to make the errno variable thread-safe on
4402 // all three operating systems (Linux, Windows, and Mac OS).
4403 // 3. To interpret the meaning of errno in a thread-safe way,
4404 // we need the strerror_r() function, which is not available on
4407 "Unable to open file \"%s\"\n",
4408 output_file_.c_str());
4412 PrintXmlUnitTest(xmlout, unit_test);
4416 // Returns an XML-escaped copy of the input string str. If is_attribute
4417 // is true, the text is meant to appear as an attribute value, and
4418 // normalizable whitespace is preserved by replacing it with character
4421 // Invalid XML characters in str, if any, are stripped from the output.
4422 // It is expected that most, if not all, of the text processed by this
4423 // module will consist of ordinary English text.
4424 // If this module is ever modified to produce version 1.1 XML output,
4425 // most invalid characters can be retained using character references.
4426 // TODO(wan): It might be nice to have a minimally invasive, human-readable
4427 // escaping scheme for invalid characters, rather than dropping them.
4428 String XmlUnitTestResultPrinter::EscapeXml(const char* str, bool is_attribute) {
4432 for (const char* src = str; *src; ++src) {
4456 if (IsValidXmlCharacter(*src)) {
4457 if (is_attribute && IsNormalizableWhitespace(*src))
4458 m << String::Format("&#x%02X;", unsigned(*src));
4467 return m.GetString();
4470 // Returns the given string with all characters invalid in XML removed.
4471 // Currently invalid characters are dropped from the string. An
4472 // alternative is to replace them with certain characters such as . or ?.
4473 string XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters(const string& str) {
4475 output.reserve(str.size());
4476 for (string::const_iterator it = str.begin(); it != str.end(); ++it)
4477 if (IsValidXmlCharacter(*it))
4478 output.push_back(*it);
4483 // The following routines generate an XML representation of a UnitTest
4486 // This is how Google Test concepts map to the DTD:
4488 // <testsuites name="AllTests"> <-- corresponds to a UnitTest object
4489 // <testsuite name="testcase-name"> <-- corresponds to a TestCase object
4490 // <testcase name="test-name"> <-- corresponds to a TestInfo object
4491 // <failure message="...">...</failure>
4492 // <failure message="...">...</failure>
4493 // <failure message="...">...</failure>
4494 // <-- individual assertion failures
4499 // Formats the given time in milliseconds as seconds.
4500 std::string FormatTimeInMillisAsSeconds(TimeInMillis ms) {
4501 ::std::stringstream ss;
4506 // Converts the given epoch time in milliseconds to a date string in the ISO
4507 // 8601 format, without the timezone information.
4508 std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms) {
4509 // Using non-reentrant version as localtime_r is not portable.
4510 time_t seconds = static_cast<time_t>(ms / 1000);
4512 # pragma warning(push) // Saves the current warning state.
4513 # pragma warning(disable:4996) // Temporarily disables warning 4996
4514 // (function or variable may be unsafe).
4515 const struct tm* const time_struct = localtime(&seconds); // NOLINT
4516 # pragma warning(pop) // Restores the warning state again.
4518 const struct tm* const time_struct = localtime(&seconds); // NOLINT
4520 if (time_struct == NULL)
4521 return ""; // Invalid ms value
4523 return String::Format("%d-%02d-%02dT%02d:%02d:%02d", // YYYY-MM-DDThh:mm:ss
4524 time_struct->tm_year + 1900,
4525 time_struct->tm_mon + 1,
4526 time_struct->tm_mday,
4527 time_struct->tm_hour,
4528 time_struct->tm_min,
4529 time_struct->tm_sec);
4532 // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
4533 void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream,
4535 const char* segment = data;
4536 *stream << "<![CDATA[";
4538 const char* const next_segment = strstr(segment, "]]>");
4539 if (next_segment != NULL) {
4541 segment, static_cast<std::streamsize>(next_segment - segment));
4542 *stream << "]]>]]><![CDATA[";
4543 segment = next_segment + strlen("]]>");
4552 // Prints an XML representation of a TestInfo object.
4553 // TODO(wan): There is also value in printing properties with the plain printer.
4554 void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream,
4555 const char* test_case_name,
4556 const TestInfo& test_info) {
4557 const TestResult& result = *test_info.result();
4558 *stream << " <testcase name=\""
4559 << EscapeXmlAttribute(test_info.name()).c_str() << "\"";
4561 if (test_info.value_param() != NULL) {
4562 *stream << " value_param=\"" << EscapeXmlAttribute(test_info.value_param())
4565 if (test_info.type_param() != NULL) {
4566 *stream << " type_param=\"" << EscapeXmlAttribute(test_info.type_param())
4570 *stream << " status=\""
4571 << (test_info.should_run() ? "run" : "notrun")
4573 << FormatTimeInMillisAsSeconds(result.elapsed_time())
4574 << "\" classname=\"" << EscapeXmlAttribute(test_case_name).c_str()
4575 << "\"" << TestPropertiesAsXmlAttributes(result).c_str();
4578 for (int i = 0; i < result.total_part_count(); ++i) {
4579 const TestPartResult& part = result.GetTestPartResult(i);
4580 if (part.failed()) {
4581 if (++failures == 1) {
4584 const string location = internal::FormatCompilerIndependentFileLocation(
4585 part.file_name(), part.line_number());
4586 const string summary = location + "\n" + part.summary();
4587 *stream << " <failure message=\""
4588 << EscapeXmlAttribute(summary.c_str())
4590 const string detail = location + "\n" + part.message();
4591 OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str());
4592 *stream << "</failure>\n";
4599 *stream << " </testcase>\n";
4602 // Prints an XML representation of a TestCase object
4603 void XmlUnitTestResultPrinter::PrintXmlTestCase(FILE* out,
4604 const TestCase& test_case) {
4606 " <testsuite name=\"%s\" tests=\"%d\" failures=\"%d\" "
4608 EscapeXmlAttribute(test_case.name()).c_str(),
4609 test_case.total_test_count(),
4610 test_case.failed_test_count(),
4611 test_case.disabled_test_count());
4613 "errors=\"0\" time=\"%s\">\n",
4614 FormatTimeInMillisAsSeconds(test_case.elapsed_time()).c_str());
4615 for (int i = 0; i < test_case.total_test_count(); ++i) {
4616 ::std::stringstream stream;
4617 OutputXmlTestInfo(&stream, test_case.name(), *test_case.GetTestInfo(i));
4618 fprintf(out, "%s", StringStreamToString(&stream).c_str());
4620 fprintf(out, " </testsuite>\n");
4623 // Prints an XML summary of unit_test to output stream out.
4624 void XmlUnitTestResultPrinter::PrintXmlUnitTest(FILE* out,
4625 const UnitTest& unit_test) {
4626 fprintf(out, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
4628 "<testsuites tests=\"%d\" failures=\"%d\" disabled=\"%d\" "
4629 "errors=\"0\" timestamp=\"%s\" time=\"%s\" ",
4630 unit_test.total_test_count(),
4631 unit_test.failed_test_count(),
4632 unit_test.disabled_test_count(),
4633 FormatEpochTimeInMillisAsIso8601(unit_test.start_timestamp()).c_str(),
4634 FormatTimeInMillisAsSeconds(unit_test.elapsed_time()).c_str());
4635 if (GTEST_FLAG(shuffle)) {
4636 fprintf(out, "random_seed=\"%d\" ", unit_test.random_seed());
4638 fprintf(out, "name=\"AllTests\">\n");
4639 for (int i = 0; i < unit_test.total_test_case_count(); ++i)
4640 PrintXmlTestCase(out, *unit_test.GetTestCase(i));
4641 fprintf(out, "</testsuites>\n");
4644 // Produces a string representing the test properties in a result as space
4645 // delimited XML attributes based on the property key="value" pairs.
4646 String XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes(
4647 const TestResult& result) {
4649 for (int i = 0; i < result.test_property_count(); ++i) {
4650 const TestProperty& property = result.GetTestProperty(i);
4651 attributes << " " << property.key() << "="
4652 << "\"" << EscapeXmlAttribute(property.value()) << "\"";
4654 return attributes.GetString();
4657 // End XmlUnitTestResultPrinter
4659 #if GTEST_CAN_STREAM_RESULTS_
4661 // Streams test results to the given port on the given host machine.
4662 class StreamingListener : public EmptyTestEventListener {
4664 // Escapes '=', '&', '%', and '\n' characters in str as "%xx".
4665 static string UrlEncode(const char* str);
4667 StreamingListener(const string& host, const string& port)
4668 : sockfd_(-1), host_name_(host), port_num_(port) {
4670 Send("gtest_streaming_protocol_version=1.0\n");
4673 virtual ~StreamingListener() {
4678 void OnTestProgramStart(const UnitTest& /* unit_test */) {
4679 Send("event=TestProgramStart\n");
4682 void OnTestProgramEnd(const UnitTest& unit_test) {
4683 // Note that Google Test current only report elapsed time for each
4684 // test iteration, not for the entire test program.
4685 Send(String::Format("event=TestProgramEnd&passed=%d\n",
4686 unit_test.Passed()));
4688 // Notify the streaming server to stop.
4692 void OnTestIterationStart(const UnitTest& /* unit_test */, int iteration) {
4693 Send(String::Format("event=TestIterationStart&iteration=%d\n",
4697 void OnTestIterationEnd(const UnitTest& unit_test, int /* iteration */) {
4698 Send(String::Format("event=TestIterationEnd&passed=%d&elapsed_time=%sms\n",
4700 StreamableToString(unit_test.elapsed_time()).c_str()));
4703 void OnTestCaseStart(const TestCase& test_case) {
4704 Send(String::Format("event=TestCaseStart&name=%s\n", test_case.name()));
4707 void OnTestCaseEnd(const TestCase& test_case) {
4708 Send(String::Format("event=TestCaseEnd&passed=%d&elapsed_time=%sms\n",
4710 StreamableToString(test_case.elapsed_time()).c_str()));
4713 void OnTestStart(const TestInfo& test_info) {
4714 Send(String::Format("event=TestStart&name=%s\n", test_info.name()));
4717 void OnTestEnd(const TestInfo& test_info) {
4718 Send(String::Format(
4719 "event=TestEnd&passed=%d&elapsed_time=%sms\n",
4720 (test_info.result())->Passed(),
4721 StreamableToString((test_info.result())->elapsed_time()).c_str()));
4724 void OnTestPartResult(const TestPartResult& test_part_result) {
4725 const char* file_name = test_part_result.file_name();
4726 if (file_name == NULL)
4728 Send(String::Format("event=TestPartResult&file=%s&line=%d&message=",
4729 UrlEncode(file_name).c_str(),
4730 test_part_result.line_number()));
4731 Send(UrlEncode(test_part_result.message()) + "\n");
4735 // Creates a client socket and connects to the server.
4736 void MakeConnection();
4738 // Closes the socket.
4739 void CloseConnection() {
4740 GTEST_CHECK_(sockfd_ != -1)
4741 << "CloseConnection() can be called only when there is a connection.";
4747 // Sends a string to the socket.
4748 void Send(const string& message) {
4749 GTEST_CHECK_(sockfd_ != -1)
4750 << "Send() can be called only when there is a connection.";
4752 const int len = static_cast<int>(message.length());
4753 if (write(sockfd_, message.c_str(), len) != len) {
4755 << "stream_result_to: failed to stream to "
4756 << host_name_ << ":" << port_num_;
4760 int sockfd_; // socket file descriptor
4761 const string host_name_;
4762 const string port_num_;
4764 GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamingListener);
4765 }; // class StreamingListener
4767 // Checks if str contains '=', '&', '%' or '\n' characters. If yes,
4768 // replaces them by "%xx" where xx is their hexadecimal value. For
4769 // example, replaces "=" with "%3D". This algorithm is O(strlen(str))
4770 // in both time and space -- important as the input str may contain an
4771 // arbitrarily long test failure message and stack trace.
4772 string StreamingListener::UrlEncode(const char* str) {
4774 result.reserve(strlen(str) + 1);
4775 for (char ch = *str; ch != '\0'; ch = *++str) {
4781 result.append(String::Format("%%%02x", static_cast<unsigned char>(ch)));
4784 result.push_back(ch);
4791 void StreamingListener::MakeConnection() {
4792 GTEST_CHECK_(sockfd_ == -1)
4793 << "MakeConnection() can't be called when there is already a connection.";
4796 memset(&hints, 0, sizeof(hints));
4797 hints.ai_family = AF_UNSPEC; // To allow both IPv4 and IPv6 addresses.
4798 hints.ai_socktype = SOCK_STREAM;
4799 addrinfo* servinfo = NULL;
4801 // Use the getaddrinfo() to get a linked list of IP addresses for
4802 // the given host name.
4803 const int error_num = getaddrinfo(
4804 host_name_.c_str(), port_num_.c_str(), &hints, &servinfo);
4805 if (error_num != 0) {
4806 GTEST_LOG_(WARNING) << "stream_result_to: getaddrinfo() failed: "
4807 << gai_strerror(error_num);
4810 // Loop through all the results and connect to the first we can.
4811 for (addrinfo* cur_addr = servinfo; sockfd_ == -1 && cur_addr != NULL;
4812 cur_addr = cur_addr->ai_next) {
4814 cur_addr->ai_family, cur_addr->ai_socktype, cur_addr->ai_protocol);
4815 if (sockfd_ != -1) {
4816 // Connect the client socket to the server socket.
4817 if (connect(sockfd_, cur_addr->ai_addr, cur_addr->ai_addrlen) == -1) {
4824 freeaddrinfo(servinfo); // all done with this structure
4826 if (sockfd_ == -1) {
4827 GTEST_LOG_(WARNING) << "stream_result_to: failed to connect to "
4828 << host_name_ << ":" << port_num_;
4832 // End of class Streaming Listener
4833 #endif // GTEST_CAN_STREAM_RESULTS__
4835 // Class ScopedTrace
4837 // Pushes the given source file location and message onto a per-thread
4838 // trace stack maintained by Google Test.
4839 ScopedTrace::ScopedTrace(const char* file, int line, const Message& message)
4840 GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) {
4844 trace.message = message.GetString();
4846 UnitTest::GetInstance()->PushGTestTrace(trace);
4849 // Pops the info pushed by the c'tor.
4850 ScopedTrace::~ScopedTrace()
4851 GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) {
4852 UnitTest::GetInstance()->PopGTestTrace();
4856 // class OsStackTraceGetter
4858 // Returns the current OS stack trace as a String. Parameters:
4860 // max_depth - the maximum number of stack frames to be included
4862 // skip_count - the number of top frames to be skipped; doesn't count
4863 // against max_depth.
4865 String OsStackTraceGetter::CurrentStackTrace(int /* max_depth */,
4866 int /* skip_count */)
4867 GTEST_LOCK_EXCLUDED_(mutex_) {
4871 void OsStackTraceGetter::UponLeavingGTest()
4872 GTEST_LOCK_EXCLUDED_(mutex_) {
4876 OsStackTraceGetter::kElidedFramesMarker =
4877 "... " GTEST_NAME_ " internal frames ...";
4879 } // namespace internal
4881 // class TestEventListeners
4883 TestEventListeners::TestEventListeners()
4884 : repeater_(new internal::TestEventRepeater()),
4885 default_result_printer_(NULL),
4886 default_xml_generator_(NULL) {
4889 TestEventListeners::~TestEventListeners() { delete repeater_; }
4891 // Returns the standard listener responsible for the default console
4892 // output. Can be removed from the listeners list to shut down default
4893 // console output. Note that removing this object from the listener list
4894 // with Release transfers its ownership to the user.
4895 void TestEventListeners::Append(TestEventListener* listener) {
4896 repeater_->Append(listener);
4899 // Removes the given event listener from the list and returns it. It then
4900 // becomes the caller's responsibility to delete the listener. Returns
4901 // NULL if the listener is not found in the list.
4902 TestEventListener* TestEventListeners::Release(TestEventListener* listener) {
4903 if (listener == default_result_printer_)
4904 default_result_printer_ = NULL;
4905 else if (listener == default_xml_generator_)
4906 default_xml_generator_ = NULL;
4907 return repeater_->Release(listener);
4910 // Returns repeater that broadcasts the TestEventListener events to all
4912 TestEventListener* TestEventListeners::repeater() { return repeater_; }
4914 // Sets the default_result_printer attribute to the provided listener.
4915 // The listener is also added to the listener list and previous
4916 // default_result_printer is removed from it and deleted. The listener can
4917 // also be NULL in which case it will not be added to the list. Does
4918 // nothing if the previous and the current listener objects are the same.
4919 void TestEventListeners::SetDefaultResultPrinter(TestEventListener* listener) {
4920 if (default_result_printer_ != listener) {
4921 // It is an error to pass this method a listener that is already in the
4923 delete Release(default_result_printer_);
4924 default_result_printer_ = listener;
4925 if (listener != NULL)
4930 // Sets the default_xml_generator attribute to the provided listener. The
4931 // listener is also added to the listener list and previous
4932 // default_xml_generator is removed from it and deleted. The listener can
4933 // also be NULL in which case it will not be added to the list. Does
4934 // nothing if the previous and the current listener objects are the same.
4935 void TestEventListeners::SetDefaultXmlGenerator(TestEventListener* listener) {
4936 if (default_xml_generator_ != listener) {
4937 // It is an error to pass this method a listener that is already in the
4939 delete Release(default_xml_generator_);
4940 default_xml_generator_ = listener;
4941 if (listener != NULL)
4946 // Controls whether events will be forwarded by the repeater to the
4947 // listeners in the list.
4948 bool TestEventListeners::EventForwardingEnabled() const {
4949 return repeater_->forwarding_enabled();
4952 void TestEventListeners::SuppressEventForwarding() {
4953 repeater_->set_forwarding_enabled(false);
4958 // Gets the singleton UnitTest object. The first time this method is
4959 // called, a UnitTest object is constructed and returned. Consecutive
4960 // calls will return the same object.
4962 // We don't protect this under mutex_ as a user is not supposed to
4963 // call this before main() starts, from which point on the return
4964 // value will never change.
4965 UnitTest * UnitTest::GetInstance() {
4966 // When compiled with MSVC 7.1 in optimized mode, destroying the
4967 // UnitTest object upon exiting the program messes up the exit code,
4968 // causing successful tests to appear failed. We have to use a
4969 // different implementation in this case to bypass the compiler bug.
4970 // This implementation makes the compiler happy, at the cost of
4971 // leaking the UnitTest object.
4973 // CodeGear C++Builder insists on a public destructor for the
4974 // default implementation. Use this implementation to keep good OO
4975 // design with private destructor.
4977 #if (defined(_MSC_VER) && _MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)
4978 static UnitTest* const instance = new UnitTest;
4981 static UnitTest instance;
4983 #endif // (defined(_MSC_VER) && _MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)
4986 // Gets the number of successful test cases.
4987 int UnitTest::successful_test_case_count() const {
4988 return impl()->successful_test_case_count();
4991 // Gets the number of failed test cases.
4992 int UnitTest::failed_test_case_count() const {
4993 return impl()->failed_test_case_count();
4996 // Gets the number of all test cases.
4997 int UnitTest::total_test_case_count() const {
4998 return impl()->total_test_case_count();
5001 // Gets the number of all test cases that contain at least one test
5003 int UnitTest::test_case_to_run_count() const {
5004 return impl()->test_case_to_run_count();
5007 // Gets the number of successful tests.
5008 int UnitTest::successful_test_count() const {
5009 return impl()->successful_test_count();
5012 // Gets the number of failed tests.
5013 int UnitTest::failed_test_count() const { return impl()->failed_test_count(); }
5015 // Gets the number of disabled tests.
5016 int UnitTest::disabled_test_count() const {
5017 return impl()->disabled_test_count();
5020 // Gets the number of all tests.
5021 int UnitTest::total_test_count() const { return impl()->total_test_count(); }
5023 // Gets the number of tests that should run.
5024 int UnitTest::test_to_run_count() const { return impl()->test_to_run_count(); }
5026 // Gets the time of the test program start, in ms from the start of the
5028 internal::TimeInMillis UnitTest::start_timestamp() const {
5029 return impl()->start_timestamp();
5032 // Gets the elapsed time, in milliseconds.
5033 internal::TimeInMillis UnitTest::elapsed_time() const {
5034 return impl()->elapsed_time();
5037 // Returns true iff the unit test passed (i.e. all test cases passed).
5038 bool UnitTest::Passed() const { return impl()->Passed(); }
5040 // Returns true iff the unit test failed (i.e. some test case failed
5041 // or something outside of all tests failed).
5042 bool UnitTest::Failed() const { return impl()->Failed(); }
5044 // Gets the i-th test case among all the test cases. i can range from 0 to
5045 // total_test_case_count() - 1. If i is not in that range, returns NULL.
5046 const TestCase* UnitTest::GetTestCase(int i) const {
5047 return impl()->GetTestCase(i);
5050 // Gets the i-th test case among all the test cases. i can range from 0 to
5051 // total_test_case_count() - 1. If i is not in that range, returns NULL.
5052 TestCase* UnitTest::GetMutableTestCase(int i) {
5053 return impl()->GetMutableTestCase(i);
5056 // Returns the list of event listeners that can be used to track events
5057 // inside Google Test.
5058 TestEventListeners& UnitTest::listeners() {
5059 return *impl()->listeners();
5062 // Registers and returns a global test environment. When a test
5063 // program is run, all global test environments will be set-up in the
5064 // order they were registered. After all tests in the program have
5065 // finished, all global test environments will be torn-down in the
5066 // *reverse* order they were registered.
5068 // The UnitTest object takes ownership of the given environment.
5070 // We don't protect this under mutex_, as we only support calling it
5071 // from the main thread.
5072 Environment* UnitTest::AddEnvironment(Environment* env) {
5077 impl_->environments().push_back(env);
5081 // Adds a TestPartResult to the current TestResult object. All Google Test
5082 // assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) eventually call
5083 // this to report their results. The user code should use the
5084 // assertion macros instead of calling this directly.
5085 void UnitTest::AddTestPartResult(
5086 TestPartResult::Type result_type,
5087 const char* file_name,
5089 const internal::String& message,
5090 const internal::String& os_stack_trace)
5091 GTEST_LOCK_EXCLUDED_(mutex_) {
5095 internal::MutexLock lock(&mutex_);
5096 if (impl_->gtest_trace_stack().size() > 0) {
5097 msg << "\n" << GTEST_NAME_ << " trace:";
5099 for (int i = static_cast<int>(impl_->gtest_trace_stack().size());
5101 const internal::TraceInfo& trace = impl_->gtest_trace_stack()[i - 1];
5102 msg << "\n" << internal::FormatFileLocation(trace.file, trace.line)
5103 << " " << trace.message;
5107 if (os_stack_trace.c_str() != NULL && !os_stack_trace.empty()) {
5108 msg << internal::kStackTraceMarker << os_stack_trace;
5111 const TestPartResult result =
5112 TestPartResult(result_type, file_name, line_number,
5113 msg.GetString().c_str());
5114 impl_->GetTestPartResultReporterForCurrentThread()->
5115 ReportTestPartResult(result);
5117 if (result_type != TestPartResult::kSuccess) {
5118 // gtest_break_on_failure takes precedence over
5119 // gtest_throw_on_failure. This allows a user to set the latter
5120 // in the code (perhaps in order to use Google Test assertions
5121 // with another testing framework) and specify the former on the
5122 // command line for debugging.
5123 if (GTEST_FLAG(break_on_failure)) {
5124 #if GTEST_OS_WINDOWS
5125 // Using DebugBreak on Windows allows gtest to still break into a debugger
5126 // when a failure happens and both the --gtest_break_on_failure and
5127 // the --gtest_catch_exceptions flags are specified.
5130 // Dereference NULL through a volatile pointer to prevent the compiler
5131 // from removing. We use this rather than abort() or __builtin_trap() for
5132 // portability: Symbian doesn't implement abort() well, and some debuggers
5133 // don't correctly trap abort().
5134 *static_cast<volatile int*>(NULL) = 1;
5135 #endif // GTEST_OS_WINDOWS
5136 } else if (GTEST_FLAG(throw_on_failure)) {
5137 #if GTEST_HAS_EXCEPTIONS
5138 throw GoogleTestFailureException(result);
5140 // We cannot call abort() as it generates a pop-up in debug mode
5141 // that cannot be suppressed in VC 7.1 or below.
5148 // Creates and adds a property to the current TestResult. If a property matching
5149 // the supplied value already exists, updates its value instead.
5150 void UnitTest::RecordPropertyForCurrentTest(const char* key,
5151 const char* value) {
5152 const TestProperty test_property(key, value);
5153 impl_->current_test_result()->RecordProperty(test_property);
5156 // Runs all tests in this UnitTest object and prints the result.
5157 // Returns 0 if successful, or 1 otherwise.
5159 // We don't protect this under mutex_, as we only support calling it
5160 // from the main thread.
5161 int UnitTest::Run() {
5162 // Captures the value of GTEST_FLAG(catch_exceptions). This value will be
5163 // used for the duration of the program.
5164 impl()->set_catch_exceptions(GTEST_FLAG(catch_exceptions));
5167 const bool in_death_test_child_process =
5168 internal::GTEST_FLAG(internal_run_death_test).length() > 0;
5170 // Either the user wants Google Test to catch exceptions thrown by the
5171 // tests or this is executing in the context of death test child
5172 // process. In either case the user does not want to see pop-up dialogs
5173 // about crashes - they are expected.
5174 if (impl()->catch_exceptions() || in_death_test_child_process) {
5175 # if !GTEST_OS_WINDOWS_MOBILE
5176 // SetErrorMode doesn't exist on CE.
5177 SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT |
5178 SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);
5179 # endif // !GTEST_OS_WINDOWS_MOBILE
5181 # if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE
5182 // Death test children can be terminated with _abort(). On Windows,
5183 // _abort() can show a dialog with a warning message. This forces the
5184 // abort message to go to stderr instead.
5185 _set_error_mode(_OUT_TO_STDERR);
5188 # if _MSC_VER >= 1400 && !GTEST_OS_WINDOWS_MOBILE
5189 // In the debug version, Visual Studio pops up a separate dialog
5190 // offering a choice to debug the aborted program. We need to suppress
5191 // this dialog or it will pop up for every EXPECT/ASSERT_DEATH statement
5192 // executed. Google Test will notify the user of any unexpected
5193 // failure via stderr.
5195 // VC++ doesn't define _set_abort_behavior() prior to the version 8.0.
5196 // Users of prior VC versions shall suffer the agony and pain of
5197 // clicking through the countless debug dialogs.
5198 // TODO(vladl@google.com): find a way to suppress the abort dialog() in the
5199 // debug mode when compiled with VC 7.1 or lower.
5200 if (!GTEST_FLAG(break_on_failure))
5201 _set_abort_behavior(
5202 0x0, // Clear the following flags:
5203 _WRITE_ABORT_MSG | _CALL_REPORTFAULT); // pop-up window, core dump.
5206 #endif // GTEST_HAS_SEH
5208 return internal::HandleExceptionsInMethodIfSupported(
5210 &internal::UnitTestImpl::RunAllTests,
5211 "auxiliary test code (environments or event listeners)") ? 0 : 1;
5214 // Returns the working directory when the first TEST() or TEST_F() was
5216 const char* UnitTest::original_working_dir() const {
5217 return impl_->original_working_dir_.c_str();
5220 // Returns the TestCase object for the test that's currently running,
5221 // or NULL if no test is running.
5222 const TestCase* UnitTest::current_test_case() const
5223 GTEST_LOCK_EXCLUDED_(mutex_) {
5224 internal::MutexLock lock(&mutex_);
5225 return impl_->current_test_case();
5228 // Returns the TestInfo object for the test that's currently running,
5229 // or NULL if no test is running.
5230 const TestInfo* UnitTest::current_test_info() const
5231 GTEST_LOCK_EXCLUDED_(mutex_) {
5232 internal::MutexLock lock(&mutex_);
5233 return impl_->current_test_info();
5236 // Returns the random seed used at the start of the current test run.
5237 int UnitTest::random_seed() const { return impl_->random_seed(); }
5239 #if GTEST_HAS_PARAM_TEST
5240 // Returns ParameterizedTestCaseRegistry object used to keep track of
5241 // value-parameterized tests and instantiate and register them.
5242 internal::ParameterizedTestCaseRegistry&
5243 UnitTest::parameterized_test_registry()
5244 GTEST_LOCK_EXCLUDED_(mutex_) {
5245 return impl_->parameterized_test_registry();
5247 #endif // GTEST_HAS_PARAM_TEST
5249 // Creates an empty UnitTest.
5250 UnitTest::UnitTest() {
5251 impl_ = new internal::UnitTestImpl(this);
5254 // Destructor of UnitTest.
5255 UnitTest::~UnitTest() {
5259 // Pushes a trace defined by SCOPED_TRACE() on to the per-thread
5260 // Google Test trace stack.
5261 void UnitTest::PushGTestTrace(const internal::TraceInfo& trace)
5262 GTEST_LOCK_EXCLUDED_(mutex_) {
5263 internal::MutexLock lock(&mutex_);
5264 impl_->gtest_trace_stack().push_back(trace);
5267 // Pops a trace from the per-thread Google Test trace stack.
5268 void UnitTest::PopGTestTrace()
5269 GTEST_LOCK_EXCLUDED_(mutex_) {
5270 internal::MutexLock lock(&mutex_);
5271 impl_->gtest_trace_stack().pop_back();
5274 namespace internal {
5276 UnitTestImpl::UnitTestImpl(UnitTest* parent)
5279 # pragma warning(push) // Saves the current warning state.
5280 # pragma warning(disable:4355) // Temporarily disables warning 4355
5281 // (using this in initializer).
5282 default_global_test_part_result_reporter_(this),
5283 default_per_thread_test_part_result_reporter_(this),
5284 # pragma warning(pop) // Restores the warning state again.
5286 default_global_test_part_result_reporter_(this),
5287 default_per_thread_test_part_result_reporter_(this),
5289 global_test_part_result_repoter_(
5290 &default_global_test_part_result_reporter_),
5291 per_thread_test_part_result_reporter_(
5292 &default_per_thread_test_part_result_reporter_),
5293 #if GTEST_HAS_PARAM_TEST
5294 parameterized_test_registry_(),
5295 parameterized_tests_registered_(false),
5296 #endif // GTEST_HAS_PARAM_TEST
5297 last_death_test_case_(-1),
5298 current_test_case_(NULL),
5299 current_test_info_(NULL),
5300 ad_hoc_test_result_(),
5301 os_stack_trace_getter_(NULL),
5302 post_flag_parse_init_performed_(false),
5303 random_seed_(0), // Will be overridden by the flag before first use.
5304 random_(0), // Will be reseeded before first use.
5305 start_timestamp_(0),
5307 #if GTEST_HAS_DEATH_TEST
5308 internal_run_death_test_flag_(NULL),
5309 death_test_factory_(new DefaultDeathTestFactory),
5311 // Will be overridden by the flag before first use.
5312 catch_exceptions_(false) {
5313 listeners()->SetDefaultResultPrinter(new PrettyUnitTestResultPrinter);
5316 UnitTestImpl::~UnitTestImpl() {
5317 // Deletes every TestCase.
5318 ForEach(test_cases_, internal::Delete<TestCase>);
5320 // Deletes every Environment.
5321 ForEach(environments_, internal::Delete<Environment>);
5323 delete os_stack_trace_getter_;
5326 #if GTEST_HAS_DEATH_TEST
5327 // Disables event forwarding if the control is currently in a death test
5328 // subprocess. Must not be called before InitGoogleTest.
5329 void UnitTestImpl::SuppressTestEventsIfInSubprocess() {
5330 if (internal_run_death_test_flag_.get() != NULL)
5331 listeners()->SuppressEventForwarding();
5333 #endif // GTEST_HAS_DEATH_TEST
5335 // Initializes event listeners performing XML output as specified by
5336 // UnitTestOptions. Must not be called before InitGoogleTest.
5337 void UnitTestImpl::ConfigureXmlOutput() {
5338 const String& output_format = UnitTestOptions::GetOutputFormat();
5339 if (output_format == "xml") {
5340 listeners()->SetDefaultXmlGenerator(new XmlUnitTestResultPrinter(
5341 UnitTestOptions::GetAbsolutePathToOutputFile().c_str()));
5342 } else if (output_format != "") {
5343 printf("WARNING: unrecognized output format \"%s\" ignored.\n",
5344 output_format.c_str());
5349 #if GTEST_CAN_STREAM_RESULTS_
5350 // Initializes event listeners for streaming test results in String form.
5351 // Must not be called before InitGoogleTest.
5352 void UnitTestImpl::ConfigureStreamingOutput() {
5353 const string& target = GTEST_FLAG(stream_result_to);
5354 if (!target.empty()) {
5355 const size_t pos = target.find(':');
5356 if (pos != string::npos) {
5357 listeners()->Append(new StreamingListener(target.substr(0, pos),
5358 target.substr(pos+1)));
5360 printf("WARNING: unrecognized streaming target \"%s\" ignored.\n",
5366 #endif // GTEST_CAN_STREAM_RESULTS_
5368 // Performs initialization dependent upon flag values obtained in
5369 // ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to
5370 // ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest
5371 // this function is also called from RunAllTests. Since this function can be
5372 // called more than once, it has to be idempotent.
5373 void UnitTestImpl::PostFlagParsingInit() {
5374 // Ensures that this function does not execute more than once.
5375 if (!post_flag_parse_init_performed_) {
5376 post_flag_parse_init_performed_ = true;
5378 #if GTEST_HAS_DEATH_TEST
5379 InitDeathTestSubprocessControlInfo();
5380 SuppressTestEventsIfInSubprocess();
5381 #endif // GTEST_HAS_DEATH_TEST
5383 // Registers parameterized tests. This makes parameterized tests
5384 // available to the UnitTest reflection API without running
5386 RegisterParameterizedTests();
5388 // Configures listeners for XML output. This makes it possible for users
5389 // to shut down the default XML output before invoking RUN_ALL_TESTS.
5390 ConfigureXmlOutput();
5392 #if GTEST_CAN_STREAM_RESULTS_
5393 // Configures listeners for streaming test results to the specified server.
5394 ConfigureStreamingOutput();
5395 #endif // GTEST_CAN_STREAM_RESULTS_
5399 // A predicate that checks the name of a TestCase against a known
5402 // This is used for implementation of the UnitTest class only. We put
5403 // it in the anonymous namespace to prevent polluting the outer
5406 // TestCaseNameIs is copyable.
5407 class TestCaseNameIs {
5410 explicit TestCaseNameIs(const String& name)
5413 // Returns true iff the name of test_case matches name_.
5414 bool operator()(const TestCase* test_case) const {
5415 return test_case != NULL && strcmp(test_case->name(), name_.c_str()) == 0;
5422 // Finds and returns a TestCase with the given name. If one doesn't
5423 // exist, creates one and returns it. It's the CALLER'S
5424 // RESPONSIBILITY to ensure that this function is only called WHEN THE
5425 // TESTS ARE NOT SHUFFLED.
5429 // test_case_name: name of the test case
5430 // type_param: the name of the test case's type parameter, or NULL if
5431 // this is not a typed or a type-parameterized test case.
5432 // set_up_tc: pointer to the function that sets up the test case
5433 // tear_down_tc: pointer to the function that tears down the test case
5434 TestCase* UnitTestImpl::GetTestCase(const char* test_case_name,
5435 const char* type_param,
5436 Test::SetUpTestCaseFunc set_up_tc,
5437 Test::TearDownTestCaseFunc tear_down_tc) {
5438 // Can we find a TestCase with the given name?
5439 const std::vector<TestCase*>::const_iterator test_case =
5440 std::find_if(test_cases_.begin(), test_cases_.end(),
5441 TestCaseNameIs(test_case_name));
5443 if (test_case != test_cases_.end())
5446 // No. Let's create one.
5447 TestCase* const new_test_case =
5448 new TestCase(test_case_name, type_param, set_up_tc, tear_down_tc);
5450 // Is this a death test case?
5451 if (internal::UnitTestOptions::MatchesFilter(String(test_case_name),
5452 kDeathTestCaseFilter)) {
5453 // Yes. Inserts the test case after the last death test case
5454 // defined so far. This only works when the test cases haven't
5455 // been shuffled. Otherwise we may end up running a death test
5456 // after a non-death test.
5457 ++last_death_test_case_;
5458 test_cases_.insert(test_cases_.begin() + last_death_test_case_,
5461 // No. Appends to the end of the list.
5462 test_cases_.push_back(new_test_case);
5465 test_case_indices_.push_back(static_cast<int>(test_case_indices_.size()));
5466 return new_test_case;
5469 // Helpers for setting up / tearing down the given environment. They
5470 // are for use in the ForEach() function.
5471 static void SetUpEnvironment(Environment* env) { env->SetUp(); }
5472 static void TearDownEnvironment(Environment* env) { env->TearDown(); }
5474 // Runs all tests in this UnitTest object, prints the result, and
5475 // returns true if all tests are successful. If any exception is
5476 // thrown during a test, the test is considered to be failed, but the
5477 // rest of the tests will still be run.
5479 // When parameterized tests are enabled, it expands and registers
5480 // parameterized tests first in RegisterParameterizedTests().
5481 // All other functions called from RunAllTests() may safely assume that
5482 // parameterized tests are ready to be counted and run.
5483 bool UnitTestImpl::RunAllTests() {
5484 // Makes sure InitGoogleTest() was called.
5485 if (!GTestIsInitialized()) {
5487 "\nThis test program did NOT call ::testing::InitGoogleTest "
5488 "before calling RUN_ALL_TESTS(). Please fix it.\n");
5492 // Do not run any test if the --help flag was specified.
5496 // Repeats the call to the post-flag parsing initialization in case the
5497 // user didn't call InitGoogleTest.
5498 PostFlagParsingInit();
5500 // Even if sharding is not on, test runners may want to use the
5501 // GTEST_SHARD_STATUS_FILE to query whether the test supports the sharding
5503 internal::WriteToShardStatusFileIfNeeded();
5505 // True iff we are in a subprocess for running a thread-safe-style
5507 bool in_subprocess_for_death_test = false;
5509 #if GTEST_HAS_DEATH_TEST
5510 in_subprocess_for_death_test = (internal_run_death_test_flag_.get() != NULL);
5511 #endif // GTEST_HAS_DEATH_TEST
5513 const bool should_shard = ShouldShard(kTestTotalShards, kTestShardIndex,
5514 in_subprocess_for_death_test);
5516 // Compares the full test names with the filter to decide which
5518 const bool has_tests_to_run = FilterTests(should_shard
5519 ? HONOR_SHARDING_PROTOCOL
5520 : IGNORE_SHARDING_PROTOCOL) > 0;
5522 // Lists the tests and exits if the --gtest_list_tests flag was specified.
5523 if (GTEST_FLAG(list_tests)) {
5524 // This must be called *after* FilterTests() has been called.
5525 ListTestsMatchingFilter();
5529 random_seed_ = GTEST_FLAG(shuffle) ?
5530 GetRandomSeedFromFlag(GTEST_FLAG(random_seed)) : 0;
5532 // True iff at least one test has failed.
5533 bool failed = false;
5535 TestEventListener* repeater = listeners()->repeater();
5537 start_timestamp_ = GetTimeInMillis();
5538 repeater->OnTestProgramStart(*parent_);
5540 // How many times to repeat the tests? We don't want to repeat them
5541 // when we are inside the subprocess of a death test.
5542 const int repeat = in_subprocess_for_death_test ? 1 : GTEST_FLAG(repeat);
5543 // Repeats forever if the repeat count is negative.
5544 const bool forever = repeat < 0;
5545 for (int i = 0; forever || i != repeat; i++) {
5546 // We want to preserve failures generated by ad-hoc test
5547 // assertions executed before RUN_ALL_TESTS().
5548 ClearNonAdHocTestResult();
5550 const TimeInMillis start = GetTimeInMillis();
5552 // Shuffles test cases and tests if requested.
5553 if (has_tests_to_run && GTEST_FLAG(shuffle)) {
5554 random()->Reseed(random_seed_);
5555 // This should be done before calling OnTestIterationStart(),
5556 // such that a test event listener can see the actual test order
5561 // Tells the unit test event listeners that the tests are about to start.
5562 repeater->OnTestIterationStart(*parent_, i);
5564 // Runs each test case if there is at least one test to run.
5565 if (has_tests_to_run) {
5566 // Sets up all environments beforehand.
5567 repeater->OnEnvironmentsSetUpStart(*parent_);
5568 ForEach(environments_, SetUpEnvironment);
5569 repeater->OnEnvironmentsSetUpEnd(*parent_);
5571 // Runs the tests only if there was no fatal failure during global
5573 if (!Test::HasFatalFailure()) {
5574 for (int test_index = 0; test_index < total_test_case_count();
5576 GetMutableTestCase(test_index)->Run();
5580 // Tears down all environments in reverse order afterwards.
5581 repeater->OnEnvironmentsTearDownStart(*parent_);
5582 std::for_each(environments_.rbegin(), environments_.rend(),
5583 TearDownEnvironment);
5584 repeater->OnEnvironmentsTearDownEnd(*parent_);
5587 elapsed_time_ = GetTimeInMillis() - start;
5589 // Tells the unit test event listener that the tests have just finished.
5590 repeater->OnTestIterationEnd(*parent_, i);
5592 // Gets the result and clears it.
5597 // Restores the original test order after the iteration. This
5598 // allows the user to quickly repro a failure that happens in the
5599 // N-th iteration without repeating the first (N - 1) iterations.
5600 // This is not enclosed in "if (GTEST_FLAG(shuffle)) { ... }", in
5601 // case the user somehow changes the value of the flag somewhere
5602 // (it's always safe to unshuffle the tests).
5605 if (GTEST_FLAG(shuffle)) {
5606 // Picks a new random seed for each iteration.
5607 random_seed_ = GetNextRandomSeed(random_seed_);
5611 repeater->OnTestProgramEnd(*parent_);
5616 // Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
5617 // if the variable is present. If a file already exists at this location, this
5618 // function will write over it. If the variable is present, but the file cannot
5619 // be created, prints an error and exits.
5620 void WriteToShardStatusFileIfNeeded() {
5621 const char* const test_shard_file = posix::GetEnv(kTestShardStatusFile);
5622 if (test_shard_file != NULL) {
5623 FILE* const file = posix::FOpen(test_shard_file, "w");
5625 ColoredPrintf(COLOR_RED,
5626 "Could not write to the test shard status file \"%s\" "
5627 "specified by the %s environment variable.\n",
5628 test_shard_file, kTestShardStatusFile);
5636 // Checks whether sharding is enabled by examining the relevant
5637 // environment variable values. If the variables are present,
5638 // but inconsistent (i.e., shard_index >= total_shards), prints
5639 // an error and exits. If in_subprocess_for_death_test, sharding is
5640 // disabled because it must only be applied to the original test
5641 // process. Otherwise, we could filter out death tests we intended to execute.
5642 bool ShouldShard(const char* total_shards_env,
5643 const char* shard_index_env,
5644 bool in_subprocess_for_death_test) {
5645 if (in_subprocess_for_death_test) {
5649 const Int32 total_shards = Int32FromEnvOrDie(total_shards_env, -1);
5650 const Int32 shard_index = Int32FromEnvOrDie(shard_index_env, -1);
5652 if (total_shards == -1 && shard_index == -1) {
5654 } else if (total_shards == -1 && shard_index != -1) {
5655 const Message msg = Message()
5656 << "Invalid environment variables: you have "
5657 << kTestShardIndex << " = " << shard_index
5658 << ", but have left " << kTestTotalShards << " unset.\n";
5659 ColoredPrintf(COLOR_RED, msg.GetString().c_str());
5662 } else if (total_shards != -1 && shard_index == -1) {
5663 const Message msg = Message()
5664 << "Invalid environment variables: you have "
5665 << kTestTotalShards << " = " << total_shards
5666 << ", but have left " << kTestShardIndex << " unset.\n";
5667 ColoredPrintf(COLOR_RED, msg.GetString().c_str());
5670 } else if (shard_index < 0 || shard_index >= total_shards) {
5671 const Message msg = Message()
5672 << "Invalid environment variables: we require 0 <= "
5673 << kTestShardIndex << " < " << kTestTotalShards
5674 << ", but you have " << kTestShardIndex << "=" << shard_index
5675 << ", " << kTestTotalShards << "=" << total_shards << ".\n";
5676 ColoredPrintf(COLOR_RED, msg.GetString().c_str());
5681 return total_shards > 1;
5684 // Parses the environment variable var as an Int32. If it is unset,
5685 // returns default_val. If it is not an Int32, prints an error
5687 Int32 Int32FromEnvOrDie(const char* var, Int32 default_val) {
5688 const char* str_val = posix::GetEnv(var);
5689 if (str_val == NULL) {
5694 if (!ParseInt32(Message() << "The value of environment variable " << var,
5695 str_val, &result)) {
5701 // Given the total number of shards, the shard index, and the test id,
5702 // returns true iff the test should be run on this shard. The test id is
5703 // some arbitrary but unique non-negative integer assigned to each test
5704 // method. Assumes that 0 <= shard_index < total_shards.
5705 bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) {
5706 return (test_id % total_shards) == shard_index;
5709 // Compares the name of each test with the user-specified filter to
5710 // decide whether the test should be run, then records the result in
5711 // each TestCase and TestInfo object.
5712 // If shard_tests == true, further filters tests based on sharding
5713 // variables in the environment - see
5714 // http://code.google.com/p/googletest/wiki/GoogleTestAdvancedGuide.
5715 // Returns the number of tests that should run.
5716 int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) {
5717 const Int32 total_shards = shard_tests == HONOR_SHARDING_PROTOCOL ?
5718 Int32FromEnvOrDie(kTestTotalShards, -1) : -1;
5719 const Int32 shard_index = shard_tests == HONOR_SHARDING_PROTOCOL ?
5720 Int32FromEnvOrDie(kTestShardIndex, -1) : -1;
5722 // num_runnable_tests are the number of tests that will
5723 // run across all shards (i.e., match filter and are not disabled).
5724 // num_selected_tests are the number of tests to be run on
5726 int num_runnable_tests = 0;
5727 int num_selected_tests = 0;
5728 for (size_t i = 0; i < test_cases_.size(); i++) {
5729 TestCase* const test_case = test_cases_[i];
5730 const String &test_case_name = test_case->name();
5731 test_case->set_should_run(false);
5733 for (size_t j = 0; j < test_case->test_info_list().size(); j++) {
5734 TestInfo* const test_info = test_case->test_info_list()[j];
5735 const String test_name(test_info->name());
5736 // A test is disabled if test case name or test name matches
5737 // kDisableTestFilter.
5738 const bool is_disabled =
5739 internal::UnitTestOptions::MatchesFilter(test_case_name,
5740 kDisableTestFilter) ||
5741 internal::UnitTestOptions::MatchesFilter(test_name,
5742 kDisableTestFilter);
5743 test_info->is_disabled_ = is_disabled;
5745 const bool matches_filter =
5746 internal::UnitTestOptions::FilterMatchesTest(test_case_name,
5748 test_info->matches_filter_ = matches_filter;
5750 const bool is_runnable =
5751 (GTEST_FLAG(also_run_disabled_tests) || !is_disabled) &&
5754 const bool is_selected = is_runnable &&
5755 (shard_tests == IGNORE_SHARDING_PROTOCOL ||
5756 ShouldRunTestOnShard(total_shards, shard_index,
5757 num_runnable_tests));
5759 num_runnable_tests += is_runnable;
5760 num_selected_tests += is_selected;
5762 test_info->should_run_ = is_selected;
5763 test_case->set_should_run(test_case->should_run() || is_selected);
5766 return num_selected_tests;
5769 // Prints the names of the tests matching the user-specified filter flag.
5770 void UnitTestImpl::ListTestsMatchingFilter() {
5771 for (size_t i = 0; i < test_cases_.size(); i++) {
5772 const TestCase* const test_case = test_cases_[i];
5773 bool printed_test_case_name = false;
5775 for (size_t j = 0; j < test_case->test_info_list().size(); j++) {
5776 const TestInfo* const test_info =
5777 test_case->test_info_list()[j];
5778 if (test_info->matches_filter_) {
5779 if (!printed_test_case_name) {
5780 printed_test_case_name = true;
5781 printf("%s.\n", test_case->name());
5783 printf(" %s\n", test_info->name());
5790 // Sets the OS stack trace getter.
5792 // Does nothing if the input and the current OS stack trace getter are
5793 // the same; otherwise, deletes the old getter and makes the input the
5795 void UnitTestImpl::set_os_stack_trace_getter(
5796 OsStackTraceGetterInterface* getter) {
5797 if (os_stack_trace_getter_ != getter) {
5798 delete os_stack_trace_getter_;
5799 os_stack_trace_getter_ = getter;
5803 // Returns the current OS stack trace getter if it is not NULL;
5804 // otherwise, creates an OsStackTraceGetter, makes it the current
5805 // getter, and returns it.
5806 OsStackTraceGetterInterface* UnitTestImpl::os_stack_trace_getter() {
5807 if (os_stack_trace_getter_ == NULL) {
5808 os_stack_trace_getter_ = new OsStackTraceGetter;
5811 return os_stack_trace_getter_;
5814 // Returns the TestResult for the test that's currently running, or
5815 // the TestResult for the ad hoc test if no test is running.
5816 TestResult* UnitTestImpl::current_test_result() {
5817 return current_test_info_ ?
5818 &(current_test_info_->result_) : &ad_hoc_test_result_;
5821 // Shuffles all test cases, and the tests within each test case,
5822 // making sure that death tests are still run first.
5823 void UnitTestImpl::ShuffleTests() {
5824 // Shuffles the death test cases.
5825 ShuffleRange(random(), 0, last_death_test_case_ + 1, &test_case_indices_);
5827 // Shuffles the non-death test cases.
5828 ShuffleRange(random(), last_death_test_case_ + 1,
5829 static_cast<int>(test_cases_.size()), &test_case_indices_);
5831 // Shuffles the tests inside each test case.
5832 for (size_t i = 0; i < test_cases_.size(); i++) {
5833 test_cases_[i]->ShuffleTests(random());
5837 // Restores the test cases and tests to their order before the first shuffle.
5838 void UnitTestImpl::UnshuffleTests() {
5839 for (size_t i = 0; i < test_cases_.size(); i++) {
5840 // Unshuffles the tests in each test case.
5841 test_cases_[i]->UnshuffleTests();
5842 // Resets the index of each test case.
5843 test_case_indices_[i] = static_cast<int>(i);
5847 // Returns the current OS stack trace as a String.
5849 // The maximum number of stack frames to be included is specified by
5850 // the gtest_stack_trace_depth flag. The skip_count parameter
5851 // specifies the number of top frames to be skipped, which doesn't
5852 // count against the number of frames to be included.
5854 // For example, if Foo() calls Bar(), which in turn calls
5855 // GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in
5856 // the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.
5857 String GetCurrentOsStackTraceExceptTop(UnitTest* /*unit_test*/,
5859 // We pass skip_count + 1 to skip this wrapper function in addition
5860 // to what the user really wants to skip.
5861 return GetUnitTestImpl()->CurrentOsStackTraceExceptTop(skip_count + 1);
5864 // Used by the GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_ macro to
5865 // suppress unreachable code warnings.
5867 class ClassUniqueToAlwaysTrue {};
5870 bool IsTrue(bool condition) { return condition; }
5873 #if GTEST_HAS_EXCEPTIONS
5874 // This condition is always false so AlwaysTrue() never actually throws,
5875 // but it makes the compiler think that it may throw.
5877 throw ClassUniqueToAlwaysTrue();
5878 #endif // GTEST_HAS_EXCEPTIONS
5882 // If *pstr starts with the given prefix, modifies *pstr to be right
5883 // past the prefix and returns true; otherwise leaves *pstr unchanged
5884 // and returns false. None of pstr, *pstr, and prefix can be NULL.
5885 bool SkipPrefix(const char* prefix, const char** pstr) {
5886 const size_t prefix_len = strlen(prefix);
5887 if (strncmp(*pstr, prefix, prefix_len) == 0) {
5888 *pstr += prefix_len;
5894 // Parses a string as a command line flag. The string should have
5895 // the format "--flag=value". When def_optional is true, the "=value"
5896 // part can be omitted.
5898 // Returns the value of the flag, or NULL if the parsing failed.
5899 static const char* ParseFlagValue(const char* str,
5901 bool def_optional) {
5902 // str and flag must not be NULL.
5903 if (str == NULL || flag == NULL) return NULL;
5905 // The flag must start with "--" followed by GTEST_FLAG_PREFIX_.
5906 const String flag_str = String::Format("--%s%s", GTEST_FLAG_PREFIX_, flag);
5907 const size_t flag_len = flag_str.length();
5908 if (strncmp(str, flag_str.c_str(), flag_len) != 0) return NULL;
5910 // Skips the flag name.
5911 const char* flag_end = str + flag_len;
5913 // When def_optional is true, it's OK to not have a "=value" part.
5914 if (def_optional && (flag_end[0] == '\0')) {
5918 // If def_optional is true and there are more characters after the
5919 // flag name, or if def_optional is false, there must be a '=' after
5921 if (flag_end[0] != '=') return NULL;
5923 // Returns the string after "=".
5924 return flag_end + 1;
5927 // Parses a string for a bool flag, in the form of either
5928 // "--flag=value" or "--flag".
5930 // In the former case, the value is taken as true as long as it does
5931 // not start with '0', 'f', or 'F'.
5933 // In the latter case, the value is taken as true.
5935 // On success, stores the value of the flag in *value, and returns
5936 // true. On failure, returns false without changing *value.
5937 static bool ParseBoolFlag(const char* str, const char* flag, bool* value) {
5938 // Gets the value of the flag as a string.
5939 const char* const value_str = ParseFlagValue(str, flag, true);
5941 // Aborts if the parsing failed.
5942 if (value_str == NULL) return false;
5944 // Converts the string value to a bool.
5945 *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F');
5949 // Parses a string for an Int32 flag, in the form of
5952 // On success, stores the value of the flag in *value, and returns
5953 // true. On failure, returns false without changing *value.
5954 bool ParseInt32Flag(const char* str, const char* flag, Int32* value) {
5955 // Gets the value of the flag as a string.
5956 const char* const value_str = ParseFlagValue(str, flag, false);
5958 // Aborts if the parsing failed.
5959 if (value_str == NULL) return false;
5961 // Sets *value to the value of the flag.
5962 return ParseInt32(Message() << "The value of flag --" << flag,
5966 // Parses a string for a string flag, in the form of
5969 // On success, stores the value of the flag in *value, and returns
5970 // true. On failure, returns false without changing *value.
5971 static bool ParseStringFlag(const char* str, const char* flag, String* value) {
5972 // Gets the value of the flag as a string.
5973 const char* const value_str = ParseFlagValue(str, flag, false);
5975 // Aborts if the parsing failed.
5976 if (value_str == NULL) return false;
5978 // Sets *value to the value of the flag.
5983 // Determines whether a string has a prefix that Google Test uses for its
5984 // flags, i.e., starts with GTEST_FLAG_PREFIX_ or GTEST_FLAG_PREFIX_DASH_.
5985 // If Google Test detects that a command line flag has its prefix but is not
5986 // recognized, it will print its help message. Flags starting with
5987 // GTEST_INTERNAL_PREFIX_ followed by "internal_" are considered Google Test
5988 // internal flags and do not trigger the help message.
5989 static bool HasGoogleTestFlagPrefix(const char* str) {
5990 return (SkipPrefix("--", &str) ||
5991 SkipPrefix("-", &str) ||
5992 SkipPrefix("/", &str)) &&
5993 !SkipPrefix(GTEST_FLAG_PREFIX_ "internal_", &str) &&
5994 (SkipPrefix(GTEST_FLAG_PREFIX_, &str) ||
5995 SkipPrefix(GTEST_FLAG_PREFIX_DASH_, &str));
5998 // Prints a string containing code-encoded text. The following escape
5999 // sequences can be used in the string to control the text color:
6001 // @@ prints a single '@' character.
6002 // @R changes the color to red.
6003 // @G changes the color to green.
6004 // @Y changes the color to yellow.
6005 // @D changes to the default terminal text color.
6007 // TODO(wan@google.com): Write tests for this once we add stdout
6008 // capturing to Google Test.
6009 static void PrintColorEncoded(const char* str) {
6010 GTestColor color = COLOR_DEFAULT; // The current color.
6012 // Conceptually, we split the string into segments divided by escape
6013 // sequences. Then we print one segment at a time. At the end of
6014 // each iteration, the str pointer advances to the beginning of the
6017 const char* p = strchr(str, '@');
6019 ColoredPrintf(color, "%s", str);
6023 ColoredPrintf(color, "%s", String(str, p - str).c_str());
6025 const char ch = p[1];
6028 ColoredPrintf(color, "@");
6029 } else if (ch == 'D') {
6030 color = COLOR_DEFAULT;
6031 } else if (ch == 'R') {
6033 } else if (ch == 'G') {
6034 color = COLOR_GREEN;
6035 } else if (ch == 'Y') {
6036 color = COLOR_YELLOW;
6043 static const char kColorEncodedHelpMessage[] =
6044 "This program contains tests written using " GTEST_NAME_ ". You can use the\n"
6045 "following command line flags to control its behavior:\n"
6048 " @G--" GTEST_FLAG_PREFIX_ "list_tests@D\n"
6049 " List the names of all tests instead of running them. The name of\n"
6050 " TEST(Foo, Bar) is \"Foo.Bar\".\n"
6051 " @G--" GTEST_FLAG_PREFIX_ "filter=@YPOSTIVE_PATTERNS"
6052 "[@G-@YNEGATIVE_PATTERNS]@D\n"
6053 " Run only the tests whose name matches one of the positive patterns but\n"
6054 " none of the negative patterns. '?' matches any single character; '*'\n"
6055 " matches any substring; ':' separates two patterns.\n"
6056 " @G--" GTEST_FLAG_PREFIX_ "also_run_disabled_tests@D\n"
6057 " Run all disabled tests too.\n"
6060 " @G--" GTEST_FLAG_PREFIX_ "repeat=@Y[COUNT]@D\n"
6061 " Run the tests repeatedly; use a negative count to repeat forever.\n"
6062 " @G--" GTEST_FLAG_PREFIX_ "shuffle@D\n"
6063 " Randomize tests' orders on every iteration.\n"
6064 " @G--" GTEST_FLAG_PREFIX_ "random_seed=@Y[NUMBER]@D\n"
6065 " Random number seed to use for shuffling test orders (between 1 and\n"
6066 " 99999, or 0 to use a seed based on the current time).\n"
6069 " @G--" GTEST_FLAG_PREFIX_ "color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\n"
6070 " Enable/disable colored output. The default is @Gauto@D.\n"
6071 " -@G-" GTEST_FLAG_PREFIX_ "print_time=0@D\n"
6072 " Don't print the elapsed time of each test.\n"
6073 " @G--" GTEST_FLAG_PREFIX_ "output=xml@Y[@G:@YDIRECTORY_PATH@G"
6074 GTEST_PATH_SEP_ "@Y|@G:@YFILE_PATH]@D\n"
6075 " Generate an XML report in the given directory or with the given file\n"
6076 " name. @YFILE_PATH@D defaults to @Gtest_details.xml@D.\n"
6077 #if GTEST_CAN_STREAM_RESULTS_
6078 " @G--" GTEST_FLAG_PREFIX_ "stream_result_to=@YHOST@G:@YPORT@D\n"
6079 " Stream test results to the given server.\n"
6080 #endif // GTEST_CAN_STREAM_RESULTS_
6082 "Assertion Behavior:\n"
6083 #if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
6084 " @G--" GTEST_FLAG_PREFIX_ "death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n"
6085 " Set the default death test style.\n"
6086 #endif // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
6087 " @G--" GTEST_FLAG_PREFIX_ "break_on_failure@D\n"
6088 " Turn assertion failures into debugger break-points.\n"
6089 " @G--" GTEST_FLAG_PREFIX_ "throw_on_failure@D\n"
6090 " Turn assertion failures into C++ exceptions.\n"
6091 " @G--" GTEST_FLAG_PREFIX_ "catch_exceptions=0@D\n"
6092 " Do not report exceptions as test failures. Instead, allow them\n"
6093 " to crash the program or throw a pop-up (on Windows).\n"
6095 "Except for @G--" GTEST_FLAG_PREFIX_ "list_tests@D, you can alternatively set "
6096 "the corresponding\n"
6097 "environment variable of a flag (all letters in upper-case). For example, to\n"
6098 "disable colored text output, you can either specify @G--" GTEST_FLAG_PREFIX_
6099 "color=no@D or set\n"
6100 "the @G" GTEST_FLAG_PREFIX_UPPER_ "COLOR@D environment variable to @Gno@D.\n"
6102 "For more information, please read the " GTEST_NAME_ " documentation at\n"
6103 "@G" GTEST_PROJECT_URL_ "@D. If you find a bug in " GTEST_NAME_ "\n"
6104 "(not one in your own code or tests), please report it to\n"
6105 "@G<" GTEST_DEV_EMAIL_ ">@D.\n";
6107 // Parses the command line for Google Test flags, without initializing
6108 // other parts of Google Test. The type parameter CharType can be
6109 // instantiated to either char or wchar_t.
6110 template <typename CharType>
6111 void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) {
6112 for (int i = 1; i < *argc; i++) {
6113 const String arg_string = StreamableToString(argv[i]);
6114 const char* const arg = arg_string.c_str();
6116 using internal::ParseBoolFlag;
6117 using internal::ParseInt32Flag;
6118 using internal::ParseStringFlag;
6120 // Do we see a Google Test flag?
6121 if (ParseBoolFlag(arg, kAlsoRunDisabledTestsFlag,
6122 >EST_FLAG(also_run_disabled_tests)) ||
6123 ParseBoolFlag(arg, kBreakOnFailureFlag,
6124 >EST_FLAG(break_on_failure)) ||
6125 ParseBoolFlag(arg, kCatchExceptionsFlag,
6126 >EST_FLAG(catch_exceptions)) ||
6127 ParseStringFlag(arg, kColorFlag, >EST_FLAG(color)) ||
6128 ParseStringFlag(arg, kDeathTestStyleFlag,
6129 >EST_FLAG(death_test_style)) ||
6130 ParseBoolFlag(arg, kDeathTestUseFork,
6131 >EST_FLAG(death_test_use_fork)) ||
6132 ParseStringFlag(arg, kFilterFlag, >EST_FLAG(filter)) ||
6133 ParseStringFlag(arg, kInternalRunDeathTestFlag,
6134 >EST_FLAG(internal_run_death_test)) ||
6135 ParseBoolFlag(arg, kListTestsFlag, >EST_FLAG(list_tests)) ||
6136 ParseStringFlag(arg, kOutputFlag, >EST_FLAG(output)) ||
6137 ParseBoolFlag(arg, kPrintTimeFlag, >EST_FLAG(print_time)) ||
6138 ParseInt32Flag(arg, kRandomSeedFlag, >EST_FLAG(random_seed)) ||
6139 ParseInt32Flag(arg, kRepeatFlag, >EST_FLAG(repeat)) ||
6140 ParseBoolFlag(arg, kShuffleFlag, >EST_FLAG(shuffle)) ||
6141 ParseInt32Flag(arg, kStackTraceDepthFlag,
6142 >EST_FLAG(stack_trace_depth)) ||
6143 ParseStringFlag(arg, kStreamResultToFlag,
6144 >EST_FLAG(stream_result_to)) ||
6145 ParseBoolFlag(arg, kThrowOnFailureFlag,
6146 >EST_FLAG(throw_on_failure))
6148 // Yes. Shift the remainder of the argv list left by one. Note
6149 // that argv has (*argc + 1) elements, the last one always being
6150 // NULL. The following loop moves the trailing NULL element as
6152 for (int j = i; j != *argc; j++) {
6153 argv[j] = argv[j + 1];
6156 // Decrements the argument count.
6159 // We also need to decrement the iterator as we just removed
6162 } else if (arg_string == "--help" || arg_string == "-h" ||
6163 arg_string == "-?" || arg_string == "/?" ||
6164 HasGoogleTestFlagPrefix(arg)) {
6165 // Both help flag and unrecognized Google Test flags (excluding
6166 // internal ones) trigger help display.
6172 // We print the help here instead of in RUN_ALL_TESTS(), as the
6173 // latter may not be called at all if the user is using Google
6174 // Test with another testing framework.
6175 PrintColorEncoded(kColorEncodedHelpMessage);
6179 // Parses the command line for Google Test flags, without initializing
6180 // other parts of Google Test.
6181 void ParseGoogleTestFlagsOnly(int* argc, char** argv) {
6182 ParseGoogleTestFlagsOnlyImpl(argc, argv);
6184 void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv) {
6185 ParseGoogleTestFlagsOnlyImpl(argc, argv);
6188 // The internal implementation of InitGoogleTest().
6190 // The type parameter CharType can be instantiated to either char or
6192 template <typename CharType>
6193 void InitGoogleTestImpl(int* argc, CharType** argv) {
6194 g_init_gtest_count++;
6196 // We don't want to run the initialization code twice.
6197 if (g_init_gtest_count != 1) return;
6199 if (*argc <= 0) return;
6201 internal::g_executable_path = internal::StreamableToString(argv[0]);
6203 #if GTEST_HAS_DEATH_TEST
6206 for (int i = 0; i != *argc; i++) {
6207 g_argvs.push_back(StreamableToString(argv[i]));
6210 #endif // GTEST_HAS_DEATH_TEST
6212 ParseGoogleTestFlagsOnly(argc, argv);
6213 GetUnitTestImpl()->PostFlagParsingInit();
6216 } // namespace internal
6218 // Initializes Google Test. This must be called before calling
6219 // RUN_ALL_TESTS(). In particular, it parses a command line for the
6220 // flags that Google Test recognizes. Whenever a Google Test flag is
6221 // seen, it is removed from argv, and *argc is decremented.
6223 // No value is returned. Instead, the Google Test flag variables are
6226 // Calling the function for the second time has no user-visible effect.
6227 void InitGoogleTest(int* argc, char** argv) {
6228 internal::InitGoogleTestImpl(argc, argv);
6231 // This overloaded version can be used in Windows programs compiled in
6233 void InitGoogleTest(int* argc, wchar_t** argv) {
6234 internal::InitGoogleTestImpl(argc, argv);
6237 } // namespace testing
6238 // Copyright 2005, Google Inc.
6239 // All rights reserved.
6241 // Redistribution and use in source and binary forms, with or without
6242 // modification, are permitted provided that the following conditions are
6245 // * Redistributions of source code must retain the above copyright
6246 // notice, this list of conditions and the following disclaimer.
6247 // * Redistributions in binary form must reproduce the above
6248 // copyright notice, this list of conditions and the following disclaimer
6249 // in the documentation and/or other materials provided with the
6251 // * Neither the name of Google Inc. nor the names of its
6252 // contributors may be used to endorse or promote products derived from
6253 // this software without specific prior written permission.
6255 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
6256 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
6257 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
6258 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
6259 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
6260 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
6261 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
6262 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
6263 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
6264 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
6265 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
6267 // Author: wan@google.com (Zhanyong Wan), vladl@google.com (Vlad Losev)
6269 // This file implements death tests.
6272 #if GTEST_HAS_DEATH_TEST
6275 # include <crt_externs.h>
6276 # endif // GTEST_OS_MAC
6280 # include <limits.h>
6283 # include <signal.h>
6284 # endif // GTEST_OS_LINUX
6286 # include <stdarg.h>
6288 # if GTEST_OS_WINDOWS
6289 # include <windows.h>
6291 # include <sys/mman.h>
6292 # include <sys/wait.h>
6293 # endif // GTEST_OS_WINDOWS
6297 # endif // GTEST_OS_QNX
6299 #endif // GTEST_HAS_DEATH_TEST
6302 // Indicates that this translation unit is part of Google Test's
6303 // implementation. It must come before gtest-internal-inl.h is
6304 // included, or there will be a compiler error. This trick is to
6305 // prevent a user from accidentally including gtest-internal-inl.h in
6307 #define GTEST_IMPLEMENTATION_ 1
6308 #undef GTEST_IMPLEMENTATION_
6314 // The default death test style.
6315 static const char kDefaultDeathTestStyle[] = "fast";
6317 GTEST_DEFINE_string_(
6319 internal::StringFromGTestEnv("death_test_style", kDefaultDeathTestStyle),
6320 "Indicates how to run a death test in a forked child process: "
6321 "\"threadsafe\" (child process re-executes the test binary "
6322 "from the beginning, running only the specific death test) or "
6323 "\"fast\" (child process runs the death test immediately "
6327 death_test_use_fork,
6328 internal::BoolFromGTestEnv("death_test_use_fork", false),
6329 "Instructs to use fork()/_exit() instead of clone() in death tests. "
6330 "Ignored and always uses fork() on POSIX systems where clone() is not "
6331 "implemented. Useful when running under valgrind or similar tools if "
6332 "those do not support clone(). Valgrind 3.3.1 will just fail if "
6333 "it sees an unsupported combination of clone() flags. "
6334 "It is not recommended to use this flag w/o valgrind though it will "
6335 "work in 99% of the cases. Once valgrind is fixed, this flag will "
6336 "most likely be removed.");
6338 namespace internal {
6339 GTEST_DEFINE_string_(
6340 internal_run_death_test, "",
6341 "Indicates the file, line number, temporal index of "
6342 "the single death test to run, and a file descriptor to "
6343 "which a success code may be sent, all separated by "
6344 "the '|' characters. This flag is specified if and only if the current "
6345 "process is a sub-process launched for running a thread-safe "
6346 "death test. FOR INTERNAL USE ONLY.");
6347 } // namespace internal
6349 #if GTEST_HAS_DEATH_TEST
6351 namespace internal {
6353 // Valid only for fast death tests. Indicates the code is running in the
6354 // child process of a fast style death test.
6355 # if !GTEST_OS_WINDOWS
6356 static bool g_in_fast_death_test_child = false;
6359 // Returns a Boolean value indicating whether the caller is currently
6360 // executing in the context of the death test child process. Tools such as
6361 // Valgrind heap checkers may need this to modify their behavior in death
6362 // tests. IMPORTANT: This is an internal utility. Using it may break the
6363 // implementation of death tests. User code MUST NOT use it.
6364 bool InDeathTestChild() {
6365 # if GTEST_OS_WINDOWS
6367 // On Windows, death tests are thread-safe regardless of the value of the
6368 // death_test_style flag.
6369 return !GTEST_FLAG(internal_run_death_test).empty();
6373 if (GTEST_FLAG(death_test_style) == "threadsafe")
6374 return !GTEST_FLAG(internal_run_death_test).empty();
6376 return g_in_fast_death_test_child;
6380 } // namespace internal
6382 // ExitedWithCode constructor.
6383 ExitedWithCode::ExitedWithCode(int exit_code) : exit_code_(exit_code) {
6386 // ExitedWithCode function-call operator.
6387 bool ExitedWithCode::operator()(int exit_status) const {
6388 # if GTEST_OS_WINDOWS
6390 return exit_status == exit_code_;
6394 return WIFEXITED(exit_status) && WEXITSTATUS(exit_status) == exit_code_;
6396 # endif // GTEST_OS_WINDOWS
6399 # if !GTEST_OS_WINDOWS
6400 // KilledBySignal constructor.
6401 KilledBySignal::KilledBySignal(int signum) : signum_(signum) {
6404 // KilledBySignal function-call operator.
6405 bool KilledBySignal::operator()(int exit_status) const {
6406 return WIFSIGNALED(exit_status) && WTERMSIG(exit_status) == signum_;
6408 # endif // !GTEST_OS_WINDOWS
6410 namespace internal {
6412 // Utilities needed for death tests.
6414 // Generates a textual description of a given exit code, in the format
6415 // specified by wait(2).
6416 static String ExitSummary(int exit_code) {
6419 # if GTEST_OS_WINDOWS
6421 m << "Exited with exit status " << exit_code;
6425 if (WIFEXITED(exit_code)) {
6426 m << "Exited with exit status " << WEXITSTATUS(exit_code);
6427 } else if (WIFSIGNALED(exit_code)) {
6428 m << "Terminated by signal " << WTERMSIG(exit_code);
6431 if (WCOREDUMP(exit_code)) {
6432 m << " (core dumped)";
6435 # endif // GTEST_OS_WINDOWS
6437 return m.GetString();
6440 // Returns true if exit_status describes a process that was terminated
6441 // by a signal, or exited normally with a nonzero exit code.
6442 bool ExitedUnsuccessfully(int exit_status) {
6443 return !ExitedWithCode(0)(exit_status);
6446 # if !GTEST_OS_WINDOWS
6447 // Generates a textual failure message when a death test finds more than
6448 // one thread running, or cannot determine the number of threads, prior
6449 // to executing the given statement. It is the responsibility of the
6450 // caller not to pass a thread_count of 1.
6451 static String DeathTestThreadWarning(size_t thread_count) {
6453 msg << "Death tests use fork(), which is unsafe particularly"
6454 << " in a threaded context. For this test, " << GTEST_NAME_ << " ";
6455 if (thread_count == 0)
6456 msg << "couldn't detect the number of threads.";
6458 msg << "detected " << thread_count << " threads.";
6459 return msg.GetString();
6461 # endif // !GTEST_OS_WINDOWS
6463 // Flag characters for reporting a death test that did not die.
6464 static const char kDeathTestLived = 'L';
6465 static const char kDeathTestReturned = 'R';
6466 static const char kDeathTestThrew = 'T';
6467 static const char kDeathTestInternalError = 'I';
6469 // An enumeration describing all of the possible ways that a death test can
6470 // conclude. DIED means that the process died while executing the test
6471 // code; LIVED means that process lived beyond the end of the test code;
6472 // RETURNED means that the test statement attempted to execute a return
6473 // statement, which is not allowed; THREW means that the test statement
6474 // returned control by throwing an exception. IN_PROGRESS means the test
6475 // has not yet concluded.
6476 // TODO(vladl@google.com): Unify names and possibly values for
6477 // AbortReason, DeathTestOutcome, and flag characters above.
6478 enum DeathTestOutcome { IN_PROGRESS, DIED, LIVED, RETURNED, THREW };
6480 // Routine for aborting the program which is safe to call from an
6481 // exec-style death test child process, in which case the error
6482 // message is propagated back to the parent process. Otherwise, the
6483 // message is simply printed to stderr. In either case, the program
6484 // then exits with status 1.
6485 static void DeathTestAbort(const String& message) {
6486 // On a POSIX system, this function may be called from a threadsafe-style
6487 // death test child process, which operates on a very small stack. Use
6488 // the heap for any additional non-minuscule memory requirements.
6489 const InternalRunDeathTestFlag* const flag =
6490 GetUnitTestImpl()->internal_run_death_test_flag();
6492 FILE* parent = posix::FDOpen(flag->write_fd(), "w");
6493 fputc(kDeathTestInternalError, parent);
6494 fprintf(parent, "%s", message.c_str());
6498 fprintf(stderr, "%s", message.c_str());
6504 // A replacement for CHECK that calls DeathTestAbort if the assertion
6506 # define GTEST_DEATH_TEST_CHECK_(expression) \
6508 if (!::testing::internal::IsTrue(expression)) { \
6509 DeathTestAbort(::testing::internal::String::Format( \
6510 "CHECK failed: File %s, line %d: %s", \
6511 __FILE__, __LINE__, #expression)); \
6513 } while (::testing::internal::AlwaysFalse())
6515 // This macro is similar to GTEST_DEATH_TEST_CHECK_, but it is meant for
6516 // evaluating any system call that fulfills two conditions: it must return
6517 // -1 on failure, and set errno to EINTR when it is interrupted and
6518 // should be tried again. The macro expands to a loop that repeatedly
6519 // evaluates the expression as long as it evaluates to -1 and sets
6520 // errno to EINTR. If the expression evaluates to -1 but errno is
6521 // something other than EINTR, DeathTestAbort is called.
6522 # define GTEST_DEATH_TEST_CHECK_SYSCALL_(expression) \
6526 gtest_retval = (expression); \
6527 } while (gtest_retval == -1 && errno == EINTR); \
6528 if (gtest_retval == -1) { \
6529 DeathTestAbort(::testing::internal::String::Format( \
6530 "CHECK failed: File %s, line %d: %s != -1", \
6531 __FILE__, __LINE__, #expression)); \
6533 } while (::testing::internal::AlwaysFalse())
6535 // Returns the message describing the last system error in errno.
6536 String GetLastErrnoDescription() {
6537 return String(errno == 0 ? "" : posix::StrError(errno));
6540 // This is called from a death test parent process to read a failure
6541 // message from the death test child process and log it with the FATAL
6542 // severity. On Windows, the message is read from a pipe handle. On other
6543 // platforms, it is read from a file descriptor.
6544 static void FailFromInternalError(int fd) {
6550 while ((num_read = posix::Read(fd, buffer, 255)) > 0) {
6551 buffer[num_read] = '\0';
6554 } while (num_read == -1 && errno == EINTR);
6556 if (num_read == 0) {
6557 GTEST_LOG_(FATAL) << error.GetString();
6559 const int last_error = errno;
6560 GTEST_LOG_(FATAL) << "Error while reading death test internal: "
6561 << GetLastErrnoDescription() << " [" << last_error << "]";
6565 // Death test constructor. Increments the running death test count
6566 // for the current test.
6567 DeathTest::DeathTest() {
6568 TestInfo* const info = GetUnitTestImpl()->current_test_info();
6570 DeathTestAbort("Cannot run a death test outside of a TEST or "
6571 "TEST_F construct");
6575 // Creates and returns a death test by dispatching to the current
6576 // death test factory.
6577 bool DeathTest::Create(const char* statement, const RE* regex,
6578 const char* file, int line, DeathTest** test) {
6579 return GetUnitTestImpl()->death_test_factory()->Create(
6580 statement, regex, file, line, test);
6583 const char* DeathTest::LastMessage() {
6584 return last_death_test_message_.c_str();
6587 void DeathTest::set_last_death_test_message(const String& message) {
6588 last_death_test_message_ = message;
6591 String DeathTest::last_death_test_message_;
6593 // Provides cross platform implementation for some death functionality.
6594 class DeathTestImpl : public DeathTest {
6596 DeathTestImpl(const char* a_statement, const RE* a_regex)
6597 : statement_(a_statement),
6601 outcome_(IN_PROGRESS),
6605 // read_fd_ is expected to be closed and cleared by a derived class.
6606 ~DeathTestImpl() { GTEST_DEATH_TEST_CHECK_(read_fd_ == -1); }
6608 void Abort(AbortReason reason);
6609 virtual bool Passed(bool status_ok);
6611 const char* statement() const { return statement_; }
6612 const RE* regex() const { return regex_; }
6613 bool spawned() const { return spawned_; }
6614 void set_spawned(bool is_spawned) { spawned_ = is_spawned; }
6615 int status() const { return status_; }
6616 void set_status(int a_status) { status_ = a_status; }
6617 DeathTestOutcome outcome() const { return outcome_; }
6618 void set_outcome(DeathTestOutcome an_outcome) { outcome_ = an_outcome; }
6619 int read_fd() const { return read_fd_; }
6620 void set_read_fd(int fd) { read_fd_ = fd; }
6621 int write_fd() const { return write_fd_; }
6622 void set_write_fd(int fd) { write_fd_ = fd; }
6624 // Called in the parent process only. Reads the result code of the death
6625 // test child process via a pipe, interprets it to set the outcome_
6626 // member, and closes read_fd_. Outputs diagnostics and terminates in
6627 // case of unexpected codes.
6628 void ReadAndInterpretStatusByte();
6631 // The textual content of the code this object is testing. This class
6632 // doesn't own this string and should not attempt to delete it.
6633 const char* const statement_;
6634 // The regular expression which test output must match. DeathTestImpl
6635 // doesn't own this object and should not attempt to delete it.
6636 const RE* const regex_;
6637 // True if the death test child process has been successfully spawned.
6639 // The exit status of the child process.
6641 // How the death test concluded.
6642 DeathTestOutcome outcome_;
6643 // Descriptor to the read end of the pipe to the child process. It is
6644 // always -1 in the child process. The child keeps its write end of the
6645 // pipe in write_fd_.
6647 // Descriptor to the child's write end of the pipe to the parent process.
6648 // It is always -1 in the parent process. The parent keeps its end of the
6649 // pipe in read_fd_.
6653 // Called in the parent process only. Reads the result code of the death
6654 // test child process via a pipe, interprets it to set the outcome_
6655 // member, and closes read_fd_. Outputs diagnostics and terminates in
6656 // case of unexpected codes.
6657 void DeathTestImpl::ReadAndInterpretStatusByte() {
6661 // The read() here blocks until data is available (signifying the
6662 // failure of the death test) or until the pipe is closed (signifying
6663 // its success), so it's okay to call this in the parent before
6664 // the child process has exited.
6666 bytes_read = posix::Read(read_fd(), &flag, 1);
6667 } while (bytes_read == -1 && errno == EINTR);
6669 if (bytes_read == 0) {
6671 } else if (bytes_read == 1) {
6673 case kDeathTestReturned:
6674 set_outcome(RETURNED);
6676 case kDeathTestThrew:
6679 case kDeathTestLived:
6682 case kDeathTestInternalError:
6683 FailFromInternalError(read_fd()); // Does not return.
6686 GTEST_LOG_(FATAL) << "Death test child process reported "
6687 << "unexpected status byte ("
6688 << static_cast<unsigned int>(flag) << ")";
6691 GTEST_LOG_(FATAL) << "Read from death test child process failed: "
6692 << GetLastErrnoDescription();
6694 GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Close(read_fd()));
6698 // Signals that the death test code which should have exited, didn't.
6699 // Should be called only in a death test child process.
6700 // Writes a status byte to the child's status file descriptor, then
6702 void DeathTestImpl::Abort(AbortReason reason) {
6703 // The parent process considers the death test to be a failure if
6704 // it finds any data in our pipe. So, here we write a single flag byte
6705 // to the pipe, then exit.
6706 const char status_ch =
6707 reason == TEST_DID_NOT_DIE ? kDeathTestLived :
6708 reason == TEST_THREW_EXCEPTION ? kDeathTestThrew : kDeathTestReturned;
6710 GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Write(write_fd(), &status_ch, 1));
6711 // We are leaking the descriptor here because on some platforms (i.e.,
6712 // when built as Windows DLL), destructors of global objects will still
6713 // run after calling _exit(). On such systems, write_fd_ will be
6714 // indirectly closed from the destructor of UnitTestImpl, causing double
6715 // close if it is also closed here. On debug configurations, double close
6716 // may assert. As there are no in-process buffers to flush here, we are
6717 // relying on the OS to close the descriptor after the process terminates
6718 // when the destructors are not run.
6719 _exit(1); // Exits w/o any normal exit hooks (we were supposed to crash)
6722 // Returns an indented copy of stderr output for a death test.
6723 // This makes distinguishing death test output lines from regular log lines
6725 static ::std::string FormatDeathTestOutput(const ::std::string& output) {
6727 for (size_t at = 0; ; ) {
6728 const size_t line_end = output.find('\n', at);
6729 ret += "[ DEATH ] ";
6730 if (line_end == ::std::string::npos) {
6731 ret += output.substr(at);
6734 ret += output.substr(at, line_end + 1 - at);
6740 // Assesses the success or failure of a death test, using both private
6741 // members which have previously been set, and one argument:
6743 // Private data members:
6744 // outcome: An enumeration describing how the death test
6745 // concluded: DIED, LIVED, THREW, or RETURNED. The death test
6746 // fails in the latter three cases.
6747 // status: The exit status of the child process. On *nix, it is in the
6748 // in the format specified by wait(2). On Windows, this is the
6749 // value supplied to the ExitProcess() API or a numeric code
6750 // of the exception that terminated the program.
6751 // regex: A regular expression object to be applied to
6752 // the test's captured standard error output; the death test
6753 // fails if it does not match.
6756 // status_ok: true if exit_status is acceptable in the context of
6757 // this particular death test, which fails if it is false
6759 // Returns true iff all of the above conditions are met. Otherwise, the
6760 // first failing condition, in the order given above, is the one that is
6761 // reported. Also sets the last death test message string.
6762 bool DeathTestImpl::Passed(bool status_ok) {
6766 const String error_message = GetCapturedStderr();
6768 bool success = false;
6771 buffer << "Death test: " << statement() << "\n";
6772 switch (outcome()) {
6774 buffer << " Result: failed to die.\n"
6775 << " Error msg:\n" << FormatDeathTestOutput(error_message);
6778 buffer << " Result: threw an exception.\n"
6779 << " Error msg:\n" << FormatDeathTestOutput(error_message);
6782 buffer << " Result: illegal return in test statement.\n"
6783 << " Error msg:\n" << FormatDeathTestOutput(error_message);
6787 const bool matched = RE::PartialMatch(error_message.c_str(), *regex());
6791 buffer << " Result: died but not with expected error.\n"
6792 << " Expected: " << regex()->pattern() << "\n"
6793 << "Actual msg:\n" << FormatDeathTestOutput(error_message);
6796 buffer << " Result: died but not with expected exit code:\n"
6797 << " " << ExitSummary(status()) << "\n"
6798 << "Actual msg:\n" << FormatDeathTestOutput(error_message);
6804 << "DeathTest::Passed somehow called before conclusion of test";
6807 DeathTest::set_last_death_test_message(buffer.GetString());
6811 # if GTEST_OS_WINDOWS
6812 // WindowsDeathTest implements death tests on Windows. Due to the
6813 // specifics of starting new processes on Windows, death tests there are
6814 // always threadsafe, and Google Test considers the
6815 // --gtest_death_test_style=fast setting to be equivalent to
6816 // --gtest_death_test_style=threadsafe there.
6818 // A few implementation notes: Like the Linux version, the Windows
6819 // implementation uses pipes for child-to-parent communication. But due to
6820 // the specifics of pipes on Windows, some extra steps are required:
6822 // 1. The parent creates a communication pipe and stores handles to both
6824 // 2. The parent starts the child and provides it with the information
6825 // necessary to acquire the handle to the write end of the pipe.
6826 // 3. The child acquires the write end of the pipe and signals the parent
6827 // using a Windows event.
6828 // 4. Now the parent can release the write end of the pipe on its side. If
6829 // this is done before step 3, the object's reference count goes down to
6830 // 0 and it is destroyed, preventing the child from acquiring it. The
6831 // parent now has to release it, or read operations on the read end of
6832 // the pipe will not return when the child terminates.
6833 // 5. The parent reads child's output through the pipe (outcome code and
6834 // any possible error messages) from the pipe, and its stderr and then
6835 // determines whether to fail the test.
6837 // Note: to distinguish Win32 API calls from the local method and function
6838 // calls, the former are explicitly resolved in the global namespace.
6840 class WindowsDeathTest : public DeathTestImpl {
6842 WindowsDeathTest(const char* a_statement,
6846 : DeathTestImpl(a_statement, a_regex), file_(file), line_(line) {}
6848 // All of these virtual functions are inherited from DeathTest.
6850 virtual TestRole AssumeRole();
6853 // The name of the file in which the death test is located.
6854 const char* const file_;
6855 // The line number on which the death test is located.
6857 // Handle to the write end of the pipe to the child process.
6858 AutoHandle write_handle_;
6859 // Child process handle.
6860 AutoHandle child_handle_;
6861 // Event the child process uses to signal the parent that it has
6862 // acquired the handle to the write end of the pipe. After seeing this
6863 // event the parent can release its own handles to make sure its
6864 // ReadFile() calls return when the child terminates.
6865 AutoHandle event_handle_;
6868 // Waits for the child in a death test to exit, returning its exit
6869 // status, or 0 if no child process exists. As a side effect, sets the
6870 // outcome data member.
6871 int WindowsDeathTest::Wait() {
6875 // Wait until the child either signals that it has acquired the write end
6876 // of the pipe or it dies.
6877 const HANDLE wait_handles[2] = { child_handle_.Get(), event_handle_.Get() };
6878 switch (::WaitForMultipleObjects(2,
6880 FALSE, // Waits for any of the handles.
6883 case WAIT_OBJECT_0 + 1:
6886 GTEST_DEATH_TEST_CHECK_(false); // Should not get here.
6889 // The child has acquired the write end of the pipe or exited.
6890 // We release the handle on our side and continue.
6891 write_handle_.Reset();
6892 event_handle_.Reset();
6894 ReadAndInterpretStatusByte();
6896 // Waits for the child process to exit if it haven't already. This
6897 // returns immediately if the child has already exited, regardless of
6898 // whether previous calls to WaitForMultipleObjects synchronized on this
6900 GTEST_DEATH_TEST_CHECK_(
6901 WAIT_OBJECT_0 == ::WaitForSingleObject(child_handle_.Get(),
6904 GTEST_DEATH_TEST_CHECK_(
6905 ::GetExitCodeProcess(child_handle_.Get(), &status_code) != FALSE);
6906 child_handle_.Reset();
6907 set_status(static_cast<int>(status_code));
6911 // The AssumeRole process for a Windows death test. It creates a child
6912 // process with the same executable as the current process to run the
6913 // death test. The child process is given the --gtest_filter and
6914 // --gtest_internal_run_death_test flags such that it knows to run the
6915 // current death test only.
6916 DeathTest::TestRole WindowsDeathTest::AssumeRole() {
6917 const UnitTestImpl* const impl = GetUnitTestImpl();
6918 const InternalRunDeathTestFlag* const flag =
6919 impl->internal_run_death_test_flag();
6920 const TestInfo* const info = impl->current_test_info();
6921 const int death_test_index = info->result()->death_test_count();
6924 // ParseInternalRunDeathTestFlag() has performed all the necessary
6926 set_write_fd(flag->write_fd());
6927 return EXECUTE_TEST;
6930 // WindowsDeathTest uses an anonymous pipe to communicate results of
6932 SECURITY_ATTRIBUTES handles_are_inheritable = {
6933 sizeof(SECURITY_ATTRIBUTES), NULL, TRUE };
6934 HANDLE read_handle, write_handle;
6935 GTEST_DEATH_TEST_CHECK_(
6936 ::CreatePipe(&read_handle, &write_handle, &handles_are_inheritable,
6937 0) // Default buffer size.
6939 set_read_fd(::_open_osfhandle(reinterpret_cast<intptr_t>(read_handle),
6941 write_handle_.Reset(write_handle);
6942 event_handle_.Reset(::CreateEvent(
6943 &handles_are_inheritable,
6944 TRUE, // The event will automatically reset to non-signaled state.
6945 FALSE, // The initial state is non-signalled.
6946 NULL)); // The even is unnamed.
6947 GTEST_DEATH_TEST_CHECK_(event_handle_.Get() != NULL);
6948 const String filter_flag = String::Format("--%s%s=%s.%s",
6949 GTEST_FLAG_PREFIX_, kFilterFlag,
6950 info->test_case_name(),
6952 const String internal_flag = String::Format(
6953 "--%s%s=%s|%d|%d|%u|%Iu|%Iu",
6955 kInternalRunDeathTestFlag,
6958 static_cast<unsigned int>(::GetCurrentProcessId()),
6959 // size_t has the same with as pointers on both 32-bit and 64-bit
6960 // Windows platforms.
6961 // See http://msdn.microsoft.com/en-us/library/tcxf1dw6.aspx.
6962 reinterpret_cast<size_t>(write_handle),
6963 reinterpret_cast<size_t>(event_handle_.Get()));
6965 char executable_path[_MAX_PATH + 1]; // NOLINT
6966 GTEST_DEATH_TEST_CHECK_(
6967 _MAX_PATH + 1 != ::GetModuleFileNameA(NULL,
6971 String command_line = String::Format("%s %s \"%s\"",
6972 ::GetCommandLineA(),
6973 filter_flag.c_str(),
6974 internal_flag.c_str());
6976 DeathTest::set_last_death_test_message("");
6979 // Flush the log buffers since the log streams are shared with the child.
6982 // The child process will share the standard handles with the parent.
6983 STARTUPINFOA startup_info;
6984 memset(&startup_info, 0, sizeof(STARTUPINFO));
6985 startup_info.dwFlags = STARTF_USESTDHANDLES;
6986 startup_info.hStdInput = ::GetStdHandle(STD_INPUT_HANDLE);
6987 startup_info.hStdOutput = ::GetStdHandle(STD_OUTPUT_HANDLE);
6988 startup_info.hStdError = ::GetStdHandle(STD_ERROR_HANDLE);
6990 PROCESS_INFORMATION process_info;
6991 GTEST_DEATH_TEST_CHECK_(::CreateProcessA(
6993 const_cast<char*>(command_line.c_str()),
6994 NULL, // Retuned process handle is not inheritable.
6995 NULL, // Retuned thread handle is not inheritable.
6996 TRUE, // Child inherits all inheritable handles (for write_handle_).
6997 0x0, // Default creation flags.
6998 NULL, // Inherit the parent's environment.
6999 UnitTest::GetInstance()->original_working_dir(),
7001 &process_info) != FALSE);
7002 child_handle_.Reset(process_info.hProcess);
7003 ::CloseHandle(process_info.hThread);
7005 return OVERSEE_TEST;
7007 # else // We are not on Windows.
7009 // ForkingDeathTest provides implementations for most of the abstract
7010 // methods of the DeathTest interface. Only the AssumeRole method is
7012 class ForkingDeathTest : public DeathTestImpl {
7014 ForkingDeathTest(const char* statement, const RE* regex);
7016 // All of these virtual functions are inherited from DeathTest.
7020 void set_child_pid(pid_t child_pid) { child_pid_ = child_pid; }
7023 // PID of child process during death test; 0 in the child process itself.
7027 // Constructs a ForkingDeathTest.
7028 ForkingDeathTest::ForkingDeathTest(const char* a_statement, const RE* a_regex)
7029 : DeathTestImpl(a_statement, a_regex),
7032 // Waits for the child in a death test to exit, returning its exit
7033 // status, or 0 if no child process exists. As a side effect, sets the
7034 // outcome data member.
7035 int ForkingDeathTest::Wait() {
7039 ReadAndInterpretStatusByte();
7042 GTEST_DEATH_TEST_CHECK_SYSCALL_(waitpid(child_pid_, &status_value, 0));
7043 set_status(status_value);
7044 return status_value;
7047 // A concrete death test class that forks, then immediately runs the test
7048 // in the child process.
7049 class NoExecDeathTest : public ForkingDeathTest {
7051 NoExecDeathTest(const char* a_statement, const RE* a_regex) :
7052 ForkingDeathTest(a_statement, a_regex) { }
7053 virtual TestRole AssumeRole();
7056 // The AssumeRole process for a fork-and-run death test. It implements a
7057 // straightforward fork, with a simple pipe to transmit the status byte.
7058 DeathTest::TestRole NoExecDeathTest::AssumeRole() {
7059 const size_t thread_count = GetThreadCount();
7060 if (thread_count != 1) {
7061 GTEST_LOG_(WARNING) << DeathTestThreadWarning(thread_count);
7065 GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
7067 DeathTest::set_last_death_test_message("");
7069 // When we fork the process below, the log file buffers are copied, but the
7070 // file descriptors are shared. We flush all log files here so that closing
7071 // the file descriptors in the child process doesn't throw off the
7072 // synchronization between descriptors and buffers in the parent process.
7073 // This is as close to the fork as possible to avoid a race condition in case
7074 // there are multiple threads running before the death test, and another
7075 // thread writes to the log file.
7078 const pid_t child_pid = fork();
7079 GTEST_DEATH_TEST_CHECK_(child_pid != -1);
7080 set_child_pid(child_pid);
7081 if (child_pid == 0) {
7082 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[0]));
7083 set_write_fd(pipe_fd[1]);
7084 // Redirects all logging to stderr in the child process to prevent
7085 // concurrent writes to the log files. We capture stderr in the parent
7086 // process and append the child process' output to a log.
7088 // Event forwarding to the listeners of event listener API mush be shut
7089 // down in death test subprocesses.
7090 GetUnitTestImpl()->listeners()->SuppressEventForwarding();
7091 g_in_fast_death_test_child = true;
7092 return EXECUTE_TEST;
7094 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
7095 set_read_fd(pipe_fd[0]);
7097 return OVERSEE_TEST;
7101 // A concrete death test class that forks and re-executes the main
7102 // program from the beginning, with command-line flags set that cause
7103 // only this specific death test to be run.
7104 class ExecDeathTest : public ForkingDeathTest {
7106 ExecDeathTest(const char* a_statement, const RE* a_regex,
7107 const char* file, int line) :
7108 ForkingDeathTest(a_statement, a_regex), file_(file), line_(line) { }
7109 virtual TestRole AssumeRole();
7111 static ::std::vector<testing::internal::string>
7112 GetArgvsForDeathTestChildProcess() {
7113 ::std::vector<testing::internal::string> args = GetInjectableArgvs();
7116 // The name of the file in which the death test is located.
7117 const char* const file_;
7118 // The line number on which the death test is located.
7122 // Utility class for accumulating command-line arguments.
7126 args_.push_back(NULL);
7130 for (std::vector<char*>::iterator i = args_.begin(); i != args_.end();
7135 void AddArgument(const char* argument) {
7136 args_.insert(args_.end() - 1, posix::StrDup(argument));
7139 template <typename Str>
7140 void AddArguments(const ::std::vector<Str>& arguments) {
7141 for (typename ::std::vector<Str>::const_iterator i = arguments.begin();
7142 i != arguments.end();
7144 args_.insert(args_.end() - 1, posix::StrDup(i->c_str()));
7147 char* const* Argv() {
7152 std::vector<char*> args_;
7155 // A struct that encompasses the arguments to the child process of a
7156 // threadsafe-style death test process.
7157 struct ExecDeathTestArgs {
7158 char* const* argv; // Command-line arguments for the child's call to exec
7159 int close_fd; // File descriptor to close; the read end of a pipe
7163 inline char** GetEnviron() {
7164 // When Google Test is built as a framework on MacOS X, the environ variable
7165 // is unavailable. Apple's documentation (man environ) recommends using
7166 // _NSGetEnviron() instead.
7167 return *_NSGetEnviron();
7170 // Some POSIX platforms expect you to declare environ. extern "C" makes
7171 // it reside in the global namespace.
7172 extern "C" char** environ;
7173 inline char** GetEnviron() { return environ; }
7174 # endif // GTEST_OS_MAC
7177 // The main function for a threadsafe-style death test child process.
7178 // This function is called in a clone()-ed process and thus must avoid
7179 // any potentially unsafe operations like malloc or libc functions.
7180 static int ExecDeathTestChildMain(void* child_arg) {
7181 ExecDeathTestArgs* const args = static_cast<ExecDeathTestArgs*>(child_arg);
7182 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(args->close_fd));
7184 // We need to execute the test program in the same environment where
7185 // it was originally invoked. Therefore we change to the original
7186 // working directory first.
7187 const char* const original_dir =
7188 UnitTest::GetInstance()->original_working_dir();
7189 // We can safely call chdir() as it's a direct system call.
7190 if (chdir(original_dir) != 0) {
7191 DeathTestAbort(String::Format("chdir(\"%s\") failed: %s",
7193 GetLastErrnoDescription().c_str()));
7194 return EXIT_FAILURE;
7197 // We can safely call execve() as it's a direct system call. We
7198 // cannot use execvp() as it's a libc function and thus potentially
7199 // unsafe. Since execve() doesn't search the PATH, the user must
7200 // invoke the test program via a valid path that contains at least
7201 // one path separator.
7202 execve(args->argv[0], args->argv, GetEnviron());
7203 DeathTestAbort(String::Format("execve(%s, ...) in %s failed: %s",
7206 GetLastErrnoDescription().c_str()));
7207 return EXIT_FAILURE;
7209 # endif // !GTEST_OS_QNX
7211 // Two utility routines that together determine the direction the stack
7213 // This could be accomplished more elegantly by a single recursive
7214 // function, but we want to guard against the unlikely possibility of
7215 // a smart compiler optimizing the recursion away.
7217 // GTEST_NO_INLINE_ is required to prevent GCC 4.6 from inlining
7218 // StackLowerThanAddress into StackGrowsDown, which then doesn't give
7220 void StackLowerThanAddress(const void* ptr, bool* result) GTEST_NO_INLINE_;
7221 void StackLowerThanAddress(const void* ptr, bool* result) {
7223 *result = (&dummy < ptr);
7227 static bool StackGrowsDown() {
7230 StackLowerThanAddress(&dummy, &result);
7235 // Spawns a child process with the same executable as the current process in
7236 // a thread-safe manner and instructs it to run the death test. The
7237 // implementation uses fork(2) + exec. On systems where clone(2) is
7238 // available, it is used instead, being slightly more thread-safe. On QNX,
7239 // fork supports only single-threaded environments, so this function uses
7240 // spawn(2) there instead. The function dies with an error message if
7241 // anything goes wrong.
7242 static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) {
7243 ExecDeathTestArgs args = { argv, close_fd };
7244 pid_t child_pid = -1;
7247 // Obtains the current directory and sets it to be closed in the child
7249 const int cwd_fd = open(".", O_RDONLY);
7250 GTEST_DEATH_TEST_CHECK_(cwd_fd != -1);
7251 GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(cwd_fd, F_SETFD, FD_CLOEXEC));
7252 // We need to execute the test program in the same environment where
7253 // it was originally invoked. Therefore we change to the original
7254 // working directory first.
7255 const char* const original_dir =
7256 UnitTest::GetInstance()->original_working_dir();
7257 // We can safely call chdir() as it's a direct system call.
7258 if (chdir(original_dir) != 0) {
7259 DeathTestAbort(String::Format("chdir(\"%s\") failed: %s",
7261 GetLastErrnoDescription().c_str()));
7262 return EXIT_FAILURE;
7266 // Set close_fd to be closed after spawn.
7267 GTEST_DEATH_TEST_CHECK_SYSCALL_(fd_flags = fcntl(close_fd, F_GETFD));
7268 GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(close_fd, F_SETFD,
7269 fd_flags | FD_CLOEXEC));
7270 struct inheritance inherit = {0};
7271 // spawn is a system call.
7272 child_pid = spawn(args.argv[0], 0, NULL, &inherit, args.argv, GetEnviron());
7273 // Restores the current working directory.
7274 GTEST_DEATH_TEST_CHECK_(fchdir(cwd_fd) != -1);
7275 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(cwd_fd));
7277 # else // GTEST_OS_QNX
7279 // When a SIGPROF signal is received while fork() or clone() are executing,
7280 // the process may hang. To avoid this, we ignore SIGPROF here and re-enable
7281 // it after the call to fork()/clone() is complete.
7282 struct sigaction saved_sigprof_action;
7283 struct sigaction ignore_sigprof_action;
7284 memset(&ignore_sigprof_action, 0, sizeof(ignore_sigprof_action));
7285 sigemptyset(&ignore_sigprof_action.sa_mask);
7286 ignore_sigprof_action.sa_handler = SIG_IGN;
7287 GTEST_DEATH_TEST_CHECK_SYSCALL_(sigaction(
7288 SIGPROF, &ignore_sigprof_action, &saved_sigprof_action));
7289 # endif // GTEST_OS_LINUX
7291 # if GTEST_HAS_CLONE
7292 const bool use_fork = GTEST_FLAG(death_test_use_fork);
7295 static const bool stack_grows_down = StackGrowsDown();
7296 const size_t stack_size = getpagesize();
7297 // MMAP_ANONYMOUS is not defined on Mac, so we use MAP_ANON instead.
7298 void* const stack = mmap(NULL, stack_size, PROT_READ | PROT_WRITE,
7299 MAP_ANON | MAP_PRIVATE, -1, 0);
7300 GTEST_DEATH_TEST_CHECK_(stack != MAP_FAILED);
7301 void* const stack_top =
7302 static_cast<char*>(stack) + (stack_grows_down ? stack_size : 0);
7304 child_pid = clone(&ExecDeathTestChildMain, stack_top, SIGCHLD, &args);
7306 GTEST_DEATH_TEST_CHECK_(munmap(stack, stack_size) != -1);
7309 const bool use_fork = true;
7310 # endif // GTEST_HAS_CLONE
7312 if (use_fork && (child_pid = fork()) == 0) {
7313 ExecDeathTestChildMain(&args);
7316 # endif // GTEST_OS_QNX
7318 GTEST_DEATH_TEST_CHECK_SYSCALL_(
7319 sigaction(SIGPROF, &saved_sigprof_action, NULL));
7320 # endif // GTEST_OS_LINUX
7322 GTEST_DEATH_TEST_CHECK_(child_pid != -1);
7326 // The AssumeRole process for a fork-and-exec death test. It re-executes the
7327 // main program from the beginning, setting the --gtest_filter
7328 // and --gtest_internal_run_death_test flags to cause only the current
7329 // death test to be re-run.
7330 DeathTest::TestRole ExecDeathTest::AssumeRole() {
7331 const UnitTestImpl* const impl = GetUnitTestImpl();
7332 const InternalRunDeathTestFlag* const flag =
7333 impl->internal_run_death_test_flag();
7334 const TestInfo* const info = impl->current_test_info();
7335 const int death_test_index = info->result()->death_test_count();
7338 set_write_fd(flag->write_fd());
7339 return EXECUTE_TEST;
7343 GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
7344 // Clear the close-on-exec flag on the write end of the pipe, lest
7345 // it be closed when the child process does an exec:
7346 GTEST_DEATH_TEST_CHECK_(fcntl(pipe_fd[1], F_SETFD, 0) != -1);
7348 const String filter_flag =
7349 String::Format("--%s%s=%s.%s",
7350 GTEST_FLAG_PREFIX_, kFilterFlag,
7351 info->test_case_name(), info->name());
7352 const String internal_flag =
7353 String::Format("--%s%s=%s|%d|%d|%d",
7354 GTEST_FLAG_PREFIX_, kInternalRunDeathTestFlag,
7355 file_, line_, death_test_index, pipe_fd[1]);
7357 args.AddArguments(GetArgvsForDeathTestChildProcess());
7358 args.AddArgument(filter_flag.c_str());
7359 args.AddArgument(internal_flag.c_str());
7361 DeathTest::set_last_death_test_message("");
7364 // See the comment in NoExecDeathTest::AssumeRole for why the next line
7368 const pid_t child_pid = ExecDeathTestSpawnChild(args.Argv(), pipe_fd[0]);
7369 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
7370 set_child_pid(child_pid);
7371 set_read_fd(pipe_fd[0]);
7373 return OVERSEE_TEST;
7376 # endif // !GTEST_OS_WINDOWS
7378 // Creates a concrete DeathTest-derived class that depends on the
7379 // --gtest_death_test_style flag, and sets the pointer pointed to
7380 // by the "test" argument to its address. If the test should be
7381 // skipped, sets that pointer to NULL. Returns true, unless the
7382 // flag is set to an invalid value.
7383 bool DefaultDeathTestFactory::Create(const char* statement, const RE* regex,
7384 const char* file, int line,
7386 UnitTestImpl* const impl = GetUnitTestImpl();
7387 const InternalRunDeathTestFlag* const flag =
7388 impl->internal_run_death_test_flag();
7389 const int death_test_index = impl->current_test_info()
7390 ->increment_death_test_count();
7393 if (death_test_index > flag->index()) {
7394 DeathTest::set_last_death_test_message(String::Format(
7395 "Death test count (%d) somehow exceeded expected maximum (%d)",
7396 death_test_index, flag->index()));
7400 if (!(flag->file() == file && flag->line() == line &&
7401 flag->index() == death_test_index)) {
7407 # if GTEST_OS_WINDOWS
7409 if (GTEST_FLAG(death_test_style) == "threadsafe" ||
7410 GTEST_FLAG(death_test_style) == "fast") {
7411 *test = new WindowsDeathTest(statement, regex, file, line);
7416 if (GTEST_FLAG(death_test_style) == "threadsafe") {
7417 *test = new ExecDeathTest(statement, regex, file, line);
7418 } else if (GTEST_FLAG(death_test_style) == "fast") {
7419 *test = new NoExecDeathTest(statement, regex);
7422 # endif // GTEST_OS_WINDOWS
7424 else { // NOLINT - this is more readable than unbalanced brackets inside #if.
7425 DeathTest::set_last_death_test_message(String::Format(
7426 "Unknown death test style \"%s\" encountered",
7427 GTEST_FLAG(death_test_style).c_str()));
7434 // Splits a given string on a given delimiter, populating a given
7435 // vector with the fields. GTEST_HAS_DEATH_TEST implies that we have
7436 // ::std::string, so we can use it here.
7437 static void SplitString(const ::std::string& str, char delimiter,
7438 ::std::vector< ::std::string>* dest) {
7439 ::std::vector< ::std::string> parsed;
7440 ::std::string::size_type pos = 0;
7441 while (::testing::internal::AlwaysTrue()) {
7442 const ::std::string::size_type colon = str.find(delimiter, pos);
7443 if (colon == ::std::string::npos) {
7444 parsed.push_back(str.substr(pos));
7447 parsed.push_back(str.substr(pos, colon - pos));
7454 # if GTEST_OS_WINDOWS
7455 // Recreates the pipe and event handles from the provided parameters,
7456 // signals the event, and returns a file descriptor wrapped around the pipe
7457 // handle. This function is called in the child process only.
7458 int GetStatusFileDescriptor(unsigned int parent_process_id,
7459 size_t write_handle_as_size_t,
7460 size_t event_handle_as_size_t) {
7461 AutoHandle parent_process_handle(::OpenProcess(PROCESS_DUP_HANDLE,
7462 FALSE, // Non-inheritable.
7463 parent_process_id));
7464 if (parent_process_handle.Get() == INVALID_HANDLE_VALUE) {
7465 DeathTestAbort(String::Format("Unable to open parent process %u",
7466 parent_process_id));
7469 // TODO(vladl@google.com): Replace the following check with a
7470 // compile-time assertion when available.
7471 GTEST_CHECK_(sizeof(HANDLE) <= sizeof(size_t));
7473 const HANDLE write_handle =
7474 reinterpret_cast<HANDLE>(write_handle_as_size_t);
7475 HANDLE dup_write_handle;
7477 // The newly initialized handle is accessible only in in the parent
7478 // process. To obtain one accessible within the child, we need to use
7480 if (!::DuplicateHandle(parent_process_handle.Get(), write_handle,
7481 ::GetCurrentProcess(), &dup_write_handle,
7482 0x0, // Requested privileges ignored since
7483 // DUPLICATE_SAME_ACCESS is used.
7484 FALSE, // Request non-inheritable handler.
7485 DUPLICATE_SAME_ACCESS)) {
7486 DeathTestAbort(String::Format(
7487 "Unable to duplicate the pipe handle %Iu from the parent process %u",
7488 write_handle_as_size_t, parent_process_id));
7491 const HANDLE event_handle = reinterpret_cast<HANDLE>(event_handle_as_size_t);
7492 HANDLE dup_event_handle;
7494 if (!::DuplicateHandle(parent_process_handle.Get(), event_handle,
7495 ::GetCurrentProcess(), &dup_event_handle,
7498 DUPLICATE_SAME_ACCESS)) {
7499 DeathTestAbort(String::Format(
7500 "Unable to duplicate the event handle %Iu from the parent process %u",
7501 event_handle_as_size_t, parent_process_id));
7504 const int write_fd =
7505 ::_open_osfhandle(reinterpret_cast<intptr_t>(dup_write_handle), O_APPEND);
7506 if (write_fd == -1) {
7507 DeathTestAbort(String::Format(
7508 "Unable to convert pipe handle %Iu to a file descriptor",
7509 write_handle_as_size_t));
7512 // Signals the parent that the write end of the pipe has been acquired
7513 // so the parent can release its own write end.
7514 ::SetEvent(dup_event_handle);
7518 # endif // GTEST_OS_WINDOWS
7520 // Returns a newly created InternalRunDeathTestFlag object with fields
7521 // initialized from the GTEST_FLAG(internal_run_death_test) flag if
7522 // the flag is specified; otherwise returns NULL.
7523 InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() {
7524 if (GTEST_FLAG(internal_run_death_test) == "") return NULL;
7526 // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we
7530 ::std::vector< ::std::string> fields;
7531 SplitString(GTEST_FLAG(internal_run_death_test).c_str(), '|', &fields);
7534 # if GTEST_OS_WINDOWS
7536 unsigned int parent_process_id = 0;
7537 size_t write_handle_as_size_t = 0;
7538 size_t event_handle_as_size_t = 0;
7540 if (fields.size() != 6
7541 || !ParseNaturalNumber(fields[1], &line)
7542 || !ParseNaturalNumber(fields[2], &index)
7543 || !ParseNaturalNumber(fields[3], &parent_process_id)
7544 || !ParseNaturalNumber(fields[4], &write_handle_as_size_t)
7545 || !ParseNaturalNumber(fields[5], &event_handle_as_size_t)) {
7546 DeathTestAbort(String::Format(
7547 "Bad --gtest_internal_run_death_test flag: %s",
7548 GTEST_FLAG(internal_run_death_test).c_str()));
7550 write_fd = GetStatusFileDescriptor(parent_process_id,
7551 write_handle_as_size_t,
7552 event_handle_as_size_t);
7555 if (fields.size() != 4
7556 || !ParseNaturalNumber(fields[1], &line)
7557 || !ParseNaturalNumber(fields[2], &index)
7558 || !ParseNaturalNumber(fields[3], &write_fd)) {
7559 DeathTestAbort(String::Format(
7560 "Bad --gtest_internal_run_death_test flag: %s",
7561 GTEST_FLAG(internal_run_death_test).c_str()));
7564 # endif // GTEST_OS_WINDOWS
7566 return new InternalRunDeathTestFlag(fields[0], line, index, write_fd);
7569 } // namespace internal
7571 #endif // GTEST_HAS_DEATH_TEST
7573 } // namespace testing
7574 // Copyright 2008, Google Inc.
7575 // All rights reserved.
7577 // Redistribution and use in source and binary forms, with or without
7578 // modification, are permitted provided that the following conditions are
7581 // * Redistributions of source code must retain the above copyright
7582 // notice, this list of conditions and the following disclaimer.
7583 // * Redistributions in binary form must reproduce the above
7584 // copyright notice, this list of conditions and the following disclaimer
7585 // in the documentation and/or other materials provided with the
7587 // * Neither the name of Google Inc. nor the names of its
7588 // contributors may be used to endorse or promote products derived from
7589 // this software without specific prior written permission.
7591 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
7592 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
7593 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
7594 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
7595 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
7596 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
7597 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
7598 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
7599 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
7600 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
7601 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
7603 // Authors: keith.ray@gmail.com (Keith Ray)
7608 #if GTEST_OS_WINDOWS_MOBILE
7609 # include <windows.h>
7610 #elif GTEST_OS_WINDOWS
7611 # include <direct.h>
7613 #elif GTEST_OS_SYMBIAN || GTEST_OS_NACL
7614 // Symbian OpenC and NaCl have PATH_MAX in sys/syslimits.h
7615 # include <sys/syslimits.h>
7617 # include <limits.h>
7618 # include <climits> // Some Linux distributions define PATH_MAX here.
7619 #endif // GTEST_OS_WINDOWS_MOBILE
7621 #if GTEST_OS_WINDOWS
7622 # define GTEST_PATH_MAX_ _MAX_PATH
7623 #elif defined(PATH_MAX)
7624 # define GTEST_PATH_MAX_ PATH_MAX
7625 #elif defined(_XOPEN_PATH_MAX)
7626 # define GTEST_PATH_MAX_ _XOPEN_PATH_MAX
7628 # define GTEST_PATH_MAX_ _POSIX_PATH_MAX
7629 #endif // GTEST_OS_WINDOWS
7633 namespace internal {
7635 #if GTEST_OS_WINDOWS
7636 // On Windows, '\\' is the standard path separator, but many tools and the
7637 // Windows API also accept '/' as an alternate path separator. Unless otherwise
7638 // noted, a file path can contain either kind of path separators, or a mixture
7640 const char kPathSeparator = '\\';
7641 const char kAlternatePathSeparator = '/';
7642 const char kPathSeparatorString[] = "\\";
7643 const char kAlternatePathSeparatorString[] = "/";
7644 # if GTEST_OS_WINDOWS_MOBILE
7645 // Windows CE doesn't have a current directory. You should not use
7646 // the current directory in tests on Windows CE, but this at least
7647 // provides a reasonable fallback.
7648 const char kCurrentDirectoryString[] = "\\";
7649 // Windows CE doesn't define INVALID_FILE_ATTRIBUTES
7650 const DWORD kInvalidFileAttributes = 0xffffffff;
7652 const char kCurrentDirectoryString[] = ".\\";
7653 # endif // GTEST_OS_WINDOWS_MOBILE
7655 const char kPathSeparator = '/';
7656 const char kPathSeparatorString[] = "/";
7657 const char kCurrentDirectoryString[] = "./";
7658 #endif // GTEST_OS_WINDOWS
7660 // Returns whether the given character is a valid path separator.
7661 static bool IsPathSeparator(char c) {
7662 #if GTEST_HAS_ALT_PATH_SEP_
7663 return (c == kPathSeparator) || (c == kAlternatePathSeparator);
7665 return c == kPathSeparator;
7669 // Returns the current working directory, or "" if unsuccessful.
7670 FilePath FilePath::GetCurrentDir() {
7671 #if GTEST_OS_WINDOWS_MOBILE
7672 // Windows CE doesn't have a current directory, so we just return
7673 // something reasonable.
7674 return FilePath(kCurrentDirectoryString);
7675 #elif GTEST_OS_WINDOWS
7676 char cwd[GTEST_PATH_MAX_ + 1] = { '\0' };
7677 return FilePath(_getcwd(cwd, sizeof(cwd)) == NULL ? "" : cwd);
7679 char cwd[GTEST_PATH_MAX_ + 1] = { '\0' };
7680 return FilePath(getcwd(cwd, sizeof(cwd)) == NULL ? "" : cwd);
7681 #endif // GTEST_OS_WINDOWS_MOBILE
7684 // Returns a copy of the FilePath with the case-insensitive extension removed.
7685 // Example: FilePath("dir/file.exe").RemoveExtension("EXE") returns
7686 // FilePath("dir/file"). If a case-insensitive extension is not
7687 // found, returns a copy of the original FilePath.
7688 FilePath FilePath::RemoveExtension(const char* extension) const {
7689 String dot_extension(String::Format(".%s", extension));
7690 if (pathname_.EndsWithCaseInsensitive(dot_extension.c_str())) {
7691 return FilePath(String(pathname_.c_str(), pathname_.length() - 4));
7696 // Returns a pointer to the last occurence of a valid path separator in
7697 // the FilePath. On Windows, for example, both '/' and '\' are valid path
7698 // separators. Returns NULL if no path separator was found.
7699 const char* FilePath::FindLastPathSeparator() const {
7700 const char* const last_sep = strrchr(c_str(), kPathSeparator);
7701 #if GTEST_HAS_ALT_PATH_SEP_
7702 const char* const last_alt_sep = strrchr(c_str(), kAlternatePathSeparator);
7703 // Comparing two pointers of which only one is NULL is undefined.
7704 if (last_alt_sep != NULL &&
7705 (last_sep == NULL || last_alt_sep > last_sep)) {
7706 return last_alt_sep;
7712 // Returns a copy of the FilePath with the directory part removed.
7713 // Example: FilePath("path/to/file").RemoveDirectoryName() returns
7714 // FilePath("file"). If there is no directory part ("just_a_file"), it returns
7715 // the FilePath unmodified. If there is no file part ("just_a_dir/") it
7716 // returns an empty FilePath ("").
7717 // On Windows platform, '\' is the path separator, otherwise it is '/'.
7718 FilePath FilePath::RemoveDirectoryName() const {
7719 const char* const last_sep = FindLastPathSeparator();
7720 return last_sep ? FilePath(String(last_sep + 1)) : *this;
7723 // RemoveFileName returns the directory path with the filename removed.
7724 // Example: FilePath("path/to/file").RemoveFileName() returns "path/to/".
7725 // If the FilePath is "a_file" or "/a_file", RemoveFileName returns
7726 // FilePath("./") or, on Windows, FilePath(".\\"). If the filepath does
7727 // not have a file, like "just/a/dir/", it returns the FilePath unmodified.
7728 // On Windows platform, '\' is the path separator, otherwise it is '/'.
7729 FilePath FilePath::RemoveFileName() const {
7730 const char* const last_sep = FindLastPathSeparator();
7733 dir = String(c_str(), last_sep + 1 - c_str());
7735 dir = kCurrentDirectoryString;
7737 return FilePath(dir);
7740 // Helper functions for naming files in a directory for xml output.
7742 // Given directory = "dir", base_name = "test", number = 0,
7743 // extension = "xml", returns "dir/test.xml". If number is greater
7744 // than zero (e.g., 12), returns "dir/test_12.xml".
7745 // On Windows platform, uses \ as the separator rather than /.
7746 FilePath FilePath::MakeFileName(const FilePath& directory,
7747 const FilePath& base_name,
7749 const char* extension) {
7752 file = String::Format("%s.%s", base_name.c_str(), extension);
7754 file = String::Format("%s_%d.%s", base_name.c_str(), number, extension);
7756 return ConcatPaths(directory, FilePath(file));
7759 // Given directory = "dir", relative_path = "test.xml", returns "dir/test.xml".
7760 // On Windows, uses \ as the separator rather than /.
7761 FilePath FilePath::ConcatPaths(const FilePath& directory,
7762 const FilePath& relative_path) {
7763 if (directory.IsEmpty())
7764 return relative_path;
7765 const FilePath dir(directory.RemoveTrailingPathSeparator());
7766 return FilePath(String::Format("%s%c%s", dir.c_str(), kPathSeparator,
7767 relative_path.c_str()));
7770 // Returns true if pathname describes something findable in the file-system,
7771 // either a file, directory, or whatever.
7772 bool FilePath::FileOrDirectoryExists() const {
7773 #if GTEST_OS_WINDOWS_MOBILE
7774 LPCWSTR unicode = String::AnsiToUtf16(pathname_.c_str());
7775 const DWORD attributes = GetFileAttributes(unicode);
7777 return attributes != kInvalidFileAttributes;
7779 posix::StatStruct file_stat;
7780 return posix::Stat(pathname_.c_str(), &file_stat) == 0;
7781 #endif // GTEST_OS_WINDOWS_MOBILE
7784 // Returns true if pathname describes a directory in the file-system
7786 bool FilePath::DirectoryExists() const {
7787 bool result = false;
7788 #if GTEST_OS_WINDOWS
7789 // Don't strip off trailing separator if path is a root directory on
7790 // Windows (like "C:\\").
7791 const FilePath& path(IsRootDirectory() ? *this :
7792 RemoveTrailingPathSeparator());
7794 const FilePath& path(*this);
7797 #if GTEST_OS_WINDOWS_MOBILE
7798 LPCWSTR unicode = String::AnsiToUtf16(path.c_str());
7799 const DWORD attributes = GetFileAttributes(unicode);
7801 if ((attributes != kInvalidFileAttributes) &&
7802 (attributes & FILE_ATTRIBUTE_DIRECTORY)) {
7806 posix::StatStruct file_stat;
7807 result = posix::Stat(path.c_str(), &file_stat) == 0 &&
7808 posix::IsDir(file_stat);
7809 #endif // GTEST_OS_WINDOWS_MOBILE
7814 // Returns true if pathname describes a root directory. (Windows has one
7815 // root directory per disk drive.)
7816 bool FilePath::IsRootDirectory() const {
7817 #if GTEST_OS_WINDOWS
7818 // TODO(wan@google.com): on Windows a network share like
7819 // \\server\share can be a root directory, although it cannot be the
7820 // current directory. Handle this properly.
7821 return pathname_.length() == 3 && IsAbsolutePath();
7823 return pathname_.length() == 1 && IsPathSeparator(pathname_.c_str()[0]);
7827 // Returns true if pathname describes an absolute path.
7828 bool FilePath::IsAbsolutePath() const {
7829 const char* const name = pathname_.c_str();
7830 #if GTEST_OS_WINDOWS
7831 return pathname_.length() >= 3 &&
7832 ((name[0] >= 'a' && name[0] <= 'z') ||
7833 (name[0] >= 'A' && name[0] <= 'Z')) &&
7835 IsPathSeparator(name[2]);
7837 return IsPathSeparator(name[0]);
7841 // Returns a pathname for a file that does not currently exist. The pathname
7842 // will be directory/base_name.extension or
7843 // directory/base_name_<number>.extension if directory/base_name.extension
7844 // already exists. The number will be incremented until a pathname is found
7845 // that does not already exist.
7846 // Examples: 'dir/foo_test.xml' or 'dir/foo_test_1.xml'.
7847 // There could be a race condition if two or more processes are calling this
7848 // function at the same time -- they could both pick the same filename.
7849 FilePath FilePath::GenerateUniqueFileName(const FilePath& directory,
7850 const FilePath& base_name,
7851 const char* extension) {
7852 FilePath full_pathname;
7855 full_pathname.Set(MakeFileName(directory, base_name, number++, extension));
7856 } while (full_pathname.FileOrDirectoryExists());
7857 return full_pathname;
7860 // Returns true if FilePath ends with a path separator, which indicates that
7861 // it is intended to represent a directory. Returns false otherwise.
7862 // This does NOT check that a directory (or file) actually exists.
7863 bool FilePath::IsDirectory() const {
7864 return !pathname_.empty() &&
7865 IsPathSeparator(pathname_.c_str()[pathname_.length() - 1]);
7868 // Create directories so that path exists. Returns true if successful or if
7869 // the directories already exist; returns false if unable to create directories
7871 bool FilePath::CreateDirectoriesRecursively() const {
7872 if (!this->IsDirectory()) {
7876 if (pathname_.length() == 0 || this->DirectoryExists()) {
7880 const FilePath parent(this->RemoveTrailingPathSeparator().RemoveFileName());
7881 return parent.CreateDirectoriesRecursively() && this->CreateFolder();
7884 // Create the directory so that path exists. Returns true if successful or
7885 // if the directory already exists; returns false if unable to create the
7886 // directory for any reason, including if the parent directory does not
7887 // exist. Not named "CreateDirectory" because that's a macro on Windows.
7888 bool FilePath::CreateFolder() const {
7889 #if GTEST_OS_WINDOWS_MOBILE
7890 FilePath removed_sep(this->RemoveTrailingPathSeparator());
7891 LPCWSTR unicode = String::AnsiToUtf16(removed_sep.c_str());
7892 int result = CreateDirectory(unicode, NULL) ? 0 : -1;
7894 #elif GTEST_OS_WINDOWS
7895 int result = _mkdir(pathname_.c_str());
7897 int result = mkdir(pathname_.c_str(), 0777);
7898 #endif // GTEST_OS_WINDOWS_MOBILE
7901 return this->DirectoryExists(); // An error is OK if the directory exists.
7903 return true; // No error.
7906 // If input name has a trailing separator character, remove it and return the
7907 // name, otherwise return the name string unmodified.
7908 // On Windows platform, uses \ as the separator, other platforms use /.
7909 FilePath FilePath::RemoveTrailingPathSeparator() const {
7910 return IsDirectory()
7911 ? FilePath(String(pathname_.c_str(), pathname_.length() - 1))
7915 // Removes any redundant separators that might be in the pathname.
7916 // For example, "bar///foo" becomes "bar/foo". Does not eliminate other
7917 // redundancies that might be in a pathname involving "." or "..".
7918 // TODO(wan@google.com): handle Windows network shares (e.g. \\server\share).
7919 void FilePath::Normalize() {
7920 if (pathname_.c_str() == NULL) {
7924 const char* src = pathname_.c_str();
7925 char* const dest = new char[pathname_.length() + 1];
7926 char* dest_ptr = dest;
7927 memset(dest_ptr, 0, pathname_.length() + 1);
7929 while (*src != '\0') {
7931 if (!IsPathSeparator(*src)) {
7934 #if GTEST_HAS_ALT_PATH_SEP_
7935 if (*dest_ptr == kAlternatePathSeparator) {
7936 *dest_ptr = kPathSeparator;
7939 while (IsPathSeparator(*src))
7949 } // namespace internal
7950 } // namespace testing
7951 // Copyright 2008, Google Inc.
7952 // All rights reserved.
7954 // Redistribution and use in source and binary forms, with or without
7955 // modification, are permitted provided that the following conditions are
7958 // * Redistributions of source code must retain the above copyright
7959 // notice, this list of conditions and the following disclaimer.
7960 // * Redistributions in binary form must reproduce the above
7961 // copyright notice, this list of conditions and the following disclaimer
7962 // in the documentation and/or other materials provided with the
7964 // * Neither the name of Google Inc. nor the names of its
7965 // contributors may be used to endorse or promote products derived from
7966 // this software without specific prior written permission.
7968 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
7969 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
7970 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
7971 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
7972 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
7973 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
7974 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
7975 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
7976 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
7977 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
7978 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
7980 // Author: wan@google.com (Zhanyong Wan)
7988 #if GTEST_OS_WINDOWS_MOBILE
7989 # include <windows.h> // For TerminateProcess()
7990 #elif GTEST_OS_WINDOWS
7992 # include <sys/stat.h>
7994 # include <unistd.h>
7995 #endif // GTEST_OS_WINDOWS_MOBILE
7998 # include <mach/mach_init.h>
7999 # include <mach/task.h>
8000 # include <mach/vm_map.h>
8001 #endif // GTEST_OS_MAC
8004 # include <devctl.h>
8005 # include <sys/procfs.h>
8006 #endif // GTEST_OS_QNX
8009 // Indicates that this translation unit is part of Google Test's
8010 // implementation. It must come before gtest-internal-inl.h is
8011 // included, or there will be a compiler error. This trick is to
8012 // prevent a user from accidentally including gtest-internal-inl.h in
8014 #define GTEST_IMPLEMENTATION_ 1
8015 #undef GTEST_IMPLEMENTATION_
8018 namespace internal {
8020 #if defined(_MSC_VER) || defined(__BORLANDC__)
8021 // MSVC and C++Builder do not provide a definition of STDERR_FILENO.
8022 const int kStdOutFileno = 1;
8023 const int kStdErrFileno = 2;
8025 const int kStdOutFileno = STDOUT_FILENO;
8026 const int kStdErrFileno = STDERR_FILENO;
8031 // Returns the number of threads running in the process, or 0 to indicate that
8032 // we cannot detect it.
8033 size_t GetThreadCount() {
8034 const task_t task = mach_task_self();
8035 mach_msg_type_number_t thread_count;
8036 thread_act_array_t thread_list;
8037 const kern_return_t status = task_threads(task, &thread_list, &thread_count);
8038 if (status == KERN_SUCCESS) {
8039 // task_threads allocates resources in thread_list and we need to free them
8042 reinterpret_cast<vm_address_t>(thread_list),
8043 sizeof(thread_t) * thread_count);
8044 return static_cast<size_t>(thread_count);
8052 // Returns the number of threads running in the process, or 0 to indicate that
8053 // we cannot detect it.
8054 size_t GetThreadCount() {
8055 const int fd = open("/proc/self/as", O_RDONLY);
8059 procfs_info process_info;
8061 devctl(fd, DCMD_PROC_INFO, &process_info, sizeof(process_info), NULL);
8063 if (status == EOK) {
8064 return static_cast<size_t>(process_info.num_threads);
8072 size_t GetThreadCount() {
8073 // There's no portable way to detect the number of threads, so we just
8074 // return 0 to indicate that we cannot detect it.
8078 #endif // GTEST_OS_MAC
8080 #if GTEST_USES_POSIX_RE
8082 // Implements RE. Currently only needed for death tests.
8086 // regfree'ing an invalid regex might crash because the content
8087 // of the regex is undefined. Since the regex's are essentially
8088 // the same, one cannot be valid (or invalid) without the other
8090 regfree(&partial_regex_);
8091 regfree(&full_regex_);
8093 free(const_cast<char*>(pattern_));
8096 // Returns true iff regular expression re matches the entire str.
8097 bool RE::FullMatch(const char* str, const RE& re) {
8098 if (!re.is_valid_) return false;
8101 return regexec(&re.full_regex_, str, 1, &match, 0) == 0;
8104 // Returns true iff regular expression re matches a substring of str
8105 // (including str itself).
8106 bool RE::PartialMatch(const char* str, const RE& re) {
8107 if (!re.is_valid_) return false;
8110 return regexec(&re.partial_regex_, str, 1, &match, 0) == 0;
8113 // Initializes an RE from its string representation.
8114 void RE::Init(const char* regex) {
8115 pattern_ = posix::StrDup(regex);
8117 // Reserves enough bytes to hold the regular expression used for a
8119 const size_t full_regex_len = strlen(regex) + 10;
8120 char* const full_pattern = new char[full_regex_len];
8122 snprintf(full_pattern, full_regex_len, "^(%s)$", regex);
8123 is_valid_ = regcomp(&full_regex_, full_pattern, REG_EXTENDED) == 0;
8124 // We want to call regcomp(&partial_regex_, ...) even if the
8125 // previous expression returns false. Otherwise partial_regex_ may
8126 // not be properly initialized can may cause trouble when it's
8129 // Some implementation of POSIX regex (e.g. on at least some
8130 // versions of Cygwin) doesn't accept the empty string as a valid
8131 // regex. We change it to an equivalent form "()" to be safe.
8133 const char* const partial_regex = (*regex == '\0') ? "()" : regex;
8134 is_valid_ = regcomp(&partial_regex_, partial_regex, REG_EXTENDED) == 0;
8136 EXPECT_TRUE(is_valid_)
8137 << "Regular expression \"" << regex
8138 << "\" is not a valid POSIX Extended regular expression.";
8140 delete[] full_pattern;
8143 #elif GTEST_USES_SIMPLE_RE
8145 // Returns true iff ch appears anywhere in str (excluding the
8146 // terminating '\0' character).
8147 bool IsInSet(char ch, const char* str) {
8148 return ch != '\0' && strchr(str, ch) != NULL;
8151 // Returns true iff ch belongs to the given classification. Unlike
8152 // similar functions in <ctype.h>, these aren't affected by the
8154 bool IsAsciiDigit(char ch) { return '0' <= ch && ch <= '9'; }
8155 bool IsAsciiPunct(char ch) {
8156 return IsInSet(ch, "^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~");
8158 bool IsRepeat(char ch) { return IsInSet(ch, "?*+"); }
8159 bool IsAsciiWhiteSpace(char ch) { return IsInSet(ch, " \f\n\r\t\v"); }
8160 bool IsAsciiWordChar(char ch) {
8161 return ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') ||
8162 ('0' <= ch && ch <= '9') || ch == '_';
8165 // Returns true iff "\\c" is a supported escape sequence.
8166 bool IsValidEscape(char c) {
8167 return (IsAsciiPunct(c) || IsInSet(c, "dDfnrsStvwW"));
8170 // Returns true iff the given atom (specified by escaped and pattern)
8171 // matches ch. The result is undefined if the atom is invalid.
8172 bool AtomMatchesChar(bool escaped, char pattern_char, char ch) {
8173 if (escaped) { // "\\p" where p is pattern_char.
8174 switch (pattern_char) {
8175 case 'd': return IsAsciiDigit(ch);
8176 case 'D': return !IsAsciiDigit(ch);
8177 case 'f': return ch == '\f';
8178 case 'n': return ch == '\n';
8179 case 'r': return ch == '\r';
8180 case 's': return IsAsciiWhiteSpace(ch);
8181 case 'S': return !IsAsciiWhiteSpace(ch);
8182 case 't': return ch == '\t';
8183 case 'v': return ch == '\v';
8184 case 'w': return IsAsciiWordChar(ch);
8185 case 'W': return !IsAsciiWordChar(ch);
8187 return IsAsciiPunct(pattern_char) && pattern_char == ch;
8190 return (pattern_char == '.' && ch != '\n') || pattern_char == ch;
8193 // Helper function used by ValidateRegex() to format error messages.
8194 String FormatRegexSyntaxError(const char* regex, int index) {
8195 return (Message() << "Syntax error at index " << index
8196 << " in simple regular expression \"" << regex << "\": ").GetString();
8199 // Generates non-fatal failures and returns false if regex is invalid;
8200 // otherwise returns true.
8201 bool ValidateRegex(const char* regex) {
8202 if (regex == NULL) {
8203 // TODO(wan@google.com): fix the source file location in the
8204 // assertion failures to match where the regex is used in user
8206 ADD_FAILURE() << "NULL is not a valid simple regular expression.";
8210 bool is_valid = true;
8212 // True iff ?, *, or + can follow the previous atom.
8213 bool prev_repeatable = false;
8214 for (int i = 0; regex[i]; i++) {
8215 if (regex[i] == '\\') { // An escape sequence
8217 if (regex[i] == '\0') {
8218 ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
8219 << "'\\' cannot appear at the end.";
8223 if (!IsValidEscape(regex[i])) {
8224 ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
8225 << "invalid escape sequence \"\\" << regex[i] << "\".";
8228 prev_repeatable = true;
8229 } else { // Not an escape sequence.
8230 const char ch = regex[i];
8232 if (ch == '^' && i > 0) {
8233 ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
8234 << "'^' can only appear at the beginning.";
8236 } else if (ch == '$' && regex[i + 1] != '\0') {
8237 ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
8238 << "'$' can only appear at the end.";
8240 } else if (IsInSet(ch, "()[]{}|")) {
8241 ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
8242 << "'" << ch << "' is unsupported.";
8244 } else if (IsRepeat(ch) && !prev_repeatable) {
8245 ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
8246 << "'" << ch << "' can only follow a repeatable token.";
8250 prev_repeatable = !IsInSet(ch, "^$?*+");
8257 // Matches a repeated regex atom followed by a valid simple regular
8258 // expression. The regex atom is defined as c if escaped is false,
8259 // or \c otherwise. repeat is the repetition meta character (?, *,
8260 // or +). The behavior is undefined if str contains too many
8261 // characters to be indexable by size_t, in which case the test will
8262 // probably time out anyway. We are fine with this limitation as
8263 // std::string has it too.
8264 bool MatchRepetitionAndRegexAtHead(
8265 bool escaped, char c, char repeat, const char* regex,
8267 const size_t min_count = (repeat == '+') ? 1 : 0;
8268 const size_t max_count = (repeat == '?') ? 1 :
8269 static_cast<size_t>(-1) - 1;
8270 // We cannot call numeric_limits::max() as it conflicts with the
8271 // max() macro on Windows.
8273 for (size_t i = 0; i <= max_count; ++i) {
8274 // We know that the atom matches each of the first i characters in str.
8275 if (i >= min_count && MatchRegexAtHead(regex, str + i)) {
8276 // We have enough matches at the head, and the tail matches too.
8277 // Since we only care about *whether* the pattern matches str
8278 // (as opposed to *how* it matches), there is no need to find a
8282 if (str[i] == '\0' || !AtomMatchesChar(escaped, c, str[i]))
8288 // Returns true iff regex matches a prefix of str. regex must be a
8289 // valid simple regular expression and not start with "^", or the
8290 // result is undefined.
8291 bool MatchRegexAtHead(const char* regex, const char* str) {
8292 if (*regex == '\0') // An empty regex matches a prefix of anything.
8295 // "$" only matches the end of a string. Note that regex being
8296 // valid guarantees that there's nothing after "$" in it.
8298 return *str == '\0';
8300 // Is the first thing in regex an escape sequence?
8301 const bool escaped = *regex == '\\';
8304 if (IsRepeat(regex[1])) {
8305 // MatchRepetitionAndRegexAtHead() calls MatchRegexAtHead(), so
8306 // here's an indirect recursion. It terminates as the regex gets
8307 // shorter in each recursion.
8308 return MatchRepetitionAndRegexAtHead(
8309 escaped, regex[0], regex[1], regex + 2, str);
8311 // regex isn't empty, isn't "$", and doesn't start with a
8312 // repetition. We match the first atom of regex with the first
8313 // character of str and recurse.
8314 return (*str != '\0') && AtomMatchesChar(escaped, *regex, *str) &&
8315 MatchRegexAtHead(regex + 1, str + 1);
8319 // Returns true iff regex matches any substring of str. regex must be
8320 // a valid simple regular expression, or the result is undefined.
8322 // The algorithm is recursive, but the recursion depth doesn't exceed
8323 // the regex length, so we won't need to worry about running out of
8324 // stack space normally. In rare cases the time complexity can be
8325 // exponential with respect to the regex length + the string length,
8326 // but usually it's must faster (often close to linear).
8327 bool MatchRegexAnywhere(const char* regex, const char* str) {
8328 if (regex == NULL || str == NULL)
8332 return MatchRegexAtHead(regex + 1, str);
8334 // A successful match can be anywhere in str.
8336 if (MatchRegexAtHead(regex, str))
8338 } while (*str++ != '\0');
8342 // Implements the RE class.
8345 free(const_cast<char*>(pattern_));
8346 free(const_cast<char*>(full_pattern_));
8349 // Returns true iff regular expression re matches the entire str.
8350 bool RE::FullMatch(const char* str, const RE& re) {
8351 return re.is_valid_ && MatchRegexAnywhere(re.full_pattern_, str);
8354 // Returns true iff regular expression re matches a substring of str
8355 // (including str itself).
8356 bool RE::PartialMatch(const char* str, const RE& re) {
8357 return re.is_valid_ && MatchRegexAnywhere(re.pattern_, str);
8360 // Initializes an RE from its string representation.
8361 void RE::Init(const char* regex) {
8362 pattern_ = full_pattern_ = NULL;
8363 if (regex != NULL) {
8364 pattern_ = posix::StrDup(regex);
8367 is_valid_ = ValidateRegex(regex);
8369 // No need to calculate the full pattern when the regex is invalid.
8373 const size_t len = strlen(regex);
8374 // Reserves enough bytes to hold the regular expression used for a
8375 // full match: we need space to prepend a '^', append a '$', and
8376 // terminate the string with '\0'.
8377 char* buffer = static_cast<char*>(malloc(len + 3));
8378 full_pattern_ = buffer;
8381 *buffer++ = '^'; // Makes sure full_pattern_ starts with '^'.
8383 // We don't use snprintf or strncpy, as they trigger a warning when
8384 // compiled with VC++ 8.0.
8385 memcpy(buffer, regex, len);
8388 if (len == 0 || regex[len - 1] != '$')
8389 *buffer++ = '$'; // Makes sure full_pattern_ ends with '$'.
8394 #endif // GTEST_USES_POSIX_RE
8396 const char kUnknownFile[] = "unknown file";
8398 // Formats a source file path and a line number as they would appear
8399 // in an error message from the compiler used to compile this code.
8400 GTEST_API_ ::std::string FormatFileLocation(const char* file, int line) {
8401 const char* const file_name = file == NULL ? kUnknownFile : file;
8404 return String::Format("%s:", file_name).c_str();
8407 return String::Format("%s(%d):", file_name, line).c_str();
8409 return String::Format("%s:%d:", file_name, line).c_str();
8413 // Formats a file location for compiler-independent XML output.
8414 // Although this function is not platform dependent, we put it next to
8415 // FormatFileLocation in order to contrast the two functions.
8416 // Note that FormatCompilerIndependentFileLocation() does NOT append colon
8417 // to the file location it produces, unlike FormatFileLocation().
8418 GTEST_API_ ::std::string FormatCompilerIndependentFileLocation(
8419 const char* file, int line) {
8420 const char* const file_name = file == NULL ? kUnknownFile : file;
8425 return String::Format("%s:%d", file_name, line).c_str();
8429 GTestLog::GTestLog(GTestLogSeverity severity, const char* file, int line)
8430 : severity_(severity) {
8431 const char* const marker =
8432 severity == GTEST_INFO ? "[ INFO ]" :
8433 severity == GTEST_WARNING ? "[WARNING]" :
8434 severity == GTEST_ERROR ? "[ ERROR ]" : "[ FATAL ]";
8435 GetStream() << ::std::endl << marker << " "
8436 << FormatFileLocation(file, line).c_str() << ": ";
8439 // Flushes the buffers and, if severity is GTEST_FATAL, aborts the program.
8440 GTestLog::~GTestLog() {
8441 GetStream() << ::std::endl;
8442 if (severity_ == GTEST_FATAL) {
8447 // Disable Microsoft deprecation warnings for POSIX functions called from
8448 // this class (creat, dup, dup2, and close)
8450 # pragma warning(push)
8451 # pragma warning(disable: 4996)
8454 #if GTEST_HAS_STREAM_REDIRECTION
8456 // Object that captures an output stream (stdout/stderr).
8457 class CapturedStream {
8459 // The ctor redirects the stream to a temporary file.
8460 CapturedStream(int fd) : fd_(fd), uncaptured_fd_(dup(fd)) {
8461 # if GTEST_OS_WINDOWS
8462 char temp_dir_path[MAX_PATH + 1] = { '\0' }; // NOLINT
8463 char temp_file_path[MAX_PATH + 1] = { '\0' }; // NOLINT
8465 ::GetTempPathA(sizeof(temp_dir_path), temp_dir_path);
8466 const UINT success = ::GetTempFileNameA(temp_dir_path,
8468 0, // Generate unique file name.
8470 GTEST_CHECK_(success != 0)
8471 << "Unable to create a temporary file in " << temp_dir_path;
8472 const int captured_fd = creat(temp_file_path, _S_IREAD | _S_IWRITE);
8473 GTEST_CHECK_(captured_fd != -1) << "Unable to open temporary file "
8475 filename_ = temp_file_path;
8477 // There's no guarantee that a test has write access to the current
8478 // directory, so we create the temporary file in the /tmp directory instead.
8479 // We use /tmp on most systems, and /mnt/sdcard on Android. That's because
8480 // Android doesn't have /tmp.
8481 # if GTEST_OS_LINUX_ANDROID
8482 char name_template[] = "/mnt/sdcard/gtest_captured_stream.XXXXXX";
8484 char name_template[] = "/tmp/captured_stream.XXXXXX";
8485 # endif // GTEST_OS_LINUX_ANDROID
8486 const int captured_fd = mkstemp(name_template);
8487 filename_ = name_template;
8488 # endif // GTEST_OS_WINDOWS
8490 dup2(captured_fd, fd_);
8495 remove(filename_.c_str());
8498 String GetCapturedString() {
8499 if (uncaptured_fd_ != -1) {
8500 // Restores the original stream.
8502 dup2(uncaptured_fd_, fd_);
8503 close(uncaptured_fd_);
8504 uncaptured_fd_ = -1;
8507 FILE* const file = posix::FOpen(filename_.c_str(), "r");
8508 const String content = ReadEntireFile(file);
8509 posix::FClose(file);
8514 // Reads the entire content of a file as a String.
8515 static String ReadEntireFile(FILE* file);
8517 // Returns the size (in bytes) of a file.
8518 static size_t GetFileSize(FILE* file);
8520 const int fd_; // A stream to capture.
8522 // Name of the temporary file holding the stderr output.
8523 ::std::string filename_;
8525 GTEST_DISALLOW_COPY_AND_ASSIGN_(CapturedStream);
8528 // Returns the size (in bytes) of a file.
8529 size_t CapturedStream::GetFileSize(FILE* file) {
8530 fseek(file, 0, SEEK_END);
8531 return static_cast<size_t>(ftell(file));
8534 // Reads the entire content of a file as a string.
8535 String CapturedStream::ReadEntireFile(FILE* file) {
8536 const size_t file_size = GetFileSize(file);
8537 char* const buffer = new char[file_size];
8539 size_t bytes_last_read = 0; // # of bytes read in the last fread()
8540 size_t bytes_read = 0; // # of bytes read so far
8542 fseek(file, 0, SEEK_SET);
8544 // Keeps reading the file until we cannot read further or the
8545 // pre-determined file size is reached.
8547 bytes_last_read = fread(buffer+bytes_read, 1, file_size-bytes_read, file);
8548 bytes_read += bytes_last_read;
8549 } while (bytes_last_read > 0 && bytes_read < file_size);
8551 const String content(buffer, bytes_read);
8558 # pragma warning(pop)
8561 static CapturedStream* g_captured_stderr = NULL;
8562 static CapturedStream* g_captured_stdout = NULL;
8564 // Starts capturing an output stream (stdout/stderr).
8565 static void CaptureStream(int fd, const char* stream_name, CapturedStream** stream) {
8566 if (*stream != NULL) {
8567 GTEST_LOG_(FATAL) << "Only one " << stream_name
8568 << " capturer can exist at a time.";
8570 *stream = new CapturedStream(fd);
8573 // Stops capturing the output stream and returns the captured string.
8574 static String GetCapturedStream(CapturedStream** captured_stream) {
8575 const String content = (*captured_stream)->GetCapturedString();
8577 delete *captured_stream;
8578 *captured_stream = NULL;
8583 // Starts capturing stdout.
8584 void CaptureStdout() {
8585 CaptureStream(kStdOutFileno, "stdout", &g_captured_stdout);
8588 // Starts capturing stderr.
8589 void CaptureStderr() {
8590 CaptureStream(kStdErrFileno, "stderr", &g_captured_stderr);
8593 // Stops capturing stdout and returns the captured string.
8594 String GetCapturedStdout() { return GetCapturedStream(&g_captured_stdout); }
8596 // Stops capturing stderr and returns the captured string.
8597 String GetCapturedStderr() { return GetCapturedStream(&g_captured_stderr); }
8599 #endif // GTEST_HAS_STREAM_REDIRECTION
8601 #if GTEST_HAS_DEATH_TEST
8603 // A copy of all command line arguments. Set by InitGoogleTest().
8604 ::std::vector<testing::internal::string> g_argvs;
8606 static const ::std::vector<testing::internal::string>* g_injected_test_argvs =
8609 void SetInjectableArgvs(const ::std::vector<testing::internal::string>* argvs) {
8610 if (g_injected_test_argvs != argvs)
8611 delete g_injected_test_argvs;
8612 g_injected_test_argvs = argvs;
8615 const ::std::vector<testing::internal::string>& GetInjectableArgvs() {
8616 if (g_injected_test_argvs != NULL) {
8617 return *g_injected_test_argvs;
8621 #endif // GTEST_HAS_DEATH_TEST
8623 #if GTEST_OS_WINDOWS_MOBILE
8627 TerminateProcess(GetCurrentProcess(), 1);
8629 } // namespace posix
8630 #endif // GTEST_OS_WINDOWS_MOBILE
8632 // Returns the name of the environment variable corresponding to the
8633 // given flag. For example, FlagToEnvVar("foo") will return
8634 // "GTEST_FOO" in the open-source version.
8635 static String FlagToEnvVar(const char* flag) {
8636 const String full_flag =
8637 (Message() << GTEST_FLAG_PREFIX_ << flag).GetString();
8640 for (size_t i = 0; i != full_flag.length(); i++) {
8641 env_var << ToUpper(full_flag.c_str()[i]);
8644 return env_var.GetString();
8647 // Parses 'str' for a 32-bit signed integer. If successful, writes
8648 // the result to *value and returns true; otherwise leaves *value
8649 // unchanged and returns false.
8650 bool ParseInt32(const Message& src_text, const char* str, Int32* value) {
8651 // Parses the environment variable as a decimal integer.
8653 const long long_value = strtol(str, &end, 10); // NOLINT
8655 // Has strtol() consumed all characters in the string?
8657 // No - an invalid character was encountered.
8659 msg << "WARNING: " << src_text
8660 << " is expected to be a 32-bit integer, but actually"
8661 << " has value \"" << str << "\".\n";
8662 printf("%s", msg.GetString().c_str());
8667 // Is the parsed value in the range of an Int32?
8668 const Int32 result = static_cast<Int32>(long_value);
8669 if (long_value == LONG_MAX || long_value == LONG_MIN ||
8670 // The parsed value overflows as a long. (strtol() returns
8671 // LONG_MAX or LONG_MIN when the input overflows.)
8672 result != long_value
8673 // The parsed value overflows as an Int32.
8676 msg << "WARNING: " << src_text
8677 << " is expected to be a 32-bit integer, but actually"
8678 << " has value " << str << ", which overflows.\n";
8679 printf("%s", msg.GetString().c_str());
8688 // Reads and returns the Boolean environment variable corresponding to
8689 // the given flag; if it's not set, returns default_value.
8691 // The value is considered true iff it's not "0".
8692 bool BoolFromGTestEnv(const char* flag, bool default_value) {
8693 const String env_var = FlagToEnvVar(flag);
8694 const char* const string_value = posix::GetEnv(env_var.c_str());
8695 return string_value == NULL ?
8696 default_value : strcmp(string_value, "0") != 0;
8699 // Reads and returns a 32-bit integer stored in the environment
8700 // variable corresponding to the given flag; if it isn't set or
8701 // doesn't represent a valid 32-bit integer, returns default_value.
8702 Int32 Int32FromGTestEnv(const char* flag, Int32 default_value) {
8703 const String env_var = FlagToEnvVar(flag);
8704 const char* const string_value = posix::GetEnv(env_var.c_str());
8705 if (string_value == NULL) {
8706 // The environment variable is not set.
8707 return default_value;
8710 Int32 result = default_value;
8711 if (!ParseInt32(Message() << "Environment variable " << env_var,
8712 string_value, &result)) {
8713 printf("The default value %s is used.\n",
8714 (Message() << default_value).GetString().c_str());
8716 return default_value;
8722 // Reads and returns the string environment variable corresponding to
8723 // the given flag; if it's not set, returns default_value.
8724 const char* StringFromGTestEnv(const char* flag, const char* default_value) {
8725 const String env_var = FlagToEnvVar(flag);
8726 const char* const value = posix::GetEnv(env_var.c_str());
8727 return value == NULL ? default_value : value;
8730 } // namespace internal
8731 } // namespace testing
8732 // Copyright 2007, Google Inc.
8733 // All rights reserved.
8735 // Redistribution and use in source and binary forms, with or without
8736 // modification, are permitted provided that the following conditions are
8739 // * Redistributions of source code must retain the above copyright
8740 // notice, this list of conditions and the following disclaimer.
8741 // * Redistributions in binary form must reproduce the above
8742 // copyright notice, this list of conditions and the following disclaimer
8743 // in the documentation and/or other materials provided with the
8745 // * Neither the name of Google Inc. nor the names of its
8746 // contributors may be used to endorse or promote products derived from
8747 // this software without specific prior written permission.
8749 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
8750 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
8751 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
8752 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
8753 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
8754 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
8755 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
8756 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
8757 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
8758 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
8759 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
8761 // Author: wan@google.com (Zhanyong Wan)
8763 // Google Test - The Google C++ Testing Framework
8765 // This file implements a universal value printer that can print a
8766 // value of any type T:
8768 // void ::testing::internal::UniversalPrinter<T>::Print(value, ostream_ptr);
8770 // It uses the << operator when possible, and prints the bytes in the
8771 // object otherwise. A user can override its behavior for a class
8772 // type Foo by defining either operator<<(::std::ostream&, const Foo&)
8773 // or void PrintTo(const Foo&, ::std::ostream*) in the namespace that
8778 #include <ostream> // NOLINT
8785 using ::std::ostream;
8787 // Prints a segment of bytes in the given object.
8788 void PrintByteSegmentInObjectTo(const unsigned char* obj_bytes, size_t start,
8789 size_t count, ostream* os) {
8791 for (size_t i = 0; i != count; i++) {
8792 const size_t j = start + i;
8794 // Organizes the bytes into groups of 2 for easy parsing by
8801 GTEST_SNPRINTF_(text, sizeof(text), "%02X", obj_bytes[j]);
8806 // Prints the bytes in the given value to the given ostream.
8807 void PrintBytesInObjectToImpl(const unsigned char* obj_bytes, size_t count,
8809 // Tells the user how big the object is.
8810 *os << count << "-byte object <";
8812 const size_t kThreshold = 132;
8813 const size_t kChunkSize = 64;
8814 // If the object size is bigger than kThreshold, we'll have to omit
8815 // some details by printing only the first and the last kChunkSize
8817 // TODO(wan): let the user control the threshold using a flag.
8818 if (count < kThreshold) {
8819 PrintByteSegmentInObjectTo(obj_bytes, 0, count, os);
8821 PrintByteSegmentInObjectTo(obj_bytes, 0, kChunkSize, os);
8823 // Rounds up to 2-byte boundary.
8824 const size_t resume_pos = (count - kChunkSize + 1)/2*2;
8825 PrintByteSegmentInObjectTo(obj_bytes, resume_pos, count - resume_pos, os);
8832 namespace internal2 {
8834 // Delegates to PrintBytesInObjectToImpl() to print the bytes in the
8835 // given object. The delegation simplifies the implementation, which
8836 // uses the << operator and thus is easier done outside of the
8837 // ::testing::internal namespace, which contains a << operator that
8838 // sometimes conflicts with the one in STL.
8839 void PrintBytesInObjectTo(const unsigned char* obj_bytes, size_t count,
8841 PrintBytesInObjectToImpl(obj_bytes, count, os);
8844 } // namespace internal2
8846 namespace internal {
8848 // Depending on the value of a char (or wchar_t), we print it in one
8849 // of three formats:
8850 // - as is if it's a printable ASCII (e.g. 'a', '2', ' '),
8851 // - as a hexidecimal escape sequence (e.g. '\x7F'), or
8852 // - as a special escape sequence (e.g. '\r', '\n').
8859 // Returns true if c is a printable ASCII character. We test the
8860 // value of c directly instead of calling isprint(), which is buggy on
8862 inline bool IsPrintableAscii(wchar_t c) {
8863 return 0x20 <= c && c <= 0x7E;
8866 // Prints a wide or narrow char c as a character literal without the
8867 // quotes, escaping it when necessary; returns how c was formatted.
8868 // The template argument UnsignedChar is the unsigned version of Char,
8869 // which is the type of c.
8870 template <typename UnsignedChar, typename Char>
8871 static CharFormat PrintAsCharLiteralTo(Char c, ostream* os) {
8872 switch (static_cast<wchar_t>(c)) {
8904 if (IsPrintableAscii(c)) {
8905 *os << static_cast<char>(c);
8908 *os << String::Format("\\x%X", static_cast<UnsignedChar>(c));
8912 return kSpecialEscape;
8915 // Prints a wchar_t c as if it's part of a string literal, escaping it when
8916 // necessary; returns how c was formatted.
8917 static CharFormat PrintAsStringLiteralTo(wchar_t c, ostream* os) {
8924 return kSpecialEscape;
8926 return PrintAsCharLiteralTo<wchar_t>(c, os);
8930 // Prints a char c as if it's part of a string literal, escaping it when
8931 // necessary; returns how c was formatted.
8932 static CharFormat PrintAsStringLiteralTo(char c, ostream* os) {
8933 return PrintAsStringLiteralTo(
8934 static_cast<wchar_t>(static_cast<unsigned char>(c)), os);
8937 // Prints a wide or narrow character c and its code. '\0' is printed
8938 // as "'\\0'", other unprintable characters are also properly escaped
8939 // using the standard C++ escape sequence. The template argument
8940 // UnsignedChar is the unsigned version of Char, which is the type of c.
8941 template <typename UnsignedChar, typename Char>
8942 void PrintCharAndCodeTo(Char c, ostream* os) {
8943 // First, print c as a literal in the most readable form we can find.
8944 *os << ((sizeof(c) > 1) ? "L'" : "'");
8945 const CharFormat format = PrintAsCharLiteralTo<UnsignedChar>(c, os);
8948 // To aid user debugging, we also print c's code in decimal, unless
8949 // it's 0 (in which case c was printed as '\\0', making the code
8953 *os << " (" << String::Format("%d", c).c_str();
8955 // For more convenience, we print c's code again in hexidecimal,
8956 // unless c was already printed in the form '\x##' or the code is in
8958 if (format == kHexEscape || (1 <= c && c <= 9)) {
8961 *os << String::Format(", 0x%X",
8962 static_cast<UnsignedChar>(c)).c_str();
8967 void PrintTo(unsigned char c, ::std::ostream* os) {
8968 PrintCharAndCodeTo<unsigned char>(c, os);
8970 void PrintTo(signed char c, ::std::ostream* os) {
8971 PrintCharAndCodeTo<unsigned char>(c, os);
8974 // Prints a wchar_t as a symbol if it is printable or as its internal
8975 // code otherwise and also as its code. L'\0' is printed as "L'\\0'".
8976 void PrintTo(wchar_t wc, ostream* os) {
8977 PrintCharAndCodeTo<wchar_t>(wc, os);
8980 // Prints the given array of characters to the ostream. CharType must be either
8982 // The array starts at begin, the length is len, it may include '\0' characters
8983 // and may not be NUL-terminated.
8984 template <typename CharType>
8985 static void PrintCharsAsStringTo(
8986 const CharType* begin, size_t len, ostream* os) {
8987 const char* const kQuoteBegin = sizeof(CharType) == 1 ? "\"" : "L\"";
8989 bool is_previous_hex = false;
8990 for (size_t index = 0; index < len; ++index) {
8991 const CharType cur = begin[index];
8992 if (is_previous_hex && IsXDigit(cur)) {
8993 // Previous character is of '\x..' form and this character can be
8994 // interpreted as another hexadecimal digit in its number. Break string to
8996 *os << "\" " << kQuoteBegin;
8998 is_previous_hex = PrintAsStringLiteralTo(cur, os) == kHexEscape;
9003 // Prints a (const) char/wchar_t array of 'len' elements, starting at address
9004 // 'begin'. CharType must be either char or wchar_t.
9005 template <typename CharType>
9006 static void UniversalPrintCharArray(
9007 const CharType* begin, size_t len, ostream* os) {
9009 // const char kFoo[] = "foo";
9010 // generates an array of 4, not 3, elements, with the last one being '\0'.
9012 // Therefore when printing a char array, we don't print the last element if
9013 // it's '\0', such that the output matches the string literal as it's
9014 // written in the source code.
9015 if (len > 0 && begin[len - 1] == '\0') {
9016 PrintCharsAsStringTo(begin, len - 1, os);
9020 // If, however, the last element in the array is not '\0', e.g.
9021 // const char kFoo[] = { 'f', 'o', 'o' };
9022 // we must print the entire array. We also print a message to indicate
9023 // that the array is not NUL-terminated.
9024 PrintCharsAsStringTo(begin, len, os);
9025 *os << " (no terminating NUL)";
9028 // Prints a (const) char array of 'len' elements, starting at address 'begin'.
9029 void UniversalPrintArray(const char* begin, size_t len, ostream* os) {
9030 UniversalPrintCharArray(begin, len, os);
9033 // Prints a (const) wchar_t array of 'len' elements, starting at address
9035 void UniversalPrintArray(const wchar_t* begin, size_t len, ostream* os) {
9036 UniversalPrintCharArray(begin, len, os);
9039 // Prints the given C string to the ostream.
9040 void PrintTo(const char* s, ostream* os) {
9044 *os << ImplicitCast_<const void*>(s) << " pointing to ";
9045 PrintCharsAsStringTo(s, strlen(s), os);
9049 // MSVC compiler can be configured to define whar_t as a typedef
9050 // of unsigned short. Defining an overload for const wchar_t* in that case
9051 // would cause pointers to unsigned shorts be printed as wide strings,
9052 // possibly accessing more memory than intended and causing invalid
9053 // memory accesses. MSVC defines _NATIVE_WCHAR_T_DEFINED symbol when
9054 // wchar_t is implemented as a native type.
9055 #if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED)
9056 // Prints the given wide C string to the ostream.
9057 void PrintTo(const wchar_t* s, ostream* os) {
9061 *os << ImplicitCast_<const void*>(s) << " pointing to ";
9062 PrintCharsAsStringTo(s, wcslen(s), os);
9065 #endif // wchar_t is native
9067 // Prints a ::string object.
9068 #if GTEST_HAS_GLOBAL_STRING
9069 void PrintStringTo(const ::string& s, ostream* os) {
9070 PrintCharsAsStringTo(s.data(), s.size(), os);
9072 #endif // GTEST_HAS_GLOBAL_STRING
9074 void PrintStringTo(const ::std::string& s, ostream* os) {
9075 PrintCharsAsStringTo(s.data(), s.size(), os);
9078 // Prints a ::wstring object.
9079 #if GTEST_HAS_GLOBAL_WSTRING
9080 void PrintWideStringTo(const ::wstring& s, ostream* os) {
9081 PrintCharsAsStringTo(s.data(), s.size(), os);
9083 #endif // GTEST_HAS_GLOBAL_WSTRING
9085 #if GTEST_HAS_STD_WSTRING
9086 void PrintWideStringTo(const ::std::wstring& s, ostream* os) {
9087 PrintCharsAsStringTo(s.data(), s.size(), os);
9089 #endif // GTEST_HAS_STD_WSTRING
9091 } // namespace internal
9093 } // namespace testing
9094 // Copyright 2008, Google Inc.
9095 // All rights reserved.
9097 // Redistribution and use in source and binary forms, with or without
9098 // modification, are permitted provided that the following conditions are
9101 // * Redistributions of source code must retain the above copyright
9102 // notice, this list of conditions and the following disclaimer.
9103 // * Redistributions in binary form must reproduce the above
9104 // copyright notice, this list of conditions and the following disclaimer
9105 // in the documentation and/or other materials provided with the
9107 // * Neither the name of Google Inc. nor the names of its
9108 // contributors may be used to endorse or promote products derived from
9109 // this software without specific prior written permission.
9111 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
9112 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
9113 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
9114 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9115 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
9116 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9117 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
9118 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
9119 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
9120 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
9121 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
9123 // Author: mheule@google.com (Markus Heule)
9125 // The Google C++ Testing Framework (Google Test)
9128 // Indicates that this translation unit is part of Google Test's
9129 // implementation. It must come before gtest-internal-inl.h is
9130 // included, or there will be a compiler error. This trick is to
9131 // prevent a user from accidentally including gtest-internal-inl.h in
9133 #define GTEST_IMPLEMENTATION_ 1
9134 #undef GTEST_IMPLEMENTATION_
9138 using internal::GetUnitTestImpl;
9140 // Gets the summary of the failure message by omitting the stack trace
9142 internal::String TestPartResult::ExtractSummary(const char* message) {
9143 const char* const stack_trace = strstr(message, internal::kStackTraceMarker);
9144 return stack_trace == NULL ? internal::String(message) :
9145 internal::String(message, stack_trace - message);
9148 // Prints a TestPartResult object.
9149 std::ostream& operator<<(std::ostream& os, const TestPartResult& result) {
9151 << result.file_name() << ":" << result.line_number() << ": "
9152 << (result.type() == TestPartResult::kSuccess ? "Success" :
9153 result.type() == TestPartResult::kFatalFailure ? "Fatal failure" :
9154 "Non-fatal failure") << ":\n"
9155 << result.message() << std::endl;
9158 // Appends a TestPartResult to the array.
9159 void TestPartResultArray::Append(const TestPartResult& result) {
9160 array_.push_back(result);
9163 // Returns the TestPartResult at the given index (0-based).
9164 const TestPartResult& TestPartResultArray::GetTestPartResult(int index) const {
9165 if (index < 0 || index >= size()) {
9166 printf("\nInvalid index (%d) into TestPartResultArray.\n", index);
9167 internal::posix::Abort();
9170 return array_[index];
9173 // Returns the number of TestPartResult objects in the array.
9174 int TestPartResultArray::size() const {
9175 return static_cast<int>(array_.size());
9178 namespace internal {
9180 HasNewFatalFailureHelper::HasNewFatalFailureHelper()
9181 : has_new_fatal_failure_(false),
9182 original_reporter_(GetUnitTestImpl()->
9183 GetTestPartResultReporterForCurrentThread()) {
9184 GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(this);
9187 HasNewFatalFailureHelper::~HasNewFatalFailureHelper() {
9188 GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(
9189 original_reporter_);
9192 void HasNewFatalFailureHelper::ReportTestPartResult(
9193 const TestPartResult& result) {
9194 if (result.fatally_failed())
9195 has_new_fatal_failure_ = true;
9196 original_reporter_->ReportTestPartResult(result);
9199 } // namespace internal
9201 } // namespace testing
9202 // Copyright 2008 Google Inc.
9203 // All Rights Reserved.
9205 // Redistribution and use in source and binary forms, with or without
9206 // modification, are permitted provided that the following conditions are
9209 // * Redistributions of source code must retain the above copyright
9210 // notice, this list of conditions and the following disclaimer.
9211 // * Redistributions in binary form must reproduce the above
9212 // copyright notice, this list of conditions and the following disclaimer
9213 // in the documentation and/or other materials provided with the
9215 // * Neither the name of Google Inc. nor the names of its
9216 // contributors may be used to endorse or promote products derived from
9217 // this software without specific prior written permission.
9219 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
9220 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
9221 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
9222 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9223 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
9224 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9225 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
9226 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
9227 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
9228 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
9229 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
9231 // Author: wan@google.com (Zhanyong Wan)
9235 namespace internal {
9237 #if GTEST_HAS_TYPED_TEST_P
9239 // Skips to the first non-space char in str. Returns an empty string if str
9240 // contains only whitespace characters.
9241 static const char* SkipSpaces(const char* str) {
9242 while (IsSpace(*str))
9247 // Verifies that registered_tests match the test names in
9248 // defined_test_names_; returns registered_tests if successful, or
9249 // aborts the program otherwise.
9250 const char* TypedTestCasePState::VerifyRegisteredTestNames(
9251 const char* file, int line, const char* registered_tests) {
9252 typedef ::std::set<const char*>::const_iterator DefinedTestIter;
9255 // Skip initial whitespace in registered_tests since some
9256 // preprocessors prefix stringizied literals with whitespace.
9257 registered_tests = SkipSpaces(registered_tests);
9260 ::std::set<String> tests;
9261 for (const char* names = registered_tests; names != NULL;
9262 names = SkipComma(names)) {
9263 const String name = GetPrefixUntilComma(names);
9264 if (tests.count(name) != 0) {
9265 errors << "Test " << name << " is listed more than once.\n";
9270 for (DefinedTestIter it = defined_test_names_.begin();
9271 it != defined_test_names_.end();
9282 errors << "No test named " << name
9283 << " can be found in this test case.\n";
9287 for (DefinedTestIter it = defined_test_names_.begin();
9288 it != defined_test_names_.end();
9290 if (tests.count(*it) == 0) {
9291 errors << "You forgot to list test " << *it << ".\n";
9295 const String& errors_str = errors.GetString();
9296 if (errors_str != "") {
9297 fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(),
9298 errors_str.c_str());
9303 return registered_tests;
9306 #endif // GTEST_HAS_TYPED_TEST_P
9308 } // namespace internal
9309 } // namespace testing