1 // Copyright 2008, Google Inc.
2 // All rights reserved.
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
8 // * Redistributions of source code must retain the above copyright
9 // notice, this list of conditions and the following disclaimer.
10 // * Redistributions in binary form must reproduce the above
11 // copyright notice, this list of conditions and the following disclaimer
12 // in the documentation and/or other materials provided with the
14 // * Neither the name of Google Inc. nor the names of its
15 // contributors may be used to endorse or promote products derived from
16 // this software without specific prior written permission.
18 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 // Author: mheule@google.com (Markus Heule)
32 // Google C++ Testing Framework (Google Test)
34 // Sometimes it's desirable to build Google Test by compiling a single file.
35 // This file serves this purpose.
37 // This line ensures that gtest.h can be compiled on its own, even
39 #include "gtest/gtest.h"
41 // The following lines pull in the real gtest *.cc files.
42 // Copyright 2005, Google Inc.
43 // All rights reserved.
45 // Redistribution and use in source and binary forms, with or without
46 // modification, are permitted provided that the following conditions are
49 // * Redistributions of source code must retain the above copyright
50 // notice, this list of conditions and the following disclaimer.
51 // * Redistributions in binary form must reproduce the above
52 // copyright notice, this list of conditions and the following disclaimer
53 // in the documentation and/or other materials provided with the
55 // * Neither the name of Google Inc. nor the names of its
56 // contributors may be used to endorse or promote products derived from
57 // this software without specific prior written permission.
59 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
60 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
61 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
62 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
63 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
64 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
65 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
66 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
67 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
68 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
69 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
71 // Author: wan@google.com (Zhanyong Wan)
73 // The Google C++ Testing Framework (Google Test)
75 // Copyright 2007, Google Inc.
76 // All rights reserved.
78 // Redistribution and use in source and binary forms, with or without
79 // modification, are permitted provided that the following conditions are
82 // * Redistributions of source code must retain the above copyright
83 // notice, this list of conditions and the following disclaimer.
84 // * Redistributions in binary form must reproduce the above
85 // copyright notice, this list of conditions and the following disclaimer
86 // in the documentation and/or other materials provided with the
88 // * Neither the name of Google Inc. nor the names of its
89 // contributors may be used to endorse or promote products derived from
90 // this software without specific prior written permission.
92 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
93 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
94 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
95 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
96 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
97 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
98 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
99 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
100 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
101 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
102 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
104 // Author: wan@google.com (Zhanyong Wan)
106 // Utilities for testing Google Test itself and code that uses Google Test
107 // (e.g. frameworks built on top of Google Test).
109 #ifndef GTEST_INCLUDE_GTEST_GTEST_SPI_H_
110 #define GTEST_INCLUDE_GTEST_GTEST_SPI_H_
115 // This helper class can be used to mock out Google Test failure reporting
116 // so that we can test Google Test or code that builds on Google Test.
118 // An object of this class appends a TestPartResult object to the
119 // TestPartResultArray object given in the constructor whenever a Google Test
120 // failure is reported. It can either intercept only failures that are
121 // generated in the same thread that created this object or it can intercept
122 // all generated failures. The scope of this mock object can be controlled with
123 // the second argument to the two arguments constructor.
124 class GTEST_API_ ScopedFakeTestPartResultReporter
125 : public TestPartResultReporterInterface
{
127 // The two possible mocking modes of this object.
129 INTERCEPT_ONLY_CURRENT_THREAD
, // Intercepts only thread local failures.
130 INTERCEPT_ALL_THREADS
// Intercepts all failures.
133 // The c'tor sets this object as the test part result reporter used
134 // by Google Test. The 'result' parameter specifies where to report the
135 // results. This reporter will only catch failures generated in the current
136 // thread. DEPRECATED
137 explicit ScopedFakeTestPartResultReporter(TestPartResultArray
* result
);
139 // Same as above, but you can choose the interception scope of this object.
140 ScopedFakeTestPartResultReporter(InterceptMode intercept_mode
,
141 TestPartResultArray
* result
);
143 // The d'tor restores the previous test part result reporter.
144 virtual ~ScopedFakeTestPartResultReporter();
146 // Appends the TestPartResult object to the TestPartResultArray
147 // received in the constructor.
149 // This method is from the TestPartResultReporterInterface
151 virtual void ReportTestPartResult(const TestPartResult
& result
);
155 const InterceptMode intercept_mode_
;
156 TestPartResultReporterInterface
* old_reporter_
;
157 TestPartResultArray
* const result_
;
159 GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedFakeTestPartResultReporter
);
164 // A helper class for implementing EXPECT_FATAL_FAILURE() and
165 // EXPECT_NONFATAL_FAILURE(). Its destructor verifies that the given
166 // TestPartResultArray contains exactly one failure that has the given
167 // type and contains the given substring. If that's not the case, a
168 // non-fatal failure will be generated.
169 class GTEST_API_ SingleFailureChecker
{
171 // The constructor remembers the arguments.
172 SingleFailureChecker(const TestPartResultArray
* results
,
173 TestPartResult::Type type
,
174 const string
& substr
);
175 ~SingleFailureChecker();
177 const TestPartResultArray
* const results_
;
178 const TestPartResult::Type type_
;
179 const string substr_
;
181 GTEST_DISALLOW_COPY_AND_ASSIGN_(SingleFailureChecker
);
184 } // namespace internal
186 } // namespace testing
188 // A set of macros for testing Google Test assertions or code that's expected
189 // to generate Google Test fatal failures. It verifies that the given
190 // statement will cause exactly one fatal Google Test failure with 'substr'
191 // being part of the failure message.
193 // There are two different versions of this macro. EXPECT_FATAL_FAILURE only
194 // affects and considers failures generated in the current thread and
195 // EXPECT_FATAL_FAILURE_ON_ALL_THREADS does the same but for all threads.
197 // The verification of the assertion is done correctly even when the statement
198 // throws an exception or aborts the current function.
200 // Known restrictions:
201 // - 'statement' cannot reference local non-static variables or
202 // non-static members of the current object.
203 // - 'statement' cannot return a value.
204 // - You cannot stream a failure message to this macro.
206 // Note that even though the implementations of the following two
207 // macros are much alike, we cannot refactor them to use a common
208 // helper macro, due to some peculiarity in how the preprocessor
209 // works. The AcceptsMacroThatExpandsToUnprotectedComma test in
210 // gtest_unittest.cc will fail to compile if we do that.
211 #define EXPECT_FATAL_FAILURE(statement, substr) \
213 class GTestExpectFatalFailureHelper {\
215 static void Execute() { statement; }\
217 ::testing::TestPartResultArray gtest_failures;\
218 ::testing::internal::SingleFailureChecker gtest_checker(\
219 >est_failures, ::testing::TestPartResult::kFatalFailure, (substr));\
221 ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
222 ::testing::ScopedFakeTestPartResultReporter:: \
223 INTERCEPT_ONLY_CURRENT_THREAD, >est_failures);\
224 GTestExpectFatalFailureHelper::Execute();\
226 } while (::testing::internal::AlwaysFalse())
228 #define EXPECT_FATAL_FAILURE_ON_ALL_THREADS(statement, substr) \
230 class GTestExpectFatalFailureHelper {\
232 static void Execute() { statement; }\
234 ::testing::TestPartResultArray gtest_failures;\
235 ::testing::internal::SingleFailureChecker gtest_checker(\
236 >est_failures, ::testing::TestPartResult::kFatalFailure, (substr));\
238 ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
239 ::testing::ScopedFakeTestPartResultReporter:: \
240 INTERCEPT_ALL_THREADS, >est_failures);\
241 GTestExpectFatalFailureHelper::Execute();\
243 } while (::testing::internal::AlwaysFalse())
245 // A macro for testing Google Test assertions or code that's expected to
246 // generate Google Test non-fatal failures. It asserts that the given
247 // statement will cause exactly one non-fatal Google Test failure with 'substr'
248 // being part of the failure message.
250 // There are two different versions of this macro. EXPECT_NONFATAL_FAILURE only
251 // affects and considers failures generated in the current thread and
252 // EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS does the same but for all threads.
254 // 'statement' is allowed to reference local variables and members of
255 // the current object.
257 // The verification of the assertion is done correctly even when the statement
258 // throws an exception or aborts the current function.
260 // Known restrictions:
261 // - You cannot stream a failure message to this macro.
263 // Note that even though the implementations of the following two
264 // macros are much alike, we cannot refactor them to use a common
265 // helper macro, due to some peculiarity in how the preprocessor
266 // works. If we do that, the code won't compile when the user gives
267 // EXPECT_NONFATAL_FAILURE() a statement that contains a macro that
268 // expands to code containing an unprotected comma. The
269 // AcceptsMacroThatExpandsToUnprotectedComma test in gtest_unittest.cc
272 // For the same reason, we have to write
273 // if (::testing::internal::AlwaysTrue()) { statement; }
275 // GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement)
276 // to avoid an MSVC warning on unreachable code.
277 #define EXPECT_NONFATAL_FAILURE(statement, substr) \
279 ::testing::TestPartResultArray gtest_failures;\
280 ::testing::internal::SingleFailureChecker gtest_checker(\
281 >est_failures, ::testing::TestPartResult::kNonFatalFailure, \
284 ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
285 ::testing::ScopedFakeTestPartResultReporter:: \
286 INTERCEPT_ONLY_CURRENT_THREAD, >est_failures);\
287 if (::testing::internal::AlwaysTrue()) { statement; }\
289 } while (::testing::internal::AlwaysFalse())
291 #define EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(statement, substr) \
293 ::testing::TestPartResultArray gtest_failures;\
294 ::testing::internal::SingleFailureChecker gtest_checker(\
295 >est_failures, ::testing::TestPartResult::kNonFatalFailure, \
298 ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
299 ::testing::ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, \
301 if (::testing::internal::AlwaysTrue()) { statement; }\
303 } while (::testing::internal::AlwaysFalse())
305 #endif // GTEST_INCLUDE_GTEST_GTEST_SPI_H_
319 #include <ostream> // NOLINT
325 // TODO(kenton@google.com): Use autoconf to detect availability of
327 # define GTEST_HAS_GETTIMEOFDAY_ 1
329 # include <fcntl.h> // NOLINT
330 # include <limits.h> // NOLINT
331 # include <sched.h> // NOLINT
332 // Declares vsnprintf(). This header is not available on Windows.
333 # include <strings.h> // NOLINT
334 # include <sys/mman.h> // NOLINT
335 # include <sys/time.h> // NOLINT
336 # include <unistd.h> // NOLINT
339 #elif GTEST_OS_SYMBIAN
340 # define GTEST_HAS_GETTIMEOFDAY_ 1
341 # include <sys/time.h> // NOLINT
344 # define GTEST_HAS_GETTIMEOFDAY_ 1
345 # include <sys/time.h> // NOLINT
347 // On z/OS we additionally need strings.h for strcasecmp.
348 # include <strings.h> // NOLINT
350 #elif GTEST_OS_WINDOWS_MOBILE // We are on Windows CE.
352 # include <windows.h> // NOLINT
354 #elif GTEST_OS_WINDOWS // We are on Windows proper.
356 # include <io.h> // NOLINT
357 # include <sys/timeb.h> // NOLINT
358 # include <sys/types.h> // NOLINT
359 # include <sys/stat.h> // NOLINT
361 # if GTEST_OS_WINDOWS_MINGW
362 // MinGW has gettimeofday() but not _ftime64().
363 // TODO(kenton@google.com): Use autoconf to detect availability of
365 // TODO(kenton@google.com): There are other ways to get the time on
366 // Windows, like GetTickCount() or GetSystemTimeAsFileTime(). MinGW
367 // supports these. consider using them instead.
368 # define GTEST_HAS_GETTIMEOFDAY_ 1
369 # include <sys/time.h> // NOLINT
370 # endif // GTEST_OS_WINDOWS_MINGW
372 // cpplint thinks that the header is already included, so we want to
374 # include <windows.h> // NOLINT
378 // Assume other platforms have gettimeofday().
379 // TODO(kenton@google.com): Use autoconf to detect availability of
381 # define GTEST_HAS_GETTIMEOFDAY_ 1
383 // cpplint thinks that the header is already included, so we want to
385 # include <sys/time.h> // NOLINT
386 # include <unistd.h> // NOLINT
388 #endif // GTEST_OS_LINUX
390 #if GTEST_HAS_EXCEPTIONS
391 # include <stdexcept>
394 #if GTEST_CAN_STREAM_RESULTS_
395 # include <arpa/inet.h> // NOLINT
396 # include <netdb.h> // NOLINT
399 // Indicates that this translation unit is part of Google Test's
400 // implementation. It must come before gtest-internal-inl.h is
401 // included, or there will be a compiler error. This trick is to
402 // prevent a user from accidentally including gtest-internal-inl.h in
404 #define GTEST_IMPLEMENTATION_ 1
405 // Copyright 2005, Google Inc.
406 // All rights reserved.
408 // Redistribution and use in source and binary forms, with or without
409 // modification, are permitted provided that the following conditions are
412 // * Redistributions of source code must retain the above copyright
413 // notice, this list of conditions and the following disclaimer.
414 // * Redistributions in binary form must reproduce the above
415 // copyright notice, this list of conditions and the following disclaimer
416 // in the documentation and/or other materials provided with the
418 // * Neither the name of Google Inc. nor the names of its
419 // contributors may be used to endorse or promote products derived from
420 // this software without specific prior written permission.
422 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
423 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
424 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
425 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
426 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
427 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
428 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
429 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
430 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
431 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
432 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
434 // Utility functions and classes used by the Google C++ testing framework.
436 // Author: wan@google.com (Zhanyong Wan)
438 // This file contains purely Google Test's internal implementation. Please
439 // DO NOT #INCLUDE IT IN A USER PROGRAM.
441 #ifndef GTEST_SRC_GTEST_INTERNAL_INL_H_
442 #define GTEST_SRC_GTEST_INTERNAL_INL_H_
444 // GTEST_IMPLEMENTATION_ is defined to 1 iff the current translation unit is
445 // part of Google Test's implementation; otherwise it's undefined.
446 #if !GTEST_IMPLEMENTATION_
447 // A user is trying to include this from his code - just say no.
448 # error "gtest-internal-inl.h is part of Google Test's internal implementation."
449 # error "It must not be included except by Google Test itself."
450 #endif // GTEST_IMPLEMENTATION_
454 #endif // !_WIN32_WCE
456 #include <stdlib.h> // For strtoll/_strtoul64/malloc/free.
457 #include <string.h> // For memmove.
464 #if GTEST_CAN_STREAM_RESULTS_
465 # include <arpa/inet.h> // NOLINT
466 # include <netdb.h> // NOLINT
470 # include <windows.h> // NOLINT
471 #endif // GTEST_OS_WINDOWS
476 // Declares the flags.
478 // We don't want the users to modify this flag in the code, but want
479 // Google Test's own unit tests to be able to access it. Therefore we
480 // declare it here as opposed to in gtest.h.
481 GTEST_DECLARE_bool_(death_test_use_fork
);
485 // The value of GetTestTypeId() as seen from within the Google Test
486 // library. This is solely for testing GetTestTypeId().
487 GTEST_API_
extern const TypeId kTestTypeIdInGoogleTest
;
489 // Names of the flags (needed for parsing Google Test flags).
490 const char kAlsoRunDisabledTestsFlag
[] = "also_run_disabled_tests";
491 const char kBreakOnFailureFlag
[] = "break_on_failure";
492 const char kCatchExceptionsFlag
[] = "catch_exceptions";
493 const char kColorFlag
[] = "color";
494 const char kFilterFlag
[] = "filter";
495 const char kListTestsFlag
[] = "list_tests";
496 const char kOutputFlag
[] = "output";
497 const char kPrintTimeFlag
[] = "print_time";
498 const char kRandomSeedFlag
[] = "random_seed";
499 const char kRepeatFlag
[] = "repeat";
500 const char kShuffleFlag
[] = "shuffle";
501 const char kStackTraceDepthFlag
[] = "stack_trace_depth";
502 const char kStreamResultToFlag
[] = "stream_result_to";
503 const char kThrowOnFailureFlag
[] = "throw_on_failure";
505 // A valid random seed must be in [1, kMaxRandomSeed].
506 const int kMaxRandomSeed
= 99999;
508 // g_help_flag is true iff the --help flag or an equivalent form is
509 // specified on the command line.
510 GTEST_API_
extern bool g_help_flag
;
512 // Returns the current time in milliseconds.
513 GTEST_API_ TimeInMillis
GetTimeInMillis();
515 // Returns true iff Google Test should use colors in the output.
516 GTEST_API_
bool ShouldUseColor(bool stdout_is_tty
);
518 // Formats the given time in milliseconds as seconds.
519 GTEST_API_
std::string
FormatTimeInMillisAsSeconds(TimeInMillis ms
);
521 // Converts the given time in milliseconds to a date string in the ISO 8601
522 // format, without the timezone information. N.B.: due to the use the
523 // non-reentrant localtime() function, this function is not thread safe. Do
524 // not use it in any code that can be called from multiple threads.
525 GTEST_API_
std::string
FormatEpochTimeInMillisAsIso8601(TimeInMillis ms
);
527 // Parses a string for an Int32 flag, in the form of "--flag=value".
529 // On success, stores the value of the flag in *value, and returns
530 // true. On failure, returns false without changing *value.
531 GTEST_API_
bool ParseInt32Flag(
532 const char* str
, const char* flag
, Int32
* value
);
534 // Returns a random seed in range [1, kMaxRandomSeed] based on the
535 // given --gtest_random_seed flag value.
536 inline int GetRandomSeedFromFlag(Int32 random_seed_flag
) {
537 const unsigned int raw_seed
= (random_seed_flag
== 0) ?
538 static_cast<unsigned int>(GetTimeInMillis()) :
539 static_cast<unsigned int>(random_seed_flag
);
541 // Normalizes the actual seed to range [1, kMaxRandomSeed] such that
542 // it's easy to type.
543 const int normalized_seed
=
544 static_cast<int>((raw_seed
- 1U) %
545 static_cast<unsigned int>(kMaxRandomSeed
)) + 1;
546 return normalized_seed
;
549 // Returns the first valid random seed after 'seed'. The behavior is
550 // undefined if 'seed' is invalid. The seed after kMaxRandomSeed is
551 // considered to be 1.
552 inline int GetNextRandomSeed(int seed
) {
553 GTEST_CHECK_(1 <= seed
&& seed
<= kMaxRandomSeed
)
554 << "Invalid random seed " << seed
<< " - must be in [1, "
555 << kMaxRandomSeed
<< "].";
556 const int next_seed
= seed
+ 1;
557 return (next_seed
> kMaxRandomSeed
) ? 1 : next_seed
;
560 // This class saves the values of all Google Test flags in its c'tor, and
561 // restores them in its d'tor.
562 class GTestFlagSaver
{
566 also_run_disabled_tests_
= GTEST_FLAG(also_run_disabled_tests
);
567 break_on_failure_
= GTEST_FLAG(break_on_failure
);
568 catch_exceptions_
= GTEST_FLAG(catch_exceptions
);
569 color_
= GTEST_FLAG(color
);
570 death_test_style_
= GTEST_FLAG(death_test_style
);
571 death_test_use_fork_
= GTEST_FLAG(death_test_use_fork
);
572 filter_
= GTEST_FLAG(filter
);
573 internal_run_death_test_
= GTEST_FLAG(internal_run_death_test
);
574 list_tests_
= GTEST_FLAG(list_tests
);
575 output_
= GTEST_FLAG(output
);
576 print_time_
= GTEST_FLAG(print_time
);
577 random_seed_
= GTEST_FLAG(random_seed
);
578 repeat_
= GTEST_FLAG(repeat
);
579 shuffle_
= GTEST_FLAG(shuffle
);
580 stack_trace_depth_
= GTEST_FLAG(stack_trace_depth
);
581 stream_result_to_
= GTEST_FLAG(stream_result_to
);
582 throw_on_failure_
= GTEST_FLAG(throw_on_failure
);
585 // The d'tor is not virtual. DO NOT INHERIT FROM THIS CLASS.
587 GTEST_FLAG(also_run_disabled_tests
) = also_run_disabled_tests_
;
588 GTEST_FLAG(break_on_failure
) = break_on_failure_
;
589 GTEST_FLAG(catch_exceptions
) = catch_exceptions_
;
590 GTEST_FLAG(color
) = color_
;
591 GTEST_FLAG(death_test_style
) = death_test_style_
;
592 GTEST_FLAG(death_test_use_fork
) = death_test_use_fork_
;
593 GTEST_FLAG(filter
) = filter_
;
594 GTEST_FLAG(internal_run_death_test
) = internal_run_death_test_
;
595 GTEST_FLAG(list_tests
) = list_tests_
;
596 GTEST_FLAG(output
) = output_
;
597 GTEST_FLAG(print_time
) = print_time_
;
598 GTEST_FLAG(random_seed
) = random_seed_
;
599 GTEST_FLAG(repeat
) = repeat_
;
600 GTEST_FLAG(shuffle
) = shuffle_
;
601 GTEST_FLAG(stack_trace_depth
) = stack_trace_depth_
;
602 GTEST_FLAG(stream_result_to
) = stream_result_to_
;
603 GTEST_FLAG(throw_on_failure
) = throw_on_failure_
;
607 // Fields for saving the original values of flags.
608 bool also_run_disabled_tests_
;
609 bool break_on_failure_
;
610 bool catch_exceptions_
;
612 std::string death_test_style_
;
613 bool death_test_use_fork_
;
615 std::string internal_run_death_test_
;
619 internal::Int32 random_seed_
;
620 internal::Int32 repeat_
;
622 internal::Int32 stack_trace_depth_
;
623 std::string stream_result_to_
;
624 bool throw_on_failure_
;
625 } GTEST_ATTRIBUTE_UNUSED_
;
627 // Converts a Unicode code point to a narrow string in UTF-8 encoding.
628 // code_point parameter is of type UInt32 because wchar_t may not be
629 // wide enough to contain a code point.
630 // If the code_point is not a valid Unicode code point
631 // (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted
632 // to "(Invalid Unicode 0xXXXXXXXX)".
633 GTEST_API_
std::string
CodePointToUtf8(UInt32 code_point
);
635 // Converts a wide string to a narrow string in UTF-8 encoding.
636 // The wide string is assumed to have the following encoding:
637 // UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS)
638 // UTF-32 if sizeof(wchar_t) == 4 (on Linux)
639 // Parameter str points to a null-terminated wide string.
640 // Parameter num_chars may additionally limit the number
641 // of wchar_t characters processed. -1 is used when the entire string
642 // should be processed.
643 // If the string contains code points that are not valid Unicode code points
644 // (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
645 // as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
646 // and contains invalid UTF-16 surrogate pairs, values in those pairs
647 // will be encoded as individual Unicode characters from Basic Normal Plane.
648 GTEST_API_
std::string
WideStringToUtf8(const wchar_t* str
, int num_chars
);
650 // Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
651 // if the variable is present. If a file already exists at this location, this
652 // function will write over it. If the variable is present, but the file cannot
653 // be created, prints an error and exits.
654 void WriteToShardStatusFileIfNeeded();
656 // Checks whether sharding is enabled by examining the relevant
657 // environment variable values. If the variables are present,
658 // but inconsistent (e.g., shard_index >= total_shards), prints
659 // an error and exits. If in_subprocess_for_death_test, sharding is
660 // disabled because it must only be applied to the original test
661 // process. Otherwise, we could filter out death tests we intended to execute.
662 GTEST_API_
bool ShouldShard(const char* total_shards_str
,
663 const char* shard_index_str
,
664 bool in_subprocess_for_death_test
);
666 // Parses the environment variable var as an Int32. If it is unset,
667 // returns default_val. If it is not an Int32, prints an error and
669 GTEST_API_ Int32
Int32FromEnvOrDie(const char* env_var
, Int32 default_val
);
671 // Given the total number of shards, the shard index, and the test id,
672 // returns true iff the test should be run on this shard. The test id is
673 // some arbitrary but unique non-negative integer assigned to each test
674 // method. Assumes that 0 <= shard_index < total_shards.
675 GTEST_API_
bool ShouldRunTestOnShard(
676 int total_shards
, int shard_index
, int test_id
);
678 // STL container utilities.
680 // Returns the number of elements in the given container that satisfy
681 // the given predicate.
682 template <class Container
, typename Predicate
>
683 inline int CountIf(const Container
& c
, Predicate predicate
) {
684 // Implemented as an explicit loop since std::count_if() in libCstd on
685 // Solaris has a non-standard signature.
687 for (typename
Container::const_iterator it
= c
.begin(); it
!= c
.end(); ++it
) {
694 // Applies a function/functor to each element in the container.
695 template <class Container
, typename Functor
>
696 void ForEach(const Container
& c
, Functor functor
) {
697 std::for_each(c
.begin(), c
.end(), functor
);
700 // Returns the i-th element of the vector, or default_value if i is not
701 // in range [0, v.size()).
702 template <typename E
>
703 inline E
GetElementOr(const std::vector
<E
>& v
, int i
, E default_value
) {
704 return (i
< 0 || i
>= static_cast<int>(v
.size())) ? default_value
: v
[i
];
707 // Performs an in-place shuffle of a range of the vector's elements.
708 // 'begin' and 'end' are element indices as an STL-style range;
709 // i.e. [begin, end) are shuffled, where 'end' == size() means to
710 // shuffle to the end of the vector.
711 template <typename E
>
712 void ShuffleRange(internal::Random
* random
, int begin
, int end
,
714 const int size
= static_cast<int>(v
->size());
715 GTEST_CHECK_(0 <= begin
&& begin
<= size
)
716 << "Invalid shuffle range start " << begin
<< ": must be in range [0, "
718 GTEST_CHECK_(begin
<= end
&& end
<= size
)
719 << "Invalid shuffle range finish " << end
<< ": must be in range ["
720 << begin
<< ", " << size
<< "].";
722 // Fisher-Yates shuffle, from
723 // http://en.wikipedia.org/wiki/Fisher-Yates_shuffle
724 for (int range_width
= end
- begin
; range_width
>= 2; range_width
--) {
725 const int last_in_range
= begin
+ range_width
- 1;
726 const int selected
= begin
+ random
->Generate(range_width
);
727 std::swap((*v
)[selected
], (*v
)[last_in_range
]);
731 // Performs an in-place shuffle of the vector's elements.
732 template <typename E
>
733 inline void Shuffle(internal::Random
* random
, std::vector
<E
>* v
) {
734 ShuffleRange(random
, 0, static_cast<int>(v
->size()), v
);
737 // A function for deleting an object. Handy for being used as a
739 template <typename T
>
740 static void Delete(T
* x
) {
744 // A predicate that checks the key of a TestProperty against a known key.
746 // TestPropertyKeyIs is copyable.
747 class TestPropertyKeyIs
{
751 // TestPropertyKeyIs has NO default constructor.
752 explicit TestPropertyKeyIs(const std::string
& key
) : key_(key
) {}
754 // Returns true iff the test name of test property matches on key_.
755 bool operator()(const TestProperty
& test_property
) const {
756 return test_property
.key() == key_
;
763 // Class UnitTestOptions.
765 // This class contains functions for processing options the user
766 // specifies when running the tests. It has only static members.
768 // In most cases, the user can specify an option using either an
769 // environment variable or a command line flag. E.g. you can set the
770 // test filter using either GTEST_FILTER or --gtest_filter. If both
771 // the variable and the flag are present, the latter overrides the
773 class GTEST_API_ UnitTestOptions
{
775 // Functions for processing the gtest_output flag.
777 // Returns the output format, or "" for normal printed output.
778 static std::string
GetOutputFormat();
780 // Returns the absolute path of the requested output file, or the
781 // default (test_detail.xml in the original working directory) if
782 // none was explicitly specified.
783 static std::string
GetAbsolutePathToOutputFile();
785 // Functions for processing the gtest_filter flag.
787 // Returns true iff the wildcard pattern matches the string. The
788 // first ':' or '\0' character in pattern marks the end of it.
790 // This recursive algorithm isn't very efficient, but is clear and
791 // works well enough for matching test names, which are short.
792 static bool PatternMatchesString(const char *pattern
, const char *str
);
794 // Returns true iff the user-specified filter matches the test case
795 // name and the test name.
796 static bool FilterMatchesTest(const std::string
&test_case_name
,
797 const std::string
&test_name
);
800 // Function for supporting the gtest_catch_exception flag.
802 // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
803 // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
804 // This function is useful as an __except condition.
805 static int GTestShouldProcessSEH(DWORD exception_code
);
806 #endif // GTEST_OS_WINDOWS
808 // Returns true if "name" matches the ':' separated list of glob-style
809 // filters in "filter".
810 static bool MatchesFilter(const std::string
& name
, const char* filter
);
813 // Returns the current application's name, removing directory path if that
814 // is present. Used by UnitTestOptions::GetOutputFile.
815 GTEST_API_ FilePath
GetCurrentExecutableName();
817 // The role interface for getting the OS stack trace as a string.
818 class OsStackTraceGetterInterface
{
820 OsStackTraceGetterInterface() {}
821 virtual ~OsStackTraceGetterInterface() {}
823 // Returns the current OS stack trace as an std::string. Parameters:
825 // max_depth - the maximum number of stack frames to be included
827 // skip_count - the number of top frames to be skipped; doesn't count
828 // against max_depth.
829 virtual string
CurrentStackTrace(int max_depth
, int skip_count
) = 0;
831 // UponLeavingGTest() should be called immediately before Google Test calls
832 // user code. It saves some information about the current stack that
833 // CurrentStackTrace() will use to find and hide Google Test stack frames.
834 virtual void UponLeavingGTest() = 0;
837 GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetterInterface
);
840 // A working implementation of the OsStackTraceGetterInterface interface.
841 class OsStackTraceGetter
: public OsStackTraceGetterInterface
{
843 OsStackTraceGetter() : caller_frame_(NULL
) {}
845 virtual string
CurrentStackTrace(int max_depth
, int skip_count
)
846 GTEST_LOCK_EXCLUDED_(mutex_
);
848 virtual void UponLeavingGTest() GTEST_LOCK_EXCLUDED_(mutex_
);
850 // This string is inserted in place of stack frames that are part of
851 // Google Test's implementation.
852 static const char* const kElidedFramesMarker
;
855 Mutex mutex_
; // protects all internal state
857 // We save the stack frame below the frame that calls user code.
858 // We do this because the address of the frame immediately below
859 // the user code changes between the call to UponLeavingGTest()
860 // and any calls to CurrentStackTrace() from within the user code.
863 GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetter
);
866 // Information about a Google Test trace point.
873 // This is the default global test part result reporter used in UnitTestImpl.
874 // This class should only be used by UnitTestImpl.
875 class DefaultGlobalTestPartResultReporter
876 : public TestPartResultReporterInterface
{
878 explicit DefaultGlobalTestPartResultReporter(UnitTestImpl
* unit_test
);
879 // Implements the TestPartResultReporterInterface. Reports the test part
880 // result in the current test.
881 virtual void ReportTestPartResult(const TestPartResult
& result
);
884 UnitTestImpl
* const unit_test_
;
886 GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultGlobalTestPartResultReporter
);
889 // This is the default per thread test part result reporter used in
890 // UnitTestImpl. This class should only be used by UnitTestImpl.
891 class DefaultPerThreadTestPartResultReporter
892 : public TestPartResultReporterInterface
{
894 explicit DefaultPerThreadTestPartResultReporter(UnitTestImpl
* unit_test
);
895 // Implements the TestPartResultReporterInterface. The implementation just
896 // delegates to the current global test part result reporter of *unit_test_.
897 virtual void ReportTestPartResult(const TestPartResult
& result
);
900 UnitTestImpl
* const unit_test_
;
902 GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultPerThreadTestPartResultReporter
);
905 // The private implementation of the UnitTest class. We don't protect
906 // the methods under a mutex, as this class is not accessible by a
907 // user and the UnitTest class that delegates work to this class does
909 class GTEST_API_ UnitTestImpl
{
911 explicit UnitTestImpl(UnitTest
* parent
);
912 virtual ~UnitTestImpl();
914 // There are two different ways to register your own TestPartResultReporter.
915 // You can register your own repoter to listen either only for test results
916 // from the current thread or for results from all threads.
917 // By default, each per-thread test result repoter just passes a new
918 // TestPartResult to the global test result reporter, which registers the
919 // test part result for the currently running test.
921 // Returns the global test part result reporter.
922 TestPartResultReporterInterface
* GetGlobalTestPartResultReporter();
924 // Sets the global test part result reporter.
925 void SetGlobalTestPartResultReporter(
926 TestPartResultReporterInterface
* reporter
);
928 // Returns the test part result reporter for the current thread.
929 TestPartResultReporterInterface
* GetTestPartResultReporterForCurrentThread();
931 // Sets the test part result reporter for the current thread.
932 void SetTestPartResultReporterForCurrentThread(
933 TestPartResultReporterInterface
* reporter
);
935 // Gets the number of successful test cases.
936 int successful_test_case_count() const;
938 // Gets the number of failed test cases.
939 int failed_test_case_count() const;
941 // Gets the number of all test cases.
942 int total_test_case_count() const;
944 // Gets the number of all test cases that contain at least one test
946 int test_case_to_run_count() const;
948 // Gets the number of successful tests.
949 int successful_test_count() const;
951 // Gets the number of failed tests.
952 int failed_test_count() const;
954 // Gets the number of disabled tests that will be reported in the XML report.
955 int reportable_disabled_test_count() const;
957 // Gets the number of disabled tests.
958 int disabled_test_count() const;
960 // Gets the number of tests to be printed in the XML report.
961 int reportable_test_count() const;
963 // Gets the number of all tests.
964 int total_test_count() const;
966 // Gets the number of tests that should run.
967 int test_to_run_count() const;
969 // Gets the time of the test program start, in ms from the start of the
971 TimeInMillis
start_timestamp() const { return start_timestamp_
; }
973 // Gets the elapsed time, in milliseconds.
974 TimeInMillis
elapsed_time() const { return elapsed_time_
; }
976 // Returns true iff the unit test passed (i.e. all test cases passed).
977 bool Passed() const { return !Failed(); }
979 // Returns true iff the unit test failed (i.e. some test case failed
980 // or something outside of all tests failed).
981 bool Failed() const {
982 return failed_test_case_count() > 0 || ad_hoc_test_result()->Failed();
985 // Gets the i-th test case among all the test cases. i can range from 0 to
986 // total_test_case_count() - 1. If i is not in that range, returns NULL.
987 const TestCase
* GetTestCase(int i
) const {
988 const int index
= GetElementOr(test_case_indices_
, i
, -1);
989 return index
< 0 ? NULL
: test_cases_
[i
];
992 // Gets the i-th test case among all the test cases. i can range from 0 to
993 // total_test_case_count() - 1. If i is not in that range, returns NULL.
994 TestCase
* GetMutableTestCase(int i
) {
995 const int index
= GetElementOr(test_case_indices_
, i
, -1);
996 return index
< 0 ? NULL
: test_cases_
[index
];
999 // Provides access to the event listener list.
1000 TestEventListeners
* listeners() { return &listeners_
; }
1002 // Returns the TestResult for the test that's currently running, or
1003 // the TestResult for the ad hoc test if no test is running.
1004 TestResult
* current_test_result();
1006 // Returns the TestResult for the ad hoc test.
1007 const TestResult
* ad_hoc_test_result() const { return &ad_hoc_test_result_
; }
1009 // Sets the OS stack trace getter.
1011 // Does nothing if the input and the current OS stack trace getter
1012 // are the same; otherwise, deletes the old getter and makes the
1013 // input the current getter.
1014 void set_os_stack_trace_getter(OsStackTraceGetterInterface
* getter
);
1016 // Returns the current OS stack trace getter if it is not NULL;
1017 // otherwise, creates an OsStackTraceGetter, makes it the current
1018 // getter, and returns it.
1019 OsStackTraceGetterInterface
* os_stack_trace_getter();
1021 // Returns the current OS stack trace as an std::string.
1023 // The maximum number of stack frames to be included is specified by
1024 // the gtest_stack_trace_depth flag. The skip_count parameter
1025 // specifies the number of top frames to be skipped, which doesn't
1026 // count against the number of frames to be included.
1028 // For example, if Foo() calls Bar(), which in turn calls
1029 // CurrentOsStackTraceExceptTop(1), Foo() will be included in the
1030 // trace but Bar() and CurrentOsStackTraceExceptTop() won't.
1031 std::string
CurrentOsStackTraceExceptTop(int skip_count
) GTEST_NO_INLINE_
;
1033 // Finds and returns a TestCase with the given name. If one doesn't
1034 // exist, creates one and returns it.
1038 // test_case_name: name of the test case
1039 // type_param: the name of the test's type parameter, or NULL if
1040 // this is not a typed or a type-parameterized test.
1041 // set_up_tc: pointer to the function that sets up the test case
1042 // tear_down_tc: pointer to the function that tears down the test case
1043 TestCase
* GetTestCase(const char* test_case_name
,
1044 const char* type_param
,
1045 Test::SetUpTestCaseFunc set_up_tc
,
1046 Test::TearDownTestCaseFunc tear_down_tc
);
1048 // Adds a TestInfo to the unit test.
1052 // set_up_tc: pointer to the function that sets up the test case
1053 // tear_down_tc: pointer to the function that tears down the test case
1054 // test_info: the TestInfo object
1055 void AddTestInfo(Test::SetUpTestCaseFunc set_up_tc
,
1056 Test::TearDownTestCaseFunc tear_down_tc
,
1057 TestInfo
* test_info
) {
1058 // In order to support thread-safe death tests, we need to
1059 // remember the original working directory when the test program
1060 // was first invoked. We cannot do this in RUN_ALL_TESTS(), as
1061 // the user may have changed the current directory before calling
1062 // RUN_ALL_TESTS(). Therefore we capture the current directory in
1063 // AddTestInfo(), which is called to register a TEST or TEST_F
1064 // before main() is reached.
1065 if (original_working_dir_
.IsEmpty()) {
1066 original_working_dir_
.Set(FilePath::GetCurrentDir());
1067 GTEST_CHECK_(!original_working_dir_
.IsEmpty())
1068 << "Failed to get the current working directory.";
1071 GetTestCase(test_info
->test_case_name(),
1072 test_info
->type_param(),
1074 tear_down_tc
)->AddTestInfo(test_info
);
1077 #if GTEST_HAS_PARAM_TEST
1078 // Returns ParameterizedTestCaseRegistry object used to keep track of
1079 // value-parameterized tests and instantiate and register them.
1080 internal::ParameterizedTestCaseRegistry
& parameterized_test_registry() {
1081 return parameterized_test_registry_
;
1083 #endif // GTEST_HAS_PARAM_TEST
1085 // Sets the TestCase object for the test that's currently running.
1086 void set_current_test_case(TestCase
* a_current_test_case
) {
1087 current_test_case_
= a_current_test_case
;
1090 // Sets the TestInfo object for the test that's currently running. If
1091 // current_test_info is NULL, the assertion results will be stored in
1092 // ad_hoc_test_result_.
1093 void set_current_test_info(TestInfo
* a_current_test_info
) {
1094 current_test_info_
= a_current_test_info
;
1097 // Registers all parameterized tests defined using TEST_P and
1098 // INSTANTIATE_TEST_CASE_P, creating regular tests for each test/parameter
1099 // combination. This method can be called more then once; it has guards
1100 // protecting from registering the tests more then once. If
1101 // value-parameterized tests are disabled, RegisterParameterizedTests is
1102 // present but does nothing.
1103 void RegisterParameterizedTests();
1105 // Runs all tests in this UnitTest object, prints the result, and
1106 // returns true if all tests are successful. If any exception is
1107 // thrown during a test, this test is considered to be failed, but
1108 // the rest of the tests will still be run.
1111 // Clears the results of all tests, except the ad hoc tests.
1112 void ClearNonAdHocTestResult() {
1113 ForEach(test_cases_
, TestCase::ClearTestCaseResult
);
1116 // Clears the results of ad-hoc test assertions.
1117 void ClearAdHocTestResult() {
1118 ad_hoc_test_result_
.Clear();
1121 // Adds a TestProperty to the current TestResult object when invoked in a
1122 // context of a test or a test case, or to the global property set. If the
1123 // result already contains a property with the same key, the value will be
1125 void RecordProperty(const TestProperty
& test_property
);
1127 enum ReactionToSharding
{
1128 HONOR_SHARDING_PROTOCOL
,
1129 IGNORE_SHARDING_PROTOCOL
1132 // Matches the full name of each test against the user-specified
1133 // filter to decide whether the test should run, then records the
1134 // result in each TestCase and TestInfo object.
1135 // If shard_tests == HONOR_SHARDING_PROTOCOL, further filters tests
1136 // based on sharding variables in the environment.
1137 // Returns the number of tests that should run.
1138 int FilterTests(ReactionToSharding shard_tests
);
1140 // Prints the names of the tests matching the user-specified filter flag.
1141 void ListTestsMatchingFilter();
1143 const TestCase
* current_test_case() const { return current_test_case_
; }
1144 TestInfo
* current_test_info() { return current_test_info_
; }
1145 const TestInfo
* current_test_info() const { return current_test_info_
; }
1147 // Returns the vector of environments that need to be set-up/torn-down
1148 // before/after the tests are run.
1149 std::vector
<Environment
*>& environments() { return environments_
; }
1151 // Getters for the per-thread Google Test trace stack.
1152 std::vector
<TraceInfo
>& gtest_trace_stack() {
1153 return *(gtest_trace_stack_
.pointer());
1155 const std::vector
<TraceInfo
>& gtest_trace_stack() const {
1156 return gtest_trace_stack_
.get();
1159 #if GTEST_HAS_DEATH_TEST
1160 void InitDeathTestSubprocessControlInfo() {
1161 internal_run_death_test_flag_
.reset(ParseInternalRunDeathTestFlag());
1163 // Returns a pointer to the parsed --gtest_internal_run_death_test
1164 // flag, or NULL if that flag was not specified.
1165 // This information is useful only in a death test child process.
1166 // Must not be called before a call to InitGoogleTest.
1167 const InternalRunDeathTestFlag
* internal_run_death_test_flag() const {
1168 return internal_run_death_test_flag_
.get();
1171 // Returns a pointer to the current death test factory.
1172 internal::DeathTestFactory
* death_test_factory() {
1173 return death_test_factory_
.get();
1176 void SuppressTestEventsIfInSubprocess();
1178 friend class ReplaceDeathTestFactory
;
1179 #endif // GTEST_HAS_DEATH_TEST
1181 // Initializes the event listener performing XML output as specified by
1182 // UnitTestOptions. Must not be called before InitGoogleTest.
1183 void ConfigureXmlOutput();
1185 #if GTEST_CAN_STREAM_RESULTS_
1186 // Initializes the event listener for streaming test results to a socket.
1187 // Must not be called before InitGoogleTest.
1188 void ConfigureStreamingOutput();
1191 // Performs initialization dependent upon flag values obtained in
1192 // ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to
1193 // ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest
1194 // this function is also called from RunAllTests. Since this function can be
1195 // called more than once, it has to be idempotent.
1196 void PostFlagParsingInit();
1198 // Gets the random seed used at the start of the current test iteration.
1199 int random_seed() const { return random_seed_
; }
1201 // Gets the random number generator.
1202 internal::Random
* random() { return &random_
; }
1204 // Shuffles all test cases, and the tests within each test case,
1205 // making sure that death tests are still run first.
1206 void ShuffleTests();
1208 // Restores the test cases and tests to their order before the first shuffle.
1209 void UnshuffleTests();
1211 // Returns the value of GTEST_FLAG(catch_exceptions) at the moment
1212 // UnitTest::Run() starts.
1213 bool catch_exceptions() const { return catch_exceptions_
; }
1216 friend class ::testing::UnitTest
;
1218 // Used by UnitTest::Run() to capture the state of
1219 // GTEST_FLAG(catch_exceptions) at the moment it starts.
1220 void set_catch_exceptions(bool value
) { catch_exceptions_
= value
; }
1222 // The UnitTest object that owns this implementation object.
1223 UnitTest
* const parent_
;
1225 // The working directory when the first TEST() or TEST_F() was
1227 internal::FilePath original_working_dir_
;
1229 // The default test part result reporters.
1230 DefaultGlobalTestPartResultReporter default_global_test_part_result_reporter_
;
1231 DefaultPerThreadTestPartResultReporter
1232 default_per_thread_test_part_result_reporter_
;
1234 // Points to (but doesn't own) the global test part result reporter.
1235 TestPartResultReporterInterface
* global_test_part_result_repoter_
;
1237 // Protects read and write access to global_test_part_result_reporter_.
1238 internal::Mutex global_test_part_result_reporter_mutex_
;
1240 // Points to (but doesn't own) the per-thread test part result reporter.
1241 internal::ThreadLocal
<TestPartResultReporterInterface
*>
1242 per_thread_test_part_result_reporter_
;
1244 // The vector of environments that need to be set-up/torn-down
1245 // before/after the tests are run.
1246 std::vector
<Environment
*> environments_
;
1248 // The vector of TestCases in their original order. It owns the
1249 // elements in the vector.
1250 std::vector
<TestCase
*> test_cases_
;
1252 // Provides a level of indirection for the test case list to allow
1253 // easy shuffling and restoring the test case order. The i-th
1254 // element of this vector is the index of the i-th test case in the
1256 std::vector
<int> test_case_indices_
;
1258 #if GTEST_HAS_PARAM_TEST
1259 // ParameterizedTestRegistry object used to register value-parameterized
1261 internal::ParameterizedTestCaseRegistry parameterized_test_registry_
;
1263 // Indicates whether RegisterParameterizedTests() has been called already.
1264 bool parameterized_tests_registered_
;
1265 #endif // GTEST_HAS_PARAM_TEST
1267 // Index of the last death test case registered. Initially -1.
1268 int last_death_test_case_
;
1270 // This points to the TestCase for the currently running test. It
1271 // changes as Google Test goes through one test case after another.
1272 // When no test is running, this is set to NULL and Google Test
1273 // stores assertion results in ad_hoc_test_result_. Initially NULL.
1274 TestCase
* current_test_case_
;
1276 // This points to the TestInfo for the currently running test. It
1277 // changes as Google Test goes through one test after another. When
1278 // no test is running, this is set to NULL and Google Test stores
1279 // assertion results in ad_hoc_test_result_. Initially NULL.
1280 TestInfo
* current_test_info_
;
1282 // Normally, a user only writes assertions inside a TEST or TEST_F,
1283 // or inside a function called by a TEST or TEST_F. Since Google
1284 // Test keeps track of which test is current running, it can
1285 // associate such an assertion with the test it belongs to.
1287 // If an assertion is encountered when no TEST or TEST_F is running,
1288 // Google Test attributes the assertion result to an imaginary "ad hoc"
1289 // test, and records the result in ad_hoc_test_result_.
1290 TestResult ad_hoc_test_result_
;
1292 // The list of event listeners that can be used to track events inside
1294 TestEventListeners listeners_
;
1296 // The OS stack trace getter. Will be deleted when the UnitTest
1297 // object is destructed. By default, an OsStackTraceGetter is used,
1298 // but the user can set this field to use a custom getter if that is
1300 OsStackTraceGetterInterface
* os_stack_trace_getter_
;
1302 // True iff PostFlagParsingInit() has been called.
1303 bool post_flag_parse_init_performed_
;
1305 // The random number seed used at the beginning of the test run.
1308 // Our random number generator.
1309 internal::Random random_
;
1311 // The time of the test program start, in ms from the start of the
1313 TimeInMillis start_timestamp_
;
1315 // How long the test took to run, in milliseconds.
1316 TimeInMillis elapsed_time_
;
1318 #if GTEST_HAS_DEATH_TEST
1319 // The decomposed components of the gtest_internal_run_death_test flag,
1320 // parsed when RUN_ALL_TESTS is called.
1321 internal::scoped_ptr
<InternalRunDeathTestFlag
> internal_run_death_test_flag_
;
1322 internal::scoped_ptr
<internal::DeathTestFactory
> death_test_factory_
;
1323 #endif // GTEST_HAS_DEATH_TEST
1325 // A per-thread stack of traces created by the SCOPED_TRACE() macro.
1326 internal::ThreadLocal
<std::vector
<TraceInfo
> > gtest_trace_stack_
;
1328 // The value of GTEST_FLAG(catch_exceptions) at the moment RunAllTests()
1330 bool catch_exceptions_
;
1332 GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTestImpl
);
1333 }; // class UnitTestImpl
1335 // Convenience function for accessing the global UnitTest
1336 // implementation object.
1337 inline UnitTestImpl
* GetUnitTestImpl() {
1338 return UnitTest::GetInstance()->impl();
1341 #if GTEST_USES_SIMPLE_RE
1343 // Internal helper functions for implementing the simple regular
1344 // expression matcher.
1345 GTEST_API_
bool IsInSet(char ch
, const char* str
);
1346 GTEST_API_
bool IsAsciiDigit(char ch
);
1347 GTEST_API_
bool IsAsciiPunct(char ch
);
1348 GTEST_API_
bool IsRepeat(char ch
);
1349 GTEST_API_
bool IsAsciiWhiteSpace(char ch
);
1350 GTEST_API_
bool IsAsciiWordChar(char ch
);
1351 GTEST_API_
bool IsValidEscape(char ch
);
1352 GTEST_API_
bool AtomMatchesChar(bool escaped
, char pattern
, char ch
);
1353 GTEST_API_
bool ValidateRegex(const char* regex
);
1354 GTEST_API_
bool MatchRegexAtHead(const char* regex
, const char* str
);
1355 GTEST_API_
bool MatchRepetitionAndRegexAtHead(
1356 bool escaped
, char ch
, char repeat
, const char* regex
, const char* str
);
1357 GTEST_API_
bool MatchRegexAnywhere(const char* regex
, const char* str
);
1359 #endif // GTEST_USES_SIMPLE_RE
1361 // Parses the command line for Google Test flags, without initializing
1362 // other parts of Google Test.
1363 GTEST_API_
void ParseGoogleTestFlagsOnly(int* argc
, char** argv
);
1364 GTEST_API_
void ParseGoogleTestFlagsOnly(int* argc
, wchar_t** argv
);
1366 #if GTEST_HAS_DEATH_TEST
1368 // Returns the message describing the last system error, regardless of the
1370 GTEST_API_
std::string
GetLastErrnoDescription();
1372 # if GTEST_OS_WINDOWS
1373 // Provides leak-safe Windows kernel handle ownership.
1376 AutoHandle() : handle_(INVALID_HANDLE_VALUE
) {}
1377 explicit AutoHandle(HANDLE handle
) : handle_(handle
) {}
1379 ~AutoHandle() { Reset(); }
1381 HANDLE
Get() const { return handle_
; }
1382 void Reset() { Reset(INVALID_HANDLE_VALUE
); }
1383 void Reset(HANDLE handle
) {
1384 if (handle
!= handle_
) {
1385 if (handle_
!= INVALID_HANDLE_VALUE
)
1386 ::CloseHandle(handle_
);
1394 GTEST_DISALLOW_COPY_AND_ASSIGN_(AutoHandle
);
1396 # endif // GTEST_OS_WINDOWS
1398 // Attempts to parse a string into a positive integer pointed to by the
1399 // number parameter. Returns true if that is possible.
1400 // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we can use
1402 template <typename Integer
>
1403 bool ParseNaturalNumber(const ::std::string
& str
, Integer
* number
) {
1404 // Fail fast if the given string does not begin with a digit;
1405 // this bypasses strtoXXX's "optional leading whitespace and plus
1406 // or minus sign" semantics, which are undesirable here.
1407 if (str
.empty() || !IsDigit(str
[0])) {
1413 // BiggestConvertible is the largest integer type that system-provided
1414 // string-to-number conversion routines can return.
1416 # if GTEST_OS_WINDOWS && !defined(__GNUC__)
1418 // MSVC and C++ Builder define __int64 instead of the standard long long.
1419 typedef unsigned __int64 BiggestConvertible
;
1420 const BiggestConvertible parsed
= _strtoui64(str
.c_str(), &end
, 10);
1424 typedef unsigned long long BiggestConvertible
; // NOLINT
1425 const BiggestConvertible parsed
= strtoull(str
.c_str(), &end
, 10);
1427 # endif // GTEST_OS_WINDOWS && !defined(__GNUC__)
1429 const bool parse_success
= *end
== '\0' && errno
== 0;
1431 // TODO(vladl@google.com): Convert this to compile time assertion when it is
1433 GTEST_CHECK_(sizeof(Integer
) <= sizeof(parsed
));
1435 const Integer result
= static_cast<Integer
>(parsed
);
1436 if (parse_success
&& static_cast<BiggestConvertible
>(result
) == parsed
) {
1442 #endif // GTEST_HAS_DEATH_TEST
1444 // TestResult contains some private methods that should be hidden from
1445 // Google Test user but are required for testing. This class allow our tests
1448 // This class is supplied only for the purpose of testing Google Test's own
1449 // constructs. Do not use it in user tests, either directly or indirectly.
1450 class TestResultAccessor
{
1452 static void RecordProperty(TestResult
* test_result
,
1453 const std::string
& xml_element
,
1454 const TestProperty
& property
) {
1455 test_result
->RecordProperty(xml_element
, property
);
1458 static void ClearTestPartResults(TestResult
* test_result
) {
1459 test_result
->ClearTestPartResults();
1462 static const std::vector
<testing::TestPartResult
>& test_part_results(
1463 const TestResult
& test_result
) {
1464 return test_result
.test_part_results();
1468 #if GTEST_CAN_STREAM_RESULTS_
1470 // Streams test results to the given port on the given host machine.
1471 class StreamingListener
: public EmptyTestEventListener
{
1473 // Abstract base class for writing strings to a socket.
1474 class AbstractSocketWriter
{
1476 virtual ~AbstractSocketWriter() {}
1478 // Sends a string to the socket.
1479 virtual void Send(const string
& message
) = 0;
1481 // Closes the socket.
1482 virtual void CloseConnection() {}
1484 // Sends a string and a newline to the socket.
1485 void SendLn(const string
& message
) {
1486 Send(message
+ "\n");
1490 // Concrete class for actually writing strings to a socket.
1491 class SocketWriter
: public AbstractSocketWriter
{
1493 SocketWriter(const string
& host
, const string
& port
)
1494 : sockfd_(-1), host_name_(host
), port_num_(port
) {
1498 virtual ~SocketWriter() {
1503 // Sends a string to the socket.
1504 virtual void Send(const string
& message
) {
1505 GTEST_CHECK_(sockfd_
!= -1)
1506 << "Send() can be called only when there is a connection.";
1508 const int len
= static_cast<int>(message
.length());
1509 if (write(sockfd_
, message
.c_str(), len
) != len
) {
1511 << "stream_result_to: failed to stream to "
1512 << host_name_
<< ":" << port_num_
;
1517 // Creates a client socket and connects to the server.
1518 void MakeConnection();
1520 // Closes the socket.
1521 void CloseConnection() {
1522 GTEST_CHECK_(sockfd_
!= -1)
1523 << "CloseConnection() can be called only when there is a connection.";
1529 int sockfd_
; // socket file descriptor
1530 const string host_name_
;
1531 const string port_num_
;
1533 GTEST_DISALLOW_COPY_AND_ASSIGN_(SocketWriter
);
1534 }; // class SocketWriter
1536 // Escapes '=', '&', '%', and '\n' characters in str as "%xx".
1537 static string
UrlEncode(const char* str
);
1539 StreamingListener(const string
& host
, const string
& port
)
1540 : socket_writer_(new SocketWriter(host
, port
)) { Start(); }
1542 explicit StreamingListener(AbstractSocketWriter
* socket_writer
)
1543 : socket_writer_(socket_writer
) { Start(); }
1545 void OnTestProgramStart(const UnitTest
& /* unit_test */) {
1546 SendLn("event=TestProgramStart");
1549 void OnTestProgramEnd(const UnitTest
& unit_test
) {
1550 // Note that Google Test current only report elapsed time for each
1551 // test iteration, not for the entire test program.
1552 SendLn("event=TestProgramEnd&passed=" + FormatBool(unit_test
.Passed()));
1554 // Notify the streaming server to stop.
1555 socket_writer_
->CloseConnection();
1558 void OnTestIterationStart(const UnitTest
& /* unit_test */, int iteration
) {
1559 SendLn("event=TestIterationStart&iteration=" +
1560 StreamableToString(iteration
));
1563 void OnTestIterationEnd(const UnitTest
& unit_test
, int /* iteration */) {
1564 SendLn("event=TestIterationEnd&passed=" +
1565 FormatBool(unit_test
.Passed()) + "&elapsed_time=" +
1566 StreamableToString(unit_test
.elapsed_time()) + "ms");
1569 void OnTestCaseStart(const TestCase
& test_case
) {
1570 SendLn(std::string("event=TestCaseStart&name=") + test_case
.name());
1573 void OnTestCaseEnd(const TestCase
& test_case
) {
1574 SendLn("event=TestCaseEnd&passed=" + FormatBool(test_case
.Passed())
1575 + "&elapsed_time=" + StreamableToString(test_case
.elapsed_time())
1579 void OnTestStart(const TestInfo
& test_info
) {
1580 SendLn(std::string("event=TestStart&name=") + test_info
.name());
1583 void OnTestEnd(const TestInfo
& test_info
) {
1584 SendLn("event=TestEnd&passed=" +
1585 FormatBool((test_info
.result())->Passed()) +
1587 StreamableToString((test_info
.result())->elapsed_time()) + "ms");
1590 void OnTestPartResult(const TestPartResult
& test_part_result
) {
1591 const char* file_name
= test_part_result
.file_name();
1592 if (file_name
== NULL
)
1594 SendLn("event=TestPartResult&file=" + UrlEncode(file_name
) +
1595 "&line=" + StreamableToString(test_part_result
.line_number()) +
1596 "&message=" + UrlEncode(test_part_result
.message()));
1600 // Sends the given message and a newline to the socket.
1601 void SendLn(const string
& message
) { socket_writer_
->SendLn(message
); }
1603 // Called at the start of streaming to notify the receiver what
1604 // protocol we are using.
1605 void Start() { SendLn("gtest_streaming_protocol_version=1.0"); }
1607 string
FormatBool(bool value
) { return value
? "1" : "0"; }
1609 const scoped_ptr
<AbstractSocketWriter
> socket_writer_
;
1611 GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamingListener
);
1612 }; // class StreamingListener
1614 #endif // GTEST_CAN_STREAM_RESULTS_
1616 } // namespace internal
1617 } // namespace testing
1619 #endif // GTEST_SRC_GTEST_INTERNAL_INL_H_
1620 #undef GTEST_IMPLEMENTATION_
1622 #if GTEST_OS_WINDOWS
1623 # define vsnprintf _vsnprintf
1624 #endif // GTEST_OS_WINDOWS
1628 using internal::CountIf
;
1629 using internal::ForEach
;
1630 using internal::GetElementOr
;
1631 using internal::Shuffle
;
1635 // A test whose test case name or test name matches this filter is
1636 // disabled and not run.
1637 static const char kDisableTestFilter
[] = "DISABLED_*:*/DISABLED_*";
1639 // A test case whose name matches this filter is considered a death
1640 // test case and will be run before test cases whose name doesn't
1641 // match this filter.
1642 static const char kDeathTestCaseFilter
[] = "*DeathTest:*DeathTest/*";
1644 // A test filter that matches everything.
1645 static const char kUniversalFilter
[] = "*";
1647 // The default output file for XML output.
1648 static const char kDefaultOutputFile
[] = "test_detail.xml";
1650 // The environment variable name for the test shard index.
1651 static const char kTestShardIndex
[] = "GTEST_SHARD_INDEX";
1652 // The environment variable name for the total number of test shards.
1653 static const char kTestTotalShards
[] = "GTEST_TOTAL_SHARDS";
1654 // The environment variable name for the test shard status file.
1655 static const char kTestShardStatusFile
[] = "GTEST_SHARD_STATUS_FILE";
1657 namespace internal
{
1659 // The text used in failure messages to indicate the start of the
1661 const char kStackTraceMarker
[] = "\nStack trace:\n";
1663 // g_help_flag is true iff the --help flag or an equivalent form is
1664 // specified on the command line.
1665 bool g_help_flag
= false;
1667 } // namespace internal
1669 static const char* GetDefaultFilter() {
1670 return kUniversalFilter
;
1674 also_run_disabled_tests
,
1675 internal::BoolFromGTestEnv("also_run_disabled_tests", false),
1676 "Run disabled tests too, in addition to the tests normally being run.");
1680 internal::BoolFromGTestEnv("break_on_failure", false),
1681 "True iff a failed assertion should be a debugger break-point.");
1685 internal::BoolFromGTestEnv("catch_exceptions", true),
1686 "True iff " GTEST_NAME_
1687 " should catch exceptions and treat them as test failures.");
1689 GTEST_DEFINE_string_(
1691 internal::StringFromGTestEnv("color", "auto"),
1692 "Whether to use colors in the output. Valid values: yes, no, "
1693 "and auto. 'auto' means to use colors if the output is "
1694 "being sent to a terminal and the TERM environment variable "
1695 "is set to a terminal type that supports colors.");
1697 GTEST_DEFINE_string_(
1699 internal::StringFromGTestEnv("filter", GetDefaultFilter()),
1700 "A colon-separated list of glob (not regex) patterns "
1701 "for filtering the tests to run, optionally followed by a "
1702 "'-' and a : separated list of negative patterns (tests to "
1703 "exclude). A test is run if it matches one of the positive "
1704 "patterns and does not match any of the negative patterns.");
1706 GTEST_DEFINE_bool_(list_tests
, false,
1707 "List all tests without running them.");
1709 GTEST_DEFINE_string_(
1711 internal::StringFromGTestEnv("output", ""),
1712 "A format (currently must be \"xml\"), optionally followed "
1713 "by a colon and an output file name or directory. A directory "
1714 "is indicated by a trailing pathname separator. "
1715 "Examples: \"xml:filename.xml\", \"xml::directoryname/\". "
1716 "If a directory is specified, output files will be created "
1717 "within that directory, with file-names based on the test "
1718 "executable's name and, if necessary, made unique by adding "
1723 internal::BoolFromGTestEnv("print_time", true),
1724 "True iff " GTEST_NAME_
1725 " should display elapsed time in text output.");
1727 GTEST_DEFINE_int32_(
1729 internal::Int32FromGTestEnv("random_seed", 0),
1730 "Random number seed to use when shuffling test orders. Must be in range "
1731 "[1, 99999], or 0 to use a seed based on the current time.");
1733 GTEST_DEFINE_int32_(
1735 internal::Int32FromGTestEnv("repeat", 1),
1736 "How many times to repeat each test. Specify a negative number "
1737 "for repeating forever. Useful for shaking out flaky tests.");
1740 show_internal_stack_frames
, false,
1741 "True iff " GTEST_NAME_
" should include internal stack frames when "
1742 "printing test failure stack traces.");
1746 internal::BoolFromGTestEnv("shuffle", false),
1747 "True iff " GTEST_NAME_
1748 " should randomize tests' order on every run.");
1750 GTEST_DEFINE_int32_(
1752 internal::Int32FromGTestEnv("stack_trace_depth", kMaxStackTraceDepth
),
1753 "The maximum number of stack frames to print when an "
1754 "assertion fails. The valid range is 0 through 100, inclusive.");
1756 GTEST_DEFINE_string_(
1758 internal::StringFromGTestEnv("stream_result_to", ""),
1759 "This flag specifies the host name and the port number on which to stream "
1760 "test results. Example: \"localhost:555\". The flag is effective only on "
1765 internal::BoolFromGTestEnv("throw_on_failure", false),
1766 "When this flag is specified, a failed assertion will throw an exception "
1767 "if exceptions are enabled or exit the program with a non-zero code "
1770 namespace internal
{
1772 // Generates a random number from [0, range), using a Linear
1773 // Congruential Generator (LCG). Crashes if 'range' is 0 or greater
1775 UInt32
Random::Generate(UInt32 range
) {
1776 // These constants are the same as are used in glibc's rand(3).
1777 state_
= (1103515245U*state_
+ 12345U) % kMaxRange
;
1779 GTEST_CHECK_(range
> 0)
1780 << "Cannot generate a number in the range [0, 0).";
1781 GTEST_CHECK_(range
<= kMaxRange
)
1782 << "Generation of a number in [0, " << range
<< ") was requested, "
1783 << "but this can only generate numbers in [0, " << kMaxRange
<< ").";
1785 // Converting via modulus introduces a bit of downward bias, but
1786 // it's simple, and a linear congruential generator isn't too good
1788 return state_
% range
;
1791 // GTestIsInitialized() returns true iff the user has initialized
1792 // Google Test. Useful for catching the user mistake of not initializing
1793 // Google Test before calling RUN_ALL_TESTS().
1795 // A user must call testing::InitGoogleTest() to initialize Google
1796 // Test. g_init_gtest_count is set to the number of times
1797 // InitGoogleTest() has been called. We don't protect this variable
1798 // under a mutex as it is only accessed in the main thread.
1799 GTEST_API_
int g_init_gtest_count
= 0;
1800 static bool GTestIsInitialized() { return g_init_gtest_count
!= 0; }
1802 // Iterates over a vector of TestCases, keeping a running sum of the
1803 // results of calling a given int-returning method on each.
1805 static int SumOverTestCaseList(const std::vector
<TestCase
*>& case_list
,
1806 int (TestCase::*method
)() const) {
1808 for (size_t i
= 0; i
< case_list
.size(); i
++) {
1809 sum
+= (case_list
[i
]->*method
)();
1814 // Returns true iff the test case passed.
1815 static bool TestCasePassed(const TestCase
* test_case
) {
1816 return test_case
->should_run() && test_case
->Passed();
1819 // Returns true iff the test case failed.
1820 static bool TestCaseFailed(const TestCase
* test_case
) {
1821 return test_case
->should_run() && test_case
->Failed();
1824 // Returns true iff test_case contains at least one test that should
1826 static bool ShouldRunTestCase(const TestCase
* test_case
) {
1827 return test_case
->should_run();
1830 // AssertHelper constructor.
1831 AssertHelper::AssertHelper(TestPartResult::Type type
,
1834 const char* message
)
1835 : data_(new AssertHelperData(type
, file
, line
, message
)) {
1838 AssertHelper::~AssertHelper() {
1842 // Message assignment, for assertion streaming support.
1843 void AssertHelper::operator=(const Message
& message
) const {
1844 UnitTest::GetInstance()->
1845 AddTestPartResult(data_
->type
, data_
->file
, data_
->line
,
1846 AppendUserMessage(data_
->message
, message
),
1847 UnitTest::GetInstance()->impl()
1848 ->CurrentOsStackTraceExceptTop(1)
1849 // Skips the stack frame for this function itself.
1853 // Mutex for linked pointers.
1854 GTEST_API_
GTEST_DEFINE_STATIC_MUTEX_(g_linked_ptr_mutex
);
1856 // Application pathname gotten in InitGoogleTest.
1857 std::string g_executable_path
;
1859 // Returns the current application's name, removing directory path if that
1861 FilePath
GetCurrentExecutableName() {
1864 #if GTEST_OS_WINDOWS
1865 result
.Set(FilePath(g_executable_path
).RemoveExtension("exe"));
1867 result
.Set(FilePath(g_executable_path
));
1868 #endif // GTEST_OS_WINDOWS
1870 return result
.RemoveDirectoryName();
1873 // Functions for processing the gtest_output flag.
1875 // Returns the output format, or "" for normal printed output.
1876 std::string
UnitTestOptions::GetOutputFormat() {
1877 const char* const gtest_output_flag
= GTEST_FLAG(output
).c_str();
1878 if (gtest_output_flag
== NULL
) return std::string("");
1880 const char* const colon
= strchr(gtest_output_flag
, ':');
1881 return (colon
== NULL
) ?
1882 std::string(gtest_output_flag
) :
1883 std::string(gtest_output_flag
, colon
- gtest_output_flag
);
1886 // Returns the name of the requested output file, or the default if none
1887 // was explicitly specified.
1888 std::string
UnitTestOptions::GetAbsolutePathToOutputFile() {
1889 const char* const gtest_output_flag
= GTEST_FLAG(output
).c_str();
1890 if (gtest_output_flag
== NULL
)
1893 const char* const colon
= strchr(gtest_output_flag
, ':');
1895 return internal::FilePath::ConcatPaths(
1897 UnitTest::GetInstance()->original_working_dir()),
1898 internal::FilePath(kDefaultOutputFile
)).string();
1900 internal::FilePath
output_name(colon
+ 1);
1901 if (!output_name
.IsAbsolutePath())
1902 // TODO(wan@google.com): on Windows \some\path is not an absolute
1903 // path (as its meaning depends on the current drive), yet the
1904 // following logic for turning it into an absolute path is wrong.
1906 output_name
= internal::FilePath::ConcatPaths(
1907 internal::FilePath(UnitTest::GetInstance()->original_working_dir()),
1908 internal::FilePath(colon
+ 1));
1910 if (!output_name
.IsDirectory())
1911 return output_name
.string();
1913 internal::FilePath
result(internal::FilePath::GenerateUniqueFileName(
1914 output_name
, internal::GetCurrentExecutableName(),
1915 GetOutputFormat().c_str()));
1916 return result
.string();
1919 // Returns true iff the wildcard pattern matches the string. The
1920 // first ':' or '\0' character in pattern marks the end of it.
1922 // This recursive algorithm isn't very efficient, but is clear and
1923 // works well enough for matching test names, which are short.
1924 bool UnitTestOptions::PatternMatchesString(const char *pattern
,
1928 case ':': // Either ':' or '\0' marks the end of the pattern.
1929 return *str
== '\0';
1930 case '?': // Matches any single character.
1931 return *str
!= '\0' && PatternMatchesString(pattern
+ 1, str
+ 1);
1932 case '*': // Matches any string (possibly empty) of characters.
1933 return (*str
!= '\0' && PatternMatchesString(pattern
, str
+ 1)) ||
1934 PatternMatchesString(pattern
+ 1, str
);
1935 default: // Non-special character. Matches itself.
1936 return *pattern
== *str
&&
1937 PatternMatchesString(pattern
+ 1, str
+ 1);
1941 bool UnitTestOptions::MatchesFilter(
1942 const std::string
& name
, const char* filter
) {
1943 const char *cur_pattern
= filter
;
1945 if (PatternMatchesString(cur_pattern
, name
.c_str())) {
1949 // Finds the next pattern in the filter.
1950 cur_pattern
= strchr(cur_pattern
, ':');
1952 // Returns if no more pattern can be found.
1953 if (cur_pattern
== NULL
) {
1957 // Skips the pattern separater (the ':' character).
1962 // Returns true iff the user-specified filter matches the test case
1963 // name and the test name.
1964 bool UnitTestOptions::FilterMatchesTest(const std::string
&test_case_name
,
1965 const std::string
&test_name
) {
1966 const std::string
& full_name
= test_case_name
+ "." + test_name
.c_str();
1968 // Split --gtest_filter at '-', if there is one, to separate into
1969 // positive filter and negative filter portions
1970 const char* const p
= GTEST_FLAG(filter
).c_str();
1971 const char* const dash
= strchr(p
, '-');
1972 std::string positive
;
1973 std::string negative
;
1975 positive
= GTEST_FLAG(filter
).c_str(); // Whole string is a positive filter
1978 positive
= std::string(p
, dash
); // Everything up to the dash
1979 negative
= std::string(dash
+ 1); // Everything after the dash
1980 if (positive
.empty()) {
1981 // Treat '-test1' as the same as '*-test1'
1982 positive
= kUniversalFilter
;
1986 // A filter is a colon-separated list of patterns. It matches a
1987 // test if any pattern in it matches the test.
1988 return (MatchesFilter(full_name
, positive
.c_str()) &&
1989 !MatchesFilter(full_name
, negative
.c_str()));
1993 // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
1994 // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
1995 // This function is useful as an __except condition.
1996 int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code
) {
1997 // Google Test should handle a SEH exception if:
1998 // 1. the user wants it to, AND
1999 // 2. this is not a breakpoint exception, AND
2000 // 3. this is not a C++ exception (VC++ implements them via SEH,
2003 // SEH exception code for C++ exceptions.
2004 // (see http://support.microsoft.com/kb/185294 for more information).
2005 const DWORD kCxxExceptionCode
= 0xe06d7363;
2007 bool should_handle
= true;
2009 if (!GTEST_FLAG(catch_exceptions
))
2010 should_handle
= false;
2011 else if (exception_code
== EXCEPTION_BREAKPOINT
)
2012 should_handle
= false;
2013 else if (exception_code
== kCxxExceptionCode
)
2014 should_handle
= false;
2016 return should_handle
? EXCEPTION_EXECUTE_HANDLER
: EXCEPTION_CONTINUE_SEARCH
;
2018 #endif // GTEST_HAS_SEH
2020 } // namespace internal
2022 // The c'tor sets this object as the test part result reporter used by
2023 // Google Test. The 'result' parameter specifies where to report the
2024 // results. Intercepts only failures from the current thread.
2025 ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
2026 TestPartResultArray
* result
)
2027 : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD
),
2032 // The c'tor sets this object as the test part result reporter used by
2033 // Google Test. The 'result' parameter specifies where to report the
2035 ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
2036 InterceptMode intercept_mode
, TestPartResultArray
* result
)
2037 : intercept_mode_(intercept_mode
),
2042 void ScopedFakeTestPartResultReporter::Init() {
2043 internal::UnitTestImpl
* const impl
= internal::GetUnitTestImpl();
2044 if (intercept_mode_
== INTERCEPT_ALL_THREADS
) {
2045 old_reporter_
= impl
->GetGlobalTestPartResultReporter();
2046 impl
->SetGlobalTestPartResultReporter(this);
2048 old_reporter_
= impl
->GetTestPartResultReporterForCurrentThread();
2049 impl
->SetTestPartResultReporterForCurrentThread(this);
2053 // The d'tor restores the test part result reporter used by Google Test
2055 ScopedFakeTestPartResultReporter::~ScopedFakeTestPartResultReporter() {
2056 internal::UnitTestImpl
* const impl
= internal::GetUnitTestImpl();
2057 if (intercept_mode_
== INTERCEPT_ALL_THREADS
) {
2058 impl
->SetGlobalTestPartResultReporter(old_reporter_
);
2060 impl
->SetTestPartResultReporterForCurrentThread(old_reporter_
);
2064 // Increments the test part result count and remembers the result.
2065 // This method is from the TestPartResultReporterInterface interface.
2066 void ScopedFakeTestPartResultReporter::ReportTestPartResult(
2067 const TestPartResult
& result
) {
2068 result_
->Append(result
);
2071 namespace internal
{
2073 // Returns the type ID of ::testing::Test. We should always call this
2074 // instead of GetTypeId< ::testing::Test>() to get the type ID of
2075 // testing::Test. This is to work around a suspected linker bug when
2076 // using Google Test as a framework on Mac OS X. The bug causes
2077 // GetTypeId< ::testing::Test>() to return different values depending
2078 // on whether the call is from the Google Test framework itself or
2079 // from user test code. GetTestTypeId() is guaranteed to always
2080 // return the same value, as it always calls GetTypeId<>() from the
2081 // gtest.cc, which is within the Google Test framework.
2082 TypeId
GetTestTypeId() {
2083 return GetTypeId
<Test
>();
2086 // The value of GetTestTypeId() as seen from within the Google Test
2087 // library. This is solely for testing GetTestTypeId().
2088 extern const TypeId kTestTypeIdInGoogleTest
= GetTestTypeId();
2090 // This predicate-formatter checks that 'results' contains a test part
2091 // failure of the given type and that the failure message contains the
2093 AssertionResult
HasOneFailure(const char* /* results_expr */,
2094 const char* /* type_expr */,
2095 const char* /* substr_expr */,
2096 const TestPartResultArray
& results
,
2097 TestPartResult::Type type
,
2098 const string
& substr
) {
2099 const std::string
expected(type
== TestPartResult::kFatalFailure
?
2101 "1 non-fatal failure");
2103 if (results
.size() != 1) {
2104 msg
<< "Expected: " << expected
<< "\n"
2105 << " Actual: " << results
.size() << " failures";
2106 for (int i
= 0; i
< results
.size(); i
++) {
2107 msg
<< "\n" << results
.GetTestPartResult(i
);
2109 return AssertionFailure() << msg
;
2112 const TestPartResult
& r
= results
.GetTestPartResult(0);
2113 if (r
.type() != type
) {
2114 return AssertionFailure() << "Expected: " << expected
<< "\n"
2119 if (strstr(r
.message(), substr
.c_str()) == NULL
) {
2120 return AssertionFailure() << "Expected: " << expected
<< " containing \""
2126 return AssertionSuccess();
2129 // The constructor of SingleFailureChecker remembers where to look up
2130 // test part results, what type of failure we expect, and what
2131 // substring the failure message should contain.
2132 SingleFailureChecker:: SingleFailureChecker(
2133 const TestPartResultArray
* results
,
2134 TestPartResult::Type type
,
2135 const string
& substr
)
2136 : results_(results
),
2140 // The destructor of SingleFailureChecker verifies that the given
2141 // TestPartResultArray contains exactly one failure that has the given
2142 // type and contains the given substring. If that's not the case, a
2143 // non-fatal failure will be generated.
2144 SingleFailureChecker::~SingleFailureChecker() {
2145 EXPECT_PRED_FORMAT3(HasOneFailure
, *results_
, type_
, substr_
);
2148 DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter(
2149 UnitTestImpl
* unit_test
) : unit_test_(unit_test
) {}
2151 void DefaultGlobalTestPartResultReporter::ReportTestPartResult(
2152 const TestPartResult
& result
) {
2153 unit_test_
->current_test_result()->AddTestPartResult(result
);
2154 unit_test_
->listeners()->repeater()->OnTestPartResult(result
);
2157 DefaultPerThreadTestPartResultReporter::DefaultPerThreadTestPartResultReporter(
2158 UnitTestImpl
* unit_test
) : unit_test_(unit_test
) {}
2160 void DefaultPerThreadTestPartResultReporter::ReportTestPartResult(
2161 const TestPartResult
& result
) {
2162 unit_test_
->GetGlobalTestPartResultReporter()->ReportTestPartResult(result
);
2165 // Returns the global test part result reporter.
2166 TestPartResultReporterInterface
*
2167 UnitTestImpl::GetGlobalTestPartResultReporter() {
2168 internal::MutexLock
lock(&global_test_part_result_reporter_mutex_
);
2169 return global_test_part_result_repoter_
;
2172 // Sets the global test part result reporter.
2173 void UnitTestImpl::SetGlobalTestPartResultReporter(
2174 TestPartResultReporterInterface
* reporter
) {
2175 internal::MutexLock
lock(&global_test_part_result_reporter_mutex_
);
2176 global_test_part_result_repoter_
= reporter
;
2179 // Returns the test part result reporter for the current thread.
2180 TestPartResultReporterInterface
*
2181 UnitTestImpl::GetTestPartResultReporterForCurrentThread() {
2182 return per_thread_test_part_result_reporter_
.get();
2185 // Sets the test part result reporter for the current thread.
2186 void UnitTestImpl::SetTestPartResultReporterForCurrentThread(
2187 TestPartResultReporterInterface
* reporter
) {
2188 per_thread_test_part_result_reporter_
.set(reporter
);
2191 // Gets the number of successful test cases.
2192 int UnitTestImpl::successful_test_case_count() const {
2193 return CountIf(test_cases_
, TestCasePassed
);
2196 // Gets the number of failed test cases.
2197 int UnitTestImpl::failed_test_case_count() const {
2198 return CountIf(test_cases_
, TestCaseFailed
);
2201 // Gets the number of all test cases.
2202 int UnitTestImpl::total_test_case_count() const {
2203 return static_cast<int>(test_cases_
.size());
2206 // Gets the number of all test cases that contain at least one test
2208 int UnitTestImpl::test_case_to_run_count() const {
2209 return CountIf(test_cases_
, ShouldRunTestCase
);
2212 // Gets the number of successful tests.
2213 int UnitTestImpl::successful_test_count() const {
2214 return SumOverTestCaseList(test_cases_
, &TestCase::successful_test_count
);
2217 // Gets the number of failed tests.
2218 int UnitTestImpl::failed_test_count() const {
2219 return SumOverTestCaseList(test_cases_
, &TestCase::failed_test_count
);
2222 // Gets the number of disabled tests that will be reported in the XML report.
2223 int UnitTestImpl::reportable_disabled_test_count() const {
2224 return SumOverTestCaseList(test_cases_
,
2225 &TestCase::reportable_disabled_test_count
);
2228 // Gets the number of disabled tests.
2229 int UnitTestImpl::disabled_test_count() const {
2230 return SumOverTestCaseList(test_cases_
, &TestCase::disabled_test_count
);
2233 // Gets the number of tests to be printed in the XML report.
2234 int UnitTestImpl::reportable_test_count() const {
2235 return SumOverTestCaseList(test_cases_
, &TestCase::reportable_test_count
);
2238 // Gets the number of all tests.
2239 int UnitTestImpl::total_test_count() const {
2240 return SumOverTestCaseList(test_cases_
, &TestCase::total_test_count
);
2243 // Gets the number of tests that should run.
2244 int UnitTestImpl::test_to_run_count() const {
2245 return SumOverTestCaseList(test_cases_
, &TestCase::test_to_run_count
);
2248 // Returns the current OS stack trace as an std::string.
2250 // The maximum number of stack frames to be included is specified by
2251 // the gtest_stack_trace_depth flag. The skip_count parameter
2252 // specifies the number of top frames to be skipped, which doesn't
2253 // count against the number of frames to be included.
2255 // For example, if Foo() calls Bar(), which in turn calls
2256 // CurrentOsStackTraceExceptTop(1), Foo() will be included in the
2257 // trace but Bar() and CurrentOsStackTraceExceptTop() won't.
2258 std::string
UnitTestImpl::CurrentOsStackTraceExceptTop(int skip_count
) {
2263 // Returns the current time in milliseconds.
2264 TimeInMillis
GetTimeInMillis() {
2265 #if GTEST_OS_WINDOWS_MOBILE || defined(__BORLANDC__)
2266 // Difference between 1970-01-01 and 1601-01-01 in milliseconds.
2267 // http://analogous.blogspot.com/2005/04/epoch.html
2268 const TimeInMillis kJavaEpochToWinFileTimeDelta
=
2269 static_cast<TimeInMillis
>(116444736UL) * 100000UL;
2270 const DWORD kTenthMicrosInMilliSecond
= 10000;
2272 SYSTEMTIME now_systime
;
2273 FILETIME now_filetime
;
2274 ULARGE_INTEGER now_int64
;
2275 // TODO(kenton@google.com): Shouldn't this just use
2276 // GetSystemTimeAsFileTime()?
2277 GetSystemTime(&now_systime
);
2278 if (SystemTimeToFileTime(&now_systime
, &now_filetime
)) {
2279 now_int64
.LowPart
= now_filetime
.dwLowDateTime
;
2280 now_int64
.HighPart
= now_filetime
.dwHighDateTime
;
2281 now_int64
.QuadPart
= (now_int64
.QuadPart
/ kTenthMicrosInMilliSecond
) -
2282 kJavaEpochToWinFileTimeDelta
;
2283 return now_int64
.QuadPart
;
2286 #elif GTEST_OS_WINDOWS && !GTEST_HAS_GETTIMEOFDAY_
2291 // MSVC 8 deprecates _ftime64(), so we want to suppress warning 4996
2292 // (deprecated function) there.
2293 // TODO(kenton@google.com): Use GetTickCount()? Or use
2294 // SystemTimeToFileTime()
2295 # pragma warning(push) // Saves the current warning state.
2296 # pragma warning(disable:4996) // Temporarily disables warning 4996.
2298 # pragma warning(pop) // Restores the warning state.
2305 return static_cast<TimeInMillis
>(now
.time
) * 1000 + now
.millitm
;
2306 #elif GTEST_HAS_GETTIMEOFDAY_
2308 gettimeofday(&now
, NULL
);
2309 return static_cast<TimeInMillis
>(now
.tv_sec
) * 1000 + now
.tv_usec
/ 1000;
2311 # error "Don't know how to get the current time on your system."
2319 #if GTEST_OS_WINDOWS_MOBILE
2320 // Creates a UTF-16 wide string from the given ANSI string, allocating
2321 // memory using new. The caller is responsible for deleting the return
2322 // value using delete[]. Returns the wide string, or NULL if the
2324 LPCWSTR
String::AnsiToUtf16(const char* ansi
) {
2325 if (!ansi
) return NULL
;
2326 const int length
= strlen(ansi
);
2327 const int unicode_length
=
2328 MultiByteToWideChar(CP_ACP
, 0, ansi
, length
,
2330 WCHAR
* unicode
= new WCHAR
[unicode_length
+ 1];
2331 MultiByteToWideChar(CP_ACP
, 0, ansi
, length
,
2332 unicode
, unicode_length
);
2333 unicode
[unicode_length
] = 0;
2337 // Creates an ANSI string from the given wide string, allocating
2338 // memory using new. The caller is responsible for deleting the return
2339 // value using delete[]. Returns the ANSI string, or NULL if the
2341 const char* String::Utf16ToAnsi(LPCWSTR utf16_str
) {
2342 if (!utf16_str
) return NULL
;
2343 const int ansi_length
=
2344 WideCharToMultiByte(CP_ACP
, 0, utf16_str
, -1,
2345 NULL
, 0, NULL
, NULL
);
2346 char* ansi
= new char[ansi_length
+ 1];
2347 WideCharToMultiByte(CP_ACP
, 0, utf16_str
, -1,
2348 ansi
, ansi_length
, NULL
, NULL
);
2349 ansi
[ansi_length
] = 0;
2353 #endif // GTEST_OS_WINDOWS_MOBILE
2355 // Compares two C strings. Returns true iff they have the same content.
2357 // Unlike strcmp(), this function can handle NULL argument(s). A NULL
2358 // C string is considered different to any non-NULL C string,
2359 // including the empty string.
2360 bool String::CStringEquals(const char * lhs
, const char * rhs
) {
2361 if ( lhs
== NULL
) return rhs
== NULL
;
2363 if ( rhs
== NULL
) return false;
2365 return strcmp(lhs
, rhs
) == 0;
2368 #if GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
2370 // Converts an array of wide chars to a narrow string using the UTF-8
2371 // encoding, and streams the result to the given Message object.
2372 static void StreamWideCharsToMessage(const wchar_t* wstr
, size_t length
,
2374 for (size_t i
= 0; i
!= length
; ) { // NOLINT
2375 if (wstr
[i
] != L
'\0') {
2376 *msg
<< WideStringToUtf8(wstr
+ i
, static_cast<int>(length
- i
));
2377 while (i
!= length
&& wstr
[i
] != L
'\0')
2386 #endif // GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
2388 } // namespace internal
2390 // Constructs an empty Message.
2391 // We allocate the stringstream separately because otherwise each use of
2392 // ASSERT/EXPECT in a procedure adds over 200 bytes to the procedure's
2393 // stack frame leading to huge stack frames in some cases; gcc does not reuse
2395 Message::Message() : ss_(new ::std::stringstream
) {
2396 // By default, we want there to be enough precision when printing
2397 // a double to a Message.
2398 *ss_
<< std::setprecision(std::numeric_limits
<double>::digits10
+ 2);
2401 // These two overloads allow streaming a wide C string to a Message
2402 // using the UTF-8 encoding.
2403 Message
& Message::operator <<(const wchar_t* wide_c_str
) {
2404 return *this << internal::String::ShowWideCString(wide_c_str
);
2406 Message
& Message::operator <<(wchar_t* wide_c_str
) {
2407 return *this << internal::String::ShowWideCString(wide_c_str
);
2410 #if GTEST_HAS_STD_WSTRING
2411 // Converts the given wide string to a narrow string using the UTF-8
2412 // encoding, and streams the result to this Message object.
2413 Message
& Message::operator <<(const ::std::wstring
& wstr
) {
2414 internal::StreamWideCharsToMessage(wstr
.c_str(), wstr
.length(), this);
2417 #endif // GTEST_HAS_STD_WSTRING
2419 #if GTEST_HAS_GLOBAL_WSTRING
2420 // Converts the given wide string to a narrow string using the UTF-8
2421 // encoding, and streams the result to this Message object.
2422 Message
& Message::operator <<(const ::wstring
& wstr
) {
2423 internal::StreamWideCharsToMessage(wstr
.c_str(), wstr
.length(), this);
2426 #endif // GTEST_HAS_GLOBAL_WSTRING
2428 // Gets the text streamed to this object so far as an std::string.
2429 // Each '\0' character in the buffer is replaced with "\\0".
2430 std::string
Message::GetString() const {
2431 return internal::StringStreamToString(ss_
.get());
2434 // AssertionResult constructors.
2435 // Used in EXPECT_TRUE/FALSE(assertion_result).
2436 AssertionResult::AssertionResult(const AssertionResult
& other
)
2437 : success_(other
.success_
),
2438 message_(other
.message_
.get() != NULL
?
2439 new ::std::string(*other
.message_
) :
2440 static_cast< ::std::string
*>(NULL
)) {
2443 // Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE.
2444 AssertionResult
AssertionResult::operator!() const {
2445 AssertionResult
negation(!success_
);
2446 if (message_
.get() != NULL
)
2447 negation
<< *message_
;
2451 // Makes a successful assertion result.
2452 AssertionResult
AssertionSuccess() {
2453 return AssertionResult(true);
2456 // Makes a failed assertion result.
2457 AssertionResult
AssertionFailure() {
2458 return AssertionResult(false);
2461 // Makes a failed assertion result with the given failure message.
2462 // Deprecated; use AssertionFailure() << message.
2463 AssertionResult
AssertionFailure(const Message
& message
) {
2464 return AssertionFailure() << message
;
2467 namespace internal
{
2469 // Constructs and returns the message for an equality assertion
2470 // (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure.
2472 // The first four parameters are the expressions used in the assertion
2473 // and their values, as strings. For example, for ASSERT_EQ(foo, bar)
2474 // where foo is 5 and bar is 6, we have:
2476 // expected_expression: "foo"
2477 // actual_expression: "bar"
2478 // expected_value: "5"
2479 // actual_value: "6"
2481 // The ignoring_case parameter is true iff the assertion is a
2482 // *_STRCASEEQ*. When it's true, the string " (ignoring case)" will
2483 // be inserted into the message.
2484 AssertionResult
EqFailure(const char* expected_expression
,
2485 const char* actual_expression
,
2486 const std::string
& expected_value
,
2487 const std::string
& actual_value
,
2488 bool ignoring_case
) {
2490 msg
<< "Value of: " << actual_expression
;
2491 if (actual_value
!= actual_expression
) {
2492 msg
<< "\n Actual: " << actual_value
;
2495 msg
<< "\nExpected: " << expected_expression
;
2496 if (ignoring_case
) {
2497 msg
<< " (ignoring case)";
2499 if (expected_value
!= expected_expression
) {
2500 msg
<< "\nWhich is: " << expected_value
;
2503 return AssertionFailure() << msg
;
2506 // Constructs a failure message for Boolean assertions such as EXPECT_TRUE.
2507 std::string
GetBoolAssertionFailureMessage(
2508 const AssertionResult
& assertion_result
,
2509 const char* expression_text
,
2510 const char* actual_predicate_value
,
2511 const char* expected_predicate_value
) {
2512 const char* actual_message
= assertion_result
.message();
2514 msg
<< "Value of: " << expression_text
2515 << "\n Actual: " << actual_predicate_value
;
2516 if (actual_message
[0] != '\0')
2517 msg
<< " (" << actual_message
<< ")";
2518 msg
<< "\nExpected: " << expected_predicate_value
;
2519 return msg
.GetString();
2522 // Helper function for implementing ASSERT_NEAR.
2523 AssertionResult
DoubleNearPredFormat(const char* expr1
,
2525 const char* abs_error_expr
,
2529 const double diff
= fabs(val1
- val2
);
2530 if (diff
<= abs_error
) return AssertionSuccess();
2532 // TODO(wan): do not print the value of an expression if it's
2533 // already a literal.
2534 return AssertionFailure()
2535 << "The difference between " << expr1
<< " and " << expr2
2536 << " is " << diff
<< ", which exceeds " << abs_error_expr
<< ", where\n"
2537 << expr1
<< " evaluates to " << val1
<< ",\n"
2538 << expr2
<< " evaluates to " << val2
<< ", and\n"
2539 << abs_error_expr
<< " evaluates to " << abs_error
<< ".";
2543 // Helper template for implementing FloatLE() and DoubleLE().
2544 template <typename RawType
>
2545 AssertionResult
FloatingPointLE(const char* expr1
,
2549 // Returns success if val1 is less than val2,
2551 return AssertionSuccess();
2554 // or if val1 is almost equal to val2.
2555 const FloatingPoint
<RawType
> lhs(val1
), rhs(val2
);
2556 if (lhs
.AlmostEquals(rhs
)) {
2557 return AssertionSuccess();
2560 // Note that the above two checks will both fail if either val1 or
2561 // val2 is NaN, as the IEEE floating-point standard requires that
2562 // any predicate involving a NaN must return false.
2564 ::std::stringstream val1_ss
;
2565 val1_ss
<< std::setprecision(std::numeric_limits
<RawType
>::digits10
+ 2)
2568 ::std::stringstream val2_ss
;
2569 val2_ss
<< std::setprecision(std::numeric_limits
<RawType
>::digits10
+ 2)
2572 return AssertionFailure()
2573 << "Expected: (" << expr1
<< ") <= (" << expr2
<< ")\n"
2574 << " Actual: " << StringStreamToString(&val1_ss
) << " vs "
2575 << StringStreamToString(&val2_ss
);
2578 } // namespace internal
2580 // Asserts that val1 is less than, or almost equal to, val2. Fails
2581 // otherwise. In particular, it fails if either val1 or val2 is NaN.
2582 AssertionResult
FloatLE(const char* expr1
, const char* expr2
,
2583 float val1
, float val2
) {
2584 return internal::FloatingPointLE
<float>(expr1
, expr2
, val1
, val2
);
2587 // Asserts that val1 is less than, or almost equal to, val2. Fails
2588 // otherwise. In particular, it fails if either val1 or val2 is NaN.
2589 AssertionResult
DoubleLE(const char* expr1
, const char* expr2
,
2590 double val1
, double val2
) {
2591 return internal::FloatingPointLE
<double>(expr1
, expr2
, val1
, val2
);
2594 namespace internal
{
2596 // The helper function for {ASSERT|EXPECT}_EQ with int or enum
2598 AssertionResult
CmpHelperEQ(const char* expected_expression
,
2599 const char* actual_expression
,
2600 BiggestInt expected
,
2601 BiggestInt actual
) {
2602 if (expected
== actual
) {
2603 return AssertionSuccess();
2606 return EqFailure(expected_expression
,
2608 FormatForComparisonFailureMessage(expected
, actual
),
2609 FormatForComparisonFailureMessage(actual
, expected
),
2613 // A macro for implementing the helper functions needed to implement
2614 // ASSERT_?? and EXPECT_?? with integer or enum arguments. It is here
2615 // just to avoid copy-and-paste of similar code.
2616 #define GTEST_IMPL_CMP_HELPER_(op_name, op)\
2617 AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \
2618 BiggestInt val1, BiggestInt val2) {\
2619 if (val1 op val2) {\
2620 return AssertionSuccess();\
2622 return AssertionFailure() \
2623 << "Expected: (" << expr1 << ") " #op " (" << expr2\
2624 << "), actual: " << FormatForComparisonFailureMessage(val1, val2)\
2625 << " vs " << FormatForComparisonFailureMessage(val2, val1);\
2629 // Implements the helper function for {ASSERT|EXPECT}_NE with int or
2631 GTEST_IMPL_CMP_HELPER_(NE
, !=)
2632 // Implements the helper function for {ASSERT|EXPECT}_LE with int or
2634 GTEST_IMPL_CMP_HELPER_(LE
, <=)
2635 // Implements the helper function for {ASSERT|EXPECT}_LT with int or
2637 GTEST_IMPL_CMP_HELPER_(LT
, < )
2638 // Implements the helper function for {ASSERT|EXPECT}_GE with int or
2640 GTEST_IMPL_CMP_HELPER_(GE
, >=)
2641 // Implements the helper function for {ASSERT|EXPECT}_GT with int or
2643 GTEST_IMPL_CMP_HELPER_(GT
, > )
2645 #undef GTEST_IMPL_CMP_HELPER_
2647 // The helper function for {ASSERT|EXPECT}_STREQ.
2648 AssertionResult
CmpHelperSTREQ(const char* expected_expression
,
2649 const char* actual_expression
,
2650 const char* expected
,
2651 const char* actual
) {
2652 if (String::CStringEquals(expected
, actual
)) {
2653 return AssertionSuccess();
2656 return EqFailure(expected_expression
,
2658 PrintToString(expected
),
2659 PrintToString(actual
),
2663 // The helper function for {ASSERT|EXPECT}_STRCASEEQ.
2664 AssertionResult
CmpHelperSTRCASEEQ(const char* expected_expression
,
2665 const char* actual_expression
,
2666 const char* expected
,
2667 const char* actual
) {
2668 if (String::CaseInsensitiveCStringEquals(expected
, actual
)) {
2669 return AssertionSuccess();
2672 return EqFailure(expected_expression
,
2674 PrintToString(expected
),
2675 PrintToString(actual
),
2679 // The helper function for {ASSERT|EXPECT}_STRNE.
2680 AssertionResult
CmpHelperSTRNE(const char* s1_expression
,
2681 const char* s2_expression
,
2684 if (!String::CStringEquals(s1
, s2
)) {
2685 return AssertionSuccess();
2687 return AssertionFailure() << "Expected: (" << s1_expression
<< ") != ("
2688 << s2_expression
<< "), actual: \""
2689 << s1
<< "\" vs \"" << s2
<< "\"";
2693 // The helper function for {ASSERT|EXPECT}_STRCASENE.
2694 AssertionResult
CmpHelperSTRCASENE(const char* s1_expression
,
2695 const char* s2_expression
,
2698 if (!String::CaseInsensitiveCStringEquals(s1
, s2
)) {
2699 return AssertionSuccess();
2701 return AssertionFailure()
2702 << "Expected: (" << s1_expression
<< ") != ("
2703 << s2_expression
<< ") (ignoring case), actual: \""
2704 << s1
<< "\" vs \"" << s2
<< "\"";
2708 } // namespace internal
2712 // Helper functions for implementing IsSubString() and IsNotSubstring().
2714 // This group of overloaded functions return true iff needle is a
2715 // substring of haystack. NULL is considered a substring of itself
2718 bool IsSubstringPred(const char* needle
, const char* haystack
) {
2719 if (needle
== NULL
|| haystack
== NULL
)
2720 return needle
== haystack
;
2722 return strstr(haystack
, needle
) != NULL
;
2725 bool IsSubstringPred(const wchar_t* needle
, const wchar_t* haystack
) {
2726 if (needle
== NULL
|| haystack
== NULL
)
2727 return needle
== haystack
;
2729 return wcsstr(haystack
, needle
) != NULL
;
2732 // StringType here can be either ::std::string or ::std::wstring.
2733 template <typename StringType
>
2734 bool IsSubstringPred(const StringType
& needle
,
2735 const StringType
& haystack
) {
2736 return haystack
.find(needle
) != StringType::npos
;
2739 // This function implements either IsSubstring() or IsNotSubstring(),
2740 // depending on the value of the expected_to_be_substring parameter.
2741 // StringType here can be const char*, const wchar_t*, ::std::string,
2742 // or ::std::wstring.
2743 template <typename StringType
>
2744 AssertionResult
IsSubstringImpl(
2745 bool expected_to_be_substring
,
2746 const char* needle_expr
, const char* haystack_expr
,
2747 const StringType
& needle
, const StringType
& haystack
) {
2748 if (IsSubstringPred(needle
, haystack
) == expected_to_be_substring
)
2749 return AssertionSuccess();
2751 const bool is_wide_string
= sizeof(needle
[0]) > 1;
2752 const char* const begin_string_quote
= is_wide_string
? "L\"" : "\"";
2753 return AssertionFailure()
2754 << "Value of: " << needle_expr
<< "\n"
2755 << " Actual: " << begin_string_quote
<< needle
<< "\"\n"
2756 << "Expected: " << (expected_to_be_substring
? "" : "not ")
2757 << "a substring of " << haystack_expr
<< "\n"
2758 << "Which is: " << begin_string_quote
<< haystack
<< "\"";
2763 // IsSubstring() and IsNotSubstring() check whether needle is a
2764 // substring of haystack (NULL is considered a substring of itself
2765 // only), and return an appropriate error message when they fail.
2767 AssertionResult
IsSubstring(
2768 const char* needle_expr
, const char* haystack_expr
,
2769 const char* needle
, const char* haystack
) {
2770 return IsSubstringImpl(true, needle_expr
, haystack_expr
, needle
, haystack
);
2773 AssertionResult
IsSubstring(
2774 const char* needle_expr
, const char* haystack_expr
,
2775 const wchar_t* needle
, const wchar_t* haystack
) {
2776 return IsSubstringImpl(true, needle_expr
, haystack_expr
, needle
, haystack
);
2779 AssertionResult
IsNotSubstring(
2780 const char* needle_expr
, const char* haystack_expr
,
2781 const char* needle
, const char* haystack
) {
2782 return IsSubstringImpl(false, needle_expr
, haystack_expr
, needle
, haystack
);
2785 AssertionResult
IsNotSubstring(
2786 const char* needle_expr
, const char* haystack_expr
,
2787 const wchar_t* needle
, const wchar_t* haystack
) {
2788 return IsSubstringImpl(false, needle_expr
, haystack_expr
, needle
, haystack
);
2791 AssertionResult
IsSubstring(
2792 const char* needle_expr
, const char* haystack_expr
,
2793 const ::std::string
& needle
, const ::std::string
& haystack
) {
2794 return IsSubstringImpl(true, needle_expr
, haystack_expr
, needle
, haystack
);
2797 AssertionResult
IsNotSubstring(
2798 const char* needle_expr
, const char* haystack_expr
,
2799 const ::std::string
& needle
, const ::std::string
& haystack
) {
2800 return IsSubstringImpl(false, needle_expr
, haystack_expr
, needle
, haystack
);
2803 #if GTEST_HAS_STD_WSTRING
2804 AssertionResult
IsSubstring(
2805 const char* needle_expr
, const char* haystack_expr
,
2806 const ::std::wstring
& needle
, const ::std::wstring
& haystack
) {
2807 return IsSubstringImpl(true, needle_expr
, haystack_expr
, needle
, haystack
);
2810 AssertionResult
IsNotSubstring(
2811 const char* needle_expr
, const char* haystack_expr
,
2812 const ::std::wstring
& needle
, const ::std::wstring
& haystack
) {
2813 return IsSubstringImpl(false, needle_expr
, haystack_expr
, needle
, haystack
);
2815 #endif // GTEST_HAS_STD_WSTRING
2817 namespace internal
{
2819 #if GTEST_OS_WINDOWS
2823 // Helper function for IsHRESULT{SuccessFailure} predicates
2824 AssertionResult
HRESULTFailureHelper(const char* expr
,
2825 const char* expected
,
2826 long hr
) { // NOLINT
2827 # if GTEST_OS_WINDOWS_MOBILE
2829 // Windows CE doesn't support FormatMessage.
2830 const char error_text
[] = "";
2834 // Looks up the human-readable system message for the HRESULT code
2835 // and since we're not passing any params to FormatMessage, we don't
2836 // want inserts expanded.
2837 const DWORD kFlags
= FORMAT_MESSAGE_FROM_SYSTEM
|
2838 FORMAT_MESSAGE_IGNORE_INSERTS
;
2839 const DWORD kBufSize
= 4096;
2840 // Gets the system's human readable message string for this HRESULT.
2841 char error_text
[kBufSize
] = { '\0' };
2842 DWORD message_length
= ::FormatMessageA(kFlags
,
2843 0, // no source, we're asking system
2845 0, // no line width restrictions
2846 error_text
, // output buffer
2847 kBufSize
, // buf size
2848 NULL
); // no arguments for inserts
2849 // Trims tailing white space (FormatMessage leaves a trailing CR-LF)
2850 for (; message_length
&& IsSpace(error_text
[message_length
- 1]);
2852 error_text
[message_length
- 1] = '\0';
2855 # endif // GTEST_OS_WINDOWS_MOBILE
2857 const std::string
error_hex("0x" + String::FormatHexInt(hr
));
2858 return ::testing::AssertionFailure()
2859 << "Expected: " << expr
<< " " << expected
<< ".\n"
2860 << " Actual: " << error_hex
<< " " << error_text
<< "\n";
2865 AssertionResult
IsHRESULTSuccess(const char* expr
, long hr
) { // NOLINT
2866 if (SUCCEEDED(hr
)) {
2867 return AssertionSuccess();
2869 return HRESULTFailureHelper(expr
, "succeeds", hr
);
2872 AssertionResult
IsHRESULTFailure(const char* expr
, long hr
) { // NOLINT
2874 return AssertionSuccess();
2876 return HRESULTFailureHelper(expr
, "fails", hr
);
2879 #endif // GTEST_OS_WINDOWS
2881 // Utility functions for encoding Unicode text (wide strings) in
2884 // A Unicode code-point can have upto 21 bits, and is encoded in UTF-8
2887 // Code-point length Encoding
2888 // 0 - 7 bits 0xxxxxxx
2889 // 8 - 11 bits 110xxxxx 10xxxxxx
2890 // 12 - 16 bits 1110xxxx 10xxxxxx 10xxxxxx
2891 // 17 - 21 bits 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
2893 // The maximum code-point a one-byte UTF-8 sequence can represent.
2894 const UInt32 kMaxCodePoint1
= (static_cast<UInt32
>(1) << 7) - 1;
2896 // The maximum code-point a two-byte UTF-8 sequence can represent.
2897 const UInt32 kMaxCodePoint2
= (static_cast<UInt32
>(1) << (5 + 6)) - 1;
2899 // The maximum code-point a three-byte UTF-8 sequence can represent.
2900 const UInt32 kMaxCodePoint3
= (static_cast<UInt32
>(1) << (4 + 2*6)) - 1;
2902 // The maximum code-point a four-byte UTF-8 sequence can represent.
2903 const UInt32 kMaxCodePoint4
= (static_cast<UInt32
>(1) << (3 + 3*6)) - 1;
2905 // Chops off the n lowest bits from a bit pattern. Returns the n
2906 // lowest bits. As a side effect, the original bit pattern will be
2907 // shifted to the right by n bits.
2908 inline UInt32
ChopLowBits(UInt32
* bits
, int n
) {
2909 const UInt32 low_bits
= *bits
& ((static_cast<UInt32
>(1) << n
) - 1);
2914 // Converts a Unicode code point to a narrow string in UTF-8 encoding.
2915 // code_point parameter is of type UInt32 because wchar_t may not be
2916 // wide enough to contain a code point.
2917 // If the code_point is not a valid Unicode code point
2918 // (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted
2919 // to "(Invalid Unicode 0xXXXXXXXX)".
2920 std::string
CodePointToUtf8(UInt32 code_point
) {
2921 if (code_point
> kMaxCodePoint4
) {
2922 return "(Invalid Unicode 0x" + String::FormatHexInt(code_point
) + ")";
2925 char str
[5]; // Big enough for the largest valid code point.
2926 if (code_point
<= kMaxCodePoint1
) {
2928 str
[0] = static_cast<char>(code_point
); // 0xxxxxxx
2929 } else if (code_point
<= kMaxCodePoint2
) {
2931 str
[1] = static_cast<char>(0x80 | ChopLowBits(&code_point
, 6)); // 10xxxxxx
2932 str
[0] = static_cast<char>(0xC0 | code_point
); // 110xxxxx
2933 } else if (code_point
<= kMaxCodePoint3
) {
2935 str
[2] = static_cast<char>(0x80 | ChopLowBits(&code_point
, 6)); // 10xxxxxx
2936 str
[1] = static_cast<char>(0x80 | ChopLowBits(&code_point
, 6)); // 10xxxxxx
2937 str
[0] = static_cast<char>(0xE0 | code_point
); // 1110xxxx
2938 } else { // code_point <= kMaxCodePoint4
2940 str
[3] = static_cast<char>(0x80 | ChopLowBits(&code_point
, 6)); // 10xxxxxx
2941 str
[2] = static_cast<char>(0x80 | ChopLowBits(&code_point
, 6)); // 10xxxxxx
2942 str
[1] = static_cast<char>(0x80 | ChopLowBits(&code_point
, 6)); // 10xxxxxx
2943 str
[0] = static_cast<char>(0xF0 | code_point
); // 11110xxx
2948 // The following two functions only make sense if the the system
2949 // uses UTF-16 for wide string encoding. All supported systems
2950 // with 16 bit wchar_t (Windows, Cygwin, Symbian OS) do use UTF-16.
2952 // Determines if the arguments constitute UTF-16 surrogate pair
2953 // and thus should be combined into a single Unicode code point
2954 // using CreateCodePointFromUtf16SurrogatePair.
2955 inline bool IsUtf16SurrogatePair(wchar_t first
, wchar_t second
) {
2956 return sizeof(wchar_t) == 2 &&
2957 (first
& 0xFC00) == 0xD800 && (second
& 0xFC00) == 0xDC00;
2960 // Creates a Unicode code point from UTF16 surrogate pair.
2961 inline UInt32
CreateCodePointFromUtf16SurrogatePair(wchar_t first
,
2963 const UInt32 mask
= (1 << 10) - 1;
2964 return (sizeof(wchar_t) == 2) ?
2965 (((first
& mask
) << 10) | (second
& mask
)) + 0x10000 :
2966 // This function should not be called when the condition is
2967 // false, but we provide a sensible default in case it is.
2968 static_cast<UInt32
>(first
);
2971 // Converts a wide string to a narrow string in UTF-8 encoding.
2972 // The wide string is assumed to have the following encoding:
2973 // UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS)
2974 // UTF-32 if sizeof(wchar_t) == 4 (on Linux)
2975 // Parameter str points to a null-terminated wide string.
2976 // Parameter num_chars may additionally limit the number
2977 // of wchar_t characters processed. -1 is used when the entire string
2978 // should be processed.
2979 // If the string contains code points that are not valid Unicode code points
2980 // (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
2981 // as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
2982 // and contains invalid UTF-16 surrogate pairs, values in those pairs
2983 // will be encoded as individual Unicode characters from Basic Normal Plane.
2984 std::string
WideStringToUtf8(const wchar_t* str
, int num_chars
) {
2985 if (num_chars
== -1)
2986 num_chars
= static_cast<int>(wcslen(str
));
2988 ::std::stringstream stream
;
2989 for (int i
= 0; i
< num_chars
; ++i
) {
2990 UInt32 unicode_code_point
;
2992 if (str
[i
] == L
'\0') {
2994 } else if (i
+ 1 < num_chars
&& IsUtf16SurrogatePair(str
[i
], str
[i
+ 1])) {
2995 unicode_code_point
= CreateCodePointFromUtf16SurrogatePair(str
[i
],
2999 unicode_code_point
= static_cast<UInt32
>(str
[i
]);
3002 stream
<< CodePointToUtf8(unicode_code_point
);
3004 return StringStreamToString(&stream
);
3007 // Converts a wide C string to an std::string using the UTF-8 encoding.
3008 // NULL will be converted to "(null)".
3009 std::string
String::ShowWideCString(const wchar_t * wide_c_str
) {
3010 if (wide_c_str
== NULL
) return "(null)";
3012 return internal::WideStringToUtf8(wide_c_str
, -1);
3015 // Compares two wide C strings. Returns true iff they have the same
3018 // Unlike wcscmp(), this function can handle NULL argument(s). A NULL
3019 // C string is considered different to any non-NULL C string,
3020 // including the empty string.
3021 bool String::WideCStringEquals(const wchar_t * lhs
, const wchar_t * rhs
) {
3022 if (lhs
== NULL
) return rhs
== NULL
;
3024 if (rhs
== NULL
) return false;
3026 return wcscmp(lhs
, rhs
) == 0;
3029 // Helper function for *_STREQ on wide strings.
3030 AssertionResult
CmpHelperSTREQ(const char* expected_expression
,
3031 const char* actual_expression
,
3032 const wchar_t* expected
,
3033 const wchar_t* actual
) {
3034 if (String::WideCStringEquals(expected
, actual
)) {
3035 return AssertionSuccess();
3038 return EqFailure(expected_expression
,
3040 PrintToString(expected
),
3041 PrintToString(actual
),
3045 // Helper function for *_STRNE on wide strings.
3046 AssertionResult
CmpHelperSTRNE(const char* s1_expression
,
3047 const char* s2_expression
,
3049 const wchar_t* s2
) {
3050 if (!String::WideCStringEquals(s1
, s2
)) {
3051 return AssertionSuccess();
3054 return AssertionFailure() << "Expected: (" << s1_expression
<< ") != ("
3055 << s2_expression
<< "), actual: "
3056 << PrintToString(s1
)
3057 << " vs " << PrintToString(s2
);
3060 // Compares two C strings, ignoring case. Returns true iff they have
3061 // the same content.
3063 // Unlike strcasecmp(), this function can handle NULL argument(s). A
3064 // NULL C string is considered different to any non-NULL C string,
3065 // including the empty string.
3066 bool String::CaseInsensitiveCStringEquals(const char * lhs
, const char * rhs
) {
3071 return posix::StrCaseCmp(lhs
, rhs
) == 0;
3074 // Compares two wide C strings, ignoring case. Returns true iff they
3075 // have the same content.
3077 // Unlike wcscasecmp(), this function can handle NULL argument(s).
3078 // A NULL C string is considered different to any non-NULL wide C string,
3079 // including the empty string.
3080 // NB: The implementations on different platforms slightly differ.
3081 // On windows, this method uses _wcsicmp which compares according to LC_CTYPE
3082 // environment variable. On GNU platform this method uses wcscasecmp
3083 // which compares according to LC_CTYPE category of the current locale.
3084 // On MacOS X, it uses towlower, which also uses LC_CTYPE category of the
3086 bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs
,
3087 const wchar_t* rhs
) {
3088 if (lhs
== NULL
) return rhs
== NULL
;
3090 if (rhs
== NULL
) return false;
3092 #if GTEST_OS_WINDOWS
3093 return _wcsicmp(lhs
, rhs
) == 0;
3094 #elif GTEST_OS_LINUX && !GTEST_OS_LINUX_ANDROID
3095 return wcscasecmp(lhs
, rhs
) == 0;
3097 // Android, Mac OS X and Cygwin don't define wcscasecmp.
3098 // Other unknown OSes may not define it either.
3101 left
= towlower(*lhs
++);
3102 right
= towlower(*rhs
++);
3103 } while (left
&& left
== right
);
3104 return left
== right
;
3105 #endif // OS selector
3108 // Returns true iff str ends with the given suffix, ignoring case.
3109 // Any string is considered to end with an empty suffix.
3110 bool String::EndsWithCaseInsensitive(
3111 const std::string
& str
, const std::string
& suffix
) {
3112 const size_t str_len
= str
.length();
3113 const size_t suffix_len
= suffix
.length();
3114 return (str_len
>= suffix_len
) &&
3115 CaseInsensitiveCStringEquals(str
.c_str() + str_len
- suffix_len
,
3119 // Formats an int value as "%02d".
3120 std::string
String::FormatIntWidth2(int value
) {
3121 std::stringstream ss
;
3122 ss
<< std::setfill('0') << std::setw(2) << value
;
3126 // Formats an int value as "%X".
3127 std::string
String::FormatHexInt(int value
) {
3128 std::stringstream ss
;
3129 ss
<< std::hex
<< std::uppercase
<< value
;
3133 // Formats a byte as "%02X".
3134 std::string
String::FormatByte(unsigned char value
) {
3135 std::stringstream ss
;
3136 ss
<< std::setfill('0') << std::setw(2) << std::hex
<< std::uppercase
3137 << static_cast<unsigned int>(value
);
3141 // Converts the buffer in a stringstream to an std::string, converting NUL
3142 // bytes to "\\0" along the way.
3143 std::string
StringStreamToString(::std::stringstream
* ss
) {
3144 const ::std::string
& str
= ss
->str();
3145 const char* const start
= str
.c_str();
3146 const char* const end
= start
+ str
.length();
3149 result
.reserve(2 * (end
- start
));
3150 for (const char* ch
= start
; ch
!= end
; ++ch
) {
3152 result
+= "\\0"; // Replaces NUL with "\\0";
3161 // Appends the user-supplied message to the Google-Test-generated message.
3162 std::string
AppendUserMessage(const std::string
& gtest_msg
,
3163 const Message
& user_msg
) {
3164 // Appends the user message if it's non-empty.
3165 const std::string user_msg_string
= user_msg
.GetString();
3166 if (user_msg_string
.empty()) {
3170 return gtest_msg
+ "\n" + user_msg_string
;
3173 } // namespace internal
3177 // Creates an empty TestResult.
3178 TestResult::TestResult()
3179 : death_test_count_(0),
3184 TestResult::~TestResult() {
3187 // Returns the i-th test part result among all the results. i can
3188 // range from 0 to total_part_count() - 1. If i is not in that range,
3189 // aborts the program.
3190 const TestPartResult
& TestResult::GetTestPartResult(int i
) const {
3191 if (i
< 0 || i
>= total_part_count())
3192 internal::posix::Abort();
3193 return test_part_results_
.at(i
);
3196 // Returns the i-th test property. i can range from 0 to
3197 // test_property_count() - 1. If i is not in that range, aborts the
3199 const TestProperty
& TestResult::GetTestProperty(int i
) const {
3200 if (i
< 0 || i
>= test_property_count())
3201 internal::posix::Abort();
3202 return test_properties_
.at(i
);
3205 // Clears the test part results.
3206 void TestResult::ClearTestPartResults() {
3207 test_part_results_
.clear();
3210 // Adds a test part result to the list.
3211 void TestResult::AddTestPartResult(const TestPartResult
& test_part_result
) {
3212 test_part_results_
.push_back(test_part_result
);
3215 // Adds a test property to the list. If a property with the same key as the
3216 // supplied property is already represented, the value of this test_property
3217 // replaces the old value for that key.
3218 void TestResult::RecordProperty(const std::string
& xml_element
,
3219 const TestProperty
& test_property
) {
3220 if (!ValidateTestProperty(xml_element
, test_property
)) {
3223 internal::MutexLock
lock(&test_properites_mutex_
);
3224 const std::vector
<TestProperty
>::iterator property_with_matching_key
=
3225 std::find_if(test_properties_
.begin(), test_properties_
.end(),
3226 internal::TestPropertyKeyIs(test_property
.key()));
3227 if (property_with_matching_key
== test_properties_
.end()) {
3228 test_properties_
.push_back(test_property
);
3231 property_with_matching_key
->SetValue(test_property
.value());
3234 // The list of reserved attributes used in the <testsuites> element of XML
3236 static const char* const kReservedTestSuitesAttributes
[] = {
3247 // The list of reserved attributes used in the <testsuite> element of XML
3249 static const char* const kReservedTestSuiteAttributes
[] = {
3258 // The list of reserved attributes used in the <testcase> element of XML output.
3259 static const char* const kReservedTestCaseAttributes
[] = {
3268 template <int kSize
>
3269 std::vector
<std::string
> ArrayAsVector(const char* const (&array
)[kSize
]) {
3270 return std::vector
<std::string
>(array
, array
+ kSize
);
3273 static std::vector
<std::string
> GetReservedAttributesForElement(
3274 const std::string
& xml_element
) {
3275 if (xml_element
== "testsuites") {
3276 return ArrayAsVector(kReservedTestSuitesAttributes
);
3277 } else if (xml_element
== "testsuite") {
3278 return ArrayAsVector(kReservedTestSuiteAttributes
);
3279 } else if (xml_element
== "testcase") {
3280 return ArrayAsVector(kReservedTestCaseAttributes
);
3282 GTEST_CHECK_(false) << "Unrecognized xml_element provided: " << xml_element
;
3284 // This code is unreachable but some compilers may not realizes that.
3285 return std::vector
<std::string
>();
3288 static std::string
FormatWordList(const std::vector
<std::string
>& words
) {
3290 for (size_t i
= 0; i
< words
.size(); ++i
) {
3291 if (i
> 0 && words
.size() > 2) {
3294 if (i
== words
.size() - 1) {
3295 word_list
<< "and ";
3297 word_list
<< "'" << words
[i
] << "'";
3299 return word_list
.GetString();
3302 bool ValidateTestPropertyName(const std::string
& property_name
,
3303 const std::vector
<std::string
>& reserved_names
) {
3304 if (std::find(reserved_names
.begin(), reserved_names
.end(), property_name
) !=
3305 reserved_names
.end()) {
3306 ADD_FAILURE() << "Reserved key used in RecordProperty(): " << property_name
3307 << " (" << FormatWordList(reserved_names
)
3308 << " are reserved by " << GTEST_NAME_
<< ")";
3314 // Adds a failure if the key is a reserved attribute of the element named
3315 // xml_element. Returns true if the property is valid.
3316 bool TestResult::ValidateTestProperty(const std::string
& xml_element
,
3317 const TestProperty
& test_property
) {
3318 return ValidateTestPropertyName(test_property
.key(),
3319 GetReservedAttributesForElement(xml_element
));
3322 // Clears the object.
3323 void TestResult::Clear() {
3324 test_part_results_
.clear();
3325 test_properties_
.clear();
3326 death_test_count_
= 0;
3330 // Returns true iff the test failed.
3331 bool TestResult::Failed() const {
3332 for (int i
= 0; i
< total_part_count(); ++i
) {
3333 if (GetTestPartResult(i
).failed())
3339 // Returns true iff the test part fatally failed.
3340 static bool TestPartFatallyFailed(const TestPartResult
& result
) {
3341 return result
.fatally_failed();
3344 // Returns true iff the test fatally failed.
3345 bool TestResult::HasFatalFailure() const {
3346 return CountIf(test_part_results_
, TestPartFatallyFailed
) > 0;
3349 // Returns true iff the test part non-fatally failed.
3350 static bool TestPartNonfatallyFailed(const TestPartResult
& result
) {
3351 return result
.nonfatally_failed();
3354 // Returns true iff the test has a non-fatal failure.
3355 bool TestResult::HasNonfatalFailure() const {
3356 return CountIf(test_part_results_
, TestPartNonfatallyFailed
) > 0;
3359 // Gets the number of all test parts. This is the sum of the number
3360 // of successful test parts and the number of failed test parts.
3361 int TestResult::total_part_count() const {
3362 return static_cast<int>(test_part_results_
.size());
3365 // Returns the number of the test properties.
3366 int TestResult::test_property_count() const {
3367 return static_cast<int>(test_properties_
.size());
3372 // Creates a Test object.
3374 // The c'tor saves the values of all Google Test flags.
3376 : gtest_flag_saver_(new internal::GTestFlagSaver
) {
3379 // The d'tor restores the values of all Google Test flags.
3381 delete gtest_flag_saver_
;
3384 // Sets up the test fixture.
3386 // A sub-class may override this.
3387 void Test::SetUp() {
3390 // Tears down the test fixture.
3392 // A sub-class may override this.
3393 void Test::TearDown() {
3396 // Allows user supplied key value pairs to be recorded for later output.
3397 void Test::RecordProperty(const std::string
& key
, const std::string
& value
) {
3398 UnitTest::GetInstance()->RecordProperty(key
, value
);
3401 // Allows user supplied key value pairs to be recorded for later output.
3402 void Test::RecordProperty(const std::string
& key
, int value
) {
3403 Message value_message
;
3404 value_message
<< value
;
3405 RecordProperty(key
, value_message
.GetString().c_str());
3408 namespace internal
{
3410 void ReportFailureInUnknownLocation(TestPartResult::Type result_type
,
3411 const std::string
& message
) {
3412 // This function is a friend of UnitTest and as such has access to
3413 // AddTestPartResult.
3414 UnitTest::GetInstance()->AddTestPartResult(
3416 NULL
, // No info about the source file where the exception occurred.
3417 -1, // We have no info on which line caused the exception.
3419 ""); // No stack trace, either.
3422 } // namespace internal
3424 // Google Test requires all tests in the same test case to use the same test
3425 // fixture class. This function checks if the current test has the
3426 // same fixture class as the first test in the current test case. If
3427 // yes, it returns true; otherwise it generates a Google Test failure and
3429 bool Test::HasSameFixtureClass() {
3430 internal::UnitTestImpl
* const impl
= internal::GetUnitTestImpl();
3431 const TestCase
* const test_case
= impl
->current_test_case();
3433 // Info about the first test in the current test case.
3434 const TestInfo
* const first_test_info
= test_case
->test_info_list()[0];
3435 const internal::TypeId first_fixture_id
= first_test_info
->fixture_class_id_
;
3436 const char* const first_test_name
= first_test_info
->name();
3438 // Info about the current test.
3439 const TestInfo
* const this_test_info
= impl
->current_test_info();
3440 const internal::TypeId this_fixture_id
= this_test_info
->fixture_class_id_
;
3441 const char* const this_test_name
= this_test_info
->name();
3443 if (this_fixture_id
!= first_fixture_id
) {
3444 // Is the first test defined using TEST?
3445 const bool first_is_TEST
= first_fixture_id
== internal::GetTestTypeId();
3446 // Is this test defined using TEST?
3447 const bool this_is_TEST
= this_fixture_id
== internal::GetTestTypeId();
3449 if (first_is_TEST
|| this_is_TEST
) {
3450 // The user mixed TEST and TEST_F in this test case - we'll tell
3451 // him/her how to fix it.
3453 // Gets the name of the TEST and the name of the TEST_F. Note
3454 // that first_is_TEST and this_is_TEST cannot both be true, as
3455 // the fixture IDs are different for the two tests.
3456 const char* const TEST_name
=
3457 first_is_TEST
? first_test_name
: this_test_name
;
3458 const char* const TEST_F_name
=
3459 first_is_TEST
? this_test_name
: first_test_name
;
3462 << "All tests in the same test case must use the same test fixture\n"
3463 << "class, so mixing TEST_F and TEST in the same test case is\n"
3464 << "illegal. In test case " << this_test_info
->test_case_name()
3466 << "test " << TEST_F_name
<< " is defined using TEST_F but\n"
3467 << "test " << TEST_name
<< " is defined using TEST. You probably\n"
3468 << "want to change the TEST to TEST_F or move it to another test\n"
3471 // The user defined two fixture classes with the same name in
3472 // two namespaces - we'll tell him/her how to fix it.
3474 << "All tests in the same test case must use the same test fixture\n"
3475 << "class. However, in test case "
3476 << this_test_info
->test_case_name() << ",\n"
3477 << "you defined test " << first_test_name
3478 << " and test " << this_test_name
<< "\n"
3479 << "using two different test fixture classes. This can happen if\n"
3480 << "the two classes are from different namespaces or translation\n"
3481 << "units and have the same name. You should probably rename one\n"
3482 << "of the classes to put the tests into different test cases.";
3492 // Adds an "exception thrown" fatal failure to the current test. This
3493 // function returns its result via an output parameter pointer because VC++
3494 // prohibits creation of objects with destructors on stack in functions
3495 // using __try (see error C2712).
3496 static std::string
* FormatSehExceptionMessage(DWORD exception_code
,
3497 const char* location
) {
3499 message
<< "SEH exception with code 0x" << std::setbase(16) <<
3500 exception_code
<< std::setbase(10) << " thrown in " << location
<< ".";
3502 return new std::string(message
.GetString());
3505 #endif // GTEST_HAS_SEH
3507 namespace internal
{
3509 #if GTEST_HAS_EXCEPTIONS
3511 // Adds an "exception thrown" fatal failure to the current test.
3512 static std::string
FormatCxxExceptionMessage(const char* description
,
3513 const char* location
) {
3515 if (description
!= NULL
) {
3516 message
<< "C++ exception with description \"" << description
<< "\"";
3518 message
<< "Unknown C++ exception";
3520 message
<< " thrown in " << location
<< ".";
3522 return message
.GetString();
3525 static std::string
PrintTestPartResultToString(
3526 const TestPartResult
& test_part_result
);
3528 GoogleTestFailureException::GoogleTestFailureException(
3529 const TestPartResult
& failure
)
3530 : ::std::runtime_error(PrintTestPartResultToString(failure
).c_str()) {}
3532 #endif // GTEST_HAS_EXCEPTIONS
3534 // We put these helper functions in the internal namespace as IBM's xlC
3535 // compiler rejects the code if they were declared static.
3537 // Runs the given method and handles SEH exceptions it throws, when
3538 // SEH is supported; returns the 0-value for type Result in case of an
3539 // SEH exception. (Microsoft compilers cannot handle SEH and C++
3540 // exceptions in the same function. Therefore, we provide a separate
3541 // wrapper function for handling SEH exceptions.)
3542 template <class T
, typename Result
>
3543 Result
HandleSehExceptionsInMethodIfSupported(
3544 T
* object
, Result (T::*method
)(), const char* location
) {
3547 return (object
->*method
)();
3548 } __except (internal::UnitTestOptions::GTestShouldProcessSEH( // NOLINT
3549 GetExceptionCode())) {
3550 // We create the exception message on the heap because VC++ prohibits
3551 // creation of objects with destructors on stack in functions using __try
3552 // (see error C2712).
3553 std::string
* exception_message
= FormatSehExceptionMessage(
3554 GetExceptionCode(), location
);
3555 internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure
,
3556 *exception_message
);
3557 delete exception_message
;
3558 return static_cast<Result
>(0);
3562 return (object
->*method
)();
3563 #endif // GTEST_HAS_SEH
3566 // Runs the given method and catches and reports C++ and/or SEH-style
3567 // exceptions, if they are supported; returns the 0-value for type
3568 // Result in case of an SEH exception.
3569 template <class T
, typename Result
>
3570 Result
HandleExceptionsInMethodIfSupported(
3571 T
* object
, Result (T::*method
)(), const char* location
) {
3572 // NOTE: The user code can affect the way in which Google Test handles
3573 // exceptions by setting GTEST_FLAG(catch_exceptions), but only before
3574 // RUN_ALL_TESTS() starts. It is technically possible to check the flag
3575 // after the exception is caught and either report or re-throw the
3576 // exception based on the flag's value:
3579 // // Perform the test method.
3581 // if (GTEST_FLAG(catch_exceptions))
3582 // // Report the exception as failure.
3584 // throw; // Re-throws the original exception.
3587 // However, the purpose of this flag is to allow the program to drop into
3588 // the debugger when the exception is thrown. On most platforms, once the
3589 // control enters the catch block, the exception origin information is
3590 // lost and the debugger will stop the program at the point of the
3591 // re-throw in this function -- instead of at the point of the original
3592 // throw statement in the code under test. For this reason, we perform
3593 // the check early, sacrificing the ability to affect Google Test's
3594 // exception handling in the method where the exception is thrown.
3595 if (internal::GetUnitTestImpl()->catch_exceptions()) {
3596 #if GTEST_HAS_EXCEPTIONS
3598 return HandleSehExceptionsInMethodIfSupported(object
, method
, location
);
3599 } catch (const internal::GoogleTestFailureException
&) { // NOLINT
3600 // This exception type can only be thrown by a failed Google
3601 // Test assertion with the intention of letting another testing
3602 // framework catch it. Therefore we just re-throw it.
3604 } catch (const std::exception
& e
) { // NOLINT
3605 internal::ReportFailureInUnknownLocation(
3606 TestPartResult::kFatalFailure
,
3607 FormatCxxExceptionMessage(e
.what(), location
));
3608 } catch (...) { // NOLINT
3609 internal::ReportFailureInUnknownLocation(
3610 TestPartResult::kFatalFailure
,
3611 FormatCxxExceptionMessage(NULL
, location
));
3613 return static_cast<Result
>(0);
3615 return HandleSehExceptionsInMethodIfSupported(object
, method
, location
);
3616 #endif // GTEST_HAS_EXCEPTIONS
3618 return (object
->*method
)();
3622 } // namespace internal
3624 // Runs the test and updates the test result.
3626 if (!HasSameFixtureClass()) return;
3628 internal::UnitTestImpl
* const impl
= internal::GetUnitTestImpl();
3629 impl
->os_stack_trace_getter()->UponLeavingGTest();
3630 internal::HandleExceptionsInMethodIfSupported(this, &Test::SetUp
, "SetUp()");
3631 // We will run the test only if SetUp() was successful.
3632 if (!HasFatalFailure()) {
3633 impl
->os_stack_trace_getter()->UponLeavingGTest();
3634 internal::HandleExceptionsInMethodIfSupported(
3635 this, &Test::TestBody
, "the test body");
3638 // However, we want to clean up as much as possible. Hence we will
3639 // always call TearDown(), even if SetUp() or the test body has
3641 impl
->os_stack_trace_getter()->UponLeavingGTest();
3642 internal::HandleExceptionsInMethodIfSupported(
3643 this, &Test::TearDown
, "TearDown()");
3646 // Returns true iff the current test has a fatal failure.
3647 bool Test::HasFatalFailure() {
3648 return internal::GetUnitTestImpl()->current_test_result()->HasFatalFailure();
3651 // Returns true iff the current test has a non-fatal failure.
3652 bool Test::HasNonfatalFailure() {
3653 return internal::GetUnitTestImpl()->current_test_result()->
3654 HasNonfatalFailure();
3659 // Constructs a TestInfo object. It assumes ownership of the test factory
3661 TestInfo::TestInfo(const std::string
& a_test_case_name
,
3662 const std::string
& a_name
,
3663 const char* a_type_param
,
3664 const char* a_value_param
,
3665 internal::TypeId fixture_class_id
,
3666 internal::TestFactoryBase
* factory
)
3667 : test_case_name_(a_test_case_name
),
3669 type_param_(a_type_param
? new std::string(a_type_param
) : NULL
),
3670 value_param_(a_value_param
? new std::string(a_value_param
) : NULL
),
3671 fixture_class_id_(fixture_class_id
),
3673 is_disabled_(false),
3674 matches_filter_(false),
3678 // Destructs a TestInfo object.
3679 TestInfo::~TestInfo() { delete factory_
; }
3681 namespace internal
{
3683 // Creates a new TestInfo object and registers it with Google Test;
3684 // returns the created object.
3688 // test_case_name: name of the test case
3689 // name: name of the test
3690 // type_param: the name of the test's type parameter, or NULL if
3691 // this is not a typed or a type-parameterized test.
3692 // value_param: text representation of the test's value parameter,
3693 // or NULL if this is not a value-parameterized test.
3694 // fixture_class_id: ID of the test fixture class
3695 // set_up_tc: pointer to the function that sets up the test case
3696 // tear_down_tc: pointer to the function that tears down the test case
3697 // factory: pointer to the factory that creates a test object.
3698 // The newly created TestInfo instance will assume
3699 // ownership of the factory object.
3700 TestInfo
* MakeAndRegisterTestInfo(
3701 const char* test_case_name
,
3703 const char* type_param
,
3704 const char* value_param
,
3705 TypeId fixture_class_id
,
3706 SetUpTestCaseFunc set_up_tc
,
3707 TearDownTestCaseFunc tear_down_tc
,
3708 TestFactoryBase
* factory
) {
3709 TestInfo
* const test_info
=
3710 new TestInfo(test_case_name
, name
, type_param
, value_param
,
3711 fixture_class_id
, factory
);
3712 GetUnitTestImpl()->AddTestInfo(set_up_tc
, tear_down_tc
, test_info
);
3716 #if GTEST_HAS_PARAM_TEST
3717 void ReportInvalidTestCaseType(const char* test_case_name
,
3718 const char* file
, int line
) {
3721 << "Attempted redefinition of test case " << test_case_name
<< ".\n"
3722 << "All tests in the same test case must use the same test fixture\n"
3723 << "class. However, in test case " << test_case_name
<< ", you tried\n"
3724 << "to define a test using a fixture class different from the one\n"
3725 << "used earlier. This can happen if the two fixture classes are\n"
3726 << "from different namespaces and have the same name. You should\n"
3727 << "probably rename one of the classes to put the tests into different\n"
3730 fprintf(stderr
, "%s %s", FormatFileLocation(file
, line
).c_str(),
3731 errors
.GetString().c_str());
3733 #endif // GTEST_HAS_PARAM_TEST
3735 } // namespace internal
3739 // A predicate that checks the test name of a TestInfo against a known
3742 // This is used for implementation of the TestCase class only. We put
3743 // it in the anonymous namespace to prevent polluting the outer
3746 // TestNameIs is copyable.
3751 // TestNameIs has NO default constructor.
3752 explicit TestNameIs(const char* name
)
3755 // Returns true iff the test name of test_info matches name_.
3756 bool operator()(const TestInfo
* test_info
) const {
3757 return test_info
&& test_info
->name() == name_
;
3766 namespace internal
{
3768 // This method expands all parameterized tests registered with macros TEST_P
3769 // and INSTANTIATE_TEST_CASE_P into regular tests and registers those.
3770 // This will be done just once during the program runtime.
3771 void UnitTestImpl::RegisterParameterizedTests() {
3772 #if GTEST_HAS_PARAM_TEST
3773 if (!parameterized_tests_registered_
) {
3774 parameterized_test_registry_
.RegisterTests();
3775 parameterized_tests_registered_
= true;
3780 } // namespace internal
3782 // Creates the test object, runs it, records its result, and then
3784 void TestInfo::Run() {
3785 if (!should_run_
) return;
3787 // Tells UnitTest where to store test result.
3788 internal::UnitTestImpl
* const impl
= internal::GetUnitTestImpl();
3789 impl
->set_current_test_info(this);
3791 TestEventListener
* repeater
= UnitTest::GetInstance()->listeners().repeater();
3793 // Notifies the unit test event listeners that a test is about to start.
3794 repeater
->OnTestStart(*this);
3796 const TimeInMillis start
= internal::GetTimeInMillis();
3798 impl
->os_stack_trace_getter()->UponLeavingGTest();
3800 // Creates the test object.
3801 Test
* const test
= internal::HandleExceptionsInMethodIfSupported(
3802 factory_
, &internal::TestFactoryBase::CreateTest
,
3803 "the test fixture's constructor");
3805 // Runs the test only if the test object was created and its
3806 // constructor didn't generate a fatal failure.
3807 if ((test
!= NULL
) && !Test::HasFatalFailure()) {
3808 // This doesn't throw as all user code that can throw are wrapped into
3809 // exception handling code.
3813 // Deletes the test object.
3814 impl
->os_stack_trace_getter()->UponLeavingGTest();
3815 internal::HandleExceptionsInMethodIfSupported(
3816 test
, &Test::DeleteSelf_
, "the test fixture's destructor");
3818 result_
.set_elapsed_time(internal::GetTimeInMillis() - start
);
3820 // Notifies the unit test event listener that a test has just finished.
3821 repeater
->OnTestEnd(*this);
3823 // Tells UnitTest to stop associating assertion results to this
3825 impl
->set_current_test_info(NULL
);
3830 // Gets the number of successful tests in this test case.
3831 int TestCase::successful_test_count() const {
3832 return CountIf(test_info_list_
, TestPassed
);
3835 // Gets the number of failed tests in this test case.
3836 int TestCase::failed_test_count() const {
3837 return CountIf(test_info_list_
, TestFailed
);
3840 // Gets the number of disabled tests that will be reported in the XML report.
3841 int TestCase::reportable_disabled_test_count() const {
3842 return CountIf(test_info_list_
, TestReportableDisabled
);
3845 // Gets the number of disabled tests in this test case.
3846 int TestCase::disabled_test_count() const {
3847 return CountIf(test_info_list_
, TestDisabled
);
3850 // Gets the number of tests to be printed in the XML report.
3851 int TestCase::reportable_test_count() const {
3852 return CountIf(test_info_list_
, TestReportable
);
3855 // Get the number of tests in this test case that should run.
3856 int TestCase::test_to_run_count() const {
3857 return CountIf(test_info_list_
, ShouldRunTest
);
3860 // Gets the number of all tests.
3861 int TestCase::total_test_count() const {
3862 return static_cast<int>(test_info_list_
.size());
3865 // Creates a TestCase with the given name.
3869 // name: name of the test case
3870 // a_type_param: the name of the test case's type parameter, or NULL if
3871 // this is not a typed or a type-parameterized test case.
3872 // set_up_tc: pointer to the function that sets up the test case
3873 // tear_down_tc: pointer to the function that tears down the test case
3874 TestCase::TestCase(const char* a_name
, const char* a_type_param
,
3875 Test::SetUpTestCaseFunc set_up_tc
,
3876 Test::TearDownTestCaseFunc tear_down_tc
)
3878 type_param_(a_type_param
? new std::string(a_type_param
) : NULL
),
3879 set_up_tc_(set_up_tc
),
3880 tear_down_tc_(tear_down_tc
),
3885 // Destructor of TestCase.
3886 TestCase::~TestCase() {
3887 // Deletes every Test in the collection.
3888 ForEach(test_info_list_
, internal::Delete
<TestInfo
>);
3891 // Returns the i-th test among all the tests. i can range from 0 to
3892 // total_test_count() - 1. If i is not in that range, returns NULL.
3893 const TestInfo
* TestCase::GetTestInfo(int i
) const {
3894 const int index
= GetElementOr(test_indices_
, i
, -1);
3895 return index
< 0 ? NULL
: test_info_list_
[index
];
3898 // Returns the i-th test among all the tests. i can range from 0 to
3899 // total_test_count() - 1. If i is not in that range, returns NULL.
3900 TestInfo
* TestCase::GetMutableTestInfo(int i
) {
3901 const int index
= GetElementOr(test_indices_
, i
, -1);
3902 return index
< 0 ? NULL
: test_info_list_
[index
];
3905 // Adds a test to this test case. Will delete the test upon
3906 // destruction of the TestCase object.
3907 void TestCase::AddTestInfo(TestInfo
* test_info
) {
3908 test_info_list_
.push_back(test_info
);
3909 test_indices_
.push_back(static_cast<int>(test_indices_
.size()));
3912 // Runs every test in this TestCase.
3913 void TestCase::Run() {
3914 if (!should_run_
) return;
3916 internal::UnitTestImpl
* const impl
= internal::GetUnitTestImpl();
3917 impl
->set_current_test_case(this);
3919 TestEventListener
* repeater
= UnitTest::GetInstance()->listeners().repeater();
3921 repeater
->OnTestCaseStart(*this);
3922 impl
->os_stack_trace_getter()->UponLeavingGTest();
3923 internal::HandleExceptionsInMethodIfSupported(
3924 this, &TestCase::RunSetUpTestCase
, "SetUpTestCase()");
3926 const internal::TimeInMillis start
= internal::GetTimeInMillis();
3927 for (int i
= 0; i
< total_test_count(); i
++) {
3928 GetMutableTestInfo(i
)->Run();
3930 elapsed_time_
= internal::GetTimeInMillis() - start
;
3932 impl
->os_stack_trace_getter()->UponLeavingGTest();
3933 internal::HandleExceptionsInMethodIfSupported(
3934 this, &TestCase::RunTearDownTestCase
, "TearDownTestCase()");
3936 repeater
->OnTestCaseEnd(*this);
3937 impl
->set_current_test_case(NULL
);
3940 // Clears the results of all tests in this test case.
3941 void TestCase::ClearResult() {
3942 ad_hoc_test_result_
.Clear();
3943 ForEach(test_info_list_
, TestInfo::ClearTestResult
);
3946 // Shuffles the tests in this test case.
3947 void TestCase::ShuffleTests(internal::Random
* random
) {
3948 Shuffle(random
, &test_indices_
);
3951 // Restores the test order to before the first shuffle.
3952 void TestCase::UnshuffleTests() {
3953 for (size_t i
= 0; i
< test_indices_
.size(); i
++) {
3954 test_indices_
[i
] = static_cast<int>(i
);
3958 // Formats a countable noun. Depending on its quantity, either the
3959 // singular form or the plural form is used. e.g.
3961 // FormatCountableNoun(1, "formula", "formuli") returns "1 formula".
3962 // FormatCountableNoun(5, "book", "books") returns "5 books".
3963 static std::string
FormatCountableNoun(int count
,
3964 const char * singular_form
,
3965 const char * plural_form
) {
3966 return internal::StreamableToString(count
) + " " +
3967 (count
== 1 ? singular_form
: plural_form
);
3970 // Formats the count of tests.
3971 static std::string
FormatTestCount(int test_count
) {
3972 return FormatCountableNoun(test_count
, "test", "tests");
3975 // Formats the count of test cases.
3976 static std::string
FormatTestCaseCount(int test_case_count
) {
3977 return FormatCountableNoun(test_case_count
, "test case", "test cases");
3980 // Converts a TestPartResult::Type enum to human-friendly string
3981 // representation. Both kNonFatalFailure and kFatalFailure are translated
3982 // to "Failure", as the user usually doesn't care about the difference
3983 // between the two when viewing the test result.
3984 static const char * TestPartResultTypeToString(TestPartResult::Type type
) {
3986 case TestPartResult::kSuccess
:
3989 case TestPartResult::kNonFatalFailure
:
3990 case TestPartResult::kFatalFailure
:
3997 return "Unknown result type";
4001 namespace internal
{
4003 // Prints a TestPartResult to an std::string.
4004 static std::string
PrintTestPartResultToString(
4005 const TestPartResult
& test_part_result
) {
4007 << internal::FormatFileLocation(test_part_result
.file_name(),
4008 test_part_result
.line_number())
4009 << " " << TestPartResultTypeToString(test_part_result
.type())
4010 << test_part_result
.message()).GetString();
4013 // Prints a TestPartResult.
4014 static void PrintTestPartResult(const TestPartResult
& test_part_result
) {
4015 const std::string
& result
=
4016 PrintTestPartResultToString(test_part_result
);
4017 printf("%s\n", result
.c_str());
4019 // If the test program runs in Visual Studio or a debugger, the
4020 // following statements add the test part result message to the Output
4021 // window such that the user can double-click on it to jump to the
4022 // corresponding source code location; otherwise they do nothing.
4023 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
4024 // We don't call OutputDebugString*() on Windows Mobile, as printing
4025 // to stdout is done by OutputDebugString() there already - we don't
4026 // want the same message printed twice.
4027 ::OutputDebugStringA(result
.c_str());
4028 ::OutputDebugStringA("\n");
4032 // class PrettyUnitTestResultPrinter
4041 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
4043 // Returns the character attribute for the given color.
4044 WORD
GetColorAttribute(GTestColor color
) {
4046 case COLOR_RED
: return FOREGROUND_RED
;
4047 case COLOR_GREEN
: return FOREGROUND_GREEN
;
4048 case COLOR_YELLOW
: return FOREGROUND_RED
| FOREGROUND_GREEN
;
4055 // Returns the ANSI color code for the given color. COLOR_DEFAULT is
4056 // an invalid input.
4057 const char* GetAnsiColorCode(GTestColor color
) {
4059 case COLOR_RED
: return "1";
4060 case COLOR_GREEN
: return "2";
4061 case COLOR_YELLOW
: return "3";
4062 default: return NULL
;
4066 #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
4068 // Returns true iff Google Test should use colors in the output.
4069 bool ShouldUseColor(bool stdout_is_tty
) {
4070 const char* const gtest_color
= GTEST_FLAG(color
).c_str();
4072 if (String::CaseInsensitiveCStringEquals(gtest_color
, "auto")) {
4073 #if GTEST_OS_WINDOWS
4074 // On Windows the TERM variable is usually not set, but the
4075 // console there does support colors.
4076 return stdout_is_tty
;
4078 // On non-Windows platforms, we rely on the TERM variable.
4079 const char* const term
= posix::GetEnv("TERM");
4080 const bool term_supports_color
=
4081 String::CStringEquals(term
, "xterm") ||
4082 String::CStringEquals(term
, "xterm-color") ||
4083 String::CStringEquals(term
, "xterm-256color") ||
4084 String::CStringEquals(term
, "screen") ||
4085 String::CStringEquals(term
, "screen-256color") ||
4086 String::CStringEquals(term
, "linux") ||
4087 String::CStringEquals(term
, "cygwin");
4088 return stdout_is_tty
&& term_supports_color
;
4089 #endif // GTEST_OS_WINDOWS
4092 return String::CaseInsensitiveCStringEquals(gtest_color
, "yes") ||
4093 String::CaseInsensitiveCStringEquals(gtest_color
, "true") ||
4094 String::CaseInsensitiveCStringEquals(gtest_color
, "t") ||
4095 String::CStringEquals(gtest_color
, "1");
4096 // We take "yes", "true", "t", and "1" as meaning "yes". If the
4097 // value is neither one of these nor "auto", we treat it as "no" to
4101 // Helpers for printing colored strings to stdout. Note that on Windows, we
4102 // cannot simply emit special characters and have the terminal change colors.
4103 // This routine must actually emit the characters rather than return a string
4104 // that would be colored when printed, as can be done on Linux.
4105 void ColoredPrintf(GTestColor color
, const char* fmt
, ...) {
4107 va_start(args
, fmt
);
4109 #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS || GTEST_OS_IOS
4110 const bool use_color
= false;
4112 static const bool in_color_mode
=
4113 ShouldUseColor(posix::IsATTY(posix::FileNo(stdout
)) != 0);
4114 const bool use_color
= in_color_mode
&& (color
!= COLOR_DEFAULT
);
4115 #endif // GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS
4116 // The '!= 0' comparison is necessary to satisfy MSVC 7.1.
4124 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
4125 const HANDLE stdout_handle
= GetStdHandle(STD_OUTPUT_HANDLE
);
4127 // Gets the current text color.
4128 CONSOLE_SCREEN_BUFFER_INFO buffer_info
;
4129 GetConsoleScreenBufferInfo(stdout_handle
, &buffer_info
);
4130 const WORD old_color_attrs
= buffer_info
.wAttributes
;
4132 // We need to flush the stream buffers into the console before each
4133 // SetConsoleTextAttribute call lest it affect the text that is already
4134 // printed but has not yet reached the console.
4136 SetConsoleTextAttribute(stdout_handle
,
4137 GetColorAttribute(color
) | FOREGROUND_INTENSITY
);
4141 // Restores the text color.
4142 SetConsoleTextAttribute(stdout_handle
, old_color_attrs
);
4144 printf("\033[0;3%sm", GetAnsiColorCode(color
));
4146 printf("\033[m"); // Resets the terminal to default.
4147 #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
4151 // Text printed in Google Test's text output and --gunit_list_tests
4152 // output to label the type parameter and value parameter for a test.
4153 static const char kTypeParamLabel
[] = "TypeParam";
4154 static const char kValueParamLabel
[] = "GetParam()";
4156 void PrintFullTestCommentIfPresent(const TestInfo
& test_info
) {
4157 const char* const type_param
= test_info
.type_param();
4158 const char* const value_param
= test_info
.value_param();
4160 if (type_param
!= NULL
|| value_param
!= NULL
) {
4162 if (type_param
!= NULL
) {
4163 printf("%s = %s", kTypeParamLabel
, type_param
);
4164 if (value_param
!= NULL
)
4167 if (value_param
!= NULL
) {
4168 printf("%s = %s", kValueParamLabel
, value_param
);
4173 // This class implements the TestEventListener interface.
4175 // Class PrettyUnitTestResultPrinter is copyable.
4176 class PrettyUnitTestResultPrinter
: public TestEventListener
{
4178 PrettyUnitTestResultPrinter() {}
4179 static void PrintTestName(const char * test_case
, const char * test
) {
4180 printf("%s.%s", test_case
, test
);
4183 // The following methods override what's in the TestEventListener class.
4184 virtual void OnTestProgramStart(const UnitTest
& /*unit_test*/) {}
4185 virtual void OnTestIterationStart(const UnitTest
& unit_test
, int iteration
);
4186 virtual void OnEnvironmentsSetUpStart(const UnitTest
& unit_test
);
4187 virtual void OnEnvironmentsSetUpEnd(const UnitTest
& /*unit_test*/) {}
4188 virtual void OnTestCaseStart(const TestCase
& test_case
);
4189 virtual void OnTestStart(const TestInfo
& test_info
);
4190 virtual void OnTestPartResult(const TestPartResult
& result
);
4191 virtual void OnTestEnd(const TestInfo
& test_info
);
4192 virtual void OnTestCaseEnd(const TestCase
& test_case
);
4193 virtual void OnEnvironmentsTearDownStart(const UnitTest
& unit_test
);
4194 virtual void OnEnvironmentsTearDownEnd(const UnitTest
& /*unit_test*/) {}
4195 virtual void OnTestIterationEnd(const UnitTest
& unit_test
, int iteration
);
4196 virtual void OnTestProgramEnd(const UnitTest
& /*unit_test*/) {}
4199 static void PrintFailedTests(const UnitTest
& unit_test
);
4202 // Fired before each iteration of tests starts.
4203 void PrettyUnitTestResultPrinter::OnTestIterationStart(
4204 const UnitTest
& unit_test
, int iteration
) {
4205 if (GTEST_FLAG(repeat
) != 1)
4206 printf("\nRepeating all tests (iteration %d) . . .\n\n", iteration
+ 1);
4208 const char* const filter
= GTEST_FLAG(filter
).c_str();
4210 // Prints the filter if it's not *. This reminds the user that some
4211 // tests may be skipped.
4212 if (!String::CStringEquals(filter
, kUniversalFilter
)) {
4213 ColoredPrintf(COLOR_YELLOW
,
4214 "Note: %s filter = %s\n", GTEST_NAME_
, filter
);
4217 if (internal::ShouldShard(kTestTotalShards
, kTestShardIndex
, false)) {
4218 const Int32 shard_index
= Int32FromEnvOrDie(kTestShardIndex
, -1);
4219 ColoredPrintf(COLOR_YELLOW
,
4220 "Note: This is test shard %d of %s.\n",
4221 static_cast<int>(shard_index
) + 1,
4222 internal::posix::GetEnv(kTestTotalShards
));
4225 if (GTEST_FLAG(shuffle
)) {
4226 ColoredPrintf(COLOR_YELLOW
,
4227 "Note: Randomizing tests' orders with a seed of %d .\n",
4228 unit_test
.random_seed());
4231 ColoredPrintf(COLOR_GREEN
, "[==========] ");
4232 printf("Running %s from %s.\n",
4233 FormatTestCount(unit_test
.test_to_run_count()).c_str(),
4234 FormatTestCaseCount(unit_test
.test_case_to_run_count()).c_str());
4238 void PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart(
4239 const UnitTest
& /*unit_test*/) {
4240 ColoredPrintf(COLOR_GREEN
, "[----------] ");
4241 printf("Global test environment set-up.\n");
4245 void PrettyUnitTestResultPrinter::OnTestCaseStart(const TestCase
& test_case
) {
4246 const std::string counts
=
4247 FormatCountableNoun(test_case
.test_to_run_count(), "test", "tests");
4248 ColoredPrintf(COLOR_GREEN
, "[----------] ");
4249 printf("%s from %s", counts
.c_str(), test_case
.name());
4250 if (test_case
.type_param() == NULL
) {
4253 printf(", where %s = %s\n", kTypeParamLabel
, test_case
.type_param());
4258 void PrettyUnitTestResultPrinter::OnTestStart(const TestInfo
& test_info
) {
4259 ColoredPrintf(COLOR_GREEN
, "[ RUN ] ");
4260 PrintTestName(test_info
.test_case_name(), test_info
.name());
4265 // Called after an assertion failure.
4266 void PrettyUnitTestResultPrinter::OnTestPartResult(
4267 const TestPartResult
& result
) {
4268 // If the test part succeeded, we don't need to do anything.
4269 if (result
.type() == TestPartResult::kSuccess
)
4272 // Print failure message from the assertion (e.g. expected this and got that).
4273 PrintTestPartResult(result
);
4277 void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo
& test_info
) {
4278 if (test_info
.result()->Passed()) {
4279 ColoredPrintf(COLOR_GREEN
, "[ OK ] ");
4281 ColoredPrintf(COLOR_RED
, "[ FAILED ] ");
4283 PrintTestName(test_info
.test_case_name(), test_info
.name());
4284 if (test_info
.result()->Failed())
4285 PrintFullTestCommentIfPresent(test_info
);
4287 if (GTEST_FLAG(print_time
)) {
4288 printf(" (%s ms)\n", internal::StreamableToString(
4289 test_info
.result()->elapsed_time()).c_str());
4296 void PrettyUnitTestResultPrinter::OnTestCaseEnd(const TestCase
& test_case
) {
4297 if (!GTEST_FLAG(print_time
)) return;
4299 const std::string counts
=
4300 FormatCountableNoun(test_case
.test_to_run_count(), "test", "tests");
4301 ColoredPrintf(COLOR_GREEN
, "[----------] ");
4302 printf("%s from %s (%s ms total)\n\n",
4303 counts
.c_str(), test_case
.name(),
4304 internal::StreamableToString(test_case
.elapsed_time()).c_str());
4308 void PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart(
4309 const UnitTest
& /*unit_test*/) {
4310 ColoredPrintf(COLOR_GREEN
, "[----------] ");
4311 printf("Global test environment tear-down\n");
4315 // Internal helper for printing the list of failed tests.
4316 void PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest
& unit_test
) {
4317 const int failed_test_count
= unit_test
.failed_test_count();
4318 if (failed_test_count
== 0) {
4322 for (int i
= 0; i
< unit_test
.total_test_case_count(); ++i
) {
4323 const TestCase
& test_case
= *unit_test
.GetTestCase(i
);
4324 if (!test_case
.should_run() || (test_case
.failed_test_count() == 0)) {
4327 for (int j
= 0; j
< test_case
.total_test_count(); ++j
) {
4328 const TestInfo
& test_info
= *test_case
.GetTestInfo(j
);
4329 if (!test_info
.should_run() || test_info
.result()->Passed()) {
4332 ColoredPrintf(COLOR_RED
, "[ FAILED ] ");
4333 printf("%s.%s", test_case
.name(), test_info
.name());
4334 PrintFullTestCommentIfPresent(test_info
);
4340 void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest
& unit_test
,
4341 int /*iteration*/) {
4342 ColoredPrintf(COLOR_GREEN
, "[==========] ");
4343 printf("%s from %s ran.",
4344 FormatTestCount(unit_test
.test_to_run_count()).c_str(),
4345 FormatTestCaseCount(unit_test
.test_case_to_run_count()).c_str());
4346 if (GTEST_FLAG(print_time
)) {
4347 printf(" (%s ms total)",
4348 internal::StreamableToString(unit_test
.elapsed_time()).c_str());
4351 ColoredPrintf(COLOR_GREEN
, "[ PASSED ] ");
4352 printf("%s.\n", FormatTestCount(unit_test
.successful_test_count()).c_str());
4354 int num_failures
= unit_test
.failed_test_count();
4355 if (!unit_test
.Passed()) {
4356 const int failed_test_count
= unit_test
.failed_test_count();
4357 ColoredPrintf(COLOR_RED
, "[ FAILED ] ");
4358 printf("%s, listed below:\n", FormatTestCount(failed_test_count
).c_str());
4359 PrintFailedTests(unit_test
);
4360 printf("\n%2d FAILED %s\n", num_failures
,
4361 num_failures
== 1 ? "TEST" : "TESTS");
4364 int num_disabled
= unit_test
.reportable_disabled_test_count();
4365 if (num_disabled
&& !GTEST_FLAG(also_run_disabled_tests
)) {
4366 if (!num_failures
) {
4367 printf("\n"); // Add a spacer if no FAILURE banner is displayed.
4369 ColoredPrintf(COLOR_YELLOW
,
4370 " YOU HAVE %d DISABLED %s\n\n",
4372 num_disabled
== 1 ? "TEST" : "TESTS");
4374 // Ensure that Google Test output is printed before, e.g., heapchecker output.
4378 // End PrettyUnitTestResultPrinter
4380 // class TestEventRepeater
4382 // This class forwards events to other event listeners.
4383 class TestEventRepeater
: public TestEventListener
{
4385 TestEventRepeater() : forwarding_enabled_(true) {}
4386 virtual ~TestEventRepeater();
4387 void Append(TestEventListener
*listener
);
4388 TestEventListener
* Release(TestEventListener
* listener
);
4390 // Controls whether events will be forwarded to listeners_. Set to false
4391 // in death test child processes.
4392 bool forwarding_enabled() const { return forwarding_enabled_
; }
4393 void set_forwarding_enabled(bool enable
) { forwarding_enabled_
= enable
; }
4395 virtual void OnTestProgramStart(const UnitTest
& unit_test
);
4396 virtual void OnTestIterationStart(const UnitTest
& unit_test
, int iteration
);
4397 virtual void OnEnvironmentsSetUpStart(const UnitTest
& unit_test
);
4398 virtual void OnEnvironmentsSetUpEnd(const UnitTest
& unit_test
);
4399 virtual void OnTestCaseStart(const TestCase
& test_case
);
4400 virtual void OnTestStart(const TestInfo
& test_info
);
4401 virtual void OnTestPartResult(const TestPartResult
& result
);
4402 virtual void OnTestEnd(const TestInfo
& test_info
);
4403 virtual void OnTestCaseEnd(const TestCase
& test_case
);
4404 virtual void OnEnvironmentsTearDownStart(const UnitTest
& unit_test
);
4405 virtual void OnEnvironmentsTearDownEnd(const UnitTest
& unit_test
);
4406 virtual void OnTestIterationEnd(const UnitTest
& unit_test
, int iteration
);
4407 virtual void OnTestProgramEnd(const UnitTest
& unit_test
);
4410 // Controls whether events will be forwarded to listeners_. Set to false
4411 // in death test child processes.
4412 bool forwarding_enabled_
;
4413 // The list of listeners that receive events.
4414 std::vector
<TestEventListener
*> listeners_
;
4416 GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventRepeater
);
4419 TestEventRepeater::~TestEventRepeater() {
4420 ForEach(listeners_
, Delete
<TestEventListener
>);
4423 void TestEventRepeater::Append(TestEventListener
*listener
) {
4424 listeners_
.push_back(listener
);
4427 // TODO(vladl@google.com): Factor the search functionality into Vector::Find.
4428 TestEventListener
* TestEventRepeater::Release(TestEventListener
*listener
) {
4429 for (size_t i
= 0; i
< listeners_
.size(); ++i
) {
4430 if (listeners_
[i
] == listener
) {
4431 listeners_
.erase(listeners_
.begin() + i
);
4439 // Since most methods are very similar, use macros to reduce boilerplate.
4440 // This defines a member that forwards the call to all listeners.
4441 #define GTEST_REPEATER_METHOD_(Name, Type) \
4442 void TestEventRepeater::Name(const Type& parameter) { \
4443 if (forwarding_enabled_) { \
4444 for (size_t i = 0; i < listeners_.size(); i++) { \
4445 listeners_[i]->Name(parameter); \
4449 // This defines a member that forwards the call to all listeners in reverse
4451 #define GTEST_REVERSE_REPEATER_METHOD_(Name, Type) \
4452 void TestEventRepeater::Name(const Type& parameter) { \
4453 if (forwarding_enabled_) { \
4454 for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) { \
4455 listeners_[i]->Name(parameter); \
4460 GTEST_REPEATER_METHOD_(OnTestProgramStart
, UnitTest
)
4461 GTEST_REPEATER_METHOD_(OnEnvironmentsSetUpStart
, UnitTest
)
4462 GTEST_REPEATER_METHOD_(OnTestCaseStart
, TestCase
)
4463 GTEST_REPEATER_METHOD_(OnTestStart
, TestInfo
)
4464 GTEST_REPEATER_METHOD_(OnTestPartResult
, TestPartResult
)
4465 GTEST_REPEATER_METHOD_(OnEnvironmentsTearDownStart
, UnitTest
)
4466 GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsSetUpEnd
, UnitTest
)
4467 GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsTearDownEnd
, UnitTest
)
4468 GTEST_REVERSE_REPEATER_METHOD_(OnTestEnd
, TestInfo
)
4469 GTEST_REVERSE_REPEATER_METHOD_(OnTestCaseEnd
, TestCase
)
4470 GTEST_REVERSE_REPEATER_METHOD_(OnTestProgramEnd
, UnitTest
)
4472 #undef GTEST_REPEATER_METHOD_
4473 #undef GTEST_REVERSE_REPEATER_METHOD_
4475 void TestEventRepeater::OnTestIterationStart(const UnitTest
& unit_test
,
4477 if (forwarding_enabled_
) {
4478 for (size_t i
= 0; i
< listeners_
.size(); i
++) {
4479 listeners_
[i
]->OnTestIterationStart(unit_test
, iteration
);
4484 void TestEventRepeater::OnTestIterationEnd(const UnitTest
& unit_test
,
4486 if (forwarding_enabled_
) {
4487 for (int i
= static_cast<int>(listeners_
.size()) - 1; i
>= 0; i
--) {
4488 listeners_
[i
]->OnTestIterationEnd(unit_test
, iteration
);
4493 // End TestEventRepeater
4495 // This class generates an XML output file.
4496 class XmlUnitTestResultPrinter
: public EmptyTestEventListener
{
4498 explicit XmlUnitTestResultPrinter(const char* output_file
);
4500 virtual void OnTestIterationEnd(const UnitTest
& unit_test
, int iteration
);
4503 // Is c a whitespace character that is normalized to a space character
4504 // when it appears in an XML attribute value?
4505 static bool IsNormalizableWhitespace(char c
) {
4506 return c
== 0x9 || c
== 0xA || c
== 0xD;
4509 // May c appear in a well-formed XML document?
4510 static bool IsValidXmlCharacter(char c
) {
4511 return IsNormalizableWhitespace(c
) || c
>= 0x20;
4514 // Returns an XML-escaped copy of the input string str. If
4515 // is_attribute is true, the text is meant to appear as an attribute
4516 // value, and normalizable whitespace is preserved by replacing it
4517 // with character references.
4518 static std::string
EscapeXml(const std::string
& str
, bool is_attribute
);
4520 // Returns the given string with all characters invalid in XML removed.
4521 static std::string
RemoveInvalidXmlCharacters(const std::string
& str
);
4523 // Convenience wrapper around EscapeXml when str is an attribute value.
4524 static std::string
EscapeXmlAttribute(const std::string
& str
) {
4525 return EscapeXml(str
, true);
4528 // Convenience wrapper around EscapeXml when str is not an attribute value.
4529 static std::string
EscapeXmlText(const char* str
) {
4530 return EscapeXml(str
, false);
4533 // Verifies that the given attribute belongs to the given element and
4534 // streams the attribute as XML.
4535 static void OutputXmlAttribute(std::ostream
* stream
,
4536 const std::string
& element_name
,
4537 const std::string
& name
,
4538 const std::string
& value
);
4540 // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
4541 static void OutputXmlCDataSection(::std::ostream
* stream
, const char* data
);
4543 // Streams an XML representation of a TestInfo object.
4544 static void OutputXmlTestInfo(::std::ostream
* stream
,
4545 const char* test_case_name
,
4546 const TestInfo
& test_info
);
4548 // Prints an XML representation of a TestCase object
4549 static void PrintXmlTestCase(::std::ostream
* stream
,
4550 const TestCase
& test_case
);
4552 // Prints an XML summary of unit_test to output stream out.
4553 static void PrintXmlUnitTest(::std::ostream
* stream
,
4554 const UnitTest
& unit_test
);
4556 // Produces a string representing the test properties in a result as space
4557 // delimited XML attributes based on the property key="value" pairs.
4558 // When the std::string is not empty, it includes a space at the beginning,
4559 // to delimit this attribute from prior attributes.
4560 static std::string
TestPropertiesAsXmlAttributes(const TestResult
& result
);
4563 const std::string output_file_
;
4565 GTEST_DISALLOW_COPY_AND_ASSIGN_(XmlUnitTestResultPrinter
);
4568 // Creates a new XmlUnitTestResultPrinter.
4569 XmlUnitTestResultPrinter::XmlUnitTestResultPrinter(const char* output_file
)
4570 : output_file_(output_file
) {
4571 if (output_file_
.c_str() == NULL
|| output_file_
.empty()) {
4572 fprintf(stderr
, "XML output file may not be null\n");
4578 // Called after the unit test ends.
4579 void XmlUnitTestResultPrinter::OnTestIterationEnd(const UnitTest
& unit_test
,
4580 int /*iteration*/) {
4581 FILE* xmlout
= NULL
;
4582 FilePath
output_file(output_file_
);
4583 FilePath
output_dir(output_file
.RemoveFileName());
4585 if (output_dir
.CreateDirectoriesRecursively()) {
4586 xmlout
= posix::FOpen(output_file_
.c_str(), "w");
4588 if (xmlout
== NULL
) {
4589 // TODO(wan): report the reason of the failure.
4591 // We don't do it for now as:
4593 // 1. There is no urgent need for it.
4594 // 2. It's a bit involved to make the errno variable thread-safe on
4595 // all three operating systems (Linux, Windows, and Mac OS).
4596 // 3. To interpret the meaning of errno in a thread-safe way,
4597 // we need the strerror_r() function, which is not available on
4600 "Unable to open file \"%s\"\n",
4601 output_file_
.c_str());
4605 std::stringstream stream
;
4606 PrintXmlUnitTest(&stream
, unit_test
);
4607 fprintf(xmlout
, "%s", StringStreamToString(&stream
).c_str());
4611 // Returns an XML-escaped copy of the input string str. If is_attribute
4612 // is true, the text is meant to appear as an attribute value, and
4613 // normalizable whitespace is preserved by replacing it with character
4616 // Invalid XML characters in str, if any, are stripped from the output.
4617 // It is expected that most, if not all, of the text processed by this
4618 // module will consist of ordinary English text.
4619 // If this module is ever modified to produce version 1.1 XML output,
4620 // most invalid characters can be retained using character references.
4621 // TODO(wan): It might be nice to have a minimally invasive, human-readable
4622 // escaping scheme for invalid characters, rather than dropping them.
4623 std::string
XmlUnitTestResultPrinter::EscapeXml(
4624 const std::string
& str
, bool is_attribute
) {
4627 for (size_t i
= 0; i
< str
.size(); ++i
) {
4628 const char ch
= str
[i
];
4652 if (IsValidXmlCharacter(ch
)) {
4653 if (is_attribute
&& IsNormalizableWhitespace(ch
))
4654 m
<< "&#x" << String::FormatByte(static_cast<unsigned char>(ch
))
4663 return m
.GetString();
4666 // Returns the given string with all characters invalid in XML removed.
4667 // Currently invalid characters are dropped from the string. An
4668 // alternative is to replace them with certain characters such as . or ?.
4669 std::string
XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters(
4670 const std::string
& str
) {
4672 output
.reserve(str
.size());
4673 for (std::string::const_iterator it
= str
.begin(); it
!= str
.end(); ++it
)
4674 if (IsValidXmlCharacter(*it
))
4675 output
.push_back(*it
);
4680 // The following routines generate an XML representation of a UnitTest
4683 // This is how Google Test concepts map to the DTD:
4685 // <testsuites name="AllTests"> <-- corresponds to a UnitTest object
4686 // <testsuite name="testcase-name"> <-- corresponds to a TestCase object
4687 // <testcase name="test-name"> <-- corresponds to a TestInfo object
4688 // <failure message="...">...</failure>
4689 // <failure message="...">...</failure>
4690 // <failure message="...">...</failure>
4691 // <-- individual assertion failures
4696 // Formats the given time in milliseconds as seconds.
4697 std::string
FormatTimeInMillisAsSeconds(TimeInMillis ms
) {
4698 ::std::stringstream ss
;
4703 // Converts the given epoch time in milliseconds to a date string in the ISO
4704 // 8601 format, without the timezone information.
4705 std::string
FormatEpochTimeInMillisAsIso8601(TimeInMillis ms
) {
4706 // Using non-reentrant version as localtime_r is not portable.
4707 time_t seconds
= static_cast<time_t>(ms
/ 1000);
4709 # pragma warning(push) // Saves the current warning state.
4710 # pragma warning(disable:4996) // Temporarily disables warning 4996
4711 // (function or variable may be unsafe).
4712 const struct tm
* const time_struct
= localtime(&seconds
); // NOLINT
4713 # pragma warning(pop) // Restores the warning state again.
4715 const struct tm
* const time_struct
= localtime(&seconds
); // NOLINT
4717 if (time_struct
== NULL
)
4718 return ""; // Invalid ms value
4720 // YYYY-MM-DDThh:mm:ss
4721 return StreamableToString(time_struct
->tm_year
+ 1900) + "-" +
4722 String::FormatIntWidth2(time_struct
->tm_mon
+ 1) + "-" +
4723 String::FormatIntWidth2(time_struct
->tm_mday
) + "T" +
4724 String::FormatIntWidth2(time_struct
->tm_hour
) + ":" +
4725 String::FormatIntWidth2(time_struct
->tm_min
) + ":" +
4726 String::FormatIntWidth2(time_struct
->tm_sec
);
4729 // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
4730 void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream
* stream
,
4732 const char* segment
= data
;
4733 *stream
<< "<![CDATA[";
4735 const char* const next_segment
= strstr(segment
, "]]>");
4736 if (next_segment
!= NULL
) {
4738 segment
, static_cast<std::streamsize
>(next_segment
- segment
));
4739 *stream
<< "]]>]]><![CDATA[";
4740 segment
= next_segment
+ strlen("]]>");
4749 void XmlUnitTestResultPrinter::OutputXmlAttribute(
4750 std::ostream
* stream
,
4751 const std::string
& element_name
,
4752 const std::string
& name
,
4753 const std::string
& value
) {
4754 const std::vector
<std::string
>& allowed_names
=
4755 GetReservedAttributesForElement(element_name
);
4757 GTEST_CHECK_(std::find(allowed_names
.begin(), allowed_names
.end(), name
) !=
4758 allowed_names
.end())
4759 << "Attribute " << name
<< " is not allowed for element <" << element_name
4762 *stream
<< " " << name
<< "=\"" << EscapeXmlAttribute(value
) << "\"";
4765 // Prints an XML representation of a TestInfo object.
4766 // TODO(wan): There is also value in printing properties with the plain printer.
4767 void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream
* stream
,
4768 const char* test_case_name
,
4769 const TestInfo
& test_info
) {
4770 const TestResult
& result
= *test_info
.result();
4771 const std::string kTestcase
= "testcase";
4773 *stream
<< " <testcase";
4774 OutputXmlAttribute(stream
, kTestcase
, "name", test_info
.name());
4776 if (test_info
.value_param() != NULL
) {
4777 OutputXmlAttribute(stream
, kTestcase
, "value_param",
4778 test_info
.value_param());
4780 if (test_info
.type_param() != NULL
) {
4781 OutputXmlAttribute(stream
, kTestcase
, "type_param", test_info
.type_param());
4784 OutputXmlAttribute(stream
, kTestcase
, "status",
4785 test_info
.should_run() ? "run" : "notrun");
4786 OutputXmlAttribute(stream
, kTestcase
, "time",
4787 FormatTimeInMillisAsSeconds(result
.elapsed_time()));
4788 OutputXmlAttribute(stream
, kTestcase
, "classname", test_case_name
);
4789 *stream
<< TestPropertiesAsXmlAttributes(result
);
4792 for (int i
= 0; i
< result
.total_part_count(); ++i
) {
4793 const TestPartResult
& part
= result
.GetTestPartResult(i
);
4794 if (part
.failed()) {
4795 if (++failures
== 1) {
4798 const string location
= internal::FormatCompilerIndependentFileLocation(
4799 part
.file_name(), part
.line_number());
4800 const string summary
= location
+ "\n" + part
.summary();
4801 *stream
<< " <failure message=\""
4802 << EscapeXmlAttribute(summary
.c_str())
4804 const string detail
= location
+ "\n" + part
.message();
4805 OutputXmlCDataSection(stream
, RemoveInvalidXmlCharacters(detail
).c_str());
4806 *stream
<< "</failure>\n";
4813 *stream
<< " </testcase>\n";
4816 // Prints an XML representation of a TestCase object
4817 void XmlUnitTestResultPrinter::PrintXmlTestCase(std::ostream
* stream
,
4818 const TestCase
& test_case
) {
4819 const std::string kTestsuite
= "testsuite";
4820 *stream
<< " <" << kTestsuite
;
4821 OutputXmlAttribute(stream
, kTestsuite
, "name", test_case
.name());
4822 OutputXmlAttribute(stream
, kTestsuite
, "tests",
4823 StreamableToString(test_case
.reportable_test_count()));
4824 OutputXmlAttribute(stream
, kTestsuite
, "failures",
4825 StreamableToString(test_case
.failed_test_count()));
4827 stream
, kTestsuite
, "disabled",
4828 StreamableToString(test_case
.reportable_disabled_test_count()));
4829 OutputXmlAttribute(stream
, kTestsuite
, "errors", "0");
4830 OutputXmlAttribute(stream
, kTestsuite
, "time",
4831 FormatTimeInMillisAsSeconds(test_case
.elapsed_time()));
4832 *stream
<< TestPropertiesAsXmlAttributes(test_case
.ad_hoc_test_result())
4835 for (int i
= 0; i
< test_case
.total_test_count(); ++i
) {
4836 if (test_case
.GetTestInfo(i
)->is_reportable())
4837 OutputXmlTestInfo(stream
, test_case
.name(), *test_case
.GetTestInfo(i
));
4839 *stream
<< " </" << kTestsuite
<< ">\n";
4842 // Prints an XML summary of unit_test to output stream out.
4843 void XmlUnitTestResultPrinter::PrintXmlUnitTest(std::ostream
* stream
,
4844 const UnitTest
& unit_test
) {
4845 const std::string kTestsuites
= "testsuites";
4847 *stream
<< "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
4848 *stream
<< "<" << kTestsuites
;
4850 OutputXmlAttribute(stream
, kTestsuites
, "tests",
4851 StreamableToString(unit_test
.reportable_test_count()));
4852 OutputXmlAttribute(stream
, kTestsuites
, "failures",
4853 StreamableToString(unit_test
.failed_test_count()));
4855 stream
, kTestsuites
, "disabled",
4856 StreamableToString(unit_test
.reportable_disabled_test_count()));
4857 OutputXmlAttribute(stream
, kTestsuites
, "errors", "0");
4859 stream
, kTestsuites
, "timestamp",
4860 FormatEpochTimeInMillisAsIso8601(unit_test
.start_timestamp()));
4861 OutputXmlAttribute(stream
, kTestsuites
, "time",
4862 FormatTimeInMillisAsSeconds(unit_test
.elapsed_time()));
4864 if (GTEST_FLAG(shuffle
)) {
4865 OutputXmlAttribute(stream
, kTestsuites
, "random_seed",
4866 StreamableToString(unit_test
.random_seed()));
4869 *stream
<< TestPropertiesAsXmlAttributes(unit_test
.ad_hoc_test_result());
4871 OutputXmlAttribute(stream
, kTestsuites
, "name", "AllTests");
4874 for (int i
= 0; i
< unit_test
.total_test_case_count(); ++i
) {
4875 if (unit_test
.GetTestCase(i
)->reportable_test_count() > 0)
4876 PrintXmlTestCase(stream
, *unit_test
.GetTestCase(i
));
4878 *stream
<< "</" << kTestsuites
<< ">\n";
4881 // Produces a string representing the test properties in a result as space
4882 // delimited XML attributes based on the property key="value" pairs.
4883 std::string
XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes(
4884 const TestResult
& result
) {
4886 for (int i
= 0; i
< result
.test_property_count(); ++i
) {
4887 const TestProperty
& property
= result
.GetTestProperty(i
);
4888 attributes
<< " " << property
.key() << "="
4889 << "\"" << EscapeXmlAttribute(property
.value()) << "\"";
4891 return attributes
.GetString();
4894 // End XmlUnitTestResultPrinter
4896 #if GTEST_CAN_STREAM_RESULTS_
4898 // Checks if str contains '=', '&', '%' or '\n' characters. If yes,
4899 // replaces them by "%xx" where xx is their hexadecimal value. For
4900 // example, replaces "=" with "%3D". This algorithm is O(strlen(str))
4901 // in both time and space -- important as the input str may contain an
4902 // arbitrarily long test failure message and stack trace.
4903 string
StreamingListener::UrlEncode(const char* str
) {
4905 result
.reserve(strlen(str
) + 1);
4906 for (char ch
= *str
; ch
!= '\0'; ch
= *++str
) {
4912 result
.append("%" + String::FormatByte(static_cast<unsigned char>(ch
)));
4915 result
.push_back(ch
);
4922 void StreamingListener::SocketWriter::MakeConnection() {
4923 GTEST_CHECK_(sockfd_
== -1)
4924 << "MakeConnection() can't be called when there is already a connection.";
4927 memset(&hints
, 0, sizeof(hints
));
4928 hints
.ai_family
= AF_UNSPEC
; // To allow both IPv4 and IPv6 addresses.
4929 hints
.ai_socktype
= SOCK_STREAM
;
4930 addrinfo
* servinfo
= NULL
;
4932 // Use the getaddrinfo() to get a linked list of IP addresses for
4933 // the given host name.
4934 const int error_num
= getaddrinfo(
4935 host_name_
.c_str(), port_num_
.c_str(), &hints
, &servinfo
);
4936 if (error_num
!= 0) {
4937 GTEST_LOG_(WARNING
) << "stream_result_to: getaddrinfo() failed: "
4938 << gai_strerror(error_num
);
4941 // Loop through all the results and connect to the first we can.
4942 for (addrinfo
* cur_addr
= servinfo
; sockfd_
== -1 && cur_addr
!= NULL
;
4943 cur_addr
= cur_addr
->ai_next
) {
4945 cur_addr
->ai_family
, cur_addr
->ai_socktype
, cur_addr
->ai_protocol
);
4946 if (sockfd_
!= -1) {
4947 // Connect the client socket to the server socket.
4948 if (connect(sockfd_
, cur_addr
->ai_addr
, cur_addr
->ai_addrlen
) == -1) {
4955 freeaddrinfo(servinfo
); // all done with this structure
4957 if (sockfd_
== -1) {
4958 GTEST_LOG_(WARNING
) << "stream_result_to: failed to connect to "
4959 << host_name_
<< ":" << port_num_
;
4963 // End of class Streaming Listener
4964 #endif // GTEST_CAN_STREAM_RESULTS__
4966 // Class ScopedTrace
4968 // Pushes the given source file location and message onto a per-thread
4969 // trace stack maintained by Google Test.
4970 ScopedTrace::ScopedTrace(const char* file
, int line
, const Message
& message
)
4971 GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_
) {
4975 trace
.message
= message
.GetString();
4977 UnitTest::GetInstance()->PushGTestTrace(trace
);
4980 // Pops the info pushed by the c'tor.
4981 ScopedTrace::~ScopedTrace()
4982 GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_
) {
4983 UnitTest::GetInstance()->PopGTestTrace();
4987 // class OsStackTraceGetter
4989 // Returns the current OS stack trace as an std::string. Parameters:
4991 // max_depth - the maximum number of stack frames to be included
4993 // skip_count - the number of top frames to be skipped; doesn't count
4994 // against max_depth.
4996 string
OsStackTraceGetter::CurrentStackTrace(int /* max_depth */,
4997 int /* skip_count */)
4998 GTEST_LOCK_EXCLUDED_(mutex_
) {
5002 void OsStackTraceGetter::UponLeavingGTest()
5003 GTEST_LOCK_EXCLUDED_(mutex_
) {
5007 OsStackTraceGetter::kElidedFramesMarker
=
5008 "... " GTEST_NAME_
" internal frames ...";
5010 // A helper class that creates the premature-exit file in its
5011 // constructor and deletes the file in its destructor.
5012 class ScopedPrematureExitFile
{
5014 explicit ScopedPrematureExitFile(const char* premature_exit_filepath
)
5015 : premature_exit_filepath_(premature_exit_filepath
) {
5016 // If a path to the premature-exit file is specified...
5017 if (premature_exit_filepath
!= NULL
&& *premature_exit_filepath
!= '\0') {
5018 // create the file with a single "0" character in it. I/O
5019 // errors are ignored as there's nothing better we can do and we
5020 // don't want to fail the test because of this.
5021 FILE* pfile
= posix::FOpen(premature_exit_filepath
, "w");
5022 fwrite("0", 1, 1, pfile
);
5027 ~ScopedPrematureExitFile() {
5028 if (premature_exit_filepath_
!= NULL
&& *premature_exit_filepath_
!= '\0') {
5029 remove(premature_exit_filepath_
);
5034 const char* const premature_exit_filepath_
;
5036 GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedPrematureExitFile
);
5039 } // namespace internal
5041 // class TestEventListeners
5043 TestEventListeners::TestEventListeners()
5044 : repeater_(new internal::TestEventRepeater()),
5045 default_result_printer_(NULL
),
5046 default_xml_generator_(NULL
) {
5049 TestEventListeners::~TestEventListeners() { delete repeater_
; }
5051 // Returns the standard listener responsible for the default console
5052 // output. Can be removed from the listeners list to shut down default
5053 // console output. Note that removing this object from the listener list
5054 // with Release transfers its ownership to the user.
5055 void TestEventListeners::Append(TestEventListener
* listener
) {
5056 repeater_
->Append(listener
);
5059 // Removes the given event listener from the list and returns it. It then
5060 // becomes the caller's responsibility to delete the listener. Returns
5061 // NULL if the listener is not found in the list.
5062 TestEventListener
* TestEventListeners::Release(TestEventListener
* listener
) {
5063 if (listener
== default_result_printer_
)
5064 default_result_printer_
= NULL
;
5065 else if (listener
== default_xml_generator_
)
5066 default_xml_generator_
= NULL
;
5067 return repeater_
->Release(listener
);
5070 // Returns repeater that broadcasts the TestEventListener events to all
5072 TestEventListener
* TestEventListeners::repeater() { return repeater_
; }
5074 // Sets the default_result_printer attribute to the provided listener.
5075 // The listener is also added to the listener list and previous
5076 // default_result_printer is removed from it and deleted. The listener can
5077 // also be NULL in which case it will not be added to the list. Does
5078 // nothing if the previous and the current listener objects are the same.
5079 void TestEventListeners::SetDefaultResultPrinter(TestEventListener
* listener
) {
5080 if (default_result_printer_
!= listener
) {
5081 // It is an error to pass this method a listener that is already in the
5083 delete Release(default_result_printer_
);
5084 default_result_printer_
= listener
;
5085 if (listener
!= NULL
)
5090 // Sets the default_xml_generator attribute to the provided listener. The
5091 // listener is also added to the listener list and previous
5092 // default_xml_generator is removed from it and deleted. The listener can
5093 // also be NULL in which case it will not be added to the list. Does
5094 // nothing if the previous and the current listener objects are the same.
5095 void TestEventListeners::SetDefaultXmlGenerator(TestEventListener
* listener
) {
5096 if (default_xml_generator_
!= listener
) {
5097 // It is an error to pass this method a listener that is already in the
5099 delete Release(default_xml_generator_
);
5100 default_xml_generator_
= listener
;
5101 if (listener
!= NULL
)
5106 // Controls whether events will be forwarded by the repeater to the
5107 // listeners in the list.
5108 bool TestEventListeners::EventForwardingEnabled() const {
5109 return repeater_
->forwarding_enabled();
5112 void TestEventListeners::SuppressEventForwarding() {
5113 repeater_
->set_forwarding_enabled(false);
5118 // Gets the singleton UnitTest object. The first time this method is
5119 // called, a UnitTest object is constructed and returned. Consecutive
5120 // calls will return the same object.
5122 // We don't protect this under mutex_ as a user is not supposed to
5123 // call this before main() starts, from which point on the return
5124 // value will never change.
5125 UnitTest
* UnitTest::GetInstance() {
5126 // When compiled with MSVC 7.1 in optimized mode, destroying the
5127 // UnitTest object upon exiting the program messes up the exit code,
5128 // causing successful tests to appear failed. We have to use a
5129 // different implementation in this case to bypass the compiler bug.
5130 // This implementation makes the compiler happy, at the cost of
5131 // leaking the UnitTest object.
5133 // CodeGear C++Builder insists on a public destructor for the
5134 // default implementation. Use this implementation to keep good OO
5135 // design with private destructor.
5137 #if (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)
5138 static UnitTest
* const instance
= new UnitTest
;
5141 static UnitTest instance
;
5143 #endif // (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)
5146 // Gets the number of successful test cases.
5147 int UnitTest::successful_test_case_count() const {
5148 return impl()->successful_test_case_count();
5151 // Gets the number of failed test cases.
5152 int UnitTest::failed_test_case_count() const {
5153 return impl()->failed_test_case_count();
5156 // Gets the number of all test cases.
5157 int UnitTest::total_test_case_count() const {
5158 return impl()->total_test_case_count();
5161 // Gets the number of all test cases that contain at least one test
5163 int UnitTest::test_case_to_run_count() const {
5164 return impl()->test_case_to_run_count();
5167 // Gets the number of successful tests.
5168 int UnitTest::successful_test_count() const {
5169 return impl()->successful_test_count();
5172 // Gets the number of failed tests.
5173 int UnitTest::failed_test_count() const { return impl()->failed_test_count(); }
5175 // Gets the number of disabled tests that will be reported in the XML report.
5176 int UnitTest::reportable_disabled_test_count() const {
5177 return impl()->reportable_disabled_test_count();
5180 // Gets the number of disabled tests.
5181 int UnitTest::disabled_test_count() const {
5182 return impl()->disabled_test_count();
5185 // Gets the number of tests to be printed in the XML report.
5186 int UnitTest::reportable_test_count() const {
5187 return impl()->reportable_test_count();
5190 // Gets the number of all tests.
5191 int UnitTest::total_test_count() const { return impl()->total_test_count(); }
5193 // Gets the number of tests that should run.
5194 int UnitTest::test_to_run_count() const { return impl()->test_to_run_count(); }
5196 // Gets the time of the test program start, in ms from the start of the
5198 internal::TimeInMillis
UnitTest::start_timestamp() const {
5199 return impl()->start_timestamp();
5202 // Gets the elapsed time, in milliseconds.
5203 internal::TimeInMillis
UnitTest::elapsed_time() const {
5204 return impl()->elapsed_time();
5207 // Returns true iff the unit test passed (i.e. all test cases passed).
5208 bool UnitTest::Passed() const { return impl()->Passed(); }
5210 // Returns true iff the unit test failed (i.e. some test case failed
5211 // or something outside of all tests failed).
5212 bool UnitTest::Failed() const { return impl()->Failed(); }
5214 // Gets the i-th test case among all the test cases. i can range from 0 to
5215 // total_test_case_count() - 1. If i is not in that range, returns NULL.
5216 const TestCase
* UnitTest::GetTestCase(int i
) const {
5217 return impl()->GetTestCase(i
);
5220 // Returns the TestResult containing information on test failures and
5221 // properties logged outside of individual test cases.
5222 const TestResult
& UnitTest::ad_hoc_test_result() const {
5223 return *impl()->ad_hoc_test_result();
5226 // Gets the i-th test case among all the test cases. i can range from 0 to
5227 // total_test_case_count() - 1. If i is not in that range, returns NULL.
5228 TestCase
* UnitTest::GetMutableTestCase(int i
) {
5229 return impl()->GetMutableTestCase(i
);
5232 // Returns the list of event listeners that can be used to track events
5233 // inside Google Test.
5234 TestEventListeners
& UnitTest::listeners() {
5235 return *impl()->listeners();
5238 // Registers and returns a global test environment. When a test
5239 // program is run, all global test environments will be set-up in the
5240 // order they were registered. After all tests in the program have
5241 // finished, all global test environments will be torn-down in the
5242 // *reverse* order they were registered.
5244 // The UnitTest object takes ownership of the given environment.
5246 // We don't protect this under mutex_, as we only support calling it
5247 // from the main thread.
5248 Environment
* UnitTest::AddEnvironment(Environment
* env
) {
5253 impl_
->environments().push_back(env
);
5257 // Adds a TestPartResult to the current TestResult object. All Google Test
5258 // assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) eventually call
5259 // this to report their results. The user code should use the
5260 // assertion macros instead of calling this directly.
5261 void UnitTest::AddTestPartResult(
5262 TestPartResult::Type result_type
,
5263 const char* file_name
,
5265 const std::string
& message
,
5266 const std::string
& os_stack_trace
) GTEST_LOCK_EXCLUDED_(mutex_
) {
5270 internal::MutexLock
lock(&mutex_
);
5271 if (impl_
->gtest_trace_stack().size() > 0) {
5272 msg
<< "\n" << GTEST_NAME_
<< " trace:";
5274 for (int i
= static_cast<int>(impl_
->gtest_trace_stack().size());
5276 const internal::TraceInfo
& trace
= impl_
->gtest_trace_stack()[i
- 1];
5277 msg
<< "\n" << internal::FormatFileLocation(trace
.file
, trace
.line
)
5278 << " " << trace
.message
;
5282 if (os_stack_trace
.c_str() != NULL
&& !os_stack_trace
.empty()) {
5283 msg
<< internal::kStackTraceMarker
<< os_stack_trace
;
5286 const TestPartResult result
=
5287 TestPartResult(result_type
, file_name
, line_number
,
5288 msg
.GetString().c_str());
5289 impl_
->GetTestPartResultReporterForCurrentThread()->
5290 ReportTestPartResult(result
);
5292 if (result_type
!= TestPartResult::kSuccess
) {
5293 // gtest_break_on_failure takes precedence over
5294 // gtest_throw_on_failure. This allows a user to set the latter
5295 // in the code (perhaps in order to use Google Test assertions
5296 // with another testing framework) and specify the former on the
5297 // command line for debugging.
5298 if (GTEST_FLAG(break_on_failure
)) {
5299 #if GTEST_OS_WINDOWS
5300 // Using DebugBreak on Windows allows gtest to still break into a debugger
5301 // when a failure happens and both the --gtest_break_on_failure and
5302 // the --gtest_catch_exceptions flags are specified.
5305 // Dereference NULL through a volatile pointer to prevent the compiler
5306 // from removing. We use this rather than abort() or __builtin_trap() for
5307 // portability: Symbian doesn't implement abort() well, and some debuggers
5308 // don't correctly trap abort().
5309 *static_cast<volatile int*>(NULL
) = 1;
5310 #endif // GTEST_OS_WINDOWS
5311 } else if (GTEST_FLAG(throw_on_failure
)) {
5312 #if GTEST_HAS_EXCEPTIONS
5313 throw internal::GoogleTestFailureException(result
);
5315 // We cannot call abort() as it generates a pop-up in debug mode
5316 // that cannot be suppressed in VC 7.1 or below.
5323 // Adds a TestProperty to the current TestResult object when invoked from
5324 // inside a test, to current TestCase's ad_hoc_test_result_ when invoked
5325 // from SetUpTestCase or TearDownTestCase, or to the global property set
5326 // when invoked elsewhere. If the result already contains a property with
5327 // the same key, the value will be updated.
5328 void UnitTest::RecordProperty(const std::string
& key
,
5329 const std::string
& value
) {
5330 impl_
->RecordProperty(TestProperty(key
, value
));
5333 // Runs all tests in this UnitTest object and prints the result.
5334 // Returns 0 if successful, or 1 otherwise.
5336 // We don't protect this under mutex_, as we only support calling it
5337 // from the main thread.
5338 int UnitTest::Run() {
5339 const bool in_death_test_child_process
=
5340 internal::GTEST_FLAG(internal_run_death_test
).length() > 0;
5342 // Google Test implements this protocol for catching that a test
5343 // program exits before returning control to Google Test:
5345 // 1. Upon start, Google Test creates a file whose absolute path
5346 // is specified by the environment variable
5347 // TEST_PREMATURE_EXIT_FILE.
5348 // 2. When Google Test has finished its work, it deletes the file.
5350 // This allows a test runner to set TEST_PREMATURE_EXIT_FILE before
5351 // running a Google-Test-based test program and check the existence
5352 // of the file at the end of the test execution to see if it has
5353 // exited prematurely.
5355 // If we are in the child process of a death test, don't
5356 // create/delete the premature exit file, as doing so is unnecessary
5357 // and will confuse the parent process. Otherwise, create/delete
5358 // the file upon entering/leaving this function. If the program
5359 // somehow exits before this function has a chance to return, the
5360 // premature-exit file will be left undeleted, causing a test runner
5361 // that understands the premature-exit-file protocol to report the
5362 // test as having failed.
5363 const internal::ScopedPrematureExitFile
premature_exit_file(
5364 in_death_test_child_process
?
5365 NULL
: internal::posix::GetEnv("TEST_PREMATURE_EXIT_FILE"));
5367 // Captures the value of GTEST_FLAG(catch_exceptions). This value will be
5368 // used for the duration of the program.
5369 impl()->set_catch_exceptions(GTEST_FLAG(catch_exceptions
));
5372 // Either the user wants Google Test to catch exceptions thrown by the
5373 // tests or this is executing in the context of death test child
5374 // process. In either case the user does not want to see pop-up dialogs
5375 // about crashes - they are expected.
5376 if (impl()->catch_exceptions() || in_death_test_child_process
) {
5377 # if !GTEST_OS_WINDOWS_MOBILE
5378 // SetErrorMode doesn't exist on CE.
5379 SetErrorMode(SEM_FAILCRITICALERRORS
| SEM_NOALIGNMENTFAULTEXCEPT
|
5380 SEM_NOGPFAULTERRORBOX
| SEM_NOOPENFILEERRORBOX
);
5381 # endif // !GTEST_OS_WINDOWS_MOBILE
5383 # if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE
5384 // Death test children can be terminated with _abort(). On Windows,
5385 // _abort() can show a dialog with a warning message. This forces the
5386 // abort message to go to stderr instead.
5387 _set_error_mode(_OUT_TO_STDERR
);
5390 # if _MSC_VER >= 1400 && !GTEST_OS_WINDOWS_MOBILE
5391 // In the debug version, Visual Studio pops up a separate dialog
5392 // offering a choice to debug the aborted program. We need to suppress
5393 // this dialog or it will pop up for every EXPECT/ASSERT_DEATH statement
5394 // executed. Google Test will notify the user of any unexpected
5395 // failure via stderr.
5397 // VC++ doesn't define _set_abort_behavior() prior to the version 8.0.
5398 // Users of prior VC versions shall suffer the agony and pain of
5399 // clicking through the countless debug dialogs.
5400 // TODO(vladl@google.com): find a way to suppress the abort dialog() in the
5401 // debug mode when compiled with VC 7.1 or lower.
5402 if (!GTEST_FLAG(break_on_failure
))
5403 _set_abort_behavior(
5404 0x0, // Clear the following flags:
5405 _WRITE_ABORT_MSG
| _CALL_REPORTFAULT
); // pop-up window, core dump.
5408 #endif // GTEST_HAS_SEH
5410 return internal::HandleExceptionsInMethodIfSupported(
5412 &internal::UnitTestImpl::RunAllTests
,
5413 "auxiliary test code (environments or event listeners)") ? 0 : 1;
5416 // Returns the working directory when the first TEST() or TEST_F() was
5418 const char* UnitTest::original_working_dir() const {
5419 return impl_
->original_working_dir_
.c_str();
5422 // Returns the TestCase object for the test that's currently running,
5423 // or NULL if no test is running.
5424 const TestCase
* UnitTest::current_test_case() const
5425 GTEST_LOCK_EXCLUDED_(mutex_
) {
5426 internal::MutexLock
lock(&mutex_
);
5427 return impl_
->current_test_case();
5430 // Returns the TestInfo object for the test that's currently running,
5431 // or NULL if no test is running.
5432 const TestInfo
* UnitTest::current_test_info() const
5433 GTEST_LOCK_EXCLUDED_(mutex_
) {
5434 internal::MutexLock
lock(&mutex_
);
5435 return impl_
->current_test_info();
5438 // Returns the random seed used at the start of the current test run.
5439 int UnitTest::random_seed() const { return impl_
->random_seed(); }
5441 #if GTEST_HAS_PARAM_TEST
5442 // Returns ParameterizedTestCaseRegistry object used to keep track of
5443 // value-parameterized tests and instantiate and register them.
5444 internal::ParameterizedTestCaseRegistry
&
5445 UnitTest::parameterized_test_registry()
5446 GTEST_LOCK_EXCLUDED_(mutex_
) {
5447 return impl_
->parameterized_test_registry();
5449 #endif // GTEST_HAS_PARAM_TEST
5451 // Creates an empty UnitTest.
5452 UnitTest::UnitTest() {
5453 impl_
= new internal::UnitTestImpl(this);
5456 // Destructor of UnitTest.
5457 UnitTest::~UnitTest() {
5461 // Pushes a trace defined by SCOPED_TRACE() on to the per-thread
5462 // Google Test trace stack.
5463 void UnitTest::PushGTestTrace(const internal::TraceInfo
& trace
)
5464 GTEST_LOCK_EXCLUDED_(mutex_
) {
5465 internal::MutexLock
lock(&mutex_
);
5466 impl_
->gtest_trace_stack().push_back(trace
);
5469 // Pops a trace from the per-thread Google Test trace stack.
5470 void UnitTest::PopGTestTrace()
5471 GTEST_LOCK_EXCLUDED_(mutex_
) {
5472 internal::MutexLock
lock(&mutex_
);
5473 impl_
->gtest_trace_stack().pop_back();
5476 namespace internal
{
5478 UnitTestImpl::UnitTestImpl(UnitTest
* parent
)
5481 # pragma warning(push) // Saves the current warning state.
5482 # pragma warning(disable:4355) // Temporarily disables warning 4355
5483 // (using this in initializer).
5484 default_global_test_part_result_reporter_(this),
5485 default_per_thread_test_part_result_reporter_(this),
5486 # pragma warning(pop) // Restores the warning state again.
5488 default_global_test_part_result_reporter_(this),
5489 default_per_thread_test_part_result_reporter_(this),
5491 global_test_part_result_repoter_(
5492 &default_global_test_part_result_reporter_
),
5493 per_thread_test_part_result_reporter_(
5494 &default_per_thread_test_part_result_reporter_
),
5495 #if GTEST_HAS_PARAM_TEST
5496 parameterized_test_registry_(),
5497 parameterized_tests_registered_(false),
5498 #endif // GTEST_HAS_PARAM_TEST
5499 last_death_test_case_(-1),
5500 current_test_case_(NULL
),
5501 current_test_info_(NULL
),
5502 ad_hoc_test_result_(),
5503 os_stack_trace_getter_(NULL
),
5504 post_flag_parse_init_performed_(false),
5505 random_seed_(0), // Will be overridden by the flag before first use.
5506 random_(0), // Will be reseeded before first use.
5507 start_timestamp_(0),
5509 #if GTEST_HAS_DEATH_TEST
5510 death_test_factory_(new DefaultDeathTestFactory
),
5512 // Will be overridden by the flag before first use.
5513 catch_exceptions_(false) {
5514 listeners()->SetDefaultResultPrinter(new PrettyUnitTestResultPrinter
);
5517 UnitTestImpl::~UnitTestImpl() {
5518 // Deletes every TestCase.
5519 ForEach(test_cases_
, internal::Delete
<TestCase
>);
5521 // Deletes every Environment.
5522 ForEach(environments_
, internal::Delete
<Environment
>);
5524 delete os_stack_trace_getter_
;
5527 // Adds a TestProperty to the current TestResult object when invoked in a
5528 // context of a test, to current test case's ad_hoc_test_result when invoke
5529 // from SetUpTestCase/TearDownTestCase, or to the global property set
5530 // otherwise. If the result already contains a property with the same key,
5531 // the value will be updated.
5532 void UnitTestImpl::RecordProperty(const TestProperty
& test_property
) {
5533 std::string xml_element
;
5534 TestResult
* test_result
; // TestResult appropriate for property recording.
5536 if (current_test_info_
!= NULL
) {
5537 xml_element
= "testcase";
5538 test_result
= &(current_test_info_
->result_
);
5539 } else if (current_test_case_
!= NULL
) {
5540 xml_element
= "testsuite";
5541 test_result
= &(current_test_case_
->ad_hoc_test_result_
);
5543 xml_element
= "testsuites";
5544 test_result
= &ad_hoc_test_result_
;
5546 test_result
->RecordProperty(xml_element
, test_property
);
5549 #if GTEST_HAS_DEATH_TEST
5550 // Disables event forwarding if the control is currently in a death test
5551 // subprocess. Must not be called before InitGoogleTest.
5552 void UnitTestImpl::SuppressTestEventsIfInSubprocess() {
5553 if (internal_run_death_test_flag_
.get() != NULL
)
5554 listeners()->SuppressEventForwarding();
5556 #endif // GTEST_HAS_DEATH_TEST
5558 // Initializes event listeners performing XML output as specified by
5559 // UnitTestOptions. Must not be called before InitGoogleTest.
5560 void UnitTestImpl::ConfigureXmlOutput() {
5561 const std::string
& output_format
= UnitTestOptions::GetOutputFormat();
5562 if (output_format
== "xml") {
5563 listeners()->SetDefaultXmlGenerator(new XmlUnitTestResultPrinter(
5564 UnitTestOptions::GetAbsolutePathToOutputFile().c_str()));
5565 } else if (output_format
!= "") {
5566 printf("WARNING: unrecognized output format \"%s\" ignored.\n",
5567 output_format
.c_str());
5572 #if GTEST_CAN_STREAM_RESULTS_
5573 // Initializes event listeners for streaming test results in string form.
5574 // Must not be called before InitGoogleTest.
5575 void UnitTestImpl::ConfigureStreamingOutput() {
5576 const std::string
& target
= GTEST_FLAG(stream_result_to
);
5577 if (!target
.empty()) {
5578 const size_t pos
= target
.find(':');
5579 if (pos
!= std::string::npos
) {
5580 listeners()->Append(new StreamingListener(target
.substr(0, pos
),
5581 target
.substr(pos
+1)));
5583 printf("WARNING: unrecognized streaming target \"%s\" ignored.\n",
5589 #endif // GTEST_CAN_STREAM_RESULTS_
5591 // Performs initialization dependent upon flag values obtained in
5592 // ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to
5593 // ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest
5594 // this function is also called from RunAllTests. Since this function can be
5595 // called more than once, it has to be idempotent.
5596 void UnitTestImpl::PostFlagParsingInit() {
5597 // Ensures that this function does not execute more than once.
5598 if (!post_flag_parse_init_performed_
) {
5599 post_flag_parse_init_performed_
= true;
5601 #if GTEST_HAS_DEATH_TEST
5602 InitDeathTestSubprocessControlInfo();
5603 SuppressTestEventsIfInSubprocess();
5604 #endif // GTEST_HAS_DEATH_TEST
5606 // Registers parameterized tests. This makes parameterized tests
5607 // available to the UnitTest reflection API without running
5609 RegisterParameterizedTests();
5611 // Configures listeners for XML output. This makes it possible for users
5612 // to shut down the default XML output before invoking RUN_ALL_TESTS.
5613 ConfigureXmlOutput();
5615 #if GTEST_CAN_STREAM_RESULTS_
5616 // Configures listeners for streaming test results to the specified server.
5617 ConfigureStreamingOutput();
5618 #endif // GTEST_CAN_STREAM_RESULTS_
5622 // A predicate that checks the name of a TestCase against a known
5625 // This is used for implementation of the UnitTest class only. We put
5626 // it in the anonymous namespace to prevent polluting the outer
5629 // TestCaseNameIs is copyable.
5630 class TestCaseNameIs
{
5633 explicit TestCaseNameIs(const std::string
& name
)
5636 // Returns true iff the name of test_case matches name_.
5637 bool operator()(const TestCase
* test_case
) const {
5638 return test_case
!= NULL
&& strcmp(test_case
->name(), name_
.c_str()) == 0;
5645 // Finds and returns a TestCase with the given name. If one doesn't
5646 // exist, creates one and returns it. It's the CALLER'S
5647 // RESPONSIBILITY to ensure that this function is only called WHEN THE
5648 // TESTS ARE NOT SHUFFLED.
5652 // test_case_name: name of the test case
5653 // type_param: the name of the test case's type parameter, or NULL if
5654 // this is not a typed or a type-parameterized test case.
5655 // set_up_tc: pointer to the function that sets up the test case
5656 // tear_down_tc: pointer to the function that tears down the test case
5657 TestCase
* UnitTestImpl::GetTestCase(const char* test_case_name
,
5658 const char* type_param
,
5659 Test::SetUpTestCaseFunc set_up_tc
,
5660 Test::TearDownTestCaseFunc tear_down_tc
) {
5661 // Can we find a TestCase with the given name?
5662 const std::vector
<TestCase
*>::const_iterator test_case
=
5663 std::find_if(test_cases_
.begin(), test_cases_
.end(),
5664 TestCaseNameIs(test_case_name
));
5666 if (test_case
!= test_cases_
.end())
5669 // No. Let's create one.
5670 TestCase
* const new_test_case
=
5671 new TestCase(test_case_name
, type_param
, set_up_tc
, tear_down_tc
);
5673 // Is this a death test case?
5674 if (internal::UnitTestOptions::MatchesFilter(test_case_name
,
5675 kDeathTestCaseFilter
)) {
5676 // Yes. Inserts the test case after the last death test case
5677 // defined so far. This only works when the test cases haven't
5678 // been shuffled. Otherwise we may end up running a death test
5679 // after a non-death test.
5680 ++last_death_test_case_
;
5681 test_cases_
.insert(test_cases_
.begin() + last_death_test_case_
,
5684 // No. Appends to the end of the list.
5685 test_cases_
.push_back(new_test_case
);
5688 test_case_indices_
.push_back(static_cast<int>(test_case_indices_
.size()));
5689 return new_test_case
;
5692 // Helpers for setting up / tearing down the given environment. They
5693 // are for use in the ForEach() function.
5694 static void SetUpEnvironment(Environment
* env
) { env
->SetUp(); }
5695 static void TearDownEnvironment(Environment
* env
) { env
->TearDown(); }
5697 // Runs all tests in this UnitTest object, prints the result, and
5698 // returns true if all tests are successful. If any exception is
5699 // thrown during a test, the test is considered to be failed, but the
5700 // rest of the tests will still be run.
5702 // When parameterized tests are enabled, it expands and registers
5703 // parameterized tests first in RegisterParameterizedTests().
5704 // All other functions called from RunAllTests() may safely assume that
5705 // parameterized tests are ready to be counted and run.
5706 bool UnitTestImpl::RunAllTests() {
5707 // Makes sure InitGoogleTest() was called.
5708 if (!GTestIsInitialized()) {
5710 "\nThis test program did NOT call ::testing::InitGoogleTest "
5711 "before calling RUN_ALL_TESTS(). Please fix it.\n");
5715 // Do not run any test if the --help flag was specified.
5719 // Repeats the call to the post-flag parsing initialization in case the
5720 // user didn't call InitGoogleTest.
5721 PostFlagParsingInit();
5723 // Even if sharding is not on, test runners may want to use the
5724 // GTEST_SHARD_STATUS_FILE to query whether the test supports the sharding
5726 internal::WriteToShardStatusFileIfNeeded();
5728 // True iff we are in a subprocess for running a thread-safe-style
5730 bool in_subprocess_for_death_test
= false;
5732 #if GTEST_HAS_DEATH_TEST
5733 in_subprocess_for_death_test
= (internal_run_death_test_flag_
.get() != NULL
);
5734 #endif // GTEST_HAS_DEATH_TEST
5736 const bool should_shard
= ShouldShard(kTestTotalShards
, kTestShardIndex
,
5737 in_subprocess_for_death_test
);
5739 // Compares the full test names with the filter to decide which
5741 const bool has_tests_to_run
= FilterTests(should_shard
5742 ? HONOR_SHARDING_PROTOCOL
5743 : IGNORE_SHARDING_PROTOCOL
) > 0;
5745 // Lists the tests and exits if the --gtest_list_tests flag was specified.
5746 if (GTEST_FLAG(list_tests
)) {
5747 // This must be called *after* FilterTests() has been called.
5748 ListTestsMatchingFilter();
5752 random_seed_
= GTEST_FLAG(shuffle
) ?
5753 GetRandomSeedFromFlag(GTEST_FLAG(random_seed
)) : 0;
5755 // True iff at least one test has failed.
5756 bool failed
= false;
5758 TestEventListener
* repeater
= listeners()->repeater();
5760 start_timestamp_
= GetTimeInMillis();
5761 repeater
->OnTestProgramStart(*parent_
);
5763 // How many times to repeat the tests? We don't want to repeat them
5764 // when we are inside the subprocess of a death test.
5765 const int repeat
= in_subprocess_for_death_test
? 1 : GTEST_FLAG(repeat
);
5766 // Repeats forever if the repeat count is negative.
5767 const bool forever
= repeat
< 0;
5768 for (int i
= 0; forever
|| i
!= repeat
; i
++) {
5769 // We want to preserve failures generated by ad-hoc test
5770 // assertions executed before RUN_ALL_TESTS().
5771 ClearNonAdHocTestResult();
5773 const TimeInMillis start
= GetTimeInMillis();
5775 // Shuffles test cases and tests if requested.
5776 if (has_tests_to_run
&& GTEST_FLAG(shuffle
)) {
5777 random()->Reseed(random_seed_
);
5778 // This should be done before calling OnTestIterationStart(),
5779 // such that a test event listener can see the actual test order
5784 // Tells the unit test event listeners that the tests are about to start.
5785 repeater
->OnTestIterationStart(*parent_
, i
);
5787 // Runs each test case if there is at least one test to run.
5788 if (has_tests_to_run
) {
5789 // Sets up all environments beforehand.
5790 repeater
->OnEnvironmentsSetUpStart(*parent_
);
5791 ForEach(environments_
, SetUpEnvironment
);
5792 repeater
->OnEnvironmentsSetUpEnd(*parent_
);
5794 // Runs the tests only if there was no fatal failure during global
5796 if (!Test::HasFatalFailure()) {
5797 for (int test_index
= 0; test_index
< total_test_case_count();
5799 GetMutableTestCase(test_index
)->Run();
5803 // Tears down all environments in reverse order afterwards.
5804 repeater
->OnEnvironmentsTearDownStart(*parent_
);
5805 std::for_each(environments_
.rbegin(), environments_
.rend(),
5806 TearDownEnvironment
);
5807 repeater
->OnEnvironmentsTearDownEnd(*parent_
);
5810 elapsed_time_
= GetTimeInMillis() - start
;
5812 // Tells the unit test event listener that the tests have just finished.
5813 repeater
->OnTestIterationEnd(*parent_
, i
);
5815 // Gets the result and clears it.
5820 // Restores the original test order after the iteration. This
5821 // allows the user to quickly repro a failure that happens in the
5822 // N-th iteration without repeating the first (N - 1) iterations.
5823 // This is not enclosed in "if (GTEST_FLAG(shuffle)) { ... }", in
5824 // case the user somehow changes the value of the flag somewhere
5825 // (it's always safe to unshuffle the tests).
5828 if (GTEST_FLAG(shuffle
)) {
5829 // Picks a new random seed for each iteration.
5830 random_seed_
= GetNextRandomSeed(random_seed_
);
5834 repeater
->OnTestProgramEnd(*parent_
);
5839 // Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
5840 // if the variable is present. If a file already exists at this location, this
5841 // function will write over it. If the variable is present, but the file cannot
5842 // be created, prints an error and exits.
5843 void WriteToShardStatusFileIfNeeded() {
5844 const char* const test_shard_file
= posix::GetEnv(kTestShardStatusFile
);
5845 if (test_shard_file
!= NULL
) {
5846 FILE* const file
= posix::FOpen(test_shard_file
, "w");
5848 ColoredPrintf(COLOR_RED
,
5849 "Could not write to the test shard status file \"%s\" "
5850 "specified by the %s environment variable.\n",
5851 test_shard_file
, kTestShardStatusFile
);
5859 // Checks whether sharding is enabled by examining the relevant
5860 // environment variable values. If the variables are present,
5861 // but inconsistent (i.e., shard_index >= total_shards), prints
5862 // an error and exits. If in_subprocess_for_death_test, sharding is
5863 // disabled because it must only be applied to the original test
5864 // process. Otherwise, we could filter out death tests we intended to execute.
5865 bool ShouldShard(const char* total_shards_env
,
5866 const char* shard_index_env
,
5867 bool in_subprocess_for_death_test
) {
5868 if (in_subprocess_for_death_test
) {
5872 const Int32 total_shards
= Int32FromEnvOrDie(total_shards_env
, -1);
5873 const Int32 shard_index
= Int32FromEnvOrDie(shard_index_env
, -1);
5875 if (total_shards
== -1 && shard_index
== -1) {
5877 } else if (total_shards
== -1 && shard_index
!= -1) {
5878 const Message msg
= Message()
5879 << "Invalid environment variables: you have "
5880 << kTestShardIndex
<< " = " << shard_index
5881 << ", but have left " << kTestTotalShards
<< " unset.\n";
5882 ColoredPrintf(COLOR_RED
, msg
.GetString().c_str());
5885 } else if (total_shards
!= -1 && shard_index
== -1) {
5886 const Message msg
= Message()
5887 << "Invalid environment variables: you have "
5888 << kTestTotalShards
<< " = " << total_shards
5889 << ", but have left " << kTestShardIndex
<< " unset.\n";
5890 ColoredPrintf(COLOR_RED
, msg
.GetString().c_str());
5893 } else if (shard_index
< 0 || shard_index
>= total_shards
) {
5894 const Message msg
= Message()
5895 << "Invalid environment variables: we require 0 <= "
5896 << kTestShardIndex
<< " < " << kTestTotalShards
5897 << ", but you have " << kTestShardIndex
<< "=" << shard_index
5898 << ", " << kTestTotalShards
<< "=" << total_shards
<< ".\n";
5899 ColoredPrintf(COLOR_RED
, msg
.GetString().c_str());
5904 return total_shards
> 1;
5907 // Parses the environment variable var as an Int32. If it is unset,
5908 // returns default_val. If it is not an Int32, prints an error
5910 Int32
Int32FromEnvOrDie(const char* var
, Int32 default_val
) {
5911 const char* str_val
= posix::GetEnv(var
);
5912 if (str_val
== NULL
) {
5917 if (!ParseInt32(Message() << "The value of environment variable " << var
,
5918 str_val
, &result
)) {
5924 // Given the total number of shards, the shard index, and the test id,
5925 // returns true iff the test should be run on this shard. The test id is
5926 // some arbitrary but unique non-negative integer assigned to each test
5927 // method. Assumes that 0 <= shard_index < total_shards.
5928 bool ShouldRunTestOnShard(int total_shards
, int shard_index
, int test_id
) {
5929 return (test_id
% total_shards
) == shard_index
;
5932 // Compares the name of each test with the user-specified filter to
5933 // decide whether the test should be run, then records the result in
5934 // each TestCase and TestInfo object.
5935 // If shard_tests == true, further filters tests based on sharding
5936 // variables in the environment - see
5937 // http://code.google.com/p/googletest/wiki/GoogleTestAdvancedGuide.
5938 // Returns the number of tests that should run.
5939 int UnitTestImpl::FilterTests(ReactionToSharding shard_tests
) {
5940 const Int32 total_shards
= shard_tests
== HONOR_SHARDING_PROTOCOL
?
5941 Int32FromEnvOrDie(kTestTotalShards
, -1) : -1;
5942 const Int32 shard_index
= shard_tests
== HONOR_SHARDING_PROTOCOL
?
5943 Int32FromEnvOrDie(kTestShardIndex
, -1) : -1;
5945 // num_runnable_tests are the number of tests that will
5946 // run across all shards (i.e., match filter and are not disabled).
5947 // num_selected_tests are the number of tests to be run on
5949 int num_runnable_tests
= 0;
5950 int num_selected_tests
= 0;
5951 for (size_t i
= 0; i
< test_cases_
.size(); i
++) {
5952 TestCase
* const test_case
= test_cases_
[i
];
5953 const std::string
&test_case_name
= test_case
->name();
5954 test_case
->set_should_run(false);
5956 for (size_t j
= 0; j
< test_case
->test_info_list().size(); j
++) {
5957 TestInfo
* const test_info
= test_case
->test_info_list()[j
];
5958 const std::string
test_name(test_info
->name());
5959 // A test is disabled if test case name or test name matches
5960 // kDisableTestFilter.
5961 const bool is_disabled
=
5962 internal::UnitTestOptions::MatchesFilter(test_case_name
,
5963 kDisableTestFilter
) ||
5964 internal::UnitTestOptions::MatchesFilter(test_name
,
5965 kDisableTestFilter
);
5966 test_info
->is_disabled_
= is_disabled
;
5968 const bool matches_filter
=
5969 internal::UnitTestOptions::FilterMatchesTest(test_case_name
,
5971 test_info
->matches_filter_
= matches_filter
;
5973 const bool is_runnable
=
5974 (GTEST_FLAG(also_run_disabled_tests
) || !is_disabled
) &&
5977 const bool is_selected
= is_runnable
&&
5978 (shard_tests
== IGNORE_SHARDING_PROTOCOL
||
5979 ShouldRunTestOnShard(total_shards
, shard_index
,
5980 num_runnable_tests
));
5982 num_runnable_tests
+= is_runnable
;
5983 num_selected_tests
+= is_selected
;
5985 test_info
->should_run_
= is_selected
;
5986 test_case
->set_should_run(test_case
->should_run() || is_selected
);
5989 return num_selected_tests
;
5992 // Prints the given C-string on a single line by replacing all '\n'
5993 // characters with string "\\n". If the output takes more than
5994 // max_length characters, only prints the first max_length characters
5996 static void PrintOnOneLine(const char* str
, int max_length
) {
5998 for (int i
= 0; *str
!= '\0'; ++str
) {
5999 if (i
>= max_length
) {
6014 // Prints the names of the tests matching the user-specified filter flag.
6015 void UnitTestImpl::ListTestsMatchingFilter() {
6016 // Print at most this many characters for each type/value parameter.
6017 const int kMaxParamLength
= 250;
6019 for (size_t i
= 0; i
< test_cases_
.size(); i
++) {
6020 const TestCase
* const test_case
= test_cases_
[i
];
6021 bool printed_test_case_name
= false;
6023 for (size_t j
= 0; j
< test_case
->test_info_list().size(); j
++) {
6024 const TestInfo
* const test_info
=
6025 test_case
->test_info_list()[j
];
6026 if (test_info
->matches_filter_
) {
6027 if (!printed_test_case_name
) {
6028 printed_test_case_name
= true;
6029 printf("%s.", test_case
->name());
6030 if (test_case
->type_param() != NULL
) {
6031 printf(" # %s = ", kTypeParamLabel
);
6032 // We print the type parameter on a single line to make
6033 // the output easy to parse by a program.
6034 PrintOnOneLine(test_case
->type_param(), kMaxParamLength
);
6038 printf(" %s", test_info
->name());
6039 if (test_info
->value_param() != NULL
) {
6040 printf(" # %s = ", kValueParamLabel
);
6041 // We print the value parameter on a single line to make the
6042 // output easy to parse by a program.
6043 PrintOnOneLine(test_info
->value_param(), kMaxParamLength
);
6052 // Sets the OS stack trace getter.
6054 // Does nothing if the input and the current OS stack trace getter are
6055 // the same; otherwise, deletes the old getter and makes the input the
6057 void UnitTestImpl::set_os_stack_trace_getter(
6058 OsStackTraceGetterInterface
* getter
) {
6059 if (os_stack_trace_getter_
!= getter
) {
6060 delete os_stack_trace_getter_
;
6061 os_stack_trace_getter_
= getter
;
6065 // Returns the current OS stack trace getter if it is not NULL;
6066 // otherwise, creates an OsStackTraceGetter, makes it the current
6067 // getter, and returns it.
6068 OsStackTraceGetterInterface
* UnitTestImpl::os_stack_trace_getter() {
6069 if (os_stack_trace_getter_
== NULL
) {
6070 os_stack_trace_getter_
= new OsStackTraceGetter
;
6073 return os_stack_trace_getter_
;
6076 // Returns the TestResult for the test that's currently running, or
6077 // the TestResult for the ad hoc test if no test is running.
6078 TestResult
* UnitTestImpl::current_test_result() {
6079 return current_test_info_
?
6080 &(current_test_info_
->result_
) : &ad_hoc_test_result_
;
6083 // Shuffles all test cases, and the tests within each test case,
6084 // making sure that death tests are still run first.
6085 void UnitTestImpl::ShuffleTests() {
6086 // Shuffles the death test cases.
6087 ShuffleRange(random(), 0, last_death_test_case_
+ 1, &test_case_indices_
);
6089 // Shuffles the non-death test cases.
6090 ShuffleRange(random(), last_death_test_case_
+ 1,
6091 static_cast<int>(test_cases_
.size()), &test_case_indices_
);
6093 // Shuffles the tests inside each test case.
6094 for (size_t i
= 0; i
< test_cases_
.size(); i
++) {
6095 test_cases_
[i
]->ShuffleTests(random());
6099 // Restores the test cases and tests to their order before the first shuffle.
6100 void UnitTestImpl::UnshuffleTests() {
6101 for (size_t i
= 0; i
< test_cases_
.size(); i
++) {
6102 // Unshuffles the tests in each test case.
6103 test_cases_
[i
]->UnshuffleTests();
6104 // Resets the index of each test case.
6105 test_case_indices_
[i
] = static_cast<int>(i
);
6109 // Returns the current OS stack trace as an std::string.
6111 // The maximum number of stack frames to be included is specified by
6112 // the gtest_stack_trace_depth flag. The skip_count parameter
6113 // specifies the number of top frames to be skipped, which doesn't
6114 // count against the number of frames to be included.
6116 // For example, if Foo() calls Bar(), which in turn calls
6117 // GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in
6118 // the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.
6119 std::string
GetCurrentOsStackTraceExceptTop(UnitTest
* /*unit_test*/,
6121 // We pass skip_count + 1 to skip this wrapper function in addition
6122 // to what the user really wants to skip.
6123 return GetUnitTestImpl()->CurrentOsStackTraceExceptTop(skip_count
+ 1);
6126 // Used by the GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_ macro to
6127 // suppress unreachable code warnings.
6129 class ClassUniqueToAlwaysTrue
{};
6132 bool IsTrue(bool condition
) { return condition
; }
6135 #if GTEST_HAS_EXCEPTIONS
6136 // This condition is always false so AlwaysTrue() never actually throws,
6137 // but it makes the compiler think that it may throw.
6139 throw ClassUniqueToAlwaysTrue();
6140 #endif // GTEST_HAS_EXCEPTIONS
6144 // If *pstr starts with the given prefix, modifies *pstr to be right
6145 // past the prefix and returns true; otherwise leaves *pstr unchanged
6146 // and returns false. None of pstr, *pstr, and prefix can be NULL.
6147 bool SkipPrefix(const char* prefix
, const char** pstr
) {
6148 const size_t prefix_len
= strlen(prefix
);
6149 if (strncmp(*pstr
, prefix
, prefix_len
) == 0) {
6150 *pstr
+= prefix_len
;
6156 // Parses a string as a command line flag. The string should have
6157 // the format "--flag=value". When def_optional is true, the "=value"
6158 // part can be omitted.
6160 // Returns the value of the flag, or NULL if the parsing failed.
6161 const char* ParseFlagValue(const char* str
,
6163 bool def_optional
) {
6164 // str and flag must not be NULL.
6165 if (str
== NULL
|| flag
== NULL
) return NULL
;
6167 // The flag must start with "--" followed by GTEST_FLAG_PREFIX_.
6168 const std::string flag_str
= std::string("--") + GTEST_FLAG_PREFIX_
+ flag
;
6169 const size_t flag_len
= flag_str
.length();
6170 if (strncmp(str
, flag_str
.c_str(), flag_len
) != 0) return NULL
;
6172 // Skips the flag name.
6173 const char* flag_end
= str
+ flag_len
;
6175 // When def_optional is true, it's OK to not have a "=value" part.
6176 if (def_optional
&& (flag_end
[0] == '\0')) {
6180 // If def_optional is true and there are more characters after the
6181 // flag name, or if def_optional is false, there must be a '=' after
6183 if (flag_end
[0] != '=') return NULL
;
6185 // Returns the string after "=".
6186 return flag_end
+ 1;
6189 // Parses a string for a bool flag, in the form of either
6190 // "--flag=value" or "--flag".
6192 // In the former case, the value is taken as true as long as it does
6193 // not start with '0', 'f', or 'F'.
6195 // In the latter case, the value is taken as true.
6197 // On success, stores the value of the flag in *value, and returns
6198 // true. On failure, returns false without changing *value.
6199 bool ParseBoolFlag(const char* str
, const char* flag
, bool* value
) {
6200 // Gets the value of the flag as a string.
6201 const char* const value_str
= ParseFlagValue(str
, flag
, true);
6203 // Aborts if the parsing failed.
6204 if (value_str
== NULL
) return false;
6206 // Converts the string value to a bool.
6207 *value
= !(*value_str
== '0' || *value_str
== 'f' || *value_str
== 'F');
6211 // Parses a string for an Int32 flag, in the form of
6214 // On success, stores the value of the flag in *value, and returns
6215 // true. On failure, returns false without changing *value.
6216 bool ParseInt32Flag(const char* str
, const char* flag
, Int32
* value
) {
6217 // Gets the value of the flag as a string.
6218 const char* const value_str
= ParseFlagValue(str
, flag
, false);
6220 // Aborts if the parsing failed.
6221 if (value_str
== NULL
) return false;
6223 // Sets *value to the value of the flag.
6224 return ParseInt32(Message() << "The value of flag --" << flag
,
6228 // Parses a string for a string flag, in the form of
6231 // On success, stores the value of the flag in *value, and returns
6232 // true. On failure, returns false without changing *value.
6233 bool ParseStringFlag(const char* str
, const char* flag
, std::string
* value
) {
6234 // Gets the value of the flag as a string.
6235 const char* const value_str
= ParseFlagValue(str
, flag
, false);
6237 // Aborts if the parsing failed.
6238 if (value_str
== NULL
) return false;
6240 // Sets *value to the value of the flag.
6245 // Determines whether a string has a prefix that Google Test uses for its
6246 // flags, i.e., starts with GTEST_FLAG_PREFIX_ or GTEST_FLAG_PREFIX_DASH_.
6247 // If Google Test detects that a command line flag has its prefix but is not
6248 // recognized, it will print its help message. Flags starting with
6249 // GTEST_INTERNAL_PREFIX_ followed by "internal_" are considered Google Test
6250 // internal flags and do not trigger the help message.
6251 static bool HasGoogleTestFlagPrefix(const char* str
) {
6252 return (SkipPrefix("--", &str
) ||
6253 SkipPrefix("-", &str
) ||
6254 SkipPrefix("/", &str
)) &&
6255 !SkipPrefix(GTEST_FLAG_PREFIX_
"internal_", &str
) &&
6256 (SkipPrefix(GTEST_FLAG_PREFIX_
, &str
) ||
6257 SkipPrefix(GTEST_FLAG_PREFIX_DASH_
, &str
));
6260 // Prints a string containing code-encoded text. The following escape
6261 // sequences can be used in the string to control the text color:
6263 // @@ prints a single '@' character.
6264 // @R changes the color to red.
6265 // @G changes the color to green.
6266 // @Y changes the color to yellow.
6267 // @D changes to the default terminal text color.
6269 // TODO(wan@google.com): Write tests for this once we add stdout
6270 // capturing to Google Test.
6271 static void PrintColorEncoded(const char* str
) {
6272 GTestColor color
= COLOR_DEFAULT
; // The current color.
6274 // Conceptually, we split the string into segments divided by escape
6275 // sequences. Then we print one segment at a time. At the end of
6276 // each iteration, the str pointer advances to the beginning of the
6279 const char* p
= strchr(str
, '@');
6281 ColoredPrintf(color
, "%s", str
);
6285 ColoredPrintf(color
, "%s", std::string(str
, p
).c_str());
6287 const char ch
= p
[1];
6290 ColoredPrintf(color
, "@");
6291 } else if (ch
== 'D') {
6292 color
= COLOR_DEFAULT
;
6293 } else if (ch
== 'R') {
6295 } else if (ch
== 'G') {
6296 color
= COLOR_GREEN
;
6297 } else if (ch
== 'Y') {
6298 color
= COLOR_YELLOW
;
6305 static const char kColorEncodedHelpMessage
[] =
6306 "This program contains tests written using " GTEST_NAME_
". You can use the\n"
6307 "following command line flags to control its behavior:\n"
6310 " @G--" GTEST_FLAG_PREFIX_
"list_tests@D\n"
6311 " List the names of all tests instead of running them. The name of\n"
6312 " TEST(Foo, Bar) is \"Foo.Bar\".\n"
6313 " @G--" GTEST_FLAG_PREFIX_
"filter=@YPOSTIVE_PATTERNS"
6314 "[@G-@YNEGATIVE_PATTERNS]@D\n"
6315 " Run only the tests whose name matches one of the positive patterns but\n"
6316 " none of the negative patterns. '?' matches any single character; '*'\n"
6317 " matches any substring; ':' separates two patterns.\n"
6318 " @G--" GTEST_FLAG_PREFIX_
"also_run_disabled_tests@D\n"
6319 " Run all disabled tests too.\n"
6322 " @G--" GTEST_FLAG_PREFIX_
"repeat=@Y[COUNT]@D\n"
6323 " Run the tests repeatedly; use a negative count to repeat forever.\n"
6324 " @G--" GTEST_FLAG_PREFIX_
"shuffle@D\n"
6325 " Randomize tests' orders on every iteration.\n"
6326 " @G--" GTEST_FLAG_PREFIX_
"random_seed=@Y[NUMBER]@D\n"
6327 " Random number seed to use for shuffling test orders (between 1 and\n"
6328 " 99999, or 0 to use a seed based on the current time).\n"
6331 " @G--" GTEST_FLAG_PREFIX_
"color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\n"
6332 " Enable/disable colored output. The default is @Gauto@D.\n"
6333 " -@G-" GTEST_FLAG_PREFIX_
"print_time=0@D\n"
6334 " Don't print the elapsed time of each test.\n"
6335 " @G--" GTEST_FLAG_PREFIX_
"output=xml@Y[@G:@YDIRECTORY_PATH@G"
6336 GTEST_PATH_SEP_
"@Y|@G:@YFILE_PATH]@D\n"
6337 " Generate an XML report in the given directory or with the given file\n"
6338 " name. @YFILE_PATH@D defaults to @Gtest_details.xml@D.\n"
6339 #if GTEST_CAN_STREAM_RESULTS_
6340 " @G--" GTEST_FLAG_PREFIX_
"stream_result_to=@YHOST@G:@YPORT@D\n"
6341 " Stream test results to the given server.\n"
6342 #endif // GTEST_CAN_STREAM_RESULTS_
6344 "Assertion Behavior:\n"
6345 #if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
6346 " @G--" GTEST_FLAG_PREFIX_
"death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n"
6347 " Set the default death test style.\n"
6348 #endif // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
6349 " @G--" GTEST_FLAG_PREFIX_
"break_on_failure@D\n"
6350 " Turn assertion failures into debugger break-points.\n"
6351 " @G--" GTEST_FLAG_PREFIX_
"throw_on_failure@D\n"
6352 " Turn assertion failures into C++ exceptions.\n"
6353 " @G--" GTEST_FLAG_PREFIX_
"catch_exceptions=0@D\n"
6354 " Do not report exceptions as test failures. Instead, allow them\n"
6355 " to crash the program or throw a pop-up (on Windows).\n"
6357 "Except for @G--" GTEST_FLAG_PREFIX_
"list_tests@D, you can alternatively set "
6358 "the corresponding\n"
6359 "environment variable of a flag (all letters in upper-case). For example, to\n"
6360 "disable colored text output, you can either specify @G--" GTEST_FLAG_PREFIX_
6361 "color=no@D or set\n"
6362 "the @G" GTEST_FLAG_PREFIX_UPPER_
"COLOR@D environment variable to @Gno@D.\n"
6364 "For more information, please read the " GTEST_NAME_
" documentation at\n"
6365 "@G" GTEST_PROJECT_URL_
"@D. If you find a bug in " GTEST_NAME_
"\n"
6366 "(not one in your own code or tests), please report it to\n"
6367 "@G<" GTEST_DEV_EMAIL_
">@D.\n";
6369 // Parses the command line for Google Test flags, without initializing
6370 // other parts of Google Test. The type parameter CharType can be
6371 // instantiated to either char or wchar_t.
6372 template <typename CharType
>
6373 void ParseGoogleTestFlagsOnlyImpl(int* argc
, CharType
** argv
) {
6374 for (int i
= 1; i
< *argc
; i
++) {
6375 const std::string arg_string
= StreamableToString(argv
[i
]);
6376 const char* const arg
= arg_string
.c_str();
6378 using internal::ParseBoolFlag
;
6379 using internal::ParseInt32Flag
;
6380 using internal::ParseStringFlag
;
6382 // Do we see a Google Test flag?
6383 if (ParseBoolFlag(arg
, kAlsoRunDisabledTestsFlag
,
6384 >EST_FLAG(also_run_disabled_tests
)) ||
6385 ParseBoolFlag(arg
, kBreakOnFailureFlag
,
6386 >EST_FLAG(break_on_failure
)) ||
6387 ParseBoolFlag(arg
, kCatchExceptionsFlag
,
6388 >EST_FLAG(catch_exceptions
)) ||
6389 ParseStringFlag(arg
, kColorFlag
, >EST_FLAG(color
)) ||
6390 ParseStringFlag(arg
, kDeathTestStyleFlag
,
6391 >EST_FLAG(death_test_style
)) ||
6392 ParseBoolFlag(arg
, kDeathTestUseFork
,
6393 >EST_FLAG(death_test_use_fork
)) ||
6394 ParseStringFlag(arg
, kFilterFlag
, >EST_FLAG(filter
)) ||
6395 ParseStringFlag(arg
, kInternalRunDeathTestFlag
,
6396 >EST_FLAG(internal_run_death_test
)) ||
6397 ParseBoolFlag(arg
, kListTestsFlag
, >EST_FLAG(list_tests
)) ||
6398 ParseStringFlag(arg
, kOutputFlag
, >EST_FLAG(output
)) ||
6399 ParseBoolFlag(arg
, kPrintTimeFlag
, >EST_FLAG(print_time
)) ||
6400 ParseInt32Flag(arg
, kRandomSeedFlag
, >EST_FLAG(random_seed
)) ||
6401 ParseInt32Flag(arg
, kRepeatFlag
, >EST_FLAG(repeat
)) ||
6402 ParseBoolFlag(arg
, kShuffleFlag
, >EST_FLAG(shuffle
)) ||
6403 ParseInt32Flag(arg
, kStackTraceDepthFlag
,
6404 >EST_FLAG(stack_trace_depth
)) ||
6405 ParseStringFlag(arg
, kStreamResultToFlag
,
6406 >EST_FLAG(stream_result_to
)) ||
6407 ParseBoolFlag(arg
, kThrowOnFailureFlag
,
6408 >EST_FLAG(throw_on_failure
))
6410 // Yes. Shift the remainder of the argv list left by one. Note
6411 // that argv has (*argc + 1) elements, the last one always being
6412 // NULL. The following loop moves the trailing NULL element as
6414 for (int j
= i
; j
!= *argc
; j
++) {
6415 argv
[j
] = argv
[j
+ 1];
6418 // Decrements the argument count.
6421 // We also need to decrement the iterator as we just removed
6424 } else if (arg_string
== "--help" || arg_string
== "-h" ||
6425 arg_string
== "-?" || arg_string
== "/?" ||
6426 HasGoogleTestFlagPrefix(arg
)) {
6427 // Both help flag and unrecognized Google Test flags (excluding
6428 // internal ones) trigger help display.
6434 // We print the help here instead of in RUN_ALL_TESTS(), as the
6435 // latter may not be called at all if the user is using Google
6436 // Test with another testing framework.
6437 PrintColorEncoded(kColorEncodedHelpMessage
);
6441 // Parses the command line for Google Test flags, without initializing
6442 // other parts of Google Test.
6443 void ParseGoogleTestFlagsOnly(int* argc
, char** argv
) {
6444 ParseGoogleTestFlagsOnlyImpl(argc
, argv
);
6446 void ParseGoogleTestFlagsOnly(int* argc
, wchar_t** argv
) {
6447 ParseGoogleTestFlagsOnlyImpl(argc
, argv
);
6450 // The internal implementation of InitGoogleTest().
6452 // The type parameter CharType can be instantiated to either char or
6454 template <typename CharType
>
6455 void InitGoogleTestImpl(int* argc
, CharType
** argv
) {
6456 g_init_gtest_count
++;
6458 // We don't want to run the initialization code twice.
6459 if (g_init_gtest_count
!= 1) return;
6461 if (*argc
<= 0) return;
6463 internal::g_executable_path
= internal::StreamableToString(argv
[0]);
6465 #if GTEST_HAS_DEATH_TEST
6468 for (int i
= 0; i
!= *argc
; i
++) {
6469 g_argvs
.push_back(StreamableToString(argv
[i
]));
6472 #endif // GTEST_HAS_DEATH_TEST
6474 ParseGoogleTestFlagsOnly(argc
, argv
);
6475 GetUnitTestImpl()->PostFlagParsingInit();
6478 } // namespace internal
6480 // Initializes Google Test. This must be called before calling
6481 // RUN_ALL_TESTS(). In particular, it parses a command line for the
6482 // flags that Google Test recognizes. Whenever a Google Test flag is
6483 // seen, it is removed from argv, and *argc is decremented.
6485 // No value is returned. Instead, the Google Test flag variables are
6488 // Calling the function for the second time has no user-visible effect.
6489 void InitGoogleTest(int* argc
, char** argv
) {
6490 internal::InitGoogleTestImpl(argc
, argv
);
6493 // This overloaded version can be used in Windows programs compiled in
6495 void InitGoogleTest(int* argc
, wchar_t** argv
) {
6496 internal::InitGoogleTestImpl(argc
, argv
);
6499 } // namespace testing
6500 // Copyright 2005, Google Inc.
6501 // All rights reserved.
6503 // Redistribution and use in source and binary forms, with or without
6504 // modification, are permitted provided that the following conditions are
6507 // * Redistributions of source code must retain the above copyright
6508 // notice, this list of conditions and the following disclaimer.
6509 // * Redistributions in binary form must reproduce the above
6510 // copyright notice, this list of conditions and the following disclaimer
6511 // in the documentation and/or other materials provided with the
6513 // * Neither the name of Google Inc. nor the names of its
6514 // contributors may be used to endorse or promote products derived from
6515 // this software without specific prior written permission.
6517 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
6518 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
6519 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
6520 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
6521 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
6522 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
6523 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
6524 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
6525 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
6526 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
6527 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
6529 // Author: wan@google.com (Zhanyong Wan), vladl@google.com (Vlad Losev)
6531 // This file implements death tests.
6534 #if GTEST_HAS_DEATH_TEST
6537 # include <crt_externs.h>
6538 # endif // GTEST_OS_MAC
6542 # include <limits.h>
6545 # include <signal.h>
6546 # endif // GTEST_OS_LINUX
6548 # include <stdarg.h>
6550 # if GTEST_OS_WINDOWS
6551 # include <windows.h>
6553 # include <sys/mman.h>
6554 # include <sys/wait.h>
6555 # endif // GTEST_OS_WINDOWS
6559 # endif // GTEST_OS_QNX
6561 #endif // GTEST_HAS_DEATH_TEST
6564 // Indicates that this translation unit is part of Google Test's
6565 // implementation. It must come before gtest-internal-inl.h is
6566 // included, or there will be a compiler error. This trick is to
6567 // prevent a user from accidentally including gtest-internal-inl.h in
6569 #define GTEST_IMPLEMENTATION_ 1
6570 #undef GTEST_IMPLEMENTATION_
6576 // The default death test style.
6577 static const char kDefaultDeathTestStyle
[] = "fast";
6579 GTEST_DEFINE_string_(
6581 internal::StringFromGTestEnv("death_test_style", kDefaultDeathTestStyle
),
6582 "Indicates how to run a death test in a forked child process: "
6583 "\"threadsafe\" (child process re-executes the test binary "
6584 "from the beginning, running only the specific death test) or "
6585 "\"fast\" (child process runs the death test immediately "
6589 death_test_use_fork
,
6590 internal::BoolFromGTestEnv("death_test_use_fork", false),
6591 "Instructs to use fork()/_exit() instead of clone() in death tests. "
6592 "Ignored and always uses fork() on POSIX systems where clone() is not "
6593 "implemented. Useful when running under valgrind or similar tools if "
6594 "those do not support clone(). Valgrind 3.3.1 will just fail if "
6595 "it sees an unsupported combination of clone() flags. "
6596 "It is not recommended to use this flag w/o valgrind though it will "
6597 "work in 99% of the cases. Once valgrind is fixed, this flag will "
6598 "most likely be removed.");
6600 namespace internal
{
6601 GTEST_DEFINE_string_(
6602 internal_run_death_test
, "",
6603 "Indicates the file, line number, temporal index of "
6604 "the single death test to run, and a file descriptor to "
6605 "which a success code may be sent, all separated by "
6606 "the '|' characters. This flag is specified if and only if the current "
6607 "process is a sub-process launched for running a thread-safe "
6608 "death test. FOR INTERNAL USE ONLY.");
6609 } // namespace internal
6611 #if GTEST_HAS_DEATH_TEST
6613 namespace internal
{
6615 // Valid only for fast death tests. Indicates the code is running in the
6616 // child process of a fast style death test.
6617 static bool g_in_fast_death_test_child
= false;
6619 // Returns a Boolean value indicating whether the caller is currently
6620 // executing in the context of the death test child process. Tools such as
6621 // Valgrind heap checkers may need this to modify their behavior in death
6622 // tests. IMPORTANT: This is an internal utility. Using it may break the
6623 // implementation of death tests. User code MUST NOT use it.
6624 bool InDeathTestChild() {
6625 # if GTEST_OS_WINDOWS
6627 // On Windows, death tests are thread-safe regardless of the value of the
6628 // death_test_style flag.
6629 return !GTEST_FLAG(internal_run_death_test
).empty();
6633 if (GTEST_FLAG(death_test_style
) == "threadsafe")
6634 return !GTEST_FLAG(internal_run_death_test
).empty();
6636 return g_in_fast_death_test_child
;
6640 } // namespace internal
6642 // ExitedWithCode constructor.
6643 ExitedWithCode::ExitedWithCode(int exit_code
) : exit_code_(exit_code
) {
6646 // ExitedWithCode function-call operator.
6647 bool ExitedWithCode::operator()(int exit_status
) const {
6648 # if GTEST_OS_WINDOWS
6650 return exit_status
== exit_code_
;
6654 return WIFEXITED(exit_status
) && WEXITSTATUS(exit_status
) == exit_code_
;
6656 # endif // GTEST_OS_WINDOWS
6659 # if !GTEST_OS_WINDOWS
6660 // KilledBySignal constructor.
6661 KilledBySignal::KilledBySignal(int signum
) : signum_(signum
) {
6664 // KilledBySignal function-call operator.
6665 bool KilledBySignal::operator()(int exit_status
) const {
6666 return WIFSIGNALED(exit_status
) && WTERMSIG(exit_status
) == signum_
;
6668 # endif // !GTEST_OS_WINDOWS
6670 namespace internal
{
6672 // Utilities needed for death tests.
6674 // Generates a textual description of a given exit code, in the format
6675 // specified by wait(2).
6676 static std::string
ExitSummary(int exit_code
) {
6679 # if GTEST_OS_WINDOWS
6681 m
<< "Exited with exit status " << exit_code
;
6685 if (WIFEXITED(exit_code
)) {
6686 m
<< "Exited with exit status " << WEXITSTATUS(exit_code
);
6687 } else if (WIFSIGNALED(exit_code
)) {
6688 m
<< "Terminated by signal " << WTERMSIG(exit_code
);
6691 if (WCOREDUMP(exit_code
)) {
6692 m
<< " (core dumped)";
6695 # endif // GTEST_OS_WINDOWS
6697 return m
.GetString();
6700 // Returns true if exit_status describes a process that was terminated
6701 // by a signal, or exited normally with a nonzero exit code.
6702 bool ExitedUnsuccessfully(int exit_status
) {
6703 return !ExitedWithCode(0)(exit_status
);
6706 # if !GTEST_OS_WINDOWS
6707 // Generates a textual failure message when a death test finds more than
6708 // one thread running, or cannot determine the number of threads, prior
6709 // to executing the given statement. It is the responsibility of the
6710 // caller not to pass a thread_count of 1.
6711 static std::string
DeathTestThreadWarning(size_t thread_count
) {
6713 msg
<< "Death tests use fork(), which is unsafe particularly"
6714 << " in a threaded context. For this test, " << GTEST_NAME_
<< " ";
6715 if (thread_count
== 0)
6716 msg
<< "couldn't detect the number of threads.";
6718 msg
<< "detected " << thread_count
<< " threads.";
6719 return msg
.GetString();
6721 # endif // !GTEST_OS_WINDOWS
6723 // Flag characters for reporting a death test that did not die.
6724 static const char kDeathTestLived
= 'L';
6725 static const char kDeathTestReturned
= 'R';
6726 static const char kDeathTestThrew
= 'T';
6727 static const char kDeathTestInternalError
= 'I';
6729 // An enumeration describing all of the possible ways that a death test can
6730 // conclude. DIED means that the process died while executing the test
6731 // code; LIVED means that process lived beyond the end of the test code;
6732 // RETURNED means that the test statement attempted to execute a return
6733 // statement, which is not allowed; THREW means that the test statement
6734 // returned control by throwing an exception. IN_PROGRESS means the test
6735 // has not yet concluded.
6736 // TODO(vladl@google.com): Unify names and possibly values for
6737 // AbortReason, DeathTestOutcome, and flag characters above.
6738 enum DeathTestOutcome
{ IN_PROGRESS
, DIED
, LIVED
, RETURNED
, THREW
};
6740 // Routine for aborting the program which is safe to call from an
6741 // exec-style death test child process, in which case the error
6742 // message is propagated back to the parent process. Otherwise, the
6743 // message is simply printed to stderr. In either case, the program
6744 // then exits with status 1.
6745 void DeathTestAbort(const std::string
& message
) {
6746 // On a POSIX system, this function may be called from a threadsafe-style
6747 // death test child process, which operates on a very small stack. Use
6748 // the heap for any additional non-minuscule memory requirements.
6749 const InternalRunDeathTestFlag
* const flag
=
6750 GetUnitTestImpl()->internal_run_death_test_flag();
6752 FILE* parent
= posix::FDOpen(flag
->write_fd(), "w");
6753 fputc(kDeathTestInternalError
, parent
);
6754 fprintf(parent
, "%s", message
.c_str());
6758 fprintf(stderr
, "%s", message
.c_str());
6764 // A replacement for CHECK that calls DeathTestAbort if the assertion
6766 # define GTEST_DEATH_TEST_CHECK_(expression) \
6768 if (!::testing::internal::IsTrue(expression)) { \
6770 ::std::string("CHECK failed: File ") + __FILE__ + ", line " \
6771 + ::testing::internal::StreamableToString(__LINE__) + ": " \
6774 } while (::testing::internal::AlwaysFalse())
6776 // This macro is similar to GTEST_DEATH_TEST_CHECK_, but it is meant for
6777 // evaluating any system call that fulfills two conditions: it must return
6778 // -1 on failure, and set errno to EINTR when it is interrupted and
6779 // should be tried again. The macro expands to a loop that repeatedly
6780 // evaluates the expression as long as it evaluates to -1 and sets
6781 // errno to EINTR. If the expression evaluates to -1 but errno is
6782 // something other than EINTR, DeathTestAbort is called.
6783 # define GTEST_DEATH_TEST_CHECK_SYSCALL_(expression) \
6787 gtest_retval = (expression); \
6788 } while (gtest_retval == -1 && errno == EINTR); \
6789 if (gtest_retval == -1) { \
6791 ::std::string("CHECK failed: File ") + __FILE__ + ", line " \
6792 + ::testing::internal::StreamableToString(__LINE__) + ": " \
6793 + #expression + " != -1"); \
6795 } while (::testing::internal::AlwaysFalse())
6797 // Returns the message describing the last system error in errno.
6798 std::string
GetLastErrnoDescription() {
6799 return errno
== 0 ? "" : posix::StrError(errno
);
6802 // This is called from a death test parent process to read a failure
6803 // message from the death test child process and log it with the FATAL
6804 // severity. On Windows, the message is read from a pipe handle. On other
6805 // platforms, it is read from a file descriptor.
6806 static void FailFromInternalError(int fd
) {
6812 while ((num_read
= posix::Read(fd
, buffer
, 255)) > 0) {
6813 buffer
[num_read
] = '\0';
6816 } while (num_read
== -1 && errno
== EINTR
);
6818 if (num_read
== 0) {
6819 GTEST_LOG_(FATAL
) << error
.GetString();
6821 const int last_error
= errno
;
6822 GTEST_LOG_(FATAL
) << "Error while reading death test internal: "
6823 << GetLastErrnoDescription() << " [" << last_error
<< "]";
6827 // Death test constructor. Increments the running death test count
6828 // for the current test.
6829 DeathTest::DeathTest() {
6830 TestInfo
* const info
= GetUnitTestImpl()->current_test_info();
6832 DeathTestAbort("Cannot run a death test outside of a TEST or "
6833 "TEST_F construct");
6837 // Creates and returns a death test by dispatching to the current
6838 // death test factory.
6839 bool DeathTest::Create(const char* statement
, const RE
* regex
,
6840 const char* file
, int line
, DeathTest
** test
) {
6841 return GetUnitTestImpl()->death_test_factory()->Create(
6842 statement
, regex
, file
, line
, test
);
6845 const char* DeathTest::LastMessage() {
6846 return last_death_test_message_
.c_str();
6849 void DeathTest::set_last_death_test_message(const std::string
& message
) {
6850 last_death_test_message_
= message
;
6853 std::string
DeathTest::last_death_test_message_
;
6855 // Provides cross platform implementation for some death functionality.
6856 class DeathTestImpl
: public DeathTest
{
6858 DeathTestImpl(const char* a_statement
, const RE
* a_regex
)
6859 : statement_(a_statement
),
6863 outcome_(IN_PROGRESS
),
6867 // read_fd_ is expected to be closed and cleared by a derived class.
6868 ~DeathTestImpl() { GTEST_DEATH_TEST_CHECK_(read_fd_
== -1); }
6870 void Abort(AbortReason reason
);
6871 virtual bool Passed(bool status_ok
);
6873 const char* statement() const { return statement_
; }
6874 const RE
* regex() const { return regex_
; }
6875 bool spawned() const { return spawned_
; }
6876 void set_spawned(bool is_spawned
) { spawned_
= is_spawned
; }
6877 int status() const { return status_
; }
6878 void set_status(int a_status
) { status_
= a_status
; }
6879 DeathTestOutcome
outcome() const { return outcome_
; }
6880 void set_outcome(DeathTestOutcome an_outcome
) { outcome_
= an_outcome
; }
6881 int read_fd() const { return read_fd_
; }
6882 void set_read_fd(int fd
) { read_fd_
= fd
; }
6883 int write_fd() const { return write_fd_
; }
6884 void set_write_fd(int fd
) { write_fd_
= fd
; }
6886 // Called in the parent process only. Reads the result code of the death
6887 // test child process via a pipe, interprets it to set the outcome_
6888 // member, and closes read_fd_. Outputs diagnostics and terminates in
6889 // case of unexpected codes.
6890 void ReadAndInterpretStatusByte();
6893 // The textual content of the code this object is testing. This class
6894 // doesn't own this string and should not attempt to delete it.
6895 const char* const statement_
;
6896 // The regular expression which test output must match. DeathTestImpl
6897 // doesn't own this object and should not attempt to delete it.
6898 const RE
* const regex_
;
6899 // True if the death test child process has been successfully spawned.
6901 // The exit status of the child process.
6903 // How the death test concluded.
6904 DeathTestOutcome outcome_
;
6905 // Descriptor to the read end of the pipe to the child process. It is
6906 // always -1 in the child process. The child keeps its write end of the
6907 // pipe in write_fd_.
6909 // Descriptor to the child's write end of the pipe to the parent process.
6910 // It is always -1 in the parent process. The parent keeps its end of the
6911 // pipe in read_fd_.
6915 // Called in the parent process only. Reads the result code of the death
6916 // test child process via a pipe, interprets it to set the outcome_
6917 // member, and closes read_fd_. Outputs diagnostics and terminates in
6918 // case of unexpected codes.
6919 void DeathTestImpl::ReadAndInterpretStatusByte() {
6923 // The read() here blocks until data is available (signifying the
6924 // failure of the death test) or until the pipe is closed (signifying
6925 // its success), so it's okay to call this in the parent before
6926 // the child process has exited.
6928 bytes_read
= posix::Read(read_fd(), &flag
, 1);
6929 } while (bytes_read
== -1 && errno
== EINTR
);
6931 if (bytes_read
== 0) {
6933 } else if (bytes_read
== 1) {
6935 case kDeathTestReturned
:
6936 set_outcome(RETURNED
);
6938 case kDeathTestThrew
:
6941 case kDeathTestLived
:
6944 case kDeathTestInternalError
:
6945 FailFromInternalError(read_fd()); // Does not return.
6948 GTEST_LOG_(FATAL
) << "Death test child process reported "
6949 << "unexpected status byte ("
6950 << static_cast<unsigned int>(flag
) << ")";
6953 GTEST_LOG_(FATAL
) << "Read from death test child process failed: "
6954 << GetLastErrnoDescription();
6956 GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Close(read_fd()));
6960 // Signals that the death test code which should have exited, didn't.
6961 // Should be called only in a death test child process.
6962 // Writes a status byte to the child's status file descriptor, then
6964 void DeathTestImpl::Abort(AbortReason reason
) {
6965 // The parent process considers the death test to be a failure if
6966 // it finds any data in our pipe. So, here we write a single flag byte
6967 // to the pipe, then exit.
6968 const char status_ch
=
6969 reason
== TEST_DID_NOT_DIE
? kDeathTestLived
:
6970 reason
== TEST_THREW_EXCEPTION
? kDeathTestThrew
: kDeathTestReturned
;
6972 GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Write(write_fd(), &status_ch
, 1));
6973 // We are leaking the descriptor here because on some platforms (i.e.,
6974 // when built as Windows DLL), destructors of global objects will still
6975 // run after calling _exit(). On such systems, write_fd_ will be
6976 // indirectly closed from the destructor of UnitTestImpl, causing double
6977 // close if it is also closed here. On debug configurations, double close
6978 // may assert. As there are no in-process buffers to flush here, we are
6979 // relying on the OS to close the descriptor after the process terminates
6980 // when the destructors are not run.
6981 _exit(1); // Exits w/o any normal exit hooks (we were supposed to crash)
6984 // Returns an indented copy of stderr output for a death test.
6985 // This makes distinguishing death test output lines from regular log lines
6987 static ::std::string
FormatDeathTestOutput(const ::std::string
& output
) {
6989 for (size_t at
= 0; ; ) {
6990 const size_t line_end
= output
.find('\n', at
);
6991 ret
+= "[ DEATH ] ";
6992 if (line_end
== ::std::string::npos
) {
6993 ret
+= output
.substr(at
);
6996 ret
+= output
.substr(at
, line_end
+ 1 - at
);
7002 // Assesses the success or failure of a death test, using both private
7003 // members which have previously been set, and one argument:
7005 // Private data members:
7006 // outcome: An enumeration describing how the death test
7007 // concluded: DIED, LIVED, THREW, or RETURNED. The death test
7008 // fails in the latter three cases.
7009 // status: The exit status of the child process. On *nix, it is in the
7010 // in the format specified by wait(2). On Windows, this is the
7011 // value supplied to the ExitProcess() API or a numeric code
7012 // of the exception that terminated the program.
7013 // regex: A regular expression object to be applied to
7014 // the test's captured standard error output; the death test
7015 // fails if it does not match.
7018 // status_ok: true if exit_status is acceptable in the context of
7019 // this particular death test, which fails if it is false
7021 // Returns true iff all of the above conditions are met. Otherwise, the
7022 // first failing condition, in the order given above, is the one that is
7023 // reported. Also sets the last death test message string.
7024 bool DeathTestImpl::Passed(bool status_ok
) {
7028 const std::string error_message
= GetCapturedStderr();
7030 bool success
= false;
7033 buffer
<< "Death test: " << statement() << "\n";
7034 switch (outcome()) {
7036 buffer
<< " Result: failed to die.\n"
7037 << " Error msg:\n" << FormatDeathTestOutput(error_message
);
7040 buffer
<< " Result: threw an exception.\n"
7041 << " Error msg:\n" << FormatDeathTestOutput(error_message
);
7044 buffer
<< " Result: illegal return in test statement.\n"
7045 << " Error msg:\n" << FormatDeathTestOutput(error_message
);
7049 const bool matched
= RE::PartialMatch(error_message
.c_str(), *regex());
7053 buffer
<< " Result: died but not with expected error.\n"
7054 << " Expected: " << regex()->pattern() << "\n"
7055 << "Actual msg:\n" << FormatDeathTestOutput(error_message
);
7058 buffer
<< " Result: died but not with expected exit code:\n"
7059 << " " << ExitSummary(status()) << "\n"
7060 << "Actual msg:\n" << FormatDeathTestOutput(error_message
);
7066 << "DeathTest::Passed somehow called before conclusion of test";
7069 DeathTest::set_last_death_test_message(buffer
.GetString());
7073 # if GTEST_OS_WINDOWS
7074 // WindowsDeathTest implements death tests on Windows. Due to the
7075 // specifics of starting new processes on Windows, death tests there are
7076 // always threadsafe, and Google Test considers the
7077 // --gtest_death_test_style=fast setting to be equivalent to
7078 // --gtest_death_test_style=threadsafe there.
7080 // A few implementation notes: Like the Linux version, the Windows
7081 // implementation uses pipes for child-to-parent communication. But due to
7082 // the specifics of pipes on Windows, some extra steps are required:
7084 // 1. The parent creates a communication pipe and stores handles to both
7086 // 2. The parent starts the child and provides it with the information
7087 // necessary to acquire the handle to the write end of the pipe.
7088 // 3. The child acquires the write end of the pipe and signals the parent
7089 // using a Windows event.
7090 // 4. Now the parent can release the write end of the pipe on its side. If
7091 // this is done before step 3, the object's reference count goes down to
7092 // 0 and it is destroyed, preventing the child from acquiring it. The
7093 // parent now has to release it, or read operations on the read end of
7094 // the pipe will not return when the child terminates.
7095 // 5. The parent reads child's output through the pipe (outcome code and
7096 // any possible error messages) from the pipe, and its stderr and then
7097 // determines whether to fail the test.
7099 // Note: to distinguish Win32 API calls from the local method and function
7100 // calls, the former are explicitly resolved in the global namespace.
7102 class WindowsDeathTest
: public DeathTestImpl
{
7104 WindowsDeathTest(const char* a_statement
,
7108 : DeathTestImpl(a_statement
, a_regex
), file_(file
), line_(line
) {}
7110 // All of these virtual functions are inherited from DeathTest.
7112 virtual TestRole
AssumeRole();
7115 // The name of the file in which the death test is located.
7116 const char* const file_
;
7117 // The line number on which the death test is located.
7119 // Handle to the write end of the pipe to the child process.
7120 AutoHandle write_handle_
;
7121 // Child process handle.
7122 AutoHandle child_handle_
;
7123 // Event the child process uses to signal the parent that it has
7124 // acquired the handle to the write end of the pipe. After seeing this
7125 // event the parent can release its own handles to make sure its
7126 // ReadFile() calls return when the child terminates.
7127 AutoHandle event_handle_
;
7130 // Waits for the child in a death test to exit, returning its exit
7131 // status, or 0 if no child process exists. As a side effect, sets the
7132 // outcome data member.
7133 int WindowsDeathTest::Wait() {
7137 // Wait until the child either signals that it has acquired the write end
7138 // of the pipe or it dies.
7139 const HANDLE wait_handles
[2] = { child_handle_
.Get(), event_handle_
.Get() };
7140 switch (::WaitForMultipleObjects(2,
7142 FALSE
, // Waits for any of the handles.
7145 case WAIT_OBJECT_0
+ 1:
7148 GTEST_DEATH_TEST_CHECK_(false); // Should not get here.
7151 // The child has acquired the write end of the pipe or exited.
7152 // We release the handle on our side and continue.
7153 write_handle_
.Reset();
7154 event_handle_
.Reset();
7156 ReadAndInterpretStatusByte();
7158 // Waits for the child process to exit if it haven't already. This
7159 // returns immediately if the child has already exited, regardless of
7160 // whether previous calls to WaitForMultipleObjects synchronized on this
7162 GTEST_DEATH_TEST_CHECK_(
7163 WAIT_OBJECT_0
== ::WaitForSingleObject(child_handle_
.Get(),
7166 GTEST_DEATH_TEST_CHECK_(
7167 ::GetExitCodeProcess(child_handle_
.Get(), &status_code
) != FALSE
);
7168 child_handle_
.Reset();
7169 set_status(static_cast<int>(status_code
));
7173 // The AssumeRole process for a Windows death test. It creates a child
7174 // process with the same executable as the current process to run the
7175 // death test. The child process is given the --gtest_filter and
7176 // --gtest_internal_run_death_test flags such that it knows to run the
7177 // current death test only.
7178 DeathTest::TestRole
WindowsDeathTest::AssumeRole() {
7179 const UnitTestImpl
* const impl
= GetUnitTestImpl();
7180 const InternalRunDeathTestFlag
* const flag
=
7181 impl
->internal_run_death_test_flag();
7182 const TestInfo
* const info
= impl
->current_test_info();
7183 const int death_test_index
= info
->result()->death_test_count();
7186 // ParseInternalRunDeathTestFlag() has performed all the necessary
7188 set_write_fd(flag
->write_fd());
7189 return EXECUTE_TEST
;
7192 // WindowsDeathTest uses an anonymous pipe to communicate results of
7194 SECURITY_ATTRIBUTES handles_are_inheritable
= {
7195 sizeof(SECURITY_ATTRIBUTES
), NULL
, TRUE
};
7196 HANDLE read_handle
, write_handle
;
7197 GTEST_DEATH_TEST_CHECK_(
7198 ::CreatePipe(&read_handle
, &write_handle
, &handles_are_inheritable
,
7199 0) // Default buffer size.
7201 set_read_fd(::_open_osfhandle(reinterpret_cast<intptr_t>(read_handle
),
7203 write_handle_
.Reset(write_handle
);
7204 event_handle_
.Reset(::CreateEvent(
7205 &handles_are_inheritable
,
7206 TRUE
, // The event will automatically reset to non-signaled state.
7207 FALSE
, // The initial state is non-signalled.
7208 NULL
)); // The even is unnamed.
7209 GTEST_DEATH_TEST_CHECK_(event_handle_
.Get() != NULL
);
7210 const std::string filter_flag
=
7211 std::string("--") + GTEST_FLAG_PREFIX_
+ kFilterFlag
+ "=" +
7212 info
->test_case_name() + "." + info
->name();
7213 const std::string internal_flag
=
7214 std::string("--") + GTEST_FLAG_PREFIX_
+ kInternalRunDeathTestFlag
+
7215 "=" + file_
+ "|" + StreamableToString(line_
) + "|" +
7216 StreamableToString(death_test_index
) + "|" +
7217 StreamableToString(static_cast<unsigned int>(::GetCurrentProcessId())) +
7218 // size_t has the same width as pointers on both 32-bit and 64-bit
7219 // Windows platforms.
7220 // See http://msdn.microsoft.com/en-us/library/tcxf1dw6.aspx.
7221 "|" + StreamableToString(reinterpret_cast<size_t>(write_handle
)) +
7222 "|" + StreamableToString(reinterpret_cast<size_t>(event_handle_
.Get()));
7224 char executable_path
[_MAX_PATH
+ 1]; // NOLINT
7225 GTEST_DEATH_TEST_CHECK_(
7226 _MAX_PATH
+ 1 != ::GetModuleFileNameA(NULL
,
7230 std::string command_line
=
7231 std::string(::GetCommandLineA()) + " " + filter_flag
+ " \"" +
7232 internal_flag
+ "\"";
7234 DeathTest::set_last_death_test_message("");
7237 // Flush the log buffers since the log streams are shared with the child.
7240 // The child process will share the standard handles with the parent.
7241 STARTUPINFOA startup_info
;
7242 memset(&startup_info
, 0, sizeof(STARTUPINFO
));
7243 startup_info
.dwFlags
= STARTF_USESTDHANDLES
;
7244 startup_info
.hStdInput
= ::GetStdHandle(STD_INPUT_HANDLE
);
7245 startup_info
.hStdOutput
= ::GetStdHandle(STD_OUTPUT_HANDLE
);
7246 startup_info
.hStdError
= ::GetStdHandle(STD_ERROR_HANDLE
);
7248 PROCESS_INFORMATION process_info
;
7249 GTEST_DEATH_TEST_CHECK_(::CreateProcessA(
7251 const_cast<char*>(command_line
.c_str()),
7252 NULL
, // Retuned process handle is not inheritable.
7253 NULL
, // Retuned thread handle is not inheritable.
7254 TRUE
, // Child inherits all inheritable handles (for write_handle_).
7255 0x0, // Default creation flags.
7256 NULL
, // Inherit the parent's environment.
7257 UnitTest::GetInstance()->original_working_dir(),
7259 &process_info
) != FALSE
);
7260 child_handle_
.Reset(process_info
.hProcess
);
7261 ::CloseHandle(process_info
.hThread
);
7263 return OVERSEE_TEST
;
7265 # else // We are not on Windows.
7267 // ForkingDeathTest provides implementations for most of the abstract
7268 // methods of the DeathTest interface. Only the AssumeRole method is
7270 class ForkingDeathTest
: public DeathTestImpl
{
7272 ForkingDeathTest(const char* statement
, const RE
* regex
);
7274 // All of these virtual functions are inherited from DeathTest.
7278 void set_child_pid(pid_t child_pid
) { child_pid_
= child_pid
; }
7281 // PID of child process during death test; 0 in the child process itself.
7285 // Constructs a ForkingDeathTest.
7286 ForkingDeathTest::ForkingDeathTest(const char* a_statement
, const RE
* a_regex
)
7287 : DeathTestImpl(a_statement
, a_regex
),
7290 // Waits for the child in a death test to exit, returning its exit
7291 // status, or 0 if no child process exists. As a side effect, sets the
7292 // outcome data member.
7293 int ForkingDeathTest::Wait() {
7297 ReadAndInterpretStatusByte();
7300 GTEST_DEATH_TEST_CHECK_SYSCALL_(waitpid(child_pid_
, &status_value
, 0));
7301 set_status(status_value
);
7302 return status_value
;
7305 // A concrete death test class that forks, then immediately runs the test
7306 // in the child process.
7307 class NoExecDeathTest
: public ForkingDeathTest
{
7309 NoExecDeathTest(const char* a_statement
, const RE
* a_regex
) :
7310 ForkingDeathTest(a_statement
, a_regex
) { }
7311 virtual TestRole
AssumeRole();
7314 // The AssumeRole process for a fork-and-run death test. It implements a
7315 // straightforward fork, with a simple pipe to transmit the status byte.
7316 DeathTest::TestRole
NoExecDeathTest::AssumeRole() {
7317 const size_t thread_count
= GetThreadCount();
7318 if (thread_count
!= 1) {
7319 GTEST_LOG_(WARNING
) << DeathTestThreadWarning(thread_count
);
7323 GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd
) != -1);
7325 DeathTest::set_last_death_test_message("");
7327 // When we fork the process below, the log file buffers are copied, but the
7328 // file descriptors are shared. We flush all log files here so that closing
7329 // the file descriptors in the child process doesn't throw off the
7330 // synchronization between descriptors and buffers in the parent process.
7331 // This is as close to the fork as possible to avoid a race condition in case
7332 // there are multiple threads running before the death test, and another
7333 // thread writes to the log file.
7336 const pid_t child_pid
= fork();
7337 GTEST_DEATH_TEST_CHECK_(child_pid
!= -1);
7338 set_child_pid(child_pid
);
7339 if (child_pid
== 0) {
7340 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd
[0]));
7341 set_write_fd(pipe_fd
[1]);
7342 // Redirects all logging to stderr in the child process to prevent
7343 // concurrent writes to the log files. We capture stderr in the parent
7344 // process and append the child process' output to a log.
7346 // Event forwarding to the listeners of event listener API mush be shut
7347 // down in death test subprocesses.
7348 GetUnitTestImpl()->listeners()->SuppressEventForwarding();
7349 g_in_fast_death_test_child
= true;
7350 return EXECUTE_TEST
;
7352 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd
[1]));
7353 set_read_fd(pipe_fd
[0]);
7355 return OVERSEE_TEST
;
7359 // A concrete death test class that forks and re-executes the main
7360 // program from the beginning, with command-line flags set that cause
7361 // only this specific death test to be run.
7362 class ExecDeathTest
: public ForkingDeathTest
{
7364 ExecDeathTest(const char* a_statement
, const RE
* a_regex
,
7365 const char* file
, int line
) :
7366 ForkingDeathTest(a_statement
, a_regex
), file_(file
), line_(line
) { }
7367 virtual TestRole
AssumeRole();
7369 static ::std::vector
<testing::internal::string
>
7370 GetArgvsForDeathTestChildProcess() {
7371 ::std::vector
<testing::internal::string
> args
= GetInjectableArgvs();
7374 // The name of the file in which the death test is located.
7375 const char* const file_
;
7376 // The line number on which the death test is located.
7380 // Utility class for accumulating command-line arguments.
7384 args_
.push_back(NULL
);
7388 for (std::vector
<char*>::iterator i
= args_
.begin(); i
!= args_
.end();
7393 void AddArgument(const char* argument
) {
7394 args_
.insert(args_
.end() - 1, posix::StrDup(argument
));
7397 template <typename Str
>
7398 void AddArguments(const ::std::vector
<Str
>& arguments
) {
7399 for (typename ::std::vector
<Str
>::const_iterator i
= arguments
.begin();
7400 i
!= arguments
.end();
7402 args_
.insert(args_
.end() - 1, posix::StrDup(i
->c_str()));
7405 char* const* Argv() {
7410 std::vector
<char*> args_
;
7413 // A struct that encompasses the arguments to the child process of a
7414 // threadsafe-style death test process.
7415 struct ExecDeathTestArgs
{
7416 char* const* argv
; // Command-line arguments for the child's call to exec
7417 int close_fd
; // File descriptor to close; the read end of a pipe
7421 inline char** GetEnviron() {
7422 // When Google Test is built as a framework on MacOS X, the environ variable
7423 // is unavailable. Apple's documentation (man environ) recommends using
7424 // _NSGetEnviron() instead.
7425 return *_NSGetEnviron();
7428 // Some POSIX platforms expect you to declare environ. extern "C" makes
7429 // it reside in the global namespace.
7430 extern "C" char** environ
;
7431 inline char** GetEnviron() { return environ
; }
7432 # endif // GTEST_OS_MAC
7435 // The main function for a threadsafe-style death test child process.
7436 // This function is called in a clone()-ed process and thus must avoid
7437 // any potentially unsafe operations like malloc or libc functions.
7438 static int ExecDeathTestChildMain(void* child_arg
) {
7439 ExecDeathTestArgs
* const args
= static_cast<ExecDeathTestArgs
*>(child_arg
);
7440 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(args
->close_fd
));
7442 // We need to execute the test program in the same environment where
7443 // it was originally invoked. Therefore we change to the original
7444 // working directory first.
7445 const char* const original_dir
=
7446 UnitTest::GetInstance()->original_working_dir();
7447 // We can safely call chdir() as it's a direct system call.
7448 if (chdir(original_dir
) != 0) {
7449 DeathTestAbort(std::string("chdir(\"") + original_dir
+ "\") failed: " +
7450 GetLastErrnoDescription());
7451 return EXIT_FAILURE
;
7454 // We can safely call execve() as it's a direct system call. We
7455 // cannot use execvp() as it's a libc function and thus potentially
7456 // unsafe. Since execve() doesn't search the PATH, the user must
7457 // invoke the test program via a valid path that contains at least
7458 // one path separator.
7459 execve(args
->argv
[0], args
->argv
, GetEnviron());
7460 DeathTestAbort(std::string("execve(") + args
->argv
[0] + ", ...) in " +
7461 original_dir
+ " failed: " +
7462 GetLastErrnoDescription());
7463 return EXIT_FAILURE
;
7465 # endif // !GTEST_OS_QNX
7467 // Two utility routines that together determine the direction the stack
7469 // This could be accomplished more elegantly by a single recursive
7470 // function, but we want to guard against the unlikely possibility of
7471 // a smart compiler optimizing the recursion away.
7473 // GTEST_NO_INLINE_ is required to prevent GCC 4.6 from inlining
7474 // StackLowerThanAddress into StackGrowsDown, which then doesn't give
7476 void StackLowerThanAddress(const void* ptr
, bool* result
) GTEST_NO_INLINE_
;
7477 void StackLowerThanAddress(const void* ptr
, bool* result
) {
7479 *result
= (&dummy
< ptr
);
7482 bool StackGrowsDown() {
7485 StackLowerThanAddress(&dummy
, &result
);
7489 // Spawns a child process with the same executable as the current process in
7490 // a thread-safe manner and instructs it to run the death test. The
7491 // implementation uses fork(2) + exec. On systems where clone(2) is
7492 // available, it is used instead, being slightly more thread-safe. On QNX,
7493 // fork supports only single-threaded environments, so this function uses
7494 // spawn(2) there instead. The function dies with an error message if
7495 // anything goes wrong.
7496 static pid_t
ExecDeathTestSpawnChild(char* const* argv
, int close_fd
) {
7497 ExecDeathTestArgs args
= { argv
, close_fd
};
7498 pid_t child_pid
= -1;
7501 // Obtains the current directory and sets it to be closed in the child
7503 const int cwd_fd
= open(".", O_RDONLY
);
7504 GTEST_DEATH_TEST_CHECK_(cwd_fd
!= -1);
7505 GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(cwd_fd
, F_SETFD
, FD_CLOEXEC
));
7506 // We need to execute the test program in the same environment where
7507 // it was originally invoked. Therefore we change to the original
7508 // working directory first.
7509 const char* const original_dir
=
7510 UnitTest::GetInstance()->original_working_dir();
7511 // We can safely call chdir() as it's a direct system call.
7512 if (chdir(original_dir
) != 0) {
7513 DeathTestAbort(std::string("chdir(\"") + original_dir
+ "\") failed: " +
7514 GetLastErrnoDescription());
7515 return EXIT_FAILURE
;
7519 // Set close_fd to be closed after spawn.
7520 GTEST_DEATH_TEST_CHECK_SYSCALL_(fd_flags
= fcntl(close_fd
, F_GETFD
));
7521 GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(close_fd
, F_SETFD
,
7522 fd_flags
| FD_CLOEXEC
));
7523 struct inheritance inherit
= {0};
7524 // spawn is a system call.
7525 child_pid
= spawn(args
.argv
[0], 0, NULL
, &inherit
, args
.argv
, GetEnviron());
7526 // Restores the current working directory.
7527 GTEST_DEATH_TEST_CHECK_(fchdir(cwd_fd
) != -1);
7528 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(cwd_fd
));
7530 # else // GTEST_OS_QNX
7532 // When a SIGPROF signal is received while fork() or clone() are executing,
7533 // the process may hang. To avoid this, we ignore SIGPROF here and re-enable
7534 // it after the call to fork()/clone() is complete.
7535 struct sigaction saved_sigprof_action
;
7536 struct sigaction ignore_sigprof_action
;
7537 memset(&ignore_sigprof_action
, 0, sizeof(ignore_sigprof_action
));
7538 sigemptyset(&ignore_sigprof_action
.sa_mask
);
7539 ignore_sigprof_action
.sa_handler
= SIG_IGN
;
7540 GTEST_DEATH_TEST_CHECK_SYSCALL_(sigaction(
7541 SIGPROF
, &ignore_sigprof_action
, &saved_sigprof_action
));
7542 # endif // GTEST_OS_LINUX
7544 # if GTEST_HAS_CLONE
7545 const bool use_fork
= GTEST_FLAG(death_test_use_fork
);
7548 static const bool stack_grows_down
= StackGrowsDown();
7549 const size_t stack_size
= getpagesize();
7550 // MMAP_ANONYMOUS is not defined on Mac, so we use MAP_ANON instead.
7551 void* const stack
= mmap(NULL
, stack_size
, PROT_READ
| PROT_WRITE
,
7552 MAP_ANON
| MAP_PRIVATE
, -1, 0);
7553 GTEST_DEATH_TEST_CHECK_(stack
!= MAP_FAILED
);
7555 // Maximum stack alignment in bytes: For a downward-growing stack, this
7556 // amount is subtracted from size of the stack space to get an address
7557 // that is within the stack space and is aligned on all systems we care
7558 // about. As far as I know there is no ABI with stack alignment greater
7559 // than 64. We assume stack and stack_size already have alignment of
7560 // kMaxStackAlignment.
7561 const size_t kMaxStackAlignment
= 64;
7562 void* const stack_top
=
7563 static_cast<char*>(stack
) +
7564 (stack_grows_down
? stack_size
- kMaxStackAlignment
: 0);
7565 GTEST_DEATH_TEST_CHECK_(stack_size
> kMaxStackAlignment
&&
7566 reinterpret_cast<intptr_t>(stack_top
) % kMaxStackAlignment
== 0);
7568 child_pid
= clone(&ExecDeathTestChildMain
, stack_top
, SIGCHLD
, &args
);
7570 GTEST_DEATH_TEST_CHECK_(munmap(stack
, stack_size
) != -1);
7573 const bool use_fork
= true;
7574 # endif // GTEST_HAS_CLONE
7576 if (use_fork
&& (child_pid
= fork()) == 0) {
7577 ExecDeathTestChildMain(&args
);
7580 # endif // GTEST_OS_QNX
7582 GTEST_DEATH_TEST_CHECK_SYSCALL_(
7583 sigaction(SIGPROF
, &saved_sigprof_action
, NULL
));
7584 # endif // GTEST_OS_LINUX
7586 GTEST_DEATH_TEST_CHECK_(child_pid
!= -1);
7590 // The AssumeRole process for a fork-and-exec death test. It re-executes the
7591 // main program from the beginning, setting the --gtest_filter
7592 // and --gtest_internal_run_death_test flags to cause only the current
7593 // death test to be re-run.
7594 DeathTest::TestRole
ExecDeathTest::AssumeRole() {
7595 const UnitTestImpl
* const impl
= GetUnitTestImpl();
7596 const InternalRunDeathTestFlag
* const flag
=
7597 impl
->internal_run_death_test_flag();
7598 const TestInfo
* const info
= impl
->current_test_info();
7599 const int death_test_index
= info
->result()->death_test_count();
7602 set_write_fd(flag
->write_fd());
7603 return EXECUTE_TEST
;
7607 GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd
) != -1);
7608 // Clear the close-on-exec flag on the write end of the pipe, lest
7609 // it be closed when the child process does an exec:
7610 GTEST_DEATH_TEST_CHECK_(fcntl(pipe_fd
[1], F_SETFD
, 0) != -1);
7612 const std::string filter_flag
=
7613 std::string("--") + GTEST_FLAG_PREFIX_
+ kFilterFlag
+ "="
7614 + info
->test_case_name() + "." + info
->name();
7615 const std::string internal_flag
=
7616 std::string("--") + GTEST_FLAG_PREFIX_
+ kInternalRunDeathTestFlag
+ "="
7617 + file_
+ "|" + StreamableToString(line_
) + "|"
7618 + StreamableToString(death_test_index
) + "|"
7619 + StreamableToString(pipe_fd
[1]);
7621 args
.AddArguments(GetArgvsForDeathTestChildProcess());
7622 args
.AddArgument(filter_flag
.c_str());
7623 args
.AddArgument(internal_flag
.c_str());
7625 DeathTest::set_last_death_test_message("");
7628 // See the comment in NoExecDeathTest::AssumeRole for why the next line
7632 const pid_t child_pid
= ExecDeathTestSpawnChild(args
.Argv(), pipe_fd
[0]);
7633 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd
[1]));
7634 set_child_pid(child_pid
);
7635 set_read_fd(pipe_fd
[0]);
7637 return OVERSEE_TEST
;
7640 # endif // !GTEST_OS_WINDOWS
7642 // Creates a concrete DeathTest-derived class that depends on the
7643 // --gtest_death_test_style flag, and sets the pointer pointed to
7644 // by the "test" argument to its address. If the test should be
7645 // skipped, sets that pointer to NULL. Returns true, unless the
7646 // flag is set to an invalid value.
7647 bool DefaultDeathTestFactory::Create(const char* statement
, const RE
* regex
,
7648 const char* file
, int line
,
7650 UnitTestImpl
* const impl
= GetUnitTestImpl();
7651 const InternalRunDeathTestFlag
* const flag
=
7652 impl
->internal_run_death_test_flag();
7653 const int death_test_index
= impl
->current_test_info()
7654 ->increment_death_test_count();
7657 if (death_test_index
> flag
->index()) {
7658 DeathTest::set_last_death_test_message(
7659 "Death test count (" + StreamableToString(death_test_index
)
7660 + ") somehow exceeded expected maximum ("
7661 + StreamableToString(flag
->index()) + ")");
7665 if (!(flag
->file() == file
&& flag
->line() == line
&&
7666 flag
->index() == death_test_index
)) {
7672 # if GTEST_OS_WINDOWS
7674 if (GTEST_FLAG(death_test_style
) == "threadsafe" ||
7675 GTEST_FLAG(death_test_style
) == "fast") {
7676 *test
= new WindowsDeathTest(statement
, regex
, file
, line
);
7681 if (GTEST_FLAG(death_test_style
) == "threadsafe") {
7682 *test
= new ExecDeathTest(statement
, regex
, file
, line
);
7683 } else if (GTEST_FLAG(death_test_style
) == "fast") {
7684 *test
= new NoExecDeathTest(statement
, regex
);
7687 # endif // GTEST_OS_WINDOWS
7689 else { // NOLINT - this is more readable than unbalanced brackets inside #if.
7690 DeathTest::set_last_death_test_message(
7691 "Unknown death test style \"" + GTEST_FLAG(death_test_style
)
7692 + "\" encountered");
7699 // Splits a given string on a given delimiter, populating a given
7700 // vector with the fields. GTEST_HAS_DEATH_TEST implies that we have
7701 // ::std::string, so we can use it here.
7702 static void SplitString(const ::std::string
& str
, char delimiter
,
7703 ::std::vector
< ::std::string
>* dest
) {
7704 ::std::vector
< ::std::string
> parsed
;
7705 ::std::string::size_type pos
= 0;
7706 while (::testing::internal::AlwaysTrue()) {
7707 const ::std::string::size_type colon
= str
.find(delimiter
, pos
);
7708 if (colon
== ::std::string::npos
) {
7709 parsed
.push_back(str
.substr(pos
));
7712 parsed
.push_back(str
.substr(pos
, colon
- pos
));
7719 # if GTEST_OS_WINDOWS
7720 // Recreates the pipe and event handles from the provided parameters,
7721 // signals the event, and returns a file descriptor wrapped around the pipe
7722 // handle. This function is called in the child process only.
7723 int GetStatusFileDescriptor(unsigned int parent_process_id
,
7724 size_t write_handle_as_size_t
,
7725 size_t event_handle_as_size_t
) {
7726 AutoHandle
parent_process_handle(::OpenProcess(PROCESS_DUP_HANDLE
,
7727 FALSE
, // Non-inheritable.
7728 parent_process_id
));
7729 if (parent_process_handle
.Get() == INVALID_HANDLE_VALUE
) {
7730 DeathTestAbort("Unable to open parent process " +
7731 StreamableToString(parent_process_id
));
7734 // TODO(vladl@google.com): Replace the following check with a
7735 // compile-time assertion when available.
7736 GTEST_CHECK_(sizeof(HANDLE
) <= sizeof(size_t));
7738 const HANDLE write_handle
=
7739 reinterpret_cast<HANDLE
>(write_handle_as_size_t
);
7740 HANDLE dup_write_handle
;
7742 // The newly initialized handle is accessible only in in the parent
7743 // process. To obtain one accessible within the child, we need to use
7745 if (!::DuplicateHandle(parent_process_handle
.Get(), write_handle
,
7746 ::GetCurrentProcess(), &dup_write_handle
,
7747 0x0, // Requested privileges ignored since
7748 // DUPLICATE_SAME_ACCESS is used.
7749 FALSE
, // Request non-inheritable handler.
7750 DUPLICATE_SAME_ACCESS
)) {
7751 DeathTestAbort("Unable to duplicate the pipe handle " +
7752 StreamableToString(write_handle_as_size_t
) +
7753 " from the parent process " +
7754 StreamableToString(parent_process_id
));
7757 const HANDLE event_handle
= reinterpret_cast<HANDLE
>(event_handle_as_size_t
);
7758 HANDLE dup_event_handle
;
7760 if (!::DuplicateHandle(parent_process_handle
.Get(), event_handle
,
7761 ::GetCurrentProcess(), &dup_event_handle
,
7764 DUPLICATE_SAME_ACCESS
)) {
7765 DeathTestAbort("Unable to duplicate the event handle " +
7766 StreamableToString(event_handle_as_size_t
) +
7767 " from the parent process " +
7768 StreamableToString(parent_process_id
));
7771 const int write_fd
=
7772 ::_open_osfhandle(reinterpret_cast<intptr_t>(dup_write_handle
), O_APPEND
);
7773 if (write_fd
== -1) {
7774 DeathTestAbort("Unable to convert pipe handle " +
7775 StreamableToString(write_handle_as_size_t
) +
7776 " to a file descriptor");
7779 // Signals the parent that the write end of the pipe has been acquired
7780 // so the parent can release its own write end.
7781 ::SetEvent(dup_event_handle
);
7785 # endif // GTEST_OS_WINDOWS
7787 // Returns a newly created InternalRunDeathTestFlag object with fields
7788 // initialized from the GTEST_FLAG(internal_run_death_test) flag if
7789 // the flag is specified; otherwise returns NULL.
7790 InternalRunDeathTestFlag
* ParseInternalRunDeathTestFlag() {
7791 if (GTEST_FLAG(internal_run_death_test
) == "") return NULL
;
7793 // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we
7797 ::std::vector
< ::std::string
> fields
;
7798 SplitString(GTEST_FLAG(internal_run_death_test
).c_str(), '|', &fields
);
7801 # if GTEST_OS_WINDOWS
7803 unsigned int parent_process_id
= 0;
7804 size_t write_handle_as_size_t
= 0;
7805 size_t event_handle_as_size_t
= 0;
7807 if (fields
.size() != 6
7808 || !ParseNaturalNumber(fields
[1], &line
)
7809 || !ParseNaturalNumber(fields
[2], &index
)
7810 || !ParseNaturalNumber(fields
[3], &parent_process_id
)
7811 || !ParseNaturalNumber(fields
[4], &write_handle_as_size_t
)
7812 || !ParseNaturalNumber(fields
[5], &event_handle_as_size_t
)) {
7813 DeathTestAbort("Bad --gtest_internal_run_death_test flag: " +
7814 GTEST_FLAG(internal_run_death_test
));
7816 write_fd
= GetStatusFileDescriptor(parent_process_id
,
7817 write_handle_as_size_t
,
7818 event_handle_as_size_t
);
7821 if (fields
.size() != 4
7822 || !ParseNaturalNumber(fields
[1], &line
)
7823 || !ParseNaturalNumber(fields
[2], &index
)
7824 || !ParseNaturalNumber(fields
[3], &write_fd
)) {
7825 DeathTestAbort("Bad --gtest_internal_run_death_test flag: "
7826 + GTEST_FLAG(internal_run_death_test
));
7829 # endif // GTEST_OS_WINDOWS
7831 return new InternalRunDeathTestFlag(fields
[0], line
, index
, write_fd
);
7834 } // namespace internal
7836 #endif // GTEST_HAS_DEATH_TEST
7838 } // namespace testing
7839 // Copyright 2008, Google Inc.
7840 // All rights reserved.
7842 // Redistribution and use in source and binary forms, with or without
7843 // modification, are permitted provided that the following conditions are
7846 // * Redistributions of source code must retain the above copyright
7847 // notice, this list of conditions and the following disclaimer.
7848 // * Redistributions in binary form must reproduce the above
7849 // copyright notice, this list of conditions and the following disclaimer
7850 // in the documentation and/or other materials provided with the
7852 // * Neither the name of Google Inc. nor the names of its
7853 // contributors may be used to endorse or promote products derived from
7854 // this software without specific prior written permission.
7856 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
7857 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
7858 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
7859 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
7860 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
7861 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
7862 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
7863 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
7864 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
7865 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
7866 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
7868 // Authors: keith.ray@gmail.com (Keith Ray)
7873 #if GTEST_OS_WINDOWS_MOBILE
7874 # include <windows.h>
7875 #elif GTEST_OS_WINDOWS
7876 # include <direct.h>
7878 #elif GTEST_OS_SYMBIAN
7879 // Symbian OpenC has PATH_MAX in sys/syslimits.h
7880 # include <sys/syslimits.h>
7882 # include <limits.h>
7883 # include <climits> // Some Linux distributions define PATH_MAX here.
7884 #endif // GTEST_OS_WINDOWS_MOBILE
7886 #if GTEST_OS_WINDOWS
7887 # define GTEST_PATH_MAX_ _MAX_PATH
7888 #elif defined(PATH_MAX)
7889 # define GTEST_PATH_MAX_ PATH_MAX
7890 #elif defined(_XOPEN_PATH_MAX)
7891 # define GTEST_PATH_MAX_ _XOPEN_PATH_MAX
7893 # define GTEST_PATH_MAX_ _POSIX_PATH_MAX
7894 #endif // GTEST_OS_WINDOWS
7898 namespace internal
{
7900 #if GTEST_OS_WINDOWS
7901 // On Windows, '\\' is the standard path separator, but many tools and the
7902 // Windows API also accept '/' as an alternate path separator. Unless otherwise
7903 // noted, a file path can contain either kind of path separators, or a mixture
7905 const char kPathSeparator
= '\\';
7906 const char kAlternatePathSeparator
= '/';
7907 const char kPathSeparatorString
[] = "\\";
7908 const char kAlternatePathSeparatorString
[] = "/";
7909 # if GTEST_OS_WINDOWS_MOBILE
7910 // Windows CE doesn't have a current directory. You should not use
7911 // the current directory in tests on Windows CE, but this at least
7912 // provides a reasonable fallback.
7913 const char kCurrentDirectoryString
[] = "\\";
7914 // Windows CE doesn't define INVALID_FILE_ATTRIBUTES
7915 const DWORD kInvalidFileAttributes
= 0xffffffff;
7917 const char kCurrentDirectoryString
[] = ".\\";
7918 # endif // GTEST_OS_WINDOWS_MOBILE
7920 const char kPathSeparator
= '/';
7921 const char kPathSeparatorString
[] = "/";
7922 const char kCurrentDirectoryString
[] = "./";
7923 #endif // GTEST_OS_WINDOWS
7925 // Returns whether the given character is a valid path separator.
7926 static bool IsPathSeparator(char c
) {
7927 #if GTEST_HAS_ALT_PATH_SEP_
7928 return (c
== kPathSeparator
) || (c
== kAlternatePathSeparator
);
7930 return c
== kPathSeparator
;
7934 // Returns the current working directory, or "" if unsuccessful.
7935 FilePath
FilePath::GetCurrentDir() {
7936 #if GTEST_OS_WINDOWS_MOBILE
7937 // Windows CE doesn't have a current directory, so we just return
7938 // something reasonable.
7939 return FilePath(kCurrentDirectoryString
);
7940 #elif GTEST_OS_WINDOWS
7941 char cwd
[GTEST_PATH_MAX_
+ 1] = { '\0' };
7942 return FilePath(_getcwd(cwd
, sizeof(cwd
)) == NULL
? "" : cwd
);
7944 char cwd
[GTEST_PATH_MAX_
+ 1] = { '\0' };
7945 return FilePath(getcwd(cwd
, sizeof(cwd
)) == NULL
? "" : cwd
);
7946 #endif // GTEST_OS_WINDOWS_MOBILE
7949 // Returns a copy of the FilePath with the case-insensitive extension removed.
7950 // Example: FilePath("dir/file.exe").RemoveExtension("EXE") returns
7951 // FilePath("dir/file"). If a case-insensitive extension is not
7952 // found, returns a copy of the original FilePath.
7953 FilePath
FilePath::RemoveExtension(const char* extension
) const {
7954 const std::string dot_extension
= std::string(".") + extension
;
7955 if (String::EndsWithCaseInsensitive(pathname_
, dot_extension
)) {
7956 return FilePath(pathname_
.substr(
7957 0, pathname_
.length() - dot_extension
.length()));
7962 // Returns a pointer to the last occurence of a valid path separator in
7963 // the FilePath. On Windows, for example, both '/' and '\' are valid path
7964 // separators. Returns NULL if no path separator was found.
7965 const char* FilePath::FindLastPathSeparator() const {
7966 const char* const last_sep
= strrchr(c_str(), kPathSeparator
);
7967 #if GTEST_HAS_ALT_PATH_SEP_
7968 const char* const last_alt_sep
= strrchr(c_str(), kAlternatePathSeparator
);
7969 // Comparing two pointers of which only one is NULL is undefined.
7970 if (last_alt_sep
!= NULL
&&
7971 (last_sep
== NULL
|| last_alt_sep
> last_sep
)) {
7972 return last_alt_sep
;
7978 // Returns a copy of the FilePath with the directory part removed.
7979 // Example: FilePath("path/to/file").RemoveDirectoryName() returns
7980 // FilePath("file"). If there is no directory part ("just_a_file"), it returns
7981 // the FilePath unmodified. If there is no file part ("just_a_dir/") it
7982 // returns an empty FilePath ("").
7983 // On Windows platform, '\' is the path separator, otherwise it is '/'.
7984 FilePath
FilePath::RemoveDirectoryName() const {
7985 const char* const last_sep
= FindLastPathSeparator();
7986 return last_sep
? FilePath(last_sep
+ 1) : *this;
7989 // RemoveFileName returns the directory path with the filename removed.
7990 // Example: FilePath("path/to/file").RemoveFileName() returns "path/to/".
7991 // If the FilePath is "a_file" or "/a_file", RemoveFileName returns
7992 // FilePath("./") or, on Windows, FilePath(".\\"). If the filepath does
7993 // not have a file, like "just/a/dir/", it returns the FilePath unmodified.
7994 // On Windows platform, '\' is the path separator, otherwise it is '/'.
7995 FilePath
FilePath::RemoveFileName() const {
7996 const char* const last_sep
= FindLastPathSeparator();
7999 dir
= std::string(c_str(), last_sep
+ 1 - c_str());
8001 dir
= kCurrentDirectoryString
;
8003 return FilePath(dir
);
8006 // Helper functions for naming files in a directory for xml output.
8008 // Given directory = "dir", base_name = "test", number = 0,
8009 // extension = "xml", returns "dir/test.xml". If number is greater
8010 // than zero (e.g., 12), returns "dir/test_12.xml".
8011 // On Windows platform, uses \ as the separator rather than /.
8012 FilePath
FilePath::MakeFileName(const FilePath
& directory
,
8013 const FilePath
& base_name
,
8015 const char* extension
) {
8018 file
= base_name
.string() + "." + extension
;
8020 file
= base_name
.string() + "_" + StreamableToString(number
)
8023 return ConcatPaths(directory
, FilePath(file
));
8026 // Given directory = "dir", relative_path = "test.xml", returns "dir/test.xml".
8027 // On Windows, uses \ as the separator rather than /.
8028 FilePath
FilePath::ConcatPaths(const FilePath
& directory
,
8029 const FilePath
& relative_path
) {
8030 if (directory
.IsEmpty())
8031 return relative_path
;
8032 const FilePath
dir(directory
.RemoveTrailingPathSeparator());
8033 return FilePath(dir
.string() + kPathSeparator
+ relative_path
.string());
8036 // Returns true if pathname describes something findable in the file-system,
8037 // either a file, directory, or whatever.
8038 bool FilePath::FileOrDirectoryExists() const {
8039 #if GTEST_OS_WINDOWS_MOBILE
8040 LPCWSTR unicode
= String::AnsiToUtf16(pathname_
.c_str());
8041 const DWORD attributes
= GetFileAttributes(unicode
);
8043 return attributes
!= kInvalidFileAttributes
;
8045 posix::StatStruct file_stat
;
8046 return posix::Stat(pathname_
.c_str(), &file_stat
) == 0;
8047 #endif // GTEST_OS_WINDOWS_MOBILE
8050 // Returns true if pathname describes a directory in the file-system
8052 bool FilePath::DirectoryExists() const {
8053 bool result
= false;
8054 #if GTEST_OS_WINDOWS
8055 // Don't strip off trailing separator if path is a root directory on
8056 // Windows (like "C:\\").
8057 const FilePath
& path(IsRootDirectory() ? *this :
8058 RemoveTrailingPathSeparator());
8060 const FilePath
& path(*this);
8063 #if GTEST_OS_WINDOWS_MOBILE
8064 LPCWSTR unicode
= String::AnsiToUtf16(path
.c_str());
8065 const DWORD attributes
= GetFileAttributes(unicode
);
8067 if ((attributes
!= kInvalidFileAttributes
) &&
8068 (attributes
& FILE_ATTRIBUTE_DIRECTORY
)) {
8072 posix::StatStruct file_stat
;
8073 result
= posix::Stat(path
.c_str(), &file_stat
) == 0 &&
8074 posix::IsDir(file_stat
);
8075 #endif // GTEST_OS_WINDOWS_MOBILE
8080 // Returns true if pathname describes a root directory. (Windows has one
8081 // root directory per disk drive.)
8082 bool FilePath::IsRootDirectory() const {
8083 #if GTEST_OS_WINDOWS
8084 // TODO(wan@google.com): on Windows a network share like
8085 // \\server\share can be a root directory, although it cannot be the
8086 // current directory. Handle this properly.
8087 return pathname_
.length() == 3 && IsAbsolutePath();
8089 return pathname_
.length() == 1 && IsPathSeparator(pathname_
.c_str()[0]);
8093 // Returns true if pathname describes an absolute path.
8094 bool FilePath::IsAbsolutePath() const {
8095 const char* const name
= pathname_
.c_str();
8096 #if GTEST_OS_WINDOWS
8097 return pathname_
.length() >= 3 &&
8098 ((name
[0] >= 'a' && name
[0] <= 'z') ||
8099 (name
[0] >= 'A' && name
[0] <= 'Z')) &&
8101 IsPathSeparator(name
[2]);
8103 return IsPathSeparator(name
[0]);
8107 // Returns a pathname for a file that does not currently exist. The pathname
8108 // will be directory/base_name.extension or
8109 // directory/base_name_<number>.extension if directory/base_name.extension
8110 // already exists. The number will be incremented until a pathname is found
8111 // that does not already exist.
8112 // Examples: 'dir/foo_test.xml' or 'dir/foo_test_1.xml'.
8113 // There could be a race condition if two or more processes are calling this
8114 // function at the same time -- they could both pick the same filename.
8115 FilePath
FilePath::GenerateUniqueFileName(const FilePath
& directory
,
8116 const FilePath
& base_name
,
8117 const char* extension
) {
8118 FilePath full_pathname
;
8121 full_pathname
.Set(MakeFileName(directory
, base_name
, number
++, extension
));
8122 } while (full_pathname
.FileOrDirectoryExists());
8123 return full_pathname
;
8126 // Returns true if FilePath ends with a path separator, which indicates that
8127 // it is intended to represent a directory. Returns false otherwise.
8128 // This does NOT check that a directory (or file) actually exists.
8129 bool FilePath::IsDirectory() const {
8130 return !pathname_
.empty() &&
8131 IsPathSeparator(pathname_
.c_str()[pathname_
.length() - 1]);
8134 // Create directories so that path exists. Returns true if successful or if
8135 // the directories already exist; returns false if unable to create directories
8137 bool FilePath::CreateDirectoriesRecursively() const {
8138 if (!this->IsDirectory()) {
8142 if (pathname_
.length() == 0 || this->DirectoryExists()) {
8146 const FilePath
parent(this->RemoveTrailingPathSeparator().RemoveFileName());
8147 return parent
.CreateDirectoriesRecursively() && this->CreateFolder();
8150 // Create the directory so that path exists. Returns true if successful or
8151 // if the directory already exists; returns false if unable to create the
8152 // directory for any reason, including if the parent directory does not
8153 // exist. Not named "CreateDirectory" because that's a macro on Windows.
8154 bool FilePath::CreateFolder() const {
8155 #if GTEST_OS_WINDOWS_MOBILE
8156 FilePath
removed_sep(this->RemoveTrailingPathSeparator());
8157 LPCWSTR unicode
= String::AnsiToUtf16(removed_sep
.c_str());
8158 int result
= CreateDirectory(unicode
, NULL
) ? 0 : -1;
8160 #elif GTEST_OS_WINDOWS
8161 int result
= _mkdir(pathname_
.c_str());
8163 int result
= mkdir(pathname_
.c_str(), 0777);
8164 #endif // GTEST_OS_WINDOWS_MOBILE
8167 return this->DirectoryExists(); // An error is OK if the directory exists.
8169 return true; // No error.
8172 // If input name has a trailing separator character, remove it and return the
8173 // name, otherwise return the name string unmodified.
8174 // On Windows platform, uses \ as the separator, other platforms use /.
8175 FilePath
FilePath::RemoveTrailingPathSeparator() const {
8176 return IsDirectory()
8177 ? FilePath(pathname_
.substr(0, pathname_
.length() - 1))
8181 // Removes any redundant separators that might be in the pathname.
8182 // For example, "bar///foo" becomes "bar/foo". Does not eliminate other
8183 // redundancies that might be in a pathname involving "." or "..".
8184 // TODO(wan@google.com): handle Windows network shares (e.g. \\server\share).
8185 void FilePath::Normalize() {
8186 if (pathname_
.c_str() == NULL
) {
8190 const char* src
= pathname_
.c_str();
8191 char* const dest
= new char[pathname_
.length() + 1];
8192 char* dest_ptr
= dest
;
8193 memset(dest_ptr
, 0, pathname_
.length() + 1);
8195 while (*src
!= '\0') {
8197 if (!IsPathSeparator(*src
)) {
8200 #if GTEST_HAS_ALT_PATH_SEP_
8201 if (*dest_ptr
== kAlternatePathSeparator
) {
8202 *dest_ptr
= kPathSeparator
;
8205 while (IsPathSeparator(*src
))
8215 } // namespace internal
8216 } // namespace testing
8217 // Copyright 2008, Google Inc.
8218 // All rights reserved.
8220 // Redistribution and use in source and binary forms, with or without
8221 // modification, are permitted provided that the following conditions are
8224 // * Redistributions of source code must retain the above copyright
8225 // notice, this list of conditions and the following disclaimer.
8226 // * Redistributions in binary form must reproduce the above
8227 // copyright notice, this list of conditions and the following disclaimer
8228 // in the documentation and/or other materials provided with the
8230 // * Neither the name of Google Inc. nor the names of its
8231 // contributors may be used to endorse or promote products derived from
8232 // this software without specific prior written permission.
8234 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
8235 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
8236 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
8237 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
8238 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
8239 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
8240 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
8241 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
8242 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
8243 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
8244 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
8246 // Author: wan@google.com (Zhanyong Wan)
8254 #if GTEST_OS_WINDOWS_MOBILE
8255 # include <windows.h> // For TerminateProcess()
8256 #elif GTEST_OS_WINDOWS
8258 # include <sys/stat.h>
8260 # include <unistd.h>
8261 #endif // GTEST_OS_WINDOWS_MOBILE
8264 # include <mach/mach_init.h>
8265 # include <mach/task.h>
8266 # include <mach/vm_map.h>
8267 #endif // GTEST_OS_MAC
8270 # include <devctl.h>
8271 # include <sys/procfs.h>
8272 #endif // GTEST_OS_QNX
8275 // Indicates that this translation unit is part of Google Test's
8276 // implementation. It must come before gtest-internal-inl.h is
8277 // included, or there will be a compiler error. This trick is to
8278 // prevent a user from accidentally including gtest-internal-inl.h in
8280 #define GTEST_IMPLEMENTATION_ 1
8281 #undef GTEST_IMPLEMENTATION_
8284 namespace internal
{
8286 #if defined(_MSC_VER) || defined(__BORLANDC__)
8287 // MSVC and C++Builder do not provide a definition of STDERR_FILENO.
8288 const int kStdOutFileno
= 1;
8289 const int kStdErrFileno
= 2;
8291 const int kStdOutFileno
= STDOUT_FILENO
;
8292 const int kStdErrFileno
= STDERR_FILENO
;
8297 // Returns the number of threads running in the process, or 0 to indicate that
8298 // we cannot detect it.
8299 size_t GetThreadCount() {
8300 const task_t task
= mach_task_self();
8301 mach_msg_type_number_t thread_count
;
8302 thread_act_array_t thread_list
;
8303 const kern_return_t status
= task_threads(task
, &thread_list
, &thread_count
);
8304 if (status
== KERN_SUCCESS
) {
8305 // task_threads allocates resources in thread_list and we need to free them
8308 reinterpret_cast<vm_address_t
>(thread_list
),
8309 sizeof(thread_t
) * thread_count
);
8310 return static_cast<size_t>(thread_count
);
8318 // Returns the number of threads running in the process, or 0 to indicate that
8319 // we cannot detect it.
8320 size_t GetThreadCount() {
8321 const int fd
= open("/proc/self/as", O_RDONLY
);
8325 procfs_info process_info
;
8327 devctl(fd
, DCMD_PROC_INFO
, &process_info
, sizeof(process_info
), NULL
);
8329 if (status
== EOK
) {
8330 return static_cast<size_t>(process_info
.num_threads
);
8338 size_t GetThreadCount() {
8339 // There's no portable way to detect the number of threads, so we just
8340 // return 0 to indicate that we cannot detect it.
8344 #endif // GTEST_OS_MAC
8346 #if GTEST_USES_POSIX_RE
8348 // Implements RE. Currently only needed for death tests.
8352 // regfree'ing an invalid regex might crash because the content
8353 // of the regex is undefined. Since the regex's are essentially
8354 // the same, one cannot be valid (or invalid) without the other
8356 regfree(&partial_regex_
);
8357 regfree(&full_regex_
);
8359 free(const_cast<char*>(pattern_
));
8362 // Returns true iff regular expression re matches the entire str.
8363 bool RE::FullMatch(const char* str
, const RE
& re
) {
8364 if (!re
.is_valid_
) return false;
8367 return regexec(&re
.full_regex_
, str
, 1, &match
, 0) == 0;
8370 // Returns true iff regular expression re matches a substring of str
8371 // (including str itself).
8372 bool RE::PartialMatch(const char* str
, const RE
& re
) {
8373 if (!re
.is_valid_
) return false;
8376 return regexec(&re
.partial_regex_
, str
, 1, &match
, 0) == 0;
8379 // Initializes an RE from its string representation.
8380 void RE::Init(const char* regex
) {
8381 pattern_
= posix::StrDup(regex
);
8383 // Reserves enough bytes to hold the regular expression used for a
8385 const size_t full_regex_len
= strlen(regex
) + 10;
8386 char* const full_pattern
= new char[full_regex_len
];
8388 snprintf(full_pattern
, full_regex_len
, "^(%s)$", regex
);
8389 is_valid_
= regcomp(&full_regex_
, full_pattern
, REG_EXTENDED
) == 0;
8390 // We want to call regcomp(&partial_regex_, ...) even if the
8391 // previous expression returns false. Otherwise partial_regex_ may
8392 // not be properly initialized can may cause trouble when it's
8395 // Some implementation of POSIX regex (e.g. on at least some
8396 // versions of Cygwin) doesn't accept the empty string as a valid
8397 // regex. We change it to an equivalent form "()" to be safe.
8399 const char* const partial_regex
= (*regex
== '\0') ? "()" : regex
;
8400 is_valid_
= regcomp(&partial_regex_
, partial_regex
, REG_EXTENDED
) == 0;
8402 EXPECT_TRUE(is_valid_
)
8403 << "Regular expression \"" << regex
8404 << "\" is not a valid POSIX Extended regular expression.";
8406 delete[] full_pattern
;
8409 #elif GTEST_USES_SIMPLE_RE
8411 // Returns true iff ch appears anywhere in str (excluding the
8412 // terminating '\0' character).
8413 bool IsInSet(char ch
, const char* str
) {
8414 return ch
!= '\0' && strchr(str
, ch
) != NULL
;
8417 // Returns true iff ch belongs to the given classification. Unlike
8418 // similar functions in <ctype.h>, these aren't affected by the
8420 bool IsAsciiDigit(char ch
) { return '0' <= ch
&& ch
<= '9'; }
8421 bool IsAsciiPunct(char ch
) {
8422 return IsInSet(ch
, "^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~");
8424 bool IsRepeat(char ch
) { return IsInSet(ch
, "?*+"); }
8425 bool IsAsciiWhiteSpace(char ch
) { return IsInSet(ch
, " \f\n\r\t\v"); }
8426 bool IsAsciiWordChar(char ch
) {
8427 return ('a' <= ch
&& ch
<= 'z') || ('A' <= ch
&& ch
<= 'Z') ||
8428 ('0' <= ch
&& ch
<= '9') || ch
== '_';
8431 // Returns true iff "\\c" is a supported escape sequence.
8432 bool IsValidEscape(char c
) {
8433 return (IsAsciiPunct(c
) || IsInSet(c
, "dDfnrsStvwW"));
8436 // Returns true iff the given atom (specified by escaped and pattern)
8437 // matches ch. The result is undefined if the atom is invalid.
8438 bool AtomMatchesChar(bool escaped
, char pattern_char
, char ch
) {
8439 if (escaped
) { // "\\p" where p is pattern_char.
8440 switch (pattern_char
) {
8441 case 'd': return IsAsciiDigit(ch
);
8442 case 'D': return !IsAsciiDigit(ch
);
8443 case 'f': return ch
== '\f';
8444 case 'n': return ch
== '\n';
8445 case 'r': return ch
== '\r';
8446 case 's': return IsAsciiWhiteSpace(ch
);
8447 case 'S': return !IsAsciiWhiteSpace(ch
);
8448 case 't': return ch
== '\t';
8449 case 'v': return ch
== '\v';
8450 case 'w': return IsAsciiWordChar(ch
);
8451 case 'W': return !IsAsciiWordChar(ch
);
8453 return IsAsciiPunct(pattern_char
) && pattern_char
== ch
;
8456 return (pattern_char
== '.' && ch
!= '\n') || pattern_char
== ch
;
8459 // Helper function used by ValidateRegex() to format error messages.
8460 std::string
FormatRegexSyntaxError(const char* regex
, int index
) {
8461 return (Message() << "Syntax error at index " << index
8462 << " in simple regular expression \"" << regex
<< "\": ").GetString();
8465 // Generates non-fatal failures and returns false if regex is invalid;
8466 // otherwise returns true.
8467 bool ValidateRegex(const char* regex
) {
8468 if (regex
== NULL
) {
8469 // TODO(wan@google.com): fix the source file location in the
8470 // assertion failures to match where the regex is used in user
8472 ADD_FAILURE() << "NULL is not a valid simple regular expression.";
8476 bool is_valid
= true;
8478 // True iff ?, *, or + can follow the previous atom.
8479 bool prev_repeatable
= false;
8480 for (int i
= 0; regex
[i
]; i
++) {
8481 if (regex
[i
] == '\\') { // An escape sequence
8483 if (regex
[i
] == '\0') {
8484 ADD_FAILURE() << FormatRegexSyntaxError(regex
, i
- 1)
8485 << "'\\' cannot appear at the end.";
8489 if (!IsValidEscape(regex
[i
])) {
8490 ADD_FAILURE() << FormatRegexSyntaxError(regex
, i
- 1)
8491 << "invalid escape sequence \"\\" << regex
[i
] << "\".";
8494 prev_repeatable
= true;
8495 } else { // Not an escape sequence.
8496 const char ch
= regex
[i
];
8498 if (ch
== '^' && i
> 0) {
8499 ADD_FAILURE() << FormatRegexSyntaxError(regex
, i
)
8500 << "'^' can only appear at the beginning.";
8502 } else if (ch
== '$' && regex
[i
+ 1] != '\0') {
8503 ADD_FAILURE() << FormatRegexSyntaxError(regex
, i
)
8504 << "'$' can only appear at the end.";
8506 } else if (IsInSet(ch
, "()[]{}|")) {
8507 ADD_FAILURE() << FormatRegexSyntaxError(regex
, i
)
8508 << "'" << ch
<< "' is unsupported.";
8510 } else if (IsRepeat(ch
) && !prev_repeatable
) {
8511 ADD_FAILURE() << FormatRegexSyntaxError(regex
, i
)
8512 << "'" << ch
<< "' can only follow a repeatable token.";
8516 prev_repeatable
= !IsInSet(ch
, "^$?*+");
8523 // Matches a repeated regex atom followed by a valid simple regular
8524 // expression. The regex atom is defined as c if escaped is false,
8525 // or \c otherwise. repeat is the repetition meta character (?, *,
8526 // or +). The behavior is undefined if str contains too many
8527 // characters to be indexable by size_t, in which case the test will
8528 // probably time out anyway. We are fine with this limitation as
8529 // std::string has it too.
8530 bool MatchRepetitionAndRegexAtHead(
8531 bool escaped
, char c
, char repeat
, const char* regex
,
8533 const size_t min_count
= (repeat
== '+') ? 1 : 0;
8534 const size_t max_count
= (repeat
== '?') ? 1 :
8535 static_cast<size_t>(-1) - 1;
8536 // We cannot call numeric_limits::max() as it conflicts with the
8537 // max() macro on Windows.
8539 for (size_t i
= 0; i
<= max_count
; ++i
) {
8540 // We know that the atom matches each of the first i characters in str.
8541 if (i
>= min_count
&& MatchRegexAtHead(regex
, str
+ i
)) {
8542 // We have enough matches at the head, and the tail matches too.
8543 // Since we only care about *whether* the pattern matches str
8544 // (as opposed to *how* it matches), there is no need to find a
8548 if (str
[i
] == '\0' || !AtomMatchesChar(escaped
, c
, str
[i
]))
8554 // Returns true iff regex matches a prefix of str. regex must be a
8555 // valid simple regular expression and not start with "^", or the
8556 // result is undefined.
8557 bool MatchRegexAtHead(const char* regex
, const char* str
) {
8558 if (*regex
== '\0') // An empty regex matches a prefix of anything.
8561 // "$" only matches the end of a string. Note that regex being
8562 // valid guarantees that there's nothing after "$" in it.
8564 return *str
== '\0';
8566 // Is the first thing in regex an escape sequence?
8567 const bool escaped
= *regex
== '\\';
8570 if (IsRepeat(regex
[1])) {
8571 // MatchRepetitionAndRegexAtHead() calls MatchRegexAtHead(), so
8572 // here's an indirect recursion. It terminates as the regex gets
8573 // shorter in each recursion.
8574 return MatchRepetitionAndRegexAtHead(
8575 escaped
, regex
[0], regex
[1], regex
+ 2, str
);
8577 // regex isn't empty, isn't "$", and doesn't start with a
8578 // repetition. We match the first atom of regex with the first
8579 // character of str and recurse.
8580 return (*str
!= '\0') && AtomMatchesChar(escaped
, *regex
, *str
) &&
8581 MatchRegexAtHead(regex
+ 1, str
+ 1);
8585 // Returns true iff regex matches any substring of str. regex must be
8586 // a valid simple regular expression, or the result is undefined.
8588 // The algorithm is recursive, but the recursion depth doesn't exceed
8589 // the regex length, so we won't need to worry about running out of
8590 // stack space normally. In rare cases the time complexity can be
8591 // exponential with respect to the regex length + the string length,
8592 // but usually it's must faster (often close to linear).
8593 bool MatchRegexAnywhere(const char* regex
, const char* str
) {
8594 if (regex
== NULL
|| str
== NULL
)
8598 return MatchRegexAtHead(regex
+ 1, str
);
8600 // A successful match can be anywhere in str.
8602 if (MatchRegexAtHead(regex
, str
))
8604 } while (*str
++ != '\0');
8608 // Implements the RE class.
8611 free(const_cast<char*>(pattern_
));
8612 free(const_cast<char*>(full_pattern_
));
8615 // Returns true iff regular expression re matches the entire str.
8616 bool RE::FullMatch(const char* str
, const RE
& re
) {
8617 return re
.is_valid_
&& MatchRegexAnywhere(re
.full_pattern_
, str
);
8620 // Returns true iff regular expression re matches a substring of str
8621 // (including str itself).
8622 bool RE::PartialMatch(const char* str
, const RE
& re
) {
8623 return re
.is_valid_
&& MatchRegexAnywhere(re
.pattern_
, str
);
8626 // Initializes an RE from its string representation.
8627 void RE::Init(const char* regex
) {
8628 pattern_
= full_pattern_
= NULL
;
8629 if (regex
!= NULL
) {
8630 pattern_
= posix::StrDup(regex
);
8633 is_valid_
= ValidateRegex(regex
);
8635 // No need to calculate the full pattern when the regex is invalid.
8639 const size_t len
= strlen(regex
);
8640 // Reserves enough bytes to hold the regular expression used for a
8641 // full match: we need space to prepend a '^', append a '$', and
8642 // terminate the string with '\0'.
8643 char* buffer
= static_cast<char*>(malloc(len
+ 3));
8644 full_pattern_
= buffer
;
8647 *buffer
++ = '^'; // Makes sure full_pattern_ starts with '^'.
8649 // We don't use snprintf or strncpy, as they trigger a warning when
8650 // compiled with VC++ 8.0.
8651 memcpy(buffer
, regex
, len
);
8654 if (len
== 0 || regex
[len
- 1] != '$')
8655 *buffer
++ = '$'; // Makes sure full_pattern_ ends with '$'.
8660 #endif // GTEST_USES_POSIX_RE
8662 const char kUnknownFile
[] = "unknown file";
8664 // Formats a source file path and a line number as they would appear
8665 // in an error message from the compiler used to compile this code.
8666 GTEST_API_ ::std::string
FormatFileLocation(const char* file
, int line
) {
8667 const std::string
file_name(file
== NULL
? kUnknownFile
: file
);
8670 return file_name
+ ":";
8673 return file_name
+ "(" + StreamableToString(line
) + "):";
8675 return file_name
+ ":" + StreamableToString(line
) + ":";
8679 // Formats a file location for compiler-independent XML output.
8680 // Although this function is not platform dependent, we put it next to
8681 // FormatFileLocation in order to contrast the two functions.
8682 // Note that FormatCompilerIndependentFileLocation() does NOT append colon
8683 // to the file location it produces, unlike FormatFileLocation().
8684 GTEST_API_ ::std::string
FormatCompilerIndependentFileLocation(
8685 const char* file
, int line
) {
8686 const std::string
file_name(file
== NULL
? kUnknownFile
: file
);
8691 return file_name
+ ":" + StreamableToString(line
);
8695 GTestLog::GTestLog(GTestLogSeverity severity
, const char* file
, int line
)
8696 : severity_(severity
) {
8697 const char* const marker
=
8698 severity
== GTEST_INFO
? "[ INFO ]" :
8699 severity
== GTEST_WARNING
? "[WARNING]" :
8700 severity
== GTEST_ERROR
? "[ ERROR ]" : "[ FATAL ]";
8701 GetStream() << ::std::endl
<< marker
<< " "
8702 << FormatFileLocation(file
, line
).c_str() << ": ";
8705 // Flushes the buffers and, if severity is GTEST_FATAL, aborts the program.
8706 GTestLog::~GTestLog() {
8707 GetStream() << ::std::endl
;
8708 if (severity_
== GTEST_FATAL
) {
8713 // Disable Microsoft deprecation warnings for POSIX functions called from
8714 // this class (creat, dup, dup2, and close)
8716 # pragma warning(push)
8717 # pragma warning(disable: 4996)
8720 #if GTEST_HAS_STREAM_REDIRECTION
8722 // Object that captures an output stream (stdout/stderr).
8723 class CapturedStream
{
8725 // The ctor redirects the stream to a temporary file.
8726 explicit CapturedStream(int fd
) : fd_(fd
), uncaptured_fd_(dup(fd
)) {
8727 # if GTEST_OS_WINDOWS
8728 char temp_dir_path
[MAX_PATH
+ 1] = { '\0' }; // NOLINT
8729 char temp_file_path
[MAX_PATH
+ 1] = { '\0' }; // NOLINT
8731 ::GetTempPathA(sizeof(temp_dir_path
), temp_dir_path
);
8732 const UINT success
= ::GetTempFileNameA(temp_dir_path
,
8734 0, // Generate unique file name.
8736 GTEST_CHECK_(success
!= 0)
8737 << "Unable to create a temporary file in " << temp_dir_path
;
8738 const int captured_fd
= creat(temp_file_path
, _S_IREAD
| _S_IWRITE
);
8739 GTEST_CHECK_(captured_fd
!= -1) << "Unable to open temporary file "
8741 filename_
= temp_file_path
;
8743 // There's no guarantee that a test has write access to the current
8744 // directory, so we create the temporary file in the /tmp directory
8745 // instead. We use /tmp on most systems, and /sdcard on Android.
8746 // That's because Android doesn't have /tmp.
8747 # if GTEST_OS_LINUX_ANDROID
8748 // Note: Android applications are expected to call the framework's
8749 // Context.getExternalStorageDirectory() method through JNI to get
8750 // the location of the world-writable SD Card directory. However,
8751 // this requires a Context handle, which cannot be retrieved
8752 // globally from native code. Doing so also precludes running the
8753 // code as part of a regular standalone executable, which doesn't
8754 // run in a Dalvik process (e.g. when running it through 'adb shell').
8756 // The location /sdcard is directly accessible from native code
8757 // and is the only location (unofficially) supported by the Android
8758 // team. It's generally a symlink to the real SD Card mount point
8759 // which can be /mnt/sdcard, /mnt/sdcard0, /system/media/sdcard, or
8760 // other OEM-customized locations. Never rely on these, and always
8762 char name_template
[] = "/sdcard/gtest_captured_stream.XXXXXX";
8764 char name_template
[] = "/tmp/captured_stream.XXXXXX";
8765 # endif // GTEST_OS_LINUX_ANDROID
8766 const int captured_fd
= mkstemp(name_template
);
8767 filename_
= name_template
;
8768 # endif // GTEST_OS_WINDOWS
8770 dup2(captured_fd
, fd_
);
8775 remove(filename_
.c_str());
8778 std::string
GetCapturedString() {
8779 if (uncaptured_fd_
!= -1) {
8780 // Restores the original stream.
8782 dup2(uncaptured_fd_
, fd_
);
8783 close(uncaptured_fd_
);
8784 uncaptured_fd_
= -1;
8787 FILE* const file
= posix::FOpen(filename_
.c_str(), "r");
8788 const std::string content
= ReadEntireFile(file
);
8789 posix::FClose(file
);
8794 // Reads the entire content of a file as an std::string.
8795 static std::string
ReadEntireFile(FILE* file
);
8797 // Returns the size (in bytes) of a file.
8798 static size_t GetFileSize(FILE* file
);
8800 const int fd_
; // A stream to capture.
8802 // Name of the temporary file holding the stderr output.
8803 ::std::string filename_
;
8805 GTEST_DISALLOW_COPY_AND_ASSIGN_(CapturedStream
);
8808 // Returns the size (in bytes) of a file.
8809 size_t CapturedStream::GetFileSize(FILE* file
) {
8810 fseek(file
, 0, SEEK_END
);
8811 return static_cast<size_t>(ftell(file
));
8814 // Reads the entire content of a file as a string.
8815 std::string
CapturedStream::ReadEntireFile(FILE* file
) {
8816 const size_t file_size
= GetFileSize(file
);
8817 char* const buffer
= new char[file_size
];
8819 size_t bytes_last_read
= 0; // # of bytes read in the last fread()
8820 size_t bytes_read
= 0; // # of bytes read so far
8822 fseek(file
, 0, SEEK_SET
);
8824 // Keeps reading the file until we cannot read further or the
8825 // pre-determined file size is reached.
8827 bytes_last_read
= fread(buffer
+bytes_read
, 1, file_size
-bytes_read
, file
);
8828 bytes_read
+= bytes_last_read
;
8829 } while (bytes_last_read
> 0 && bytes_read
< file_size
);
8831 const std::string
content(buffer
, bytes_read
);
8838 # pragma warning(pop)
8841 static CapturedStream
* g_captured_stderr
= NULL
;
8842 static CapturedStream
* g_captured_stdout
= NULL
;
8844 // Starts capturing an output stream (stdout/stderr).
8845 void CaptureStream(int fd
, const char* stream_name
, CapturedStream
** stream
) {
8846 if (*stream
!= NULL
) {
8847 GTEST_LOG_(FATAL
) << "Only one " << stream_name
8848 << " capturer can exist at a time.";
8850 *stream
= new CapturedStream(fd
);
8853 // Stops capturing the output stream and returns the captured string.
8854 std::string
GetCapturedStream(CapturedStream
** captured_stream
) {
8855 const std::string content
= (*captured_stream
)->GetCapturedString();
8857 delete *captured_stream
;
8858 *captured_stream
= NULL
;
8863 // Starts capturing stdout.
8864 void CaptureStdout() {
8865 CaptureStream(kStdOutFileno
, "stdout", &g_captured_stdout
);
8868 // Starts capturing stderr.
8869 void CaptureStderr() {
8870 CaptureStream(kStdErrFileno
, "stderr", &g_captured_stderr
);
8873 // Stops capturing stdout and returns the captured string.
8874 std::string
GetCapturedStdout() {
8875 return GetCapturedStream(&g_captured_stdout
);
8878 // Stops capturing stderr and returns the captured string.
8879 std::string
GetCapturedStderr() {
8880 return GetCapturedStream(&g_captured_stderr
);
8883 #endif // GTEST_HAS_STREAM_REDIRECTION
8885 #if GTEST_HAS_DEATH_TEST
8887 // A copy of all command line arguments. Set by InitGoogleTest().
8888 ::std::vector
<testing::internal::string
> g_argvs
;
8890 static const ::std::vector
<testing::internal::string
>* g_injected_test_argvs
=
8893 void SetInjectableArgvs(const ::std::vector
<testing::internal::string
>* argvs
) {
8894 if (g_injected_test_argvs
!= argvs
)
8895 delete g_injected_test_argvs
;
8896 g_injected_test_argvs
= argvs
;
8899 const ::std::vector
<testing::internal::string
>& GetInjectableArgvs() {
8900 if (g_injected_test_argvs
!= NULL
) {
8901 return *g_injected_test_argvs
;
8905 #endif // GTEST_HAS_DEATH_TEST
8907 #if GTEST_OS_WINDOWS_MOBILE
8911 TerminateProcess(GetCurrentProcess(), 1);
8913 } // namespace posix
8914 #endif // GTEST_OS_WINDOWS_MOBILE
8916 // Returns the name of the environment variable corresponding to the
8917 // given flag. For example, FlagToEnvVar("foo") will return
8918 // "GTEST_FOO" in the open-source version.
8919 static std::string
FlagToEnvVar(const char* flag
) {
8920 const std::string full_flag
=
8921 (Message() << GTEST_FLAG_PREFIX_
<< flag
).GetString();
8924 for (size_t i
= 0; i
!= full_flag
.length(); i
++) {
8925 env_var
<< ToUpper(full_flag
.c_str()[i
]);
8928 return env_var
.GetString();
8931 // Parses 'str' for a 32-bit signed integer. If successful, writes
8932 // the result to *value and returns true; otherwise leaves *value
8933 // unchanged and returns false.
8934 bool ParseInt32(const Message
& src_text
, const char* str
, Int32
* value
) {
8935 // Parses the environment variable as a decimal integer.
8937 const long long_value
= strtol(str
, &end
, 10); // NOLINT
8939 // Has strtol() consumed all characters in the string?
8941 // No - an invalid character was encountered.
8943 msg
<< "WARNING: " << src_text
8944 << " is expected to be a 32-bit integer, but actually"
8945 << " has value \"" << str
<< "\".\n";
8946 printf("%s", msg
.GetString().c_str());
8951 // Is the parsed value in the range of an Int32?
8952 const Int32 result
= static_cast<Int32
>(long_value
);
8953 if (long_value
== LONG_MAX
|| long_value
== LONG_MIN
||
8954 // The parsed value overflows as a long. (strtol() returns
8955 // LONG_MAX or LONG_MIN when the input overflows.)
8956 result
!= long_value
8957 // The parsed value overflows as an Int32.
8960 msg
<< "WARNING: " << src_text
8961 << " is expected to be a 32-bit integer, but actually"
8962 << " has value " << str
<< ", which overflows.\n";
8963 printf("%s", msg
.GetString().c_str());
8972 // Reads and returns the Boolean environment variable corresponding to
8973 // the given flag; if it's not set, returns default_value.
8975 // The value is considered true iff it's not "0".
8976 bool BoolFromGTestEnv(const char* flag
, bool default_value
) {
8977 const std::string env_var
= FlagToEnvVar(flag
);
8978 const char* const string_value
= posix::GetEnv(env_var
.c_str());
8979 return string_value
== NULL
?
8980 default_value
: strcmp(string_value
, "0") != 0;
8983 // Reads and returns a 32-bit integer stored in the environment
8984 // variable corresponding to the given flag; if it isn't set or
8985 // doesn't represent a valid 32-bit integer, returns default_value.
8986 Int32
Int32FromGTestEnv(const char* flag
, Int32 default_value
) {
8987 const std::string env_var
= FlagToEnvVar(flag
);
8988 const char* const string_value
= posix::GetEnv(env_var
.c_str());
8989 if (string_value
== NULL
) {
8990 // The environment variable is not set.
8991 return default_value
;
8994 Int32 result
= default_value
;
8995 if (!ParseInt32(Message() << "Environment variable " << env_var
,
8996 string_value
, &result
)) {
8997 printf("The default value %s is used.\n",
8998 (Message() << default_value
).GetString().c_str());
9000 return default_value
;
9006 // Reads and returns the string environment variable corresponding to
9007 // the given flag; if it's not set, returns default_value.
9008 const char* StringFromGTestEnv(const char* flag
, const char* default_value
) {
9009 const std::string env_var
= FlagToEnvVar(flag
);
9010 const char* const value
= posix::GetEnv(env_var
.c_str());
9011 return value
== NULL
? default_value
: value
;
9014 } // namespace internal
9015 } // namespace testing
9016 // Copyright 2007, Google Inc.
9017 // All rights reserved.
9019 // Redistribution and use in source and binary forms, with or without
9020 // modification, are permitted provided that the following conditions are
9023 // * Redistributions of source code must retain the above copyright
9024 // notice, this list of conditions and the following disclaimer.
9025 // * Redistributions in binary form must reproduce the above
9026 // copyright notice, this list of conditions and the following disclaimer
9027 // in the documentation and/or other materials provided with the
9029 // * Neither the name of Google Inc. nor the names of its
9030 // contributors may be used to endorse or promote products derived from
9031 // this software without specific prior written permission.
9033 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
9034 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
9035 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
9036 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9037 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
9038 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9039 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
9040 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
9041 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
9042 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
9043 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
9045 // Author: wan@google.com (Zhanyong Wan)
9047 // Google Test - The Google C++ Testing Framework
9049 // This file implements a universal value printer that can print a
9050 // value of any type T:
9052 // void ::testing::internal::UniversalPrinter<T>::Print(value, ostream_ptr);
9054 // It uses the << operator when possible, and prints the bytes in the
9055 // object otherwise. A user can override its behavior for a class
9056 // type Foo by defining either operator<<(::std::ostream&, const Foo&)
9057 // or void PrintTo(const Foo&, ::std::ostream*) in the namespace that
9062 #include <ostream> // NOLINT
9069 using ::std::ostream
;
9071 // Prints a segment of bytes in the given object.
9072 void PrintByteSegmentInObjectTo(const unsigned char* obj_bytes
, size_t start
,
9073 size_t count
, ostream
* os
) {
9075 for (size_t i
= 0; i
!= count
; i
++) {
9076 const size_t j
= start
+ i
;
9078 // Organizes the bytes into groups of 2 for easy parsing by
9085 GTEST_SNPRINTF_(text
, sizeof(text
), "%02X", obj_bytes
[j
]);
9090 // Prints the bytes in the given value to the given ostream.
9091 void PrintBytesInObjectToImpl(const unsigned char* obj_bytes
, size_t count
,
9093 // Tells the user how big the object is.
9094 *os
<< count
<< "-byte object <";
9096 const size_t kThreshold
= 132;
9097 const size_t kChunkSize
= 64;
9098 // If the object size is bigger than kThreshold, we'll have to omit
9099 // some details by printing only the first and the last kChunkSize
9101 // TODO(wan): let the user control the threshold using a flag.
9102 if (count
< kThreshold
) {
9103 PrintByteSegmentInObjectTo(obj_bytes
, 0, count
, os
);
9105 PrintByteSegmentInObjectTo(obj_bytes
, 0, kChunkSize
, os
);
9107 // Rounds up to 2-byte boundary.
9108 const size_t resume_pos
= (count
- kChunkSize
+ 1)/2*2;
9109 PrintByteSegmentInObjectTo(obj_bytes
, resume_pos
, count
- resume_pos
, os
);
9116 namespace internal2
{
9118 // Delegates to PrintBytesInObjectToImpl() to print the bytes in the
9119 // given object. The delegation simplifies the implementation, which
9120 // uses the << operator and thus is easier done outside of the
9121 // ::testing::internal namespace, which contains a << operator that
9122 // sometimes conflicts with the one in STL.
9123 void PrintBytesInObjectTo(const unsigned char* obj_bytes
, size_t count
,
9125 PrintBytesInObjectToImpl(obj_bytes
, count
, os
);
9128 } // namespace internal2
9130 namespace internal
{
9132 // Depending on the value of a char (or wchar_t), we print it in one
9133 // of three formats:
9134 // - as is if it's a printable ASCII (e.g. 'a', '2', ' '),
9135 // - as a hexidecimal escape sequence (e.g. '\x7F'), or
9136 // - as a special escape sequence (e.g. '\r', '\n').
9143 // Returns true if c is a printable ASCII character. We test the
9144 // value of c directly instead of calling isprint(), which is buggy on
9146 inline bool IsPrintableAscii(wchar_t c
) {
9147 return 0x20 <= c
&& c
<= 0x7E;
9150 // Prints a wide or narrow char c as a character literal without the
9151 // quotes, escaping it when necessary; returns how c was formatted.
9152 // The template argument UnsignedChar is the unsigned version of Char,
9153 // which is the type of c.
9154 template <typename UnsignedChar
, typename Char
>
9155 static CharFormat
PrintAsCharLiteralTo(Char c
, ostream
* os
) {
9156 switch (static_cast<wchar_t>(c
)) {
9188 if (IsPrintableAscii(c
)) {
9189 *os
<< static_cast<char>(c
);
9192 *os
<< "\\x" + String::FormatHexInt(static_cast<UnsignedChar
>(c
));
9196 return kSpecialEscape
;
9199 // Prints a wchar_t c as if it's part of a string literal, escaping it when
9200 // necessary; returns how c was formatted.
9201 static CharFormat
PrintAsStringLiteralTo(wchar_t c
, ostream
* os
) {
9208 return kSpecialEscape
;
9210 return PrintAsCharLiteralTo
<wchar_t>(c
, os
);
9214 // Prints a char c as if it's part of a string literal, escaping it when
9215 // necessary; returns how c was formatted.
9216 static CharFormat
PrintAsStringLiteralTo(char c
, ostream
* os
) {
9217 return PrintAsStringLiteralTo(
9218 static_cast<wchar_t>(static_cast<unsigned char>(c
)), os
);
9221 // Prints a wide or narrow character c and its code. '\0' is printed
9222 // as "'\\0'", other unprintable characters are also properly escaped
9223 // using the standard C++ escape sequence. The template argument
9224 // UnsignedChar is the unsigned version of Char, which is the type of c.
9225 template <typename UnsignedChar
, typename Char
>
9226 void PrintCharAndCodeTo(Char c
, ostream
* os
) {
9227 // First, print c as a literal in the most readable form we can find.
9228 *os
<< ((sizeof(c
) > 1) ? "L'" : "'");
9229 const CharFormat format
= PrintAsCharLiteralTo
<UnsignedChar
>(c
, os
);
9232 // To aid user debugging, we also print c's code in decimal, unless
9233 // it's 0 (in which case c was printed as '\\0', making the code
9237 *os
<< " (" << static_cast<int>(c
);
9239 // For more convenience, we print c's code again in hexidecimal,
9240 // unless c was already printed in the form '\x##' or the code is in
9242 if (format
== kHexEscape
|| (1 <= c
&& c
<= 9)) {
9245 *os
<< ", 0x" << String::FormatHexInt(static_cast<UnsignedChar
>(c
));
9250 void PrintTo(unsigned char c
, ::std::ostream
* os
) {
9251 PrintCharAndCodeTo
<unsigned char>(c
, os
);
9253 void PrintTo(signed char c
, ::std::ostream
* os
) {
9254 PrintCharAndCodeTo
<unsigned char>(c
, os
);
9257 // Prints a wchar_t as a symbol if it is printable or as its internal
9258 // code otherwise and also as its code. L'\0' is printed as "L'\\0'".
9259 void PrintTo(wchar_t wc
, ostream
* os
) {
9260 PrintCharAndCodeTo
<wchar_t>(wc
, os
);
9263 // Prints the given array of characters to the ostream. CharType must be either
9265 // The array starts at begin, the length is len, it may include '\0' characters
9266 // and may not be NUL-terminated.
9267 template <typename CharType
>
9268 static void PrintCharsAsStringTo(
9269 const CharType
* begin
, size_t len
, ostream
* os
) {
9270 const char* const kQuoteBegin
= sizeof(CharType
) == 1 ? "\"" : "L\"";
9272 bool is_previous_hex
= false;
9273 for (size_t index
= 0; index
< len
; ++index
) {
9274 const CharType cur
= begin
[index
];
9275 if (is_previous_hex
&& IsXDigit(cur
)) {
9276 // Previous character is of '\x..' form and this character can be
9277 // interpreted as another hexadecimal digit in its number. Break string to
9279 *os
<< "\" " << kQuoteBegin
;
9281 is_previous_hex
= PrintAsStringLiteralTo(cur
, os
) == kHexEscape
;
9286 // Prints a (const) char/wchar_t array of 'len' elements, starting at address
9287 // 'begin'. CharType must be either char or wchar_t.
9288 template <typename CharType
>
9289 static void UniversalPrintCharArray(
9290 const CharType
* begin
, size_t len
, ostream
* os
) {
9292 // const char kFoo[] = "foo";
9293 // generates an array of 4, not 3, elements, with the last one being '\0'.
9295 // Therefore when printing a char array, we don't print the last element if
9296 // it's '\0', such that the output matches the string literal as it's
9297 // written in the source code.
9298 if (len
> 0 && begin
[len
- 1] == '\0') {
9299 PrintCharsAsStringTo(begin
, len
- 1, os
);
9303 // If, however, the last element in the array is not '\0', e.g.
9304 // const char kFoo[] = { 'f', 'o', 'o' };
9305 // we must print the entire array. We also print a message to indicate
9306 // that the array is not NUL-terminated.
9307 PrintCharsAsStringTo(begin
, len
, os
);
9308 *os
<< " (no terminating NUL)";
9311 // Prints a (const) char array of 'len' elements, starting at address 'begin'.
9312 void UniversalPrintArray(const char* begin
, size_t len
, ostream
* os
) {
9313 UniversalPrintCharArray(begin
, len
, os
);
9316 // Prints a (const) wchar_t array of 'len' elements, starting at address
9318 void UniversalPrintArray(const wchar_t* begin
, size_t len
, ostream
* os
) {
9319 UniversalPrintCharArray(begin
, len
, os
);
9322 // Prints the given C string to the ostream.
9323 void PrintTo(const char* s
, ostream
* os
) {
9327 *os
<< ImplicitCast_
<const void*>(s
) << " pointing to ";
9328 PrintCharsAsStringTo(s
, strlen(s
), os
);
9332 // MSVC compiler can be configured to define whar_t as a typedef
9333 // of unsigned short. Defining an overload for const wchar_t* in that case
9334 // would cause pointers to unsigned shorts be printed as wide strings,
9335 // possibly accessing more memory than intended and causing invalid
9336 // memory accesses. MSVC defines _NATIVE_WCHAR_T_DEFINED symbol when
9337 // wchar_t is implemented as a native type.
9338 #if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED)
9339 // Prints the given wide C string to the ostream.
9340 void PrintTo(const wchar_t* s
, ostream
* os
) {
9344 *os
<< ImplicitCast_
<const void*>(s
) << " pointing to ";
9345 PrintCharsAsStringTo(s
, wcslen(s
), os
);
9348 #endif // wchar_t is native
9350 // Prints a ::string object.
9351 #if GTEST_HAS_GLOBAL_STRING
9352 void PrintStringTo(const ::string
& s
, ostream
* os
) {
9353 PrintCharsAsStringTo(s
.data(), s
.size(), os
);
9355 #endif // GTEST_HAS_GLOBAL_STRING
9357 void PrintStringTo(const ::std::string
& s
, ostream
* os
) {
9358 PrintCharsAsStringTo(s
.data(), s
.size(), os
);
9361 // Prints a ::wstring object.
9362 #if GTEST_HAS_GLOBAL_WSTRING
9363 void PrintWideStringTo(const ::wstring
& s
, ostream
* os
) {
9364 PrintCharsAsStringTo(s
.data(), s
.size(), os
);
9366 #endif // GTEST_HAS_GLOBAL_WSTRING
9368 #if GTEST_HAS_STD_WSTRING
9369 void PrintWideStringTo(const ::std::wstring
& s
, ostream
* os
) {
9370 PrintCharsAsStringTo(s
.data(), s
.size(), os
);
9372 #endif // GTEST_HAS_STD_WSTRING
9374 } // namespace internal
9376 } // namespace testing
9377 // Copyright 2008, Google Inc.
9378 // All rights reserved.
9380 // Redistribution and use in source and binary forms, with or without
9381 // modification, are permitted provided that the following conditions are
9384 // * Redistributions of source code must retain the above copyright
9385 // notice, this list of conditions and the following disclaimer.
9386 // * Redistributions in binary form must reproduce the above
9387 // copyright notice, this list of conditions and the following disclaimer
9388 // in the documentation and/or other materials provided with the
9390 // * Neither the name of Google Inc. nor the names of its
9391 // contributors may be used to endorse or promote products derived from
9392 // this software without specific prior written permission.
9394 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
9395 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
9396 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
9397 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9398 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
9399 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9400 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
9401 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
9402 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
9403 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
9404 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
9406 // Author: mheule@google.com (Markus Heule)
9408 // The Google C++ Testing Framework (Google Test)
9411 // Indicates that this translation unit is part of Google Test's
9412 // implementation. It must come before gtest-internal-inl.h is
9413 // included, or there will be a compiler error. This trick is to
9414 // prevent a user from accidentally including gtest-internal-inl.h in
9416 #define GTEST_IMPLEMENTATION_ 1
9417 #undef GTEST_IMPLEMENTATION_
9421 using internal::GetUnitTestImpl
;
9423 // Gets the summary of the failure message by omitting the stack trace
9425 std::string
TestPartResult::ExtractSummary(const char* message
) {
9426 const char* const stack_trace
= strstr(message
, internal::kStackTraceMarker
);
9427 return stack_trace
== NULL
? message
:
9428 std::string(message
, stack_trace
);
9431 // Prints a TestPartResult object.
9432 std::ostream
& operator<<(std::ostream
& os
, const TestPartResult
& result
) {
9434 << result
.file_name() << ":" << result
.line_number() << ": "
9435 << (result
.type() == TestPartResult::kSuccess
? "Success" :
9436 result
.type() == TestPartResult::kFatalFailure
? "Fatal failure" :
9437 "Non-fatal failure") << ":\n"
9438 << result
.message() << std::endl
;
9441 // Appends a TestPartResult to the array.
9442 void TestPartResultArray::Append(const TestPartResult
& result
) {
9443 array_
.push_back(result
);
9446 // Returns the TestPartResult at the given index (0-based).
9447 const TestPartResult
& TestPartResultArray::GetTestPartResult(int index
) const {
9448 if (index
< 0 || index
>= size()) {
9449 printf("\nInvalid index (%d) into TestPartResultArray.\n", index
);
9450 internal::posix::Abort();
9453 return array_
[index
];
9456 // Returns the number of TestPartResult objects in the array.
9457 int TestPartResultArray::size() const {
9458 return static_cast<int>(array_
.size());
9461 namespace internal
{
9463 HasNewFatalFailureHelper::HasNewFatalFailureHelper()
9464 : has_new_fatal_failure_(false),
9465 original_reporter_(GetUnitTestImpl()->
9466 GetTestPartResultReporterForCurrentThread()) {
9467 GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(this);
9470 HasNewFatalFailureHelper::~HasNewFatalFailureHelper() {
9471 GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(
9472 original_reporter_
);
9475 void HasNewFatalFailureHelper::ReportTestPartResult(
9476 const TestPartResult
& result
) {
9477 if (result
.fatally_failed())
9478 has_new_fatal_failure_
= true;
9479 original_reporter_
->ReportTestPartResult(result
);
9482 } // namespace internal
9484 } // namespace testing
9485 // Copyright 2008 Google Inc.
9486 // All Rights Reserved.
9488 // Redistribution and use in source and binary forms, with or without
9489 // modification, are permitted provided that the following conditions are
9492 // * Redistributions of source code must retain the above copyright
9493 // notice, this list of conditions and the following disclaimer.
9494 // * Redistributions in binary form must reproduce the above
9495 // copyright notice, this list of conditions and the following disclaimer
9496 // in the documentation and/or other materials provided with the
9498 // * Neither the name of Google Inc. nor the names of its
9499 // contributors may be used to endorse or promote products derived from
9500 // this software without specific prior written permission.
9502 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
9503 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
9504 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
9505 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9506 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
9507 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9508 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
9509 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
9510 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
9511 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
9512 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
9514 // Author: wan@google.com (Zhanyong Wan)
9518 namespace internal
{
9520 #if GTEST_HAS_TYPED_TEST_P
9522 // Skips to the first non-space char in str. Returns an empty string if str
9523 // contains only whitespace characters.
9524 static const char* SkipSpaces(const char* str
) {
9525 while (IsSpace(*str
))
9530 // Verifies that registered_tests match the test names in
9531 // defined_test_names_; returns registered_tests if successful, or
9532 // aborts the program otherwise.
9533 const char* TypedTestCasePState::VerifyRegisteredTestNames(
9534 const char* file
, int line
, const char* registered_tests
) {
9535 typedef ::std::set
<const char*>::const_iterator DefinedTestIter
;
9538 // Skip initial whitespace in registered_tests since some
9539 // preprocessors prefix stringizied literals with whitespace.
9540 registered_tests
= SkipSpaces(registered_tests
);
9543 ::std::set
<std::string
> tests
;
9544 for (const char* names
= registered_tests
; names
!= NULL
;
9545 names
= SkipComma(names
)) {
9546 const std::string name
= GetPrefixUntilComma(names
);
9547 if (tests
.count(name
) != 0) {
9548 errors
<< "Test " << name
<< " is listed more than once.\n";
9553 for (DefinedTestIter it
= defined_test_names_
.begin();
9554 it
!= defined_test_names_
.end();
9565 errors
<< "No test named " << name
9566 << " can be found in this test case.\n";
9570 for (DefinedTestIter it
= defined_test_names_
.begin();
9571 it
!= defined_test_names_
.end();
9573 if (tests
.count(*it
) == 0) {
9574 errors
<< "You forgot to list test " << *it
<< ".\n";
9578 const std::string
& errors_str
= errors
.GetString();
9579 if (errors_str
!= "") {
9580 fprintf(stderr
, "%s %s", FormatFileLocation(file
, line
).c_str(),
9581 errors_str
.c_str());
9586 return registered_tests
;
9589 #endif // GTEST_HAS_TYPED_TEST_P
9591 } // namespace internal
9592 } // namespace testing