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
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_
114 // This helper class can be used to mock out Google Test failure reporting
115 // so that we can test Google Test or code that builds on Google Test.
117 // An object of this class appends a TestPartResult object to the
118 // TestPartResultArray object given in the constructor whenever a Google Test
119 // failure is reported. It can either intercept only failures that are
120 // generated in the same thread that created this object or it can intercept
121 // all generated failures. The scope of this mock object can be controlled with
122 // the second argument to the two arguments constructor.
123 class GTEST_API_ ScopedFakeTestPartResultReporter
124 : public TestPartResultReporterInterface
{
126 // The two possible mocking modes of this object.
128 INTERCEPT_ONLY_CURRENT_THREAD
, // Intercepts only thread local failures.
129 INTERCEPT_ALL_THREADS
// Intercepts all failures.
132 // The c'tor sets this object as the test part result reporter used
133 // by Google Test. The 'result' parameter specifies where to report the
134 // results. This reporter will only catch failures generated in the current
135 // thread. DEPRECATED
136 explicit ScopedFakeTestPartResultReporter(TestPartResultArray
* result
);
138 // Same as above, but you can choose the interception scope of this object.
139 ScopedFakeTestPartResultReporter(InterceptMode intercept_mode
,
140 TestPartResultArray
* result
);
142 // The d'tor restores the previous test part result reporter.
143 virtual ~ScopedFakeTestPartResultReporter();
145 // Appends the TestPartResult object to the TestPartResultArray
146 // received in the constructor.
148 // This method is from the TestPartResultReporterInterface
150 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
, const string
& substr
);
174 ~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, \
222 ::testing::ScopedFakeTestPartResultReporter gtest_reporter( \
223 ::testing::ScopedFakeTestPartResultReporter:: \
224 INTERCEPT_ONLY_CURRENT_THREAD, \
226 GTestExpectFatalFailureHelper::Execute(); \
228 } while (::testing::internal::AlwaysFalse())
230 # define EXPECT_FATAL_FAILURE_ON_ALL_THREADS(statement, substr) \
232 class GTestExpectFatalFailureHelper { \
234 static void Execute() { statement; } \
236 ::testing::TestPartResultArray gtest_failures; \
237 ::testing::internal::SingleFailureChecker gtest_checker( \
238 >est_failures, ::testing::TestPartResult::kFatalFailure, \
241 ::testing::ScopedFakeTestPartResultReporter gtest_reporter( \
242 ::testing::ScopedFakeTestPartResultReporter:: \
243 INTERCEPT_ALL_THREADS, \
245 GTestExpectFatalFailureHelper::Execute(); \
247 } while (::testing::internal::AlwaysFalse())
249 // A macro for testing Google Test assertions or code that's expected to
250 // generate Google Test non-fatal failures. It asserts that the given
251 // statement will cause exactly one non-fatal Google Test failure with 'substr'
252 // being part of the failure message.
254 // There are two different versions of this macro. EXPECT_NONFATAL_FAILURE only
255 // affects and considers failures generated in the current thread and
256 // EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS does the same but for all threads.
258 // 'statement' is allowed to reference local variables and members of
259 // the current object.
261 // The verification of the assertion is done correctly even when the statement
262 // throws an exception or aborts the current function.
264 // Known restrictions:
265 // - You cannot stream a failure message to this macro.
267 // Note that even though the implementations of the following two
268 // macros are much alike, we cannot refactor them to use a common
269 // helper macro, due to some peculiarity in how the preprocessor
270 // works. If we do that, the code won't compile when the user gives
271 // EXPECT_NONFATAL_FAILURE() a statement that contains a macro that
272 // expands to code containing an unprotected comma. The
273 // AcceptsMacroThatExpandsToUnprotectedComma test in gtest_unittest.cc
276 // For the same reason, we have to write
277 // if (::testing::internal::AlwaysTrue()) { statement; }
279 // GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement)
280 // to avoid an MSVC warning on unreachable code.
281 # define EXPECT_NONFATAL_FAILURE(statement, substr) \
283 ::testing::TestPartResultArray gtest_failures; \
284 ::testing::internal::SingleFailureChecker gtest_checker( \
285 >est_failures, ::testing::TestPartResult::kNonFatalFailure, \
288 ::testing::ScopedFakeTestPartResultReporter gtest_reporter( \
289 ::testing::ScopedFakeTestPartResultReporter:: \
290 INTERCEPT_ONLY_CURRENT_THREAD, \
292 if (::testing::internal::AlwaysTrue()) { \
296 } while (::testing::internal::AlwaysFalse())
298 # define EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(statement, substr) \
300 ::testing::TestPartResultArray gtest_failures; \
301 ::testing::internal::SingleFailureChecker gtest_checker( \
302 >est_failures, ::testing::TestPartResult::kNonFatalFailure, \
305 ::testing::ScopedFakeTestPartResultReporter gtest_reporter( \
306 ::testing::ScopedFakeTestPartResultReporter:: \
307 INTERCEPT_ALL_THREADS, \
309 if (::testing::internal::AlwaysTrue()) { \
313 } while (::testing::internal::AlwaysFalse())
315 #endif // GTEST_INCLUDE_GTEST_GTEST_SPI_H_
329 #include <ostream> // NOLINT
335 // TODO(kenton@google.com): Use autoconf to detect availability of
337 # define GTEST_HAS_GETTIMEOFDAY_ 1
339 # include <fcntl.h> // NOLINT
340 # include <limits.h> // NOLINT
341 # include <sched.h> // NOLINT
342 // Declares vsnprintf(). This header is not available on Windows.
343 # include <strings.h> // NOLINT
344 # include <sys/mman.h> // NOLINT
345 # include <sys/time.h> // NOLINT
346 # include <unistd.h> // NOLINT
350 #elif GTEST_OS_SYMBIAN
351 # define GTEST_HAS_GETTIMEOFDAY_ 1
352 # include <sys/time.h> // NOLINT
355 # define GTEST_HAS_GETTIMEOFDAY_ 1
356 # include <sys/time.h> // NOLINT
358 // On z/OS we additionally need strings.h for strcasecmp.
359 # include <strings.h> // NOLINT
361 #elif GTEST_OS_WINDOWS_MOBILE // We are on Windows CE.
363 # include <windows.h> // NOLINT
365 #elif GTEST_OS_WINDOWS // We are on Windows proper.
367 # include <io.h> // NOLINT
368 # include <sys/stat.h> // NOLINT
369 # include <sys/timeb.h> // NOLINT
370 # include <sys/types.h> // NOLINT
372 # if GTEST_OS_WINDOWS_MINGW
373 // MinGW has gettimeofday() but not _ftime64().
374 // TODO(kenton@google.com): Use autoconf to detect availability of
376 // TODO(kenton@google.com): There are other ways to get the time on
377 // Windows, like GetTickCount() or GetSystemTimeAsFileTime(). MinGW
378 // supports these. consider using them instead.
379 # define GTEST_HAS_GETTIMEOFDAY_ 1
380 # include <sys/time.h> // NOLINT
381 # endif // GTEST_OS_WINDOWS_MINGW
383 // cpplint thinks that the header is already included, so we want to
385 # include <windows.h> // NOLINT
389 // Assume other platforms have gettimeofday().
390 // TODO(kenton@google.com): Use autoconf to detect availability of
392 # define GTEST_HAS_GETTIMEOFDAY_ 1
394 // cpplint thinks that the header is already included, so we want to
396 # include <sys/time.h> // NOLINT
397 # include <unistd.h> // NOLINT
399 #endif // GTEST_OS_LINUX
401 #if GTEST_HAS_EXCEPTIONS
402 # include <stdexcept>
405 #if GTEST_CAN_STREAM_RESULTS_
406 # include <arpa/inet.h> // NOLINT
407 # include <netdb.h> // NOLINT
410 // Indicates that this translation unit is part of Google Test's
411 // implementation. It must come before gtest-internal-inl.h is
412 // included, or there will be a compiler error. This trick is to
413 // prevent a user from accidentally including gtest-internal-inl.h in
415 #define GTEST_IMPLEMENTATION_ 1
416 // Copyright 2005, Google Inc.
417 // All rights reserved.
419 // Redistribution and use in source and binary forms, with or without
420 // modification, are permitted provided that the following conditions are
423 // * Redistributions of source code must retain the above copyright
424 // notice, this list of conditions and the following disclaimer.
425 // * Redistributions in binary form must reproduce the above
426 // copyright notice, this list of conditions and the following disclaimer
427 // in the documentation and/or other materials provided with the
429 // * Neither the name of Google Inc. nor the names of its
430 // contributors may be used to endorse or promote products derived from
431 // this software without specific prior written permission.
433 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
434 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
435 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
436 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
437 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
438 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
439 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
440 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
441 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
442 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
443 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
445 // Utility functions and classes used by the Google C++ testing framework.
447 // Author: wan@google.com (Zhanyong Wan)
449 // This file contains purely Google Test's internal implementation. Please
450 // DO NOT #INCLUDE IT IN A USER PROGRAM.
452 #ifndef GTEST_SRC_GTEST_INTERNAL_INL_H_
453 # define GTEST_SRC_GTEST_INTERNAL_INL_H_
455 // GTEST_IMPLEMENTATION_ is defined to 1 iff the current translation unit is
456 // part of Google Test's implementation; otherwise it's undefined.
457 # if !GTEST_IMPLEMENTATION_
458 // A user is trying to include this from his code - just say no.
460 "gtest-internal-inl.h is part of Google Test's internal implementation."
461 # error "It must not be included except by Google Test itself."
462 # endif // GTEST_IMPLEMENTATION_
466 # endif // !_WIN32_WCE
468 # include <stdlib.h> // For strtoll/_strtoul64/malloc/free.
469 # include <string.h> // For memmove.
471 # include <algorithm>
475 # if GTEST_CAN_STREAM_RESULTS_
476 # include <arpa/inet.h> // NOLINT
477 # include <netdb.h> // NOLINT
480 # if GTEST_OS_WINDOWS
481 # include <windows.h> // NOLINT
482 # endif // GTEST_OS_WINDOWS
486 // Declares the flags.
488 // We don't want the users to modify this flag in the code, but want
489 // Google Test's own unit tests to be able to access it. Therefore we
490 // declare it here as opposed to in gtest.h.
491 GTEST_DECLARE_bool_(death_test_use_fork
);
495 // The value of GetTestTypeId() as seen from within the Google Test
496 // library. This is solely for testing GetTestTypeId().
497 GTEST_API_
extern const TypeId kTestTypeIdInGoogleTest
;
499 // Names of the flags (needed for parsing Google Test flags).
500 const char kAlsoRunDisabledTestsFlag
[] = "also_run_disabled_tests";
501 const char kBreakOnFailureFlag
[] = "break_on_failure";
502 const char kCatchExceptionsFlag
[] = "catch_exceptions";
503 const char kColorFlag
[] = "color";
504 const char kFilterFlag
[] = "filter";
505 const char kListTestsFlag
[] = "list_tests";
506 const char kOutputFlag
[] = "output";
507 const char kPrintTimeFlag
[] = "print_time";
508 const char kRandomSeedFlag
[] = "random_seed";
509 const char kRepeatFlag
[] = "repeat";
510 const char kShuffleFlag
[] = "shuffle";
511 const char kStackTraceDepthFlag
[] = "stack_trace_depth";
512 const char kStreamResultToFlag
[] = "stream_result_to";
513 const char kThrowOnFailureFlag
[] = "throw_on_failure";
515 // A valid random seed must be in [1, kMaxRandomSeed].
516 const int kMaxRandomSeed
= 99999;
518 // g_help_flag is true iff the --help flag or an equivalent form is
519 // specified on the command line.
520 GTEST_API_
extern bool g_help_flag
;
522 // Returns the current time in milliseconds.
523 GTEST_API_ TimeInMillis
GetTimeInMillis();
525 // Returns true iff Google Test should use colors in the output.
526 GTEST_API_
bool ShouldUseColor(bool stdout_is_tty
);
528 // Formats the given time in milliseconds as seconds.
529 GTEST_API_
std::string
FormatTimeInMillisAsSeconds(TimeInMillis ms
);
531 // Converts the given time in milliseconds to a date string in the ISO 8601
532 // format, without the timezone information. N.B.: due to the use the
533 // non-reentrant localtime() function, this function is not thread safe. Do
534 // not use it in any code that can be called from multiple threads.
535 GTEST_API_
std::string
FormatEpochTimeInMillisAsIso8601(TimeInMillis ms
);
537 // Parses a string for an Int32 flag, in the form of "--flag=value".
539 // On success, stores the value of the flag in *value, and returns
540 // true. On failure, returns false without changing *value.
541 GTEST_API_
bool ParseInt32Flag(const char* str
, const char* flag
, Int32
* value
);
543 // Returns a random seed in range [1, kMaxRandomSeed] based on the
544 // given --gtest_random_seed flag value.
545 inline int GetRandomSeedFromFlag(Int32 random_seed_flag
) {
546 const unsigned int raw_seed
=
547 (random_seed_flag
== 0) ? static_cast<unsigned int>(GetTimeInMillis())
548 : static_cast<unsigned int>(random_seed_flag
);
550 // Normalizes the actual seed to range [1, kMaxRandomSeed] such that
551 // it's easy to type.
552 const int normalized_seed
=
553 static_cast<int>((raw_seed
- 1U) %
554 static_cast<unsigned int>(kMaxRandomSeed
)) +
556 return normalized_seed
;
559 // Returns the first valid random seed after 'seed'. The behavior is
560 // undefined if 'seed' is invalid. The seed after kMaxRandomSeed is
561 // considered to be 1.
562 inline int GetNextRandomSeed(int seed
) {
563 GTEST_CHECK_(1 <= seed
&& seed
<= kMaxRandomSeed
)
564 << "Invalid random seed " << seed
<< " - must be in [1, "
565 << kMaxRandomSeed
<< "].";
566 const int next_seed
= seed
+ 1;
567 return (next_seed
> kMaxRandomSeed
) ? 1 : next_seed
;
570 // This class saves the values of all Google Test flags in its c'tor, and
571 // restores them in its d'tor.
572 class GTestFlagSaver
{
576 also_run_disabled_tests_
= GTEST_FLAG(also_run_disabled_tests
);
577 break_on_failure_
= GTEST_FLAG(break_on_failure
);
578 catch_exceptions_
= GTEST_FLAG(catch_exceptions
);
579 color_
= GTEST_FLAG(color
);
580 death_test_style_
= GTEST_FLAG(death_test_style
);
581 death_test_use_fork_
= GTEST_FLAG(death_test_use_fork
);
582 filter_
= GTEST_FLAG(filter
);
583 internal_run_death_test_
= GTEST_FLAG(internal_run_death_test
);
584 list_tests_
= GTEST_FLAG(list_tests
);
585 output_
= GTEST_FLAG(output
);
586 print_time_
= GTEST_FLAG(print_time
);
587 random_seed_
= GTEST_FLAG(random_seed
);
588 repeat_
= GTEST_FLAG(repeat
);
589 shuffle_
= GTEST_FLAG(shuffle
);
590 stack_trace_depth_
= GTEST_FLAG(stack_trace_depth
);
591 stream_result_to_
= GTEST_FLAG(stream_result_to
);
592 throw_on_failure_
= GTEST_FLAG(throw_on_failure
);
595 // The d'tor is not virtual. DO NOT INHERIT FROM THIS CLASS.
597 GTEST_FLAG(also_run_disabled_tests
) = also_run_disabled_tests_
;
598 GTEST_FLAG(break_on_failure
) = break_on_failure_
;
599 GTEST_FLAG(catch_exceptions
) = catch_exceptions_
;
600 GTEST_FLAG(color
) = color_
;
601 GTEST_FLAG(death_test_style
) = death_test_style_
;
602 GTEST_FLAG(death_test_use_fork
) = death_test_use_fork_
;
603 GTEST_FLAG(filter
) = filter_
;
604 GTEST_FLAG(internal_run_death_test
) = internal_run_death_test_
;
605 GTEST_FLAG(list_tests
) = list_tests_
;
606 GTEST_FLAG(output
) = output_
;
607 GTEST_FLAG(print_time
) = print_time_
;
608 GTEST_FLAG(random_seed
) = random_seed_
;
609 GTEST_FLAG(repeat
) = repeat_
;
610 GTEST_FLAG(shuffle
) = shuffle_
;
611 GTEST_FLAG(stack_trace_depth
) = stack_trace_depth_
;
612 GTEST_FLAG(stream_result_to
) = stream_result_to_
;
613 GTEST_FLAG(throw_on_failure
) = throw_on_failure_
;
617 // Fields for saving the original values of flags.
618 bool also_run_disabled_tests_
;
619 bool break_on_failure_
;
620 bool catch_exceptions_
;
622 std::string death_test_style_
;
623 bool death_test_use_fork_
;
625 std::string internal_run_death_test_
;
629 internal::Int32 random_seed_
;
630 internal::Int32 repeat_
;
632 internal::Int32 stack_trace_depth_
;
633 std::string stream_result_to_
;
634 bool throw_on_failure_
;
635 } GTEST_ATTRIBUTE_UNUSED_
;
637 // Converts a Unicode code point to a narrow string in UTF-8 encoding.
638 // code_point parameter is of type UInt32 because wchar_t may not be
639 // wide enough to contain a code point.
640 // If the code_point is not a valid Unicode code point
641 // (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted
642 // to "(Invalid Unicode 0xXXXXXXXX)".
643 GTEST_API_
std::string
CodePointToUtf8(UInt32 code_point
);
645 // Converts a wide string to a narrow string in UTF-8 encoding.
646 // The wide string is assumed to have the following encoding:
647 // UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS)
648 // UTF-32 if sizeof(wchar_t) == 4 (on Linux)
649 // Parameter str points to a null-terminated wide string.
650 // Parameter num_chars may additionally limit the number
651 // of wchar_t characters processed. -1 is used when the entire string
652 // should be processed.
653 // If the string contains code points that are not valid Unicode code points
654 // (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
655 // as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
656 // and contains invalid UTF-16 surrogate pairs, values in those pairs
657 // will be encoded as individual Unicode characters from Basic Normal Plane.
658 GTEST_API_
std::string
WideStringToUtf8(const wchar_t* str
, int num_chars
);
660 // Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
661 // if the variable is present. If a file already exists at this location, this
662 // function will write over it. If the variable is present, but the file cannot
663 // be created, prints an error and exits.
664 void WriteToShardStatusFileIfNeeded();
666 // Checks whether sharding is enabled by examining the relevant
667 // environment variable values. If the variables are present,
668 // but inconsistent (e.g., shard_index >= total_shards), prints
669 // an error and exits. If in_subprocess_for_death_test, sharding is
670 // disabled because it must only be applied to the original test
671 // process. Otherwise, we could filter out death tests we intended to execute.
672 GTEST_API_
bool ShouldShard(const char* total_shards_str
,
673 const char* shard_index_str
,
674 bool in_subprocess_for_death_test
);
676 // Parses the environment variable var as an Int32. If it is unset,
677 // returns default_val. If it is not an Int32, prints an error and
679 GTEST_API_ Int32
Int32FromEnvOrDie(const char* env_var
, Int32 default_val
);
681 // Given the total number of shards, the shard index, and the test id,
682 // returns true iff the test should be run on this shard. The test id is
683 // some arbitrary but unique non-negative integer assigned to each test
684 // method. Assumes that 0 <= shard_index < total_shards.
685 GTEST_API_
bool ShouldRunTestOnShard(int total_shards
, int shard_index
,
688 // STL container utilities.
690 // Returns the number of elements in the given container that satisfy
691 // the given predicate.
692 template <class Container
, typename Predicate
>
693 inline int CountIf(const Container
& c
, Predicate predicate
) {
694 // Implemented as an explicit loop since std::count_if() in libCstd on
695 // Solaris has a non-standard signature.
697 for (typename
Container::const_iterator it
= c
.begin(); it
!= c
.end(); ++it
) {
698 if (predicate(*it
)) ++count
;
703 // Applies a function/functor to each element in the container.
704 template <class Container
, typename Functor
>
705 void ForEach(const Container
& c
, Functor functor
) {
706 std::for_each(c
.begin(), c
.end(), functor
);
709 // Returns the i-th element of the vector, or default_value if i is not
710 // in range [0, v.size()).
711 template <typename E
>
712 inline E
GetElementOr(const std::vector
<E
>& v
, int i
, E default_value
) {
713 return (i
< 0 || i
>= static_cast<int>(v
.size())) ? default_value
: v
[i
];
716 // Performs an in-place shuffle of a range of the vector's elements.
717 // 'begin' and 'end' are element indices as an STL-style range;
718 // i.e. [begin, end) are shuffled, where 'end' == size() means to
719 // shuffle to the end of the vector.
720 template <typename E
>
721 void ShuffleRange(internal::Random
* random
, int begin
, int end
,
723 const int size
= static_cast<int>(v
->size());
724 GTEST_CHECK_(0 <= begin
&& begin
<= size
)
725 << "Invalid shuffle range start " << begin
<< ": must be in range [0, "
727 GTEST_CHECK_(begin
<= end
&& end
<= size
)
728 << "Invalid shuffle range finish " << end
<< ": must be in range ["
729 << begin
<< ", " << size
<< "].";
731 // Fisher-Yates shuffle, from
732 // http://en.wikipedia.org/wiki/Fisher-Yates_shuffle
733 for (int range_width
= end
- begin
; range_width
>= 2; range_width
--) {
734 const int last_in_range
= begin
+ range_width
- 1;
735 const int selected
= begin
+ random
->Generate(range_width
);
736 std::swap((*v
)[selected
], (*v
)[last_in_range
]);
740 // Performs an in-place shuffle of the vector's elements.
741 template <typename E
>
742 inline void Shuffle(internal::Random
* random
, std::vector
<E
>* v
) {
743 ShuffleRange(random
, 0, static_cast<int>(v
->size()), v
);
746 // A function for deleting an object. Handy for being used as a
748 template <typename T
> static void Delete(T
* x
) { delete x
; }
750 // A predicate that checks the key of a TestProperty against a known key.
752 // TestPropertyKeyIs is copyable.
753 class TestPropertyKeyIs
{
757 // TestPropertyKeyIs has NO default constructor.
758 explicit TestPropertyKeyIs(const std::string
& key
) : key_(key
) {}
760 // Returns true iff the test name of test property matches on key_.
761 bool operator()(const TestProperty
& test_property
) const {
762 return test_property
.key() == key_
;
769 // Class UnitTestOptions.
771 // This class contains functions for processing options the user
772 // specifies when running the tests. It has only static members.
774 // In most cases, the user can specify an option using either an
775 // environment variable or a command line flag. E.g. you can set the
776 // test filter using either GTEST_FILTER or --gtest_filter. If both
777 // the variable and the flag are present, the latter overrides the
779 class GTEST_API_ UnitTestOptions
{
781 // Functions for processing the gtest_output flag.
783 // Returns the output format, or "" for normal printed output.
784 static std::string
GetOutputFormat();
786 // Returns the absolute path of the requested output file, or the
787 // default (test_detail.xml in the original working directory) if
788 // none was explicitly specified.
789 static std::string
GetAbsolutePathToOutputFile();
791 // Functions for processing the gtest_filter flag.
793 // Returns true iff the wildcard pattern matches the string. The
794 // first ':' or '\0' character in pattern marks the end of it.
796 // This recursive algorithm isn't very efficient, but is clear and
797 // works well enough for matching test names, which are short.
798 static bool PatternMatchesString(const char* pattern
, const char* str
);
800 // Returns true iff the user-specified filter matches the test case
801 // name and the test name.
802 static bool FilterMatchesTest(const std::string
& test_case_name
,
803 const std::string
& test_name
);
805 # if GTEST_OS_WINDOWS
806 // Function for supporting the gtest_catch_exception flag.
808 // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
809 // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
810 // This function is useful as an __except condition.
811 static int GTestShouldProcessSEH(DWORD exception_code
);
812 # endif // GTEST_OS_WINDOWS
814 // Returns true if "name" matches the ':' separated list of glob-style
815 // filters in "filter".
816 static bool MatchesFilter(const std::string
& name
, const char* filter
);
819 // Returns the current application's name, removing directory path if that
820 // is present. Used by UnitTestOptions::GetOutputFile.
821 GTEST_API_ FilePath
GetCurrentExecutableName();
823 // The role interface for getting the OS stack trace as a string.
824 class OsStackTraceGetterInterface
{
826 OsStackTraceGetterInterface() {}
827 virtual ~OsStackTraceGetterInterface() {}
829 // Returns the current OS stack trace as an std::string. Parameters:
831 // max_depth - the maximum number of stack frames to be included
833 // skip_count - the number of top frames to be skipped; doesn't count
834 // against max_depth.
835 virtual string
CurrentStackTrace(int max_depth
, int skip_count
) = 0;
837 // UponLeavingGTest() should be called immediately before Google Test calls
838 // user code. It saves some information about the current stack that
839 // CurrentStackTrace() will use to find and hide Google Test stack frames.
840 virtual void UponLeavingGTest() = 0;
843 GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetterInterface
);
846 // A working implementation of the OsStackTraceGetterInterface interface.
847 class OsStackTraceGetter
: public OsStackTraceGetterInterface
{
849 OsStackTraceGetter() : caller_frame_(NULL
) {}
851 virtual string
CurrentStackTrace(int max_depth
, int skip_count
)
852 GTEST_LOCK_EXCLUDED_(mutex_
);
854 virtual void UponLeavingGTest() GTEST_LOCK_EXCLUDED_(mutex_
);
856 // This string is inserted in place of stack frames that are part of
857 // Google Test's implementation.
858 static const char* const kElidedFramesMarker
;
861 Mutex mutex_
; // protects all internal state
863 // We save the stack frame below the frame that calls user code.
864 // We do this because the address of the frame immediately below
865 // the user code changes between the call to UponLeavingGTest()
866 // and any calls to CurrentStackTrace() from within the user code.
869 GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetter
);
872 // Information about a Google Test trace point.
879 // This is the default global test part result reporter used in UnitTestImpl.
880 // This class should only be used by UnitTestImpl.
881 class DefaultGlobalTestPartResultReporter
882 : public TestPartResultReporterInterface
{
884 explicit DefaultGlobalTestPartResultReporter(UnitTestImpl
* unit_test
);
885 // Implements the TestPartResultReporterInterface. Reports the test part
886 // result in the current test.
887 virtual void ReportTestPartResult(const TestPartResult
& result
);
890 UnitTestImpl
* const unit_test_
;
892 GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultGlobalTestPartResultReporter
);
895 // This is the default per thread test part result reporter used in
896 // UnitTestImpl. This class should only be used by UnitTestImpl.
897 class DefaultPerThreadTestPartResultReporter
898 : public TestPartResultReporterInterface
{
900 explicit DefaultPerThreadTestPartResultReporter(UnitTestImpl
* unit_test
);
901 // Implements the TestPartResultReporterInterface. The implementation just
902 // delegates to the current global test part result reporter of *unit_test_.
903 virtual void ReportTestPartResult(const TestPartResult
& result
);
906 UnitTestImpl
* const unit_test_
;
908 GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultPerThreadTestPartResultReporter
);
911 // The private implementation of the UnitTest class. We don't protect
912 // the methods under a mutex, as this class is not accessible by a
913 // user and the UnitTest class that delegates work to this class does
915 class GTEST_API_ UnitTestImpl
{
917 explicit UnitTestImpl(UnitTest
* parent
);
918 virtual ~UnitTestImpl();
920 // There are two different ways to register your own TestPartResultReporter.
921 // You can register your own repoter to listen either only for test results
922 // from the current thread or for results from all threads.
923 // By default, each per-thread test result repoter just passes a new
924 // TestPartResult to the global test result reporter, which registers the
925 // test part result for the currently running test.
927 // Returns the global test part result reporter.
928 TestPartResultReporterInterface
* GetGlobalTestPartResultReporter();
930 // Sets the global test part result reporter.
931 void SetGlobalTestPartResultReporter(
932 TestPartResultReporterInterface
* reporter
);
934 // Returns the test part result reporter for the current thread.
935 TestPartResultReporterInterface
* GetTestPartResultReporterForCurrentThread();
937 // Sets the test part result reporter for the current thread.
938 void SetTestPartResultReporterForCurrentThread(
939 TestPartResultReporterInterface
* reporter
);
941 // Gets the number of successful test cases.
942 int successful_test_case_count() const;
944 // Gets the number of failed test cases.
945 int failed_test_case_count() const;
947 // Gets the number of all test cases.
948 int total_test_case_count() const;
950 // Gets the number of all test cases that contain at least one test
952 int test_case_to_run_count() const;
954 // Gets the number of successful tests.
955 int successful_test_count() const;
957 // Gets the number of failed tests.
958 int failed_test_count() const;
960 // Gets the number of disabled tests that will be reported in the XML report.
961 int reportable_disabled_test_count() const;
963 // Gets the number of disabled tests.
964 int disabled_test_count() const;
966 // Gets the number of tests to be printed in the XML report.
967 int reportable_test_count() const;
969 // Gets the number of all tests.
970 int total_test_count() const;
972 // Gets the number of tests that should run.
973 int test_to_run_count() const;
975 // Gets the time of the test program start, in ms from the start of the
977 TimeInMillis
start_timestamp() const { return start_timestamp_
; }
979 // Gets the elapsed time, in milliseconds.
980 TimeInMillis
elapsed_time() const { return elapsed_time_
; }
982 // Returns true iff the unit test passed (i.e. all test cases passed).
983 bool Passed() const { return !Failed(); }
985 // Returns true iff the unit test failed (i.e. some test case failed
986 // or something outside of all tests failed).
987 bool Failed() const {
988 return failed_test_case_count() > 0 || ad_hoc_test_result()->Failed();
991 // Gets the i-th test case among all the test cases. i can range from 0 to
992 // total_test_case_count() - 1. If i is not in that range, returns NULL.
993 const TestCase
* GetTestCase(int i
) const {
994 const int index
= GetElementOr(test_case_indices_
, i
, -1);
995 return index
< 0 ? NULL
: test_cases_
[i
];
998 // Gets the i-th test case among all the test cases. i can range from 0 to
999 // total_test_case_count() - 1. If i is not in that range, returns NULL.
1000 TestCase
* GetMutableTestCase(int i
) {
1001 const int index
= GetElementOr(test_case_indices_
, i
, -1);
1002 return index
< 0 ? NULL
: test_cases_
[index
];
1005 // Provides access to the event listener list.
1006 TestEventListeners
* listeners() { return &listeners_
; }
1008 // Returns the TestResult for the test that's currently running, or
1009 // the TestResult for the ad hoc test if no test is running.
1010 TestResult
* current_test_result();
1012 // Returns the TestResult for the ad hoc test.
1013 const TestResult
* ad_hoc_test_result() const { return &ad_hoc_test_result_
; }
1015 // Sets the OS stack trace getter.
1017 // Does nothing if the input and the current OS stack trace getter
1018 // are the same; otherwise, deletes the old getter and makes the
1019 // input the current getter.
1020 void set_os_stack_trace_getter(OsStackTraceGetterInterface
* getter
);
1022 // Returns the current OS stack trace getter if it is not NULL;
1023 // otherwise, creates an OsStackTraceGetter, makes it the current
1024 // getter, and returns it.
1025 OsStackTraceGetterInterface
* os_stack_trace_getter();
1027 // Returns the current OS stack trace as an std::string.
1029 // The maximum number of stack frames to be included is specified by
1030 // the gtest_stack_trace_depth flag. The skip_count parameter
1031 // specifies the number of top frames to be skipped, which doesn't
1032 // count against the number of frames to be included.
1034 // For example, if Foo() calls Bar(), which in turn calls
1035 // CurrentOsStackTraceExceptTop(1), Foo() will be included in the
1036 // trace but Bar() and CurrentOsStackTraceExceptTop() won't.
1037 std::string
CurrentOsStackTraceExceptTop(int skip_count
) GTEST_NO_INLINE_
;
1039 // Finds and returns a TestCase with the given name. If one doesn't
1040 // exist, creates one and returns it.
1044 // test_case_name: name of the test case
1045 // type_param: the name of the test's type parameter, or NULL if
1046 // this is not a typed or a type-parameterized test.
1047 // set_up_tc: pointer to the function that sets up the test case
1048 // tear_down_tc: pointer to the function that tears down the test case
1049 TestCase
* GetTestCase(const char* test_case_name
, const char* type_param
,
1050 Test::SetUpTestCaseFunc set_up_tc
,
1051 Test::TearDownTestCaseFunc tear_down_tc
);
1053 // Adds a TestInfo to the unit test.
1057 // set_up_tc: pointer to the function that sets up the test case
1058 // tear_down_tc: pointer to the function that tears down the test case
1059 // test_info: the TestInfo object
1060 void AddTestInfo(Test::SetUpTestCaseFunc set_up_tc
,
1061 Test::TearDownTestCaseFunc tear_down_tc
,
1062 TestInfo
* test_info
) {
1063 // In order to support thread-safe death tests, we need to
1064 // remember the original working directory when the test program
1065 // was first invoked. We cannot do this in RUN_ALL_TESTS(), as
1066 // the user may have changed the current directory before calling
1067 // RUN_ALL_TESTS(). Therefore we capture the current directory in
1068 // AddTestInfo(), which is called to register a TEST or TEST_F
1069 // before main() is reached.
1070 if (original_working_dir_
.IsEmpty()) {
1071 original_working_dir_
.Set(FilePath::GetCurrentDir());
1072 GTEST_CHECK_(!original_working_dir_
.IsEmpty())
1073 << "Failed to get the current working directory.";
1076 GetTestCase(test_info
->test_case_name(), test_info
->type_param(), set_up_tc
,
1078 ->AddTestInfo(test_info
);
1081 # if GTEST_HAS_PARAM_TEST
1082 // Returns ParameterizedTestCaseRegistry object used to keep track of
1083 // value-parameterized tests and instantiate and register them.
1084 internal::ParameterizedTestCaseRegistry
& parameterized_test_registry() {
1085 return parameterized_test_registry_
;
1087 # endif // GTEST_HAS_PARAM_TEST
1089 // Sets the TestCase object for the test that's currently running.
1090 void set_current_test_case(TestCase
* a_current_test_case
) {
1091 current_test_case_
= a_current_test_case
;
1094 // Sets the TestInfo object for the test that's currently running. If
1095 // current_test_info is NULL, the assertion results will be stored in
1096 // ad_hoc_test_result_.
1097 void set_current_test_info(TestInfo
* a_current_test_info
) {
1098 current_test_info_
= a_current_test_info
;
1101 // Registers all parameterized tests defined using TEST_P and
1102 // INSTANTIATE_TEST_CASE_P, creating regular tests for each test/parameter
1103 // combination. This method can be called more then once; it has guards
1104 // protecting from registering the tests more then once. If
1105 // value-parameterized tests are disabled, RegisterParameterizedTests is
1106 // present but does nothing.
1107 void RegisterParameterizedTests();
1109 // Runs all tests in this UnitTest object, prints the result, and
1110 // returns true if all tests are successful. If any exception is
1111 // thrown during a test, this test is considered to be failed, but
1112 // the rest of the tests will still be run.
1115 // Clears the results of all tests, except the ad hoc tests.
1116 void ClearNonAdHocTestResult() {
1117 ForEach(test_cases_
, TestCase::ClearTestCaseResult
);
1120 // Clears the results of ad-hoc test assertions.
1121 void ClearAdHocTestResult() { ad_hoc_test_result_
.Clear(); }
1123 // Adds a TestProperty to the current TestResult object when invoked in a
1124 // context of a test or a test case, or to the global property set. If the
1125 // result already contains a property with the same key, the value will be
1127 void RecordProperty(const TestProperty
& test_property
);
1129 enum ReactionToSharding
{ HONOR_SHARDING_PROTOCOL
, IGNORE_SHARDING_PROTOCOL
};
1131 // Matches the full name of each test against the user-specified
1132 // filter to decide whether the test should run, then records the
1133 // result in each TestCase and TestInfo object.
1134 // If shard_tests == HONOR_SHARDING_PROTOCOL, further filters tests
1135 // based on sharding variables in the environment.
1136 // Returns the number of tests that should run.
1137 int FilterTests(ReactionToSharding shard_tests
);
1139 // Prints the names of the tests matching the user-specified filter flag.
1140 void ListTestsMatchingFilter();
1142 const TestCase
* current_test_case() const { return current_test_case_
; }
1143 TestInfo
* current_test_info() { return current_test_info_
; }
1144 const TestInfo
* current_test_info() const { return current_test_info_
; }
1146 // Returns the vector of environments that need to be set-up/torn-down
1147 // before/after the tests are run.
1148 std::vector
<Environment
*>& environments() { return environments_
; }
1150 // Getters for the per-thread Google Test trace stack.
1151 std::vector
<TraceInfo
>& gtest_trace_stack() {
1152 return *(gtest_trace_stack_
.pointer());
1154 const std::vector
<TraceInfo
>& gtest_trace_stack() const {
1155 return gtest_trace_stack_
.get();
1158 # if GTEST_HAS_DEATH_TEST
1159 void InitDeathTestSubprocessControlInfo() {
1160 internal_run_death_test_flag_
.reset(ParseInternalRunDeathTestFlag());
1162 // Returns a pointer to the parsed --gtest_internal_run_death_test
1163 // flag, or NULL if that flag was not specified.
1164 // This information is useful only in a death test child process.
1165 // Must not be called before a call to InitGoogleTest.
1166 const InternalRunDeathTestFlag
* internal_run_death_test_flag() const {
1167 return internal_run_death_test_flag_
.get();
1170 // Returns a pointer to the current death test factory.
1171 internal::DeathTestFactory
* death_test_factory() {
1172 return death_test_factory_
.get();
1175 void SuppressTestEventsIfInSubprocess();
1177 friend class ReplaceDeathTestFactory
;
1178 # endif // GTEST_HAS_DEATH_TEST
1180 // Initializes the event listener performing XML output as specified by
1181 // UnitTestOptions. Must not be called before InitGoogleTest.
1182 void ConfigureXmlOutput();
1184 # if GTEST_CAN_STREAM_RESULTS_
1185 // Initializes the event listener for streaming test results to a socket.
1186 // Must not be called before InitGoogleTest.
1187 void ConfigureStreamingOutput();
1190 // Performs initialization dependent upon flag values obtained in
1191 // ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to
1192 // ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest
1193 // this function is also called from RunAllTests. Since this function can be
1194 // called more than once, it has to be idempotent.
1195 void PostFlagParsingInit();
1197 // Gets the random seed used at the start of the current test iteration.
1198 int random_seed() const { return random_seed_
; }
1200 // Gets the random number generator.
1201 internal::Random
* random() { return &random_
; }
1203 // Shuffles all test cases, and the tests within each test case,
1204 // making sure that death tests are still run first.
1205 void ShuffleTests();
1207 // Restores the test cases and tests to their order before the first shuffle.
1208 void UnshuffleTests();
1210 // Returns the value of GTEST_FLAG(catch_exceptions) at the moment
1211 // UnitTest::Run() starts.
1212 bool catch_exceptions() const { return catch_exceptions_
; }
1215 friend class ::testing::UnitTest
;
1217 // Used by UnitTest::Run() to capture the state of
1218 // GTEST_FLAG(catch_exceptions) at the moment it starts.
1219 void set_catch_exceptions(bool value
) { catch_exceptions_
= value
; }
1221 // The UnitTest object that owns this implementation object.
1222 UnitTest
* const parent_
;
1224 // The working directory when the first TEST() or TEST_F() was
1226 internal::FilePath original_working_dir_
;
1228 // The default test part result reporters.
1229 DefaultGlobalTestPartResultReporter default_global_test_part_result_reporter_
;
1230 DefaultPerThreadTestPartResultReporter
1231 default_per_thread_test_part_result_reporter_
;
1233 // Points to (but doesn't own) the global test part result reporter.
1234 TestPartResultReporterInterface
* global_test_part_result_repoter_
;
1236 // Protects read and write access to global_test_part_result_reporter_.
1237 internal::Mutex global_test_part_result_reporter_mutex_
;
1239 // Points to (but doesn't own) the per-thread test part result reporter.
1240 internal::ThreadLocal
<TestPartResultReporterInterface
*>
1241 per_thread_test_part_result_reporter_
;
1243 // The vector of environments that need to be set-up/torn-down
1244 // before/after the tests are run.
1245 std::vector
<Environment
*> environments_
;
1247 // The vector of TestCases in their original order. It owns the
1248 // elements in the vector.
1249 std::vector
<TestCase
*> test_cases_
;
1251 // Provides a level of indirection for the test case list to allow
1252 // easy shuffling and restoring the test case order. The i-th
1253 // element of this vector is the index of the i-th test case in the
1255 std::vector
<int> test_case_indices_
;
1257 # if GTEST_HAS_PARAM_TEST
1258 // ParameterizedTestRegistry object used to register value-parameterized
1260 internal::ParameterizedTestCaseRegistry parameterized_test_registry_
;
1262 // Indicates whether RegisterParameterizedTests() has been called already.
1263 bool parameterized_tests_registered_
;
1264 # endif // GTEST_HAS_PARAM_TEST
1266 // Index of the last death test case registered. Initially -1.
1267 int last_death_test_case_
;
1269 // This points to the TestCase for the currently running test. It
1270 // changes as Google Test goes through one test case after another.
1271 // When no test is running, this is set to NULL and Google Test
1272 // stores assertion results in ad_hoc_test_result_. Initially NULL.
1273 TestCase
* current_test_case_
;
1275 // This points to the TestInfo for the currently running test. It
1276 // changes as Google Test goes through one test after another. When
1277 // no test is running, this is set to NULL and Google Test stores
1278 // assertion results in ad_hoc_test_result_. Initially NULL.
1279 TestInfo
* current_test_info_
;
1281 // Normally, a user only writes assertions inside a TEST or TEST_F,
1282 // or inside a function called by a TEST or TEST_F. Since Google
1283 // Test keeps track of which test is current running, it can
1284 // associate such an assertion with the test it belongs to.
1286 // If an assertion is encountered when no TEST or TEST_F is running,
1287 // Google Test attributes the assertion result to an imaginary "ad hoc"
1288 // test, and records the result in ad_hoc_test_result_.
1289 TestResult ad_hoc_test_result_
;
1291 // The list of event listeners that can be used to track events inside
1293 TestEventListeners listeners_
;
1295 // The OS stack trace getter. Will be deleted when the UnitTest
1296 // object is destructed. By default, an OsStackTraceGetter is used,
1297 // but the user can set this field to use a custom getter if that is
1299 OsStackTraceGetterInterface
* os_stack_trace_getter_
;
1301 // True iff PostFlagParsingInit() has been called.
1302 bool post_flag_parse_init_performed_
;
1304 // The random number seed used at the beginning of the test run.
1307 // Our random number generator.
1308 internal::Random random_
;
1310 // The time of the test program start, in ms from the start of the
1312 TimeInMillis start_timestamp_
;
1314 // How long the test took to run, in milliseconds.
1315 TimeInMillis elapsed_time_
;
1317 # if GTEST_HAS_DEATH_TEST
1318 // The decomposed components of the gtest_internal_run_death_test flag,
1319 // parsed when RUN_ALL_TESTS is called.
1320 internal::scoped_ptr
<InternalRunDeathTestFlag
> internal_run_death_test_flag_
;
1321 internal::scoped_ptr
<internal::DeathTestFactory
> death_test_factory_
;
1322 # endif // GTEST_HAS_DEATH_TEST
1324 // A per-thread stack of traces created by the SCOPED_TRACE() macro.
1325 internal::ThreadLocal
<std::vector
<TraceInfo
> > gtest_trace_stack_
;
1327 // The value of GTEST_FLAG(catch_exceptions) at the moment RunAllTests()
1329 bool catch_exceptions_
;
1331 GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTestImpl
);
1332 }; // class UnitTestImpl
1334 // Convenience function for accessing the global UnitTest
1335 // implementation object.
1336 inline UnitTestImpl
* GetUnitTestImpl() {
1337 return UnitTest::GetInstance()->impl();
1340 # if GTEST_USES_SIMPLE_RE
1342 // Internal helper functions for implementing the simple regular
1343 // expression matcher.
1344 GTEST_API_
bool IsInSet(char ch
, const char* str
);
1345 GTEST_API_
bool IsAsciiDigit(char ch
);
1346 GTEST_API_
bool IsAsciiPunct(char ch
);
1347 GTEST_API_
bool IsRepeat(char ch
);
1348 GTEST_API_
bool IsAsciiWhiteSpace(char ch
);
1349 GTEST_API_
bool IsAsciiWordChar(char ch
);
1350 GTEST_API_
bool IsValidEscape(char ch
);
1351 GTEST_API_
bool AtomMatchesChar(bool escaped
, char pattern
, char ch
);
1352 GTEST_API_
bool ValidateRegex(const char* regex
);
1353 GTEST_API_
bool MatchRegexAtHead(const char* regex
, const char* str
);
1354 GTEST_API_
bool MatchRepetitionAndRegexAtHead(bool escaped
, char ch
,
1355 char repeat
, const char* regex
,
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
) ::CloseHandle(handle_
);
1393 GTEST_DISALLOW_COPY_AND_ASSIGN_(AutoHandle
);
1395 # endif // GTEST_OS_WINDOWS
1397 // Attempts to parse a string into a positive integer pointed to by the
1398 // number parameter. Returns true if that is possible.
1399 // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we can use
1401 template <typename Integer
>
1402 bool ParseNaturalNumber(const ::std::string
& str
, Integer
* number
) {
1403 // Fail fast if the given string does not begin with a digit;
1404 // this bypasses strtoXXX's "optional leading whitespace and plus
1405 // or minus sign" semantics, which are undesirable here.
1406 if (str
.empty() || !IsDigit(str
[0])) {
1412 // BiggestConvertible is the largest integer type that system-provided
1413 // string-to-number conversion routines can return.
1415 # if GTEST_OS_WINDOWS && !defined(__GNUC__)
1417 // MSVC and C++ Builder define __int64 instead of the standard long long.
1418 typedef unsigned __int64 BiggestConvertible
;
1419 const BiggestConvertible parsed
= _strtoui64(str
.c_str(), &end
, 10);
1423 typedef unsigned long long BiggestConvertible
; // NOLINT
1424 const BiggestConvertible parsed
= strtoull(str
.c_str(), &end
, 10);
1426 # endif // GTEST_OS_WINDOWS && !defined(__GNUC__)
1428 const bool parse_success
= *end
== '\0' && errno
== 0;
1430 // TODO(vladl@google.com): Convert this to compile time assertion when it is
1432 GTEST_CHECK_(sizeof(Integer
) <= sizeof(parsed
));
1434 const Integer result
= static_cast<Integer
>(parsed
);
1435 if (parse_success
&& static_cast<BiggestConvertible
>(result
) == parsed
) {
1441 # endif // GTEST_HAS_DEATH_TEST
1443 // TestResult contains some private methods that should be hidden from
1444 // Google Test user but are required for testing. This class allow our tests
1447 // This class is supplied only for the purpose of testing Google Test's own
1448 // constructs. Do not use it in user tests, either directly or indirectly.
1449 class TestResultAccessor
{
1451 static void RecordProperty(TestResult
* test_result
,
1452 const std::string
& xml_element
,
1453 const TestProperty
& property
) {
1454 test_result
->RecordProperty(xml_element
, property
);
1457 static void ClearTestPartResults(TestResult
* test_result
) {
1458 test_result
->ClearTestPartResults();
1461 static const std::vector
<testing::TestPartResult
>& test_part_results(
1462 const TestResult
& test_result
) {
1463 return test_result
.test_part_results();
1467 # if GTEST_CAN_STREAM_RESULTS_
1469 // Streams test results to the given port on the given host machine.
1470 class StreamingListener
: public EmptyTestEventListener
{
1472 // Abstract base class for writing strings to a socket.
1473 class AbstractSocketWriter
{
1475 virtual ~AbstractSocketWriter() {}
1477 // Sends a string to the socket.
1478 virtual void Send(const string
& message
) = 0;
1480 // Closes the socket.
1481 virtual void CloseConnection() {}
1483 // Sends a string and a newline to the socket.
1484 void SendLn(const string
& message
) { Send(message
+ "\n"); }
1487 // Concrete class for actually writing strings to a socket.
1488 class SocketWriter
: public AbstractSocketWriter
{
1490 SocketWriter(const string
& host
, const string
& port
)
1491 : sockfd_(-1), host_name_(host
), port_num_(port
) {
1495 virtual ~SocketWriter() {
1496 if (sockfd_
!= -1) CloseConnection();
1499 // Sends a string to the socket.
1500 virtual void Send(const string
& message
) {
1501 GTEST_CHECK_(sockfd_
!= -1)
1502 << "Send() can be called only when there is a connection.";
1504 const int len
= static_cast<int>(message
.length());
1505 if (write(sockfd_
, message
.c_str(), len
) != len
) {
1506 GTEST_LOG_(WARNING
) << "stream_result_to: failed to stream to "
1507 << host_name_
<< ":" << port_num_
;
1512 // Creates a client socket and connects to the server.
1513 void MakeConnection();
1515 // Closes the socket.
1516 void CloseConnection() {
1517 GTEST_CHECK_(sockfd_
!= -1)
1518 << "CloseConnection() can be called only when there is a connection.";
1524 int sockfd_
; // socket file descriptor
1525 const string host_name_
;
1526 const string port_num_
;
1528 GTEST_DISALLOW_COPY_AND_ASSIGN_(SocketWriter
);
1529 }; // class SocketWriter
1531 // Escapes '=', '&', '%', and '\n' characters in str as "%xx".
1532 static string
UrlEncode(const char* str
);
1534 StreamingListener(const string
& host
, const string
& port
)
1535 : socket_writer_(new SocketWriter(host
, port
)) {
1539 explicit StreamingListener(AbstractSocketWriter
* socket_writer
)
1540 : socket_writer_(socket_writer
) {
1544 void OnTestProgramStart(const UnitTest
& /* unit_test */) {
1545 SendLn("event=TestProgramStart");
1548 void OnTestProgramEnd(const UnitTest
& unit_test
) {
1549 // Note that Google Test current only report elapsed time for each
1550 // test iteration, not for the entire test program.
1551 SendLn("event=TestProgramEnd&passed=" + FormatBool(unit_test
.Passed()));
1553 // Notify the streaming server to stop.
1554 socket_writer_
->CloseConnection();
1557 void OnTestIterationStart(const UnitTest
& /* unit_test */, int iteration
) {
1558 SendLn("event=TestIterationStart&iteration=" +
1559 StreamableToString(iteration
));
1562 void OnTestIterationEnd(const UnitTest
& unit_test
, int /* iteration */) {
1563 SendLn("event=TestIterationEnd&passed=" + FormatBool(unit_test
.Passed()) +
1564 "&elapsed_time=" + StreamableToString(unit_test
.elapsed_time()) +
1568 void OnTestCaseStart(const TestCase
& test_case
) {
1569 SendLn(std::string("event=TestCaseStart&name=") + test_case
.name());
1572 void OnTestCaseEnd(const TestCase
& test_case
) {
1573 SendLn("event=TestCaseEnd&passed=" + FormatBool(test_case
.Passed()) +
1574 "&elapsed_time=" + StreamableToString(test_case
.elapsed_time()) +
1578 void OnTestStart(const TestInfo
& test_info
) {
1579 SendLn(std::string("event=TestStart&name=") + test_info
.name());
1582 void OnTestEnd(const TestInfo
& test_info
) {
1583 SendLn("event=TestEnd&passed=" +
1584 FormatBool((test_info
.result())->Passed()) + "&elapsed_time=" +
1585 StreamableToString((test_info
.result())->elapsed_time()) + "ms");
1588 void OnTestPartResult(const TestPartResult
& test_part_result
) {
1589 const char* file_name
= test_part_result
.file_name();
1590 if (file_name
== NULL
) file_name
= "";
1591 SendLn("event=TestPartResult&file=" + UrlEncode(file_name
) +
1592 "&line=" + StreamableToString(test_part_result
.line_number()) +
1593 "&message=" + UrlEncode(test_part_result
.message()));
1597 // Sends the given message and a newline to the socket.
1598 void SendLn(const string
& message
) { socket_writer_
->SendLn(message
); }
1600 // Called at the start of streaming to notify the receiver what
1601 // protocol we are using.
1602 void Start() { SendLn("gtest_streaming_protocol_version=1.0"); }
1604 string
FormatBool(bool value
) { return value
? "1" : "0"; }
1606 const scoped_ptr
<AbstractSocketWriter
> socket_writer_
;
1608 GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamingListener
);
1609 }; // class StreamingListener
1611 # endif // GTEST_CAN_STREAM_RESULTS_
1613 } // namespace internal
1614 } // namespace testing
1616 #endif // GTEST_SRC_GTEST_INTERNAL_INL_H_
1617 #undef GTEST_IMPLEMENTATION_
1619 #if GTEST_OS_WINDOWS
1620 # define vsnprintf _vsnprintf
1621 #endif // GTEST_OS_WINDOWS
1625 using internal::CountIf
;
1626 using internal::ForEach
;
1627 using internal::GetElementOr
;
1628 using internal::Shuffle
;
1632 // A test whose test case name or test name matches this filter is
1633 // disabled and not run.
1634 static const char kDisableTestFilter
[] = "DISABLED_*:*/DISABLED_*";
1636 // A test case whose name matches this filter is considered a death
1637 // test case and will be run before test cases whose name doesn't
1638 // match this filter.
1639 static const char kDeathTestCaseFilter
[] = "*DeathTest:*DeathTest/*";
1641 // A test filter that matches everything.
1642 static const char kUniversalFilter
[] = "*";
1644 // The default output file for XML output.
1645 static const char kDefaultOutputFile
[] = "test_detail.xml";
1647 // The environment variable name for the test shard index.
1648 static const char kTestShardIndex
[] = "GTEST_SHARD_INDEX";
1649 // The environment variable name for the total number of test shards.
1650 static const char kTestTotalShards
[] = "GTEST_TOTAL_SHARDS";
1651 // The environment variable name for the test shard status file.
1652 static const char kTestShardStatusFile
[] = "GTEST_SHARD_STATUS_FILE";
1654 namespace internal
{
1656 // The text used in failure messages to indicate the start of the
1658 const char kStackTraceMarker
[] = "\nStack trace:\n";
1660 // g_help_flag is true iff the --help flag or an equivalent form is
1661 // specified on the command line.
1662 bool g_help_flag
= false;
1664 } // namespace internal
1666 static const char* GetDefaultFilter() { return kUniversalFilter
; }
1669 also_run_disabled_tests
,
1670 internal::BoolFromGTestEnv("also_run_disabled_tests", false),
1671 "Run disabled tests too, in addition to the tests normally being run.");
1674 break_on_failure
, internal::BoolFromGTestEnv("break_on_failure", false),
1675 "True iff a failed assertion should be a debugger break-point.");
1677 GTEST_DEFINE_bool_(catch_exceptions
,
1678 internal::BoolFromGTestEnv("catch_exceptions", true),
1679 "True iff " GTEST_NAME_
1680 " should catch exceptions and treat them as test failures.");
1682 GTEST_DEFINE_string_(
1683 color
, internal::StringFromGTestEnv("color", "auto"),
1684 "Whether to use colors in the output. Valid values: yes, no, "
1685 "and auto. 'auto' means to use colors if the output is "
1686 "being sent to a terminal and the TERM environment variable "
1687 "is set to a terminal type that supports colors.");
1689 GTEST_DEFINE_string_(
1690 filter
, internal::StringFromGTestEnv("filter", GetDefaultFilter()),
1691 "A colon-separated list of glob (not regex) patterns "
1692 "for filtering the tests to run, optionally followed by a "
1693 "'-' and a : separated list of negative patterns (tests to "
1694 "exclude). A test is run if it matches one of the positive "
1695 "patterns and does not match any of the negative patterns.");
1697 GTEST_DEFINE_bool_(list_tests
, false, "List all tests without running them.");
1699 GTEST_DEFINE_string_(
1700 output
, internal::StringFromGTestEnv("output", ""),
1701 "A format (currently must be \"xml\"), optionally followed "
1702 "by a colon and an output file name or directory. A directory "
1703 "is indicated by a trailing pathname separator. "
1704 "Examples: \"xml:filename.xml\", \"xml::directoryname/\". "
1705 "If a directory is specified, output files will be created "
1706 "within that directory, with file-names based on the test "
1707 "executable's name and, if necessary, made unique by adding "
1710 GTEST_DEFINE_bool_(print_time
, internal::BoolFromGTestEnv("print_time", true),
1711 "True iff " GTEST_NAME_
1712 " should display elapsed time in text output.");
1714 GTEST_DEFINE_int32_(
1715 random_seed
, internal::Int32FromGTestEnv("random_seed", 0),
1716 "Random number seed to use when shuffling test orders. Must be in range "
1717 "[1, 99999], or 0 to use a seed based on the current time.");
1719 GTEST_DEFINE_int32_(
1720 repeat
, internal::Int32FromGTestEnv("repeat", 1),
1721 "How many times to repeat each test. Specify a negative number "
1722 "for repeating forever. Useful for shaking out flaky tests.");
1724 GTEST_DEFINE_bool_(show_internal_stack_frames
, false,
1725 "True iff " GTEST_NAME_
1726 " should include internal stack frames when "
1727 "printing test failure stack traces.");
1729 GTEST_DEFINE_bool_(shuffle
, internal::BoolFromGTestEnv("shuffle", false),
1730 "True iff " GTEST_NAME_
1731 " should randomize tests' order on every run.");
1733 GTEST_DEFINE_int32_(
1735 internal::Int32FromGTestEnv("stack_trace_depth", kMaxStackTraceDepth
),
1736 "The maximum number of stack frames to print when an "
1737 "assertion fails. The valid range is 0 through 100, inclusive.");
1739 GTEST_DEFINE_string_(
1740 stream_result_to
, internal::StringFromGTestEnv("stream_result_to", ""),
1741 "This flag specifies the host name and the port number on which to stream "
1742 "test results. Example: \"localhost:555\". The flag is effective only on "
1746 throw_on_failure
, internal::BoolFromGTestEnv("throw_on_failure", false),
1747 "When this flag is specified, a failed assertion will throw an exception "
1748 "if exceptions are enabled or exit the program with a non-zero code "
1751 namespace internal
{
1753 // Generates a random number from [0, range), using a Linear
1754 // Congruential Generator (LCG). Crashes if 'range' is 0 or greater
1756 UInt32
Random::Generate(UInt32 range
) {
1757 // These constants are the same as are used in glibc's rand(3).
1758 state_
= (1103515245U * state_
+ 12345U) % kMaxRange
;
1760 GTEST_CHECK_(range
> 0) << "Cannot generate a number in the range [0, 0).";
1761 GTEST_CHECK_(range
<= kMaxRange
)
1762 << "Generation of a number in [0, " << range
<< ") was requested, "
1763 << "but this can only generate numbers in [0, " << kMaxRange
<< ").";
1765 // Converting via modulus introduces a bit of downward bias, but
1766 // it's simple, and a linear congruential generator isn't too good
1768 return state_
% range
;
1771 // GTestIsInitialized() returns true iff the user has initialized
1772 // Google Test. Useful for catching the user mistake of not initializing
1773 // Google Test before calling RUN_ALL_TESTS().
1775 // A user must call testing::InitGoogleTest() to initialize Google
1776 // Test. g_init_gtest_count is set to the number of times
1777 // InitGoogleTest() has been called. We don't protect this variable
1778 // under a mutex as it is only accessed in the main thread.
1779 GTEST_API_
int g_init_gtest_count
= 0;
1780 static bool GTestIsInitialized() { return g_init_gtest_count
!= 0; }
1782 // Iterates over a vector of TestCases, keeping a running sum of the
1783 // results of calling a given int-returning method on each.
1785 static int SumOverTestCaseList(const std::vector
<TestCase
*>& case_list
,
1786 int (TestCase::*method
)() const) {
1788 for (size_t i
= 0; i
< case_list
.size(); i
++) {
1789 sum
+= (case_list
[i
]->*method
)();
1794 // Returns true iff the test case passed.
1795 static bool TestCasePassed(const TestCase
* test_case
) {
1796 return test_case
->should_run() && test_case
->Passed();
1799 // Returns true iff the test case failed.
1800 static bool TestCaseFailed(const TestCase
* test_case
) {
1801 return test_case
->should_run() && test_case
->Failed();
1804 // Returns true iff test_case contains at least one test that should
1806 static bool ShouldRunTestCase(const TestCase
* test_case
) {
1807 return test_case
->should_run();
1810 // AssertHelper constructor.
1811 AssertHelper::AssertHelper(TestPartResult::Type type
, const char* file
,
1812 int line
, const char* message
)
1813 : data_(new AssertHelperData(type
, file
, line
, message
)) {}
1815 AssertHelper::~AssertHelper() { delete data_
; }
1817 // Message assignment, for assertion streaming support.
1818 void AssertHelper::operator=(const Message
& message
) const {
1819 UnitTest::GetInstance()->AddTestPartResult(
1820 data_
->type
, data_
->file
, data_
->line
,
1821 AppendUserMessage(data_
->message
, message
),
1822 UnitTest::GetInstance()->impl()->CurrentOsStackTraceExceptTop(1)
1823 // Skips the stack frame for this function itself.
1827 // Mutex for linked pointers.
1828 GTEST_API_
GTEST_DEFINE_STATIC_MUTEX_(g_linked_ptr_mutex
);
1830 // Application pathname gotten in InitGoogleTest.
1831 std::string g_executable_path
;
1833 // Returns the current application's name, removing directory path if that
1835 FilePath
GetCurrentExecutableName() {
1838 #if GTEST_OS_WINDOWS
1839 result
.Set(FilePath(g_executable_path
).RemoveExtension("exe"));
1841 result
.Set(FilePath(g_executable_path
));
1842 #endif // GTEST_OS_WINDOWS
1844 return result
.RemoveDirectoryName();
1847 // Functions for processing the gtest_output flag.
1849 // Returns the output format, or "" for normal printed output.
1850 std::string
UnitTestOptions::GetOutputFormat() {
1851 const char* const gtest_output_flag
= GTEST_FLAG(output
).c_str();
1852 if (gtest_output_flag
== NULL
) return std::string("");
1854 const char* const colon
= strchr(gtest_output_flag
, ':');
1855 return (colon
== NULL
)
1856 ? std::string(gtest_output_flag
)
1857 : std::string(gtest_output_flag
, colon
- gtest_output_flag
);
1860 // Returns the name of the requested output file, or the default if none
1861 // was explicitly specified.
1862 std::string
UnitTestOptions::GetAbsolutePathToOutputFile() {
1863 const char* const gtest_output_flag
= GTEST_FLAG(output
).c_str();
1864 if (gtest_output_flag
== NULL
) return "";
1866 const char* const colon
= strchr(gtest_output_flag
, ':');
1868 return internal::FilePath::ConcatPaths(
1870 UnitTest::GetInstance()->original_working_dir()),
1871 internal::FilePath(kDefaultOutputFile
))
1874 internal::FilePath
output_name(colon
+ 1);
1875 if (!output_name
.IsAbsolutePath())
1876 // TODO(wan@google.com): on Windows \some\path is not an absolute
1877 // path (as its meaning depends on the current drive), yet the
1878 // following logic for turning it into an absolute path is wrong.
1880 output_name
= internal::FilePath::ConcatPaths(
1881 internal::FilePath(UnitTest::GetInstance()->original_working_dir()),
1882 internal::FilePath(colon
+ 1));
1884 if (!output_name
.IsDirectory()) return output_name
.string();
1886 internal::FilePath
result(internal::FilePath::GenerateUniqueFileName(
1887 output_name
, internal::GetCurrentExecutableName(),
1888 GetOutputFormat().c_str()));
1889 return result
.string();
1892 // Returns true iff the wildcard pattern matches the string. The
1893 // first ':' or '\0' character in pattern marks the end of it.
1895 // This recursive algorithm isn't very efficient, but is clear and
1896 // works well enough for matching test names, which are short.
1897 bool UnitTestOptions::PatternMatchesString(const char* pattern
,
1901 case ':': // Either ':' or '\0' marks the end of the pattern.
1902 return *str
== '\0';
1903 case '?': // Matches any single character.
1904 return *str
!= '\0' && PatternMatchesString(pattern
+ 1, str
+ 1);
1905 case '*': // Matches any string (possibly empty) of characters.
1906 return (*str
!= '\0' && PatternMatchesString(pattern
, str
+ 1)) ||
1907 PatternMatchesString(pattern
+ 1, str
);
1908 default: // Non-special character. Matches itself.
1909 return *pattern
== *str
&& PatternMatchesString(pattern
+ 1, str
+ 1);
1913 bool UnitTestOptions::MatchesFilter(const std::string
& name
,
1914 const char* filter
) {
1915 const char* cur_pattern
= filter
;
1917 if (PatternMatchesString(cur_pattern
, name
.c_str())) {
1921 // Finds the next pattern in the filter.
1922 cur_pattern
= strchr(cur_pattern
, ':');
1924 // Returns if no more pattern can be found.
1925 if (cur_pattern
== NULL
) {
1929 // Skips the pattern separater (the ':' character).
1934 // Returns true iff the user-specified filter matches the test case
1935 // name and the test name.
1936 bool UnitTestOptions::FilterMatchesTest(const std::string
& test_case_name
,
1937 const std::string
& test_name
) {
1938 const std::string
& full_name
= test_case_name
+ "." + test_name
.c_str();
1940 // Split --gtest_filter at '-', if there is one, to separate into
1941 // positive filter and negative filter portions
1942 const char* const p
= GTEST_FLAG(filter
).c_str();
1943 const char* const dash
= strchr(p
, '-');
1944 std::string positive
;
1945 std::string negative
;
1947 positive
= GTEST_FLAG(filter
).c_str(); // Whole string is a positive filter
1950 positive
= std::string(p
, dash
); // Everything up to the dash
1951 negative
= std::string(dash
+ 1); // Everything after the dash
1952 if (positive
.empty()) {
1953 // Treat '-test1' as the same as '*-test1'
1954 positive
= kUniversalFilter
;
1958 // A filter is a colon-separated list of patterns. It matches a
1959 // test if any pattern in it matches the test.
1960 return (MatchesFilter(full_name
, positive
.c_str()) &&
1961 !MatchesFilter(full_name
, negative
.c_str()));
1965 // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
1966 // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
1967 // This function is useful as an __except condition.
1968 int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code
) {
1969 // Google Test should handle a SEH exception if:
1970 // 1. the user wants it to, AND
1971 // 2. this is not a breakpoint exception, AND
1972 // 3. this is not a C++ exception (VC++ implements them via SEH,
1975 // SEH exception code for C++ exceptions.
1976 // (see http://support.microsoft.com/kb/185294 for more information).
1977 const DWORD kCxxExceptionCode
= 0xe06d7363;
1979 bool should_handle
= true;
1981 if (!GTEST_FLAG(catch_exceptions
))
1982 should_handle
= false;
1983 else if (exception_code
== EXCEPTION_BREAKPOINT
)
1984 should_handle
= false;
1985 else if (exception_code
== kCxxExceptionCode
)
1986 should_handle
= false;
1988 return should_handle
? EXCEPTION_EXECUTE_HANDLER
: EXCEPTION_CONTINUE_SEARCH
;
1990 #endif // GTEST_HAS_SEH
1992 } // namespace internal
1994 // The c'tor sets this object as the test part result reporter used by
1995 // Google Test. The 'result' parameter specifies where to report the
1996 // results. Intercepts only failures from the current thread.
1997 ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
1998 TestPartResultArray
* result
)
1999 : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD
), result_(result
) {
2003 // The c'tor sets this object as the test part result reporter used by
2004 // Google Test. The 'result' parameter specifies where to report the
2006 ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
2007 InterceptMode intercept_mode
, TestPartResultArray
* result
)
2008 : intercept_mode_(intercept_mode
), result_(result
) {
2012 void ScopedFakeTestPartResultReporter::Init() {
2013 internal::UnitTestImpl
* const impl
= internal::GetUnitTestImpl();
2014 if (intercept_mode_
== INTERCEPT_ALL_THREADS
) {
2015 old_reporter_
= impl
->GetGlobalTestPartResultReporter();
2016 impl
->SetGlobalTestPartResultReporter(this);
2018 old_reporter_
= impl
->GetTestPartResultReporterForCurrentThread();
2019 impl
->SetTestPartResultReporterForCurrentThread(this);
2023 // The d'tor restores the test part result reporter used by Google Test
2025 ScopedFakeTestPartResultReporter::~ScopedFakeTestPartResultReporter() {
2026 internal::UnitTestImpl
* const impl
= internal::GetUnitTestImpl();
2027 if (intercept_mode_
== INTERCEPT_ALL_THREADS
) {
2028 impl
->SetGlobalTestPartResultReporter(old_reporter_
);
2030 impl
->SetTestPartResultReporterForCurrentThread(old_reporter_
);
2034 // Increments the test part result count and remembers the result.
2035 // This method is from the TestPartResultReporterInterface interface.
2036 void ScopedFakeTestPartResultReporter::ReportTestPartResult(
2037 const TestPartResult
& result
) {
2038 result_
->Append(result
);
2041 namespace internal
{
2043 // Returns the type ID of ::testing::Test. We should always call this
2044 // instead of GetTypeId< ::testing::Test>() to get the type ID of
2045 // testing::Test. This is to work around a suspected linker bug when
2046 // using Google Test as a framework on Mac OS X. The bug causes
2047 // GetTypeId< ::testing::Test>() to return different values depending
2048 // on whether the call is from the Google Test framework itself or
2049 // from user test code. GetTestTypeId() is guaranteed to always
2050 // return the same value, as it always calls GetTypeId<>() from the
2051 // gtest.cc, which is within the Google Test framework.
2052 TypeId
GetTestTypeId() { return GetTypeId
<Test
>(); }
2054 // The value of GetTestTypeId() as seen from within the Google Test
2055 // library. This is solely for testing GetTestTypeId().
2056 extern const TypeId kTestTypeIdInGoogleTest
= GetTestTypeId();
2058 // This predicate-formatter checks that 'results' contains a test part
2059 // failure of the given type and that the failure message contains the
2061 AssertionResult
HasOneFailure(const char* /* results_expr */,
2062 const char* /* type_expr */,
2063 const char* /* substr_expr */,
2064 const TestPartResultArray
& results
,
2065 TestPartResult::Type type
, const string
& substr
) {
2066 const std::string
expected(type
== TestPartResult::kFatalFailure
2068 : "1 non-fatal failure");
2070 if (results
.size() != 1) {
2071 msg
<< "Expected: " << expected
<< "\n"
2072 << " Actual: " << results
.size() << " failures";
2073 for (int i
= 0; i
< results
.size(); i
++) {
2074 msg
<< "\n" << results
.GetTestPartResult(i
);
2076 return AssertionFailure() << msg
;
2079 const TestPartResult
& r
= results
.GetTestPartResult(0);
2080 if (r
.type() != type
) {
2081 return AssertionFailure() << "Expected: " << expected
<< "\n"
2086 if (strstr(r
.message(), substr
.c_str()) == NULL
) {
2087 return AssertionFailure()
2088 << "Expected: " << expected
<< " containing \"" << substr
<< "\"\n"
2093 return AssertionSuccess();
2096 // The constructor of SingleFailureChecker remembers where to look up
2097 // test part results, what type of failure we expect, and what
2098 // substring the failure message should contain.
2099 SingleFailureChecker::SingleFailureChecker(const TestPartResultArray
* results
,
2100 TestPartResult::Type type
,
2101 const string
& substr
)
2102 : results_(results
), type_(type
), substr_(substr
) {}
2104 // The destructor of SingleFailureChecker verifies that the given
2105 // TestPartResultArray contains exactly one failure that has the given
2106 // type and contains the given substring. If that's not the case, a
2107 // non-fatal failure will be generated.
2108 SingleFailureChecker::~SingleFailureChecker() {
2109 EXPECT_PRED_FORMAT3(HasOneFailure
, *results_
, type_
, substr_
);
2112 DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter(
2113 UnitTestImpl
* unit_test
)
2114 : unit_test_(unit_test
) {}
2116 void DefaultGlobalTestPartResultReporter::ReportTestPartResult(
2117 const TestPartResult
& result
) {
2118 unit_test_
->current_test_result()->AddTestPartResult(result
);
2119 unit_test_
->listeners()->repeater()->OnTestPartResult(result
);
2122 DefaultPerThreadTestPartResultReporter::DefaultPerThreadTestPartResultReporter(
2123 UnitTestImpl
* unit_test
)
2124 : unit_test_(unit_test
) {}
2126 void DefaultPerThreadTestPartResultReporter::ReportTestPartResult(
2127 const TestPartResult
& result
) {
2128 unit_test_
->GetGlobalTestPartResultReporter()->ReportTestPartResult(result
);
2131 // Returns the global test part result reporter.
2132 TestPartResultReporterInterface
*
2133 UnitTestImpl::GetGlobalTestPartResultReporter() {
2134 internal::MutexLock
lock(&global_test_part_result_reporter_mutex_
);
2135 return global_test_part_result_repoter_
;
2138 // Sets the global test part result reporter.
2139 void UnitTestImpl::SetGlobalTestPartResultReporter(
2140 TestPartResultReporterInterface
* reporter
) {
2141 internal::MutexLock
lock(&global_test_part_result_reporter_mutex_
);
2142 global_test_part_result_repoter_
= reporter
;
2145 // Returns the test part result reporter for the current thread.
2146 TestPartResultReporterInterface
*
2147 UnitTestImpl::GetTestPartResultReporterForCurrentThread() {
2148 return per_thread_test_part_result_reporter_
.get();
2151 // Sets the test part result reporter for the current thread.
2152 void UnitTestImpl::SetTestPartResultReporterForCurrentThread(
2153 TestPartResultReporterInterface
* reporter
) {
2154 per_thread_test_part_result_reporter_
.set(reporter
);
2157 // Gets the number of successful test cases.
2158 int UnitTestImpl::successful_test_case_count() const {
2159 return CountIf(test_cases_
, TestCasePassed
);
2162 // Gets the number of failed test cases.
2163 int UnitTestImpl::failed_test_case_count() const {
2164 return CountIf(test_cases_
, TestCaseFailed
);
2167 // Gets the number of all test cases.
2168 int UnitTestImpl::total_test_case_count() const {
2169 return static_cast<int>(test_cases_
.size());
2172 // Gets the number of all test cases that contain at least one test
2174 int UnitTestImpl::test_case_to_run_count() const {
2175 return CountIf(test_cases_
, ShouldRunTestCase
);
2178 // Gets the number of successful tests.
2179 int UnitTestImpl::successful_test_count() const {
2180 return SumOverTestCaseList(test_cases_
, &TestCase::successful_test_count
);
2183 // Gets the number of failed tests.
2184 int UnitTestImpl::failed_test_count() const {
2185 return SumOverTestCaseList(test_cases_
, &TestCase::failed_test_count
);
2188 // Gets the number of disabled tests that will be reported in the XML report.
2189 int UnitTestImpl::reportable_disabled_test_count() const {
2190 return SumOverTestCaseList(test_cases_
,
2191 &TestCase::reportable_disabled_test_count
);
2194 // Gets the number of disabled tests.
2195 int UnitTestImpl::disabled_test_count() const {
2196 return SumOverTestCaseList(test_cases_
, &TestCase::disabled_test_count
);
2199 // Gets the number of tests to be printed in the XML report.
2200 int UnitTestImpl::reportable_test_count() const {
2201 return SumOverTestCaseList(test_cases_
, &TestCase::reportable_test_count
);
2204 // Gets the number of all tests.
2205 int UnitTestImpl::total_test_count() const {
2206 return SumOverTestCaseList(test_cases_
, &TestCase::total_test_count
);
2209 // Gets the number of tests that should run.
2210 int UnitTestImpl::test_to_run_count() const {
2211 return SumOverTestCaseList(test_cases_
, &TestCase::test_to_run_count
);
2214 // Returns the current OS stack trace as an std::string.
2216 // The maximum number of stack frames to be included is specified by
2217 // the gtest_stack_trace_depth flag. The skip_count parameter
2218 // specifies the number of top frames to be skipped, which doesn't
2219 // count against the number of frames to be included.
2221 // For example, if Foo() calls Bar(), which in turn calls
2222 // CurrentOsStackTraceExceptTop(1), Foo() will be included in the
2223 // trace but Bar() and CurrentOsStackTraceExceptTop() won't.
2224 std::string
UnitTestImpl::CurrentOsStackTraceExceptTop(int skip_count
) {
2229 // Returns the current time in milliseconds.
2230 TimeInMillis
GetTimeInMillis() {
2231 #if GTEST_OS_WINDOWS_MOBILE || defined(__BORLANDC__)
2232 // Difference between 1970-01-01 and 1601-01-01 in milliseconds.
2233 // http://analogous.blogspot.com/2005/04/epoch.html
2234 const TimeInMillis kJavaEpochToWinFileTimeDelta
=
2235 static_cast<TimeInMillis
>(116444736UL) * 100000UL;
2236 const DWORD kTenthMicrosInMilliSecond
= 10000;
2238 SYSTEMTIME now_systime
;
2239 FILETIME now_filetime
;
2240 ULARGE_INTEGER now_int64
;
2241 // TODO(kenton@google.com): Shouldn't this just use
2242 // GetSystemTimeAsFileTime()?
2243 GetSystemTime(&now_systime
);
2244 if (SystemTimeToFileTime(&now_systime
, &now_filetime
)) {
2245 now_int64
.LowPart
= now_filetime
.dwLowDateTime
;
2246 now_int64
.HighPart
= now_filetime
.dwHighDateTime
;
2247 now_int64
.QuadPart
= (now_int64
.QuadPart
/ kTenthMicrosInMilliSecond
) -
2248 kJavaEpochToWinFileTimeDelta
;
2249 return now_int64
.QuadPart
;
2252 #elif GTEST_OS_WINDOWS && !GTEST_HAS_GETTIMEOFDAY_
2257 // MSVC 8 deprecates _ftime64(), so we want to suppress warning 4996
2258 // (deprecated function) there.
2259 // TODO(kenton@google.com): Use GetTickCount()? Or use
2260 // SystemTimeToFileTime()
2261 # pragma warning(push) // Saves the current warning state.
2262 # pragma warning(disable : 4996) // Temporarily disables warning 4996.
2264 # pragma warning(pop) // Restores the warning state.
2271 return static_cast<TimeInMillis
>(now
.time
) * 1000 + now
.millitm
;
2272 #elif GTEST_HAS_GETTIMEOFDAY_
2274 gettimeofday(&now
, NULL
);
2275 return static_cast<TimeInMillis
>(now
.tv_sec
) * 1000 + now
.tv_usec
/ 1000;
2277 # error "Don't know how to get the current time on your system."
2285 #if GTEST_OS_WINDOWS_MOBILE
2286 // Creates a UTF-16 wide string from the given ANSI string, allocating
2287 // memory using new. The caller is responsible for deleting the return
2288 // value using delete[]. Returns the wide string, or NULL if the
2290 LPCWSTR
String::AnsiToUtf16(const char* ansi
) {
2291 if (!ansi
) return NULL
;
2292 const int length
= strlen(ansi
);
2293 const int unicode_length
=
2294 MultiByteToWideChar(CP_ACP
, 0, ansi
, length
, NULL
, 0);
2295 WCHAR
* unicode
= new WCHAR
[unicode_length
+ 1];
2296 MultiByteToWideChar(CP_ACP
, 0, ansi
, length
, unicode
, unicode_length
);
2297 unicode
[unicode_length
] = 0;
2301 // Creates an ANSI string from the given wide string, allocating
2302 // memory using new. The caller is responsible for deleting the return
2303 // value using delete[]. Returns the ANSI string, or NULL if the
2305 const char* String::Utf16ToAnsi(LPCWSTR utf16_str
) {
2306 if (!utf16_str
) return NULL
;
2307 const int ansi_length
=
2308 WideCharToMultiByte(CP_ACP
, 0, utf16_str
, -1, NULL
, 0, NULL
, NULL
);
2309 char* ansi
= new char[ansi_length
+ 1];
2310 WideCharToMultiByte(CP_ACP
, 0, utf16_str
, -1, ansi
, ansi_length
, NULL
, NULL
);
2311 ansi
[ansi_length
] = 0;
2315 #endif // GTEST_OS_WINDOWS_MOBILE
2317 // Compares two C strings. Returns true iff they have the same content.
2319 // Unlike strcmp(), this function can handle NULL argument(s). A NULL
2320 // C string is considered different to any non-NULL C string,
2321 // including the empty string.
2322 bool String::CStringEquals(const char* lhs
, const char* rhs
) {
2323 if (lhs
== NULL
) return rhs
== NULL
;
2325 if (rhs
== NULL
) return false;
2327 return strcmp(lhs
, rhs
) == 0;
2330 #if GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
2332 // Converts an array of wide chars to a narrow string using the UTF-8
2333 // encoding, and streams the result to the given Message object.
2334 static void StreamWideCharsToMessage(const wchar_t* wstr
, size_t length
,
2336 for (size_t i
= 0; i
!= length
;) { // NOLINT
2337 if (wstr
[i
] != L
'\0') {
2338 *msg
<< WideStringToUtf8(wstr
+ i
, static_cast<int>(length
- i
));
2339 while (i
!= length
&& wstr
[i
] != L
'\0') i
++;
2347 #endif // GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
2349 } // namespace internal
2351 // Constructs an empty Message.
2352 // We allocate the stringstream separately because otherwise each use of
2353 // ASSERT/EXPECT in a procedure adds over 200 bytes to the procedure's
2354 // stack frame leading to huge stack frames in some cases; gcc does not reuse
2356 Message::Message() : ss_(new ::std::stringstream
) {
2357 // By default, we want there to be enough precision when printing
2358 // a double to a Message.
2359 *ss_
<< std::setprecision(std::numeric_limits
<double>::digits10
+ 2);
2362 // These two overloads allow streaming a wide C string to a Message
2363 // using the UTF-8 encoding.
2364 Message
& Message::operator<<(const wchar_t* wide_c_str
) {
2365 return *this << internal::String::ShowWideCString(wide_c_str
);
2367 Message
& Message::operator<<(wchar_t* wide_c_str
) {
2368 return *this << internal::String::ShowWideCString(wide_c_str
);
2371 #if GTEST_HAS_STD_WSTRING
2372 // Converts the given wide string to a narrow string using the UTF-8
2373 // encoding, and streams the result to this Message object.
2374 Message
& Message::operator<<(const ::std::wstring
& wstr
) {
2375 internal::StreamWideCharsToMessage(wstr
.c_str(), wstr
.length(), this);
2378 #endif // GTEST_HAS_STD_WSTRING
2380 #if GTEST_HAS_GLOBAL_WSTRING
2381 // Converts the given wide string to a narrow string using the UTF-8
2382 // encoding, and streams the result to this Message object.
2383 Message
& Message::operator<<(const ::wstring
& wstr
) {
2384 internal::StreamWideCharsToMessage(wstr
.c_str(), wstr
.length(), this);
2387 #endif // GTEST_HAS_GLOBAL_WSTRING
2389 // Gets the text streamed to this object so far as an std::string.
2390 // Each '\0' character in the buffer is replaced with "\\0".
2391 std::string
Message::GetString() const {
2392 return internal::StringStreamToString(ss_
.get());
2395 // AssertionResult constructors.
2396 // Used in EXPECT_TRUE/FALSE(assertion_result).
2397 AssertionResult::AssertionResult(const AssertionResult
& other
)
2398 : success_(other
.success_
),
2399 message_(other
.message_
.get() != NULL
2400 ? new ::std::string(*other
.message_
)
2401 : static_cast< ::std::string
*>(NULL
)) {}
2403 // Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE.
2404 AssertionResult
AssertionResult::operator!() const {
2405 AssertionResult
negation(!success_
);
2406 if (message_
.get() != NULL
) negation
<< *message_
;
2410 // Makes a successful assertion result.
2411 AssertionResult
AssertionSuccess() { return AssertionResult(true); }
2413 // Makes a failed assertion result.
2414 AssertionResult
AssertionFailure() { return AssertionResult(false); }
2416 // Makes a failed assertion result with the given failure message.
2417 // Deprecated; use AssertionFailure() << message.
2418 AssertionResult
AssertionFailure(const Message
& message
) {
2419 return AssertionFailure() << message
;
2422 namespace internal
{
2424 // Constructs and returns the message for an equality assertion
2425 // (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure.
2427 // The first four parameters are the expressions used in the assertion
2428 // and their values, as strings. For example, for ASSERT_EQ(foo, bar)
2429 // where foo is 5 and bar is 6, we have:
2431 // expected_expression: "foo"
2432 // actual_expression: "bar"
2433 // expected_value: "5"
2434 // actual_value: "6"
2436 // The ignoring_case parameter is true iff the assertion is a
2437 // *_STRCASEEQ*. When it's true, the string " (ignoring case)" will
2438 // be inserted into the message.
2439 AssertionResult
EqFailure(const char* expected_expression
,
2440 const char* actual_expression
,
2441 const std::string
& expected_value
,
2442 const std::string
& actual_value
, bool ignoring_case
) {
2444 msg
<< "Value of: " << actual_expression
;
2445 if (actual_value
!= actual_expression
) {
2446 msg
<< "\n Actual: " << actual_value
;
2449 msg
<< "\nExpected: " << expected_expression
;
2450 if (ignoring_case
) {
2451 msg
<< " (ignoring case)";
2453 if (expected_value
!= expected_expression
) {
2454 msg
<< "\nWhich is: " << expected_value
;
2457 return AssertionFailure() << msg
;
2460 // Constructs a failure message for Boolean assertions such as EXPECT_TRUE.
2461 std::string
GetBoolAssertionFailureMessage(
2462 const AssertionResult
& assertion_result
, const char* expression_text
,
2463 const char* actual_predicate_value
, const char* expected_predicate_value
) {
2464 const char* actual_message
= assertion_result
.message();
2466 msg
<< "Value of: " << expression_text
2467 << "\n Actual: " << actual_predicate_value
;
2468 if (actual_message
[0] != '\0') msg
<< " (" << actual_message
<< ")";
2469 msg
<< "\nExpected: " << expected_predicate_value
;
2470 return msg
.GetString();
2473 // Helper function for implementing ASSERT_NEAR.
2474 AssertionResult
DoubleNearPredFormat(const char* expr1
, const char* expr2
,
2475 const char* abs_error_expr
, double val1
,
2476 double val2
, double abs_error
) {
2477 const double diff
= fabs(val1
- val2
);
2478 if (diff
<= abs_error
) return AssertionSuccess();
2480 // TODO(wan): do not print the value of an expression if it's
2481 // already a literal.
2482 return AssertionFailure()
2483 << "The difference between " << expr1
<< " and " << expr2
<< " is "
2484 << diff
<< ", which exceeds " << abs_error_expr
<< ", where\n"
2485 << expr1
<< " evaluates to " << val1
<< ",\n"
2486 << expr2
<< " evaluates to " << val2
<< ", and\n"
2487 << abs_error_expr
<< " evaluates to " << abs_error
<< ".";
2490 // Helper template for implementing FloatLE() and DoubleLE().
2491 template <typename RawType
>
2492 AssertionResult
FloatingPointLE(const char* expr1
, const char* expr2
,
2493 RawType val1
, RawType val2
) {
2494 // Returns success if val1 is less than val2,
2496 return AssertionSuccess();
2499 // or if val1 is almost equal to val2.
2500 const FloatingPoint
<RawType
> lhs(val1
), rhs(val2
);
2501 if (lhs
.AlmostEquals(rhs
)) {
2502 return AssertionSuccess();
2505 // Note that the above two checks will both fail if either val1 or
2506 // val2 is NaN, as the IEEE floating-point standard requires that
2507 // any predicate involving a NaN must return false.
2509 ::std::stringstream val1_ss
;
2510 val1_ss
<< std::setprecision(std::numeric_limits
<RawType
>::digits10
+ 2)
2513 ::std::stringstream val2_ss
;
2514 val2_ss
<< std::setprecision(std::numeric_limits
<RawType
>::digits10
+ 2)
2517 return AssertionFailure()
2518 << "Expected: (" << expr1
<< ") <= (" << expr2
<< ")\n"
2519 << " Actual: " << StringStreamToString(&val1_ss
) << " vs "
2520 << StringStreamToString(&val2_ss
);
2523 } // namespace internal
2525 // Asserts that val1 is less than, or almost equal to, val2. Fails
2526 // otherwise. In particular, it fails if either val1 or val2 is NaN.
2527 AssertionResult
FloatLE(const char* expr1
, const char* expr2
, float val1
,
2529 return internal::FloatingPointLE
<float>(expr1
, expr2
, val1
, val2
);
2532 // Asserts that val1 is less than, or almost equal to, val2. Fails
2533 // otherwise. In particular, it fails if either val1 or val2 is NaN.
2534 AssertionResult
DoubleLE(const char* expr1
, const char* expr2
, double val1
,
2536 return internal::FloatingPointLE
<double>(expr1
, expr2
, val1
, val2
);
2539 namespace internal
{
2541 // The helper function for {ASSERT|EXPECT}_EQ with int or enum
2543 AssertionResult
CmpHelperEQ(const char* expected_expression
,
2544 const char* actual_expression
, BiggestInt expected
,
2545 BiggestInt actual
) {
2546 if (expected
== actual
) {
2547 return AssertionSuccess();
2550 return EqFailure(expected_expression
, actual_expression
,
2551 FormatForComparisonFailureMessage(expected
, actual
),
2552 FormatForComparisonFailureMessage(actual
, expected
), false);
2555 // A macro for implementing the helper functions needed to implement
2556 // ASSERT_?? and EXPECT_?? with integer or enum arguments. It is here
2557 // just to avoid copy-and-paste of similar code.
2558 #define GTEST_IMPL_CMP_HELPER_(op_name, op) \
2559 AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \
2560 BiggestInt val1, BiggestInt val2) { \
2561 if (val1 op val2) { \
2562 return AssertionSuccess(); \
2564 return AssertionFailure() \
2565 << "Expected: (" << expr1 << ") " #op " (" << expr2 \
2566 << "), actual: " << FormatForComparisonFailureMessage(val1, val2) \
2567 << " vs " << FormatForComparisonFailureMessage(val2, val1); \
2571 // Implements the helper function for {ASSERT|EXPECT}_NE with int or
2573 GTEST_IMPL_CMP_HELPER_(NE
, !=)
2574 // Implements the helper function for {ASSERT|EXPECT}_LE with int or
2576 GTEST_IMPL_CMP_HELPER_(LE
, <=)
2577 // Implements the helper function for {ASSERT|EXPECT}_LT with int or
2579 GTEST_IMPL_CMP_HELPER_(LT
, <)
2580 // Implements the helper function for {ASSERT|EXPECT}_GE with int or
2582 GTEST_IMPL_CMP_HELPER_(GE
, >=)
2583 // Implements the helper function for {ASSERT|EXPECT}_GT with int or
2585 GTEST_IMPL_CMP_HELPER_(GT
, >)
2587 #undef GTEST_IMPL_CMP_HELPER_
2589 // The helper function for {ASSERT|EXPECT}_STREQ.
2590 AssertionResult
CmpHelperSTREQ(const char* expected_expression
,
2591 const char* actual_expression
,
2592 const char* expected
, const char* actual
) {
2593 if (String::CStringEquals(expected
, actual
)) {
2594 return AssertionSuccess();
2597 return EqFailure(expected_expression
, actual_expression
,
2598 PrintToString(expected
), PrintToString(actual
), false);
2601 // The helper function for {ASSERT|EXPECT}_STRCASEEQ.
2602 AssertionResult
CmpHelperSTRCASEEQ(const char* expected_expression
,
2603 const char* actual_expression
,
2604 const char* expected
, const char* actual
) {
2605 if (String::CaseInsensitiveCStringEquals(expected
, actual
)) {
2606 return AssertionSuccess();
2609 return EqFailure(expected_expression
, actual_expression
,
2610 PrintToString(expected
), PrintToString(actual
), true);
2613 // The helper function for {ASSERT|EXPECT}_STRNE.
2614 AssertionResult
CmpHelperSTRNE(const char* s1_expression
,
2615 const char* s2_expression
, const char* s1
,
2617 if (!String::CStringEquals(s1
, s2
)) {
2618 return AssertionSuccess();
2620 return AssertionFailure()
2621 << "Expected: (" << s1_expression
<< ") != (" << s2_expression
2622 << "), actual: \"" << s1
<< "\" vs \"" << s2
<< "\"";
2626 // The helper function for {ASSERT|EXPECT}_STRCASENE.
2627 AssertionResult
CmpHelperSTRCASENE(const char* s1_expression
,
2628 const char* s2_expression
, const char* s1
,
2630 if (!String::CaseInsensitiveCStringEquals(s1
, s2
)) {
2631 return AssertionSuccess();
2633 return AssertionFailure()
2634 << "Expected: (" << s1_expression
<< ") != (" << s2_expression
2635 << ") (ignoring case), actual: \"" << s1
<< "\" vs \"" << s2
<< "\"";
2639 } // namespace internal
2643 // Helper functions for implementing IsSubString() and IsNotSubstring().
2645 // This group of overloaded functions return true iff needle is a
2646 // substring of haystack. NULL is considered a substring of itself
2649 bool IsSubstringPred(const char* needle
, const char* haystack
) {
2650 if (needle
== NULL
|| haystack
== NULL
) return needle
== haystack
;
2652 return strstr(haystack
, needle
) != NULL
;
2655 bool IsSubstringPred(const wchar_t* needle
, const wchar_t* haystack
) {
2656 if (needle
== NULL
|| haystack
== NULL
) return needle
== haystack
;
2658 return wcsstr(haystack
, needle
) != NULL
;
2661 // StringType here can be either ::std::string or ::std::wstring.
2662 template <typename StringType
>
2663 bool IsSubstringPred(const StringType
& needle
, const StringType
& haystack
) {
2664 return haystack
.find(needle
) != StringType::npos
;
2667 // This function implements either IsSubstring() or IsNotSubstring(),
2668 // depending on the value of the expected_to_be_substring parameter.
2669 // StringType here can be const char*, const wchar_t*, ::std::string,
2670 // or ::std::wstring.
2671 template <typename StringType
>
2672 AssertionResult
IsSubstringImpl(bool expected_to_be_substring
,
2673 const char* needle_expr
,
2674 const char* haystack_expr
,
2675 const StringType
& needle
,
2676 const StringType
& haystack
) {
2677 if (IsSubstringPred(needle
, haystack
) == expected_to_be_substring
)
2678 return AssertionSuccess();
2680 const bool is_wide_string
= sizeof(needle
[0]) > 1;
2681 const char* const begin_string_quote
= is_wide_string
? "L\"" : "\"";
2682 return AssertionFailure()
2683 << "Value of: " << needle_expr
<< "\n"
2684 << " Actual: " << begin_string_quote
<< needle
<< "\"\n"
2685 << "Expected: " << (expected_to_be_substring
? "" : "not ")
2686 << "a substring of " << haystack_expr
<< "\n"
2687 << "Which is: " << begin_string_quote
<< haystack
<< "\"";
2692 // IsSubstring() and IsNotSubstring() check whether needle is a
2693 // substring of haystack (NULL is considered a substring of itself
2694 // only), and return an appropriate error message when they fail.
2696 AssertionResult
IsSubstring(const char* needle_expr
, const char* haystack_expr
,
2697 const char* needle
, const char* haystack
) {
2698 return IsSubstringImpl(true, needle_expr
, haystack_expr
, needle
, haystack
);
2701 AssertionResult
IsSubstring(const char* needle_expr
, const char* haystack_expr
,
2702 const wchar_t* needle
, const wchar_t* haystack
) {
2703 return IsSubstringImpl(true, needle_expr
, haystack_expr
, needle
, haystack
);
2706 AssertionResult
IsNotSubstring(const char* needle_expr
,
2707 const char* haystack_expr
, const char* needle
,
2708 const char* haystack
) {
2709 return IsSubstringImpl(false, needle_expr
, haystack_expr
, needle
, haystack
);
2712 AssertionResult
IsNotSubstring(const char* needle_expr
,
2713 const char* haystack_expr
, const wchar_t* needle
,
2714 const wchar_t* haystack
) {
2715 return IsSubstringImpl(false, needle_expr
, haystack_expr
, needle
, haystack
);
2718 AssertionResult
IsSubstring(const char* needle_expr
, const char* haystack_expr
,
2719 const ::std::string
& needle
,
2720 const ::std::string
& haystack
) {
2721 return IsSubstringImpl(true, needle_expr
, haystack_expr
, needle
, haystack
);
2724 AssertionResult
IsNotSubstring(const char* needle_expr
,
2725 const char* haystack_expr
,
2726 const ::std::string
& needle
,
2727 const ::std::string
& haystack
) {
2728 return IsSubstringImpl(false, needle_expr
, haystack_expr
, needle
, haystack
);
2731 #if GTEST_HAS_STD_WSTRING
2732 AssertionResult
IsSubstring(const char* needle_expr
, const char* haystack_expr
,
2733 const ::std::wstring
& needle
,
2734 const ::std::wstring
& haystack
) {
2735 return IsSubstringImpl(true, needle_expr
, haystack_expr
, needle
, haystack
);
2738 AssertionResult
IsNotSubstring(const char* needle_expr
,
2739 const char* haystack_expr
,
2740 const ::std::wstring
& needle
,
2741 const ::std::wstring
& haystack
) {
2742 return IsSubstringImpl(false, needle_expr
, haystack_expr
, needle
, haystack
);
2744 #endif // GTEST_HAS_STD_WSTRING
2746 namespace internal
{
2748 #if GTEST_OS_WINDOWS
2752 // Helper function for IsHRESULT{SuccessFailure} predicates
2753 AssertionResult
HRESULTFailureHelper(const char* expr
, const char* expected
,
2754 long hr
) { // NOLINT
2755 # if GTEST_OS_WINDOWS_MOBILE
2757 // Windows CE doesn't support FormatMessage.
2758 const char error_text
[] = "";
2762 // Looks up the human-readable system message for the HRESULT code
2763 // and since we're not passing any params to FormatMessage, we don't
2764 // want inserts expanded.
2765 const DWORD kFlags
=
2766 FORMAT_MESSAGE_FROM_SYSTEM
| FORMAT_MESSAGE_IGNORE_INSERTS
;
2767 const DWORD kBufSize
= 4096;
2768 // Gets the system's human readable message string for this HRESULT.
2769 char error_text
[kBufSize
] = {'\0'};
2770 DWORD message_length
= ::FormatMessageA(kFlags
,
2771 0, // no source, we're asking system
2773 0, // no line width restrictions
2774 error_text
, // output buffer
2775 kBufSize
, // buf size
2776 NULL
); // no arguments for inserts
2777 // Trims tailing white space (FormatMessage leaves a trailing CR-LF)
2778 for (; message_length
&& IsSpace(error_text
[message_length
- 1]);
2780 error_text
[message_length
- 1] = '\0';
2783 # endif // GTEST_OS_WINDOWS_MOBILE
2785 const std::string
error_hex("0x" + String::FormatHexInt(hr
));
2786 return ::testing::AssertionFailure()
2787 << "Expected: " << expr
<< " " << expected
<< ".\n"
2788 << " Actual: " << error_hex
<< " " << error_text
<< "\n";
2793 AssertionResult
IsHRESULTSuccess(const char* expr
, long hr
) { // NOLINT
2794 if (SUCCEEDED(hr
)) {
2795 return AssertionSuccess();
2797 return HRESULTFailureHelper(expr
, "succeeds", hr
);
2800 AssertionResult
IsHRESULTFailure(const char* expr
, long hr
) { // NOLINT
2802 return AssertionSuccess();
2804 return HRESULTFailureHelper(expr
, "fails", hr
);
2807 #endif // GTEST_OS_WINDOWS
2809 // Utility functions for encoding Unicode text (wide strings) in
2812 // A Unicode code-point can have upto 21 bits, and is encoded in UTF-8
2815 // Code-point length Encoding
2816 // 0 - 7 bits 0xxxxxxx
2817 // 8 - 11 bits 110xxxxx 10xxxxxx
2818 // 12 - 16 bits 1110xxxx 10xxxxxx 10xxxxxx
2819 // 17 - 21 bits 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
2821 // The maximum code-point a one-byte UTF-8 sequence can represent.
2822 const UInt32 kMaxCodePoint1
= (static_cast<UInt32
>(1) << 7) - 1;
2824 // The maximum code-point a two-byte UTF-8 sequence can represent.
2825 const UInt32 kMaxCodePoint2
= (static_cast<UInt32
>(1) << (5 + 6)) - 1;
2827 // The maximum code-point a three-byte UTF-8 sequence can represent.
2828 const UInt32 kMaxCodePoint3
= (static_cast<UInt32
>(1) << (4 + 2 * 6)) - 1;
2830 // The maximum code-point a four-byte UTF-8 sequence can represent.
2831 const UInt32 kMaxCodePoint4
= (static_cast<UInt32
>(1) << (3 + 3 * 6)) - 1;
2833 // Chops off the n lowest bits from a bit pattern. Returns the n
2834 // lowest bits. As a side effect, the original bit pattern will be
2835 // shifted to the right by n bits.
2836 inline UInt32
ChopLowBits(UInt32
* bits
, int n
) {
2837 const UInt32 low_bits
= *bits
& ((static_cast<UInt32
>(1) << n
) - 1);
2842 // Converts a Unicode code point to a narrow string in UTF-8 encoding.
2843 // code_point parameter is of type UInt32 because wchar_t may not be
2844 // wide enough to contain a code point.
2845 // If the code_point is not a valid Unicode code point
2846 // (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted
2847 // to "(Invalid Unicode 0xXXXXXXXX)".
2848 std::string
CodePointToUtf8(UInt32 code_point
) {
2849 if (code_point
> kMaxCodePoint4
) {
2850 return "(Invalid Unicode 0x" + String::FormatHexInt(code_point
) + ")";
2853 char str
[5]; // Big enough for the largest valid code point.
2854 if (code_point
<= kMaxCodePoint1
) {
2856 str
[0] = static_cast<char>(code_point
); // 0xxxxxxx
2857 } else if (code_point
<= kMaxCodePoint2
) {
2859 str
[1] = static_cast<char>(0x80 | ChopLowBits(&code_point
, 6)); // 10xxxxxx
2860 str
[0] = static_cast<char>(0xC0 | code_point
); // 110xxxxx
2861 } else if (code_point
<= kMaxCodePoint3
) {
2863 str
[2] = static_cast<char>(0x80 | ChopLowBits(&code_point
, 6)); // 10xxxxxx
2864 str
[1] = static_cast<char>(0x80 | ChopLowBits(&code_point
, 6)); // 10xxxxxx
2865 str
[0] = static_cast<char>(0xE0 | code_point
); // 1110xxxx
2866 } else { // code_point <= kMaxCodePoint4
2868 str
[3] = static_cast<char>(0x80 | ChopLowBits(&code_point
, 6)); // 10xxxxxx
2869 str
[2] = static_cast<char>(0x80 | ChopLowBits(&code_point
, 6)); // 10xxxxxx
2870 str
[1] = static_cast<char>(0x80 | ChopLowBits(&code_point
, 6)); // 10xxxxxx
2871 str
[0] = static_cast<char>(0xF0 | code_point
); // 11110xxx
2876 // The following two functions only make sense if the the system
2877 // uses UTF-16 for wide string encoding. All supported systems
2878 // with 16 bit wchar_t (Windows, Cygwin, Symbian OS) do use UTF-16.
2880 // Determines if the arguments constitute UTF-16 surrogate pair
2881 // and thus should be combined into a single Unicode code point
2882 // using CreateCodePointFromUtf16SurrogatePair.
2883 inline bool IsUtf16SurrogatePair(wchar_t first
, wchar_t second
) {
2884 return sizeof(wchar_t) == 2 && (first
& 0xFC00) == 0xD800 &&
2885 (second
& 0xFC00) == 0xDC00;
2888 // Creates a Unicode code point from UTF16 surrogate pair.
2889 inline UInt32
CreateCodePointFromUtf16SurrogatePair(wchar_t first
,
2891 const UInt32 mask
= (1 << 10) - 1;
2892 return (sizeof(wchar_t) == 2)
2893 ? (((first
& mask
) << 10) | (second
& mask
)) + 0x10000
2895 // This function should not be called when the condition is
2896 // false, but we provide a sensible default in case it is.
2897 static_cast<UInt32
>(first
);
2900 // Converts a wide string to a narrow string in UTF-8 encoding.
2901 // The wide string is assumed to have the following encoding:
2902 // UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS)
2903 // UTF-32 if sizeof(wchar_t) == 4 (on Linux)
2904 // Parameter str points to a null-terminated wide string.
2905 // Parameter num_chars may additionally limit the number
2906 // of wchar_t characters processed. -1 is used when the entire string
2907 // should be processed.
2908 // If the string contains code points that are not valid Unicode code points
2909 // (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
2910 // as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
2911 // and contains invalid UTF-16 surrogate pairs, values in those pairs
2912 // will be encoded as individual Unicode characters from Basic Normal Plane.
2913 std::string
WideStringToUtf8(const wchar_t* str
, int num_chars
) {
2914 if (num_chars
== -1) num_chars
= static_cast<int>(wcslen(str
));
2916 ::std::stringstream stream
;
2917 for (int i
= 0; i
< num_chars
; ++i
) {
2918 UInt32 unicode_code_point
;
2920 if (str
[i
] == L
'\0') {
2922 } else if (i
+ 1 < num_chars
&& IsUtf16SurrogatePair(str
[i
], str
[i
+ 1])) {
2923 unicode_code_point
=
2924 CreateCodePointFromUtf16SurrogatePair(str
[i
], str
[i
+ 1]);
2927 unicode_code_point
= static_cast<UInt32
>(str
[i
]);
2930 stream
<< CodePointToUtf8(unicode_code_point
);
2932 return StringStreamToString(&stream
);
2935 // Converts a wide C string to an std::string using the UTF-8 encoding.
2936 // NULL will be converted to "(null)".
2937 std::string
String::ShowWideCString(const wchar_t* wide_c_str
) {
2938 if (wide_c_str
== NULL
) return "(null)";
2940 return internal::WideStringToUtf8(wide_c_str
, -1);
2943 // Compares two wide C strings. Returns true iff they have the same
2946 // Unlike wcscmp(), this function can handle NULL argument(s). A NULL
2947 // C string is considered different to any non-NULL C string,
2948 // including the empty string.
2949 bool String::WideCStringEquals(const wchar_t* lhs
, const wchar_t* rhs
) {
2950 if (lhs
== NULL
) return rhs
== NULL
;
2952 if (rhs
== NULL
) return false;
2954 return wcscmp(lhs
, rhs
) == 0;
2957 // Helper function for *_STREQ on wide strings.
2958 AssertionResult
CmpHelperSTREQ(const char* expected_expression
,
2959 const char* actual_expression
,
2960 const wchar_t* expected
, const wchar_t* actual
) {
2961 if (String::WideCStringEquals(expected
, actual
)) {
2962 return AssertionSuccess();
2965 return EqFailure(expected_expression
, actual_expression
,
2966 PrintToString(expected
), PrintToString(actual
), false);
2969 // Helper function for *_STRNE on wide strings.
2970 AssertionResult
CmpHelperSTRNE(const char* s1_expression
,
2971 const char* s2_expression
, const wchar_t* s1
,
2972 const wchar_t* s2
) {
2973 if (!String::WideCStringEquals(s1
, s2
)) {
2974 return AssertionSuccess();
2977 return AssertionFailure()
2978 << "Expected: (" << s1_expression
<< ") != (" << s2_expression
2979 << "), actual: " << PrintToString(s1
) << " vs " << PrintToString(s2
);
2982 // Compares two C strings, ignoring case. Returns true iff they have
2983 // the same content.
2985 // Unlike strcasecmp(), this function can handle NULL argument(s). A
2986 // NULL C string is considered different to any non-NULL C string,
2987 // including the empty string.
2988 bool String::CaseInsensitiveCStringEquals(const char* lhs
, const char* rhs
) {
2989 if (lhs
== NULL
) return rhs
== NULL
;
2990 if (rhs
== NULL
) return false;
2991 return posix::StrCaseCmp(lhs
, rhs
) == 0;
2994 // Compares two wide C strings, ignoring case. Returns true iff they
2995 // have the same content.
2997 // Unlike wcscasecmp(), this function can handle NULL argument(s).
2998 // A NULL C string is considered different to any non-NULL wide C string,
2999 // including the empty string.
3000 // NB: The implementations on different platforms slightly differ.
3001 // On windows, this method uses _wcsicmp which compares according to LC_CTYPE
3002 // environment variable. On GNU platform this method uses wcscasecmp
3003 // which compares according to LC_CTYPE category of the current locale.
3004 // On MacOS X, it uses towlower, which also uses LC_CTYPE category of the
3006 bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs
,
3007 const wchar_t* rhs
) {
3008 if (lhs
== NULL
) return rhs
== NULL
;
3010 if (rhs
== NULL
) return false;
3012 #if GTEST_OS_WINDOWS
3013 return _wcsicmp(lhs
, rhs
) == 0;
3014 #elif GTEST_OS_LINUX && !GTEST_OS_LINUX_ANDROID
3015 return wcscasecmp(lhs
, rhs
) == 0;
3017 // Android, Mac OS X and Cygwin don't define wcscasecmp.
3018 // Other unknown OSes may not define it either.
3021 left
= towlower(*lhs
++);
3022 right
= towlower(*rhs
++);
3023 } while (left
&& left
== right
);
3024 return left
== right
;
3025 #endif // OS selector
3028 // Returns true iff str ends with the given suffix, ignoring case.
3029 // Any string is considered to end with an empty suffix.
3030 bool String::EndsWithCaseInsensitive(const std::string
& str
,
3031 const std::string
& suffix
) {
3032 const size_t str_len
= str
.length();
3033 const size_t suffix_len
= suffix
.length();
3034 return (str_len
>= suffix_len
) &&
3035 CaseInsensitiveCStringEquals(str
.c_str() + str_len
- suffix_len
,
3039 // Formats an int value as "%02d".
3040 std::string
String::FormatIntWidth2(int value
) {
3041 std::stringstream ss
;
3042 ss
<< std::setfill('0') << std::setw(2) << value
;
3046 // Formats an int value as "%X".
3047 std::string
String::FormatHexInt(int value
) {
3048 std::stringstream ss
;
3049 ss
<< std::hex
<< std::uppercase
<< value
;
3053 // Formats a byte as "%02X".
3054 std::string
String::FormatByte(unsigned char value
) {
3055 std::stringstream ss
;
3056 ss
<< std::setfill('0') << std::setw(2) << std::hex
<< std::uppercase
3057 << static_cast<unsigned int>(value
);
3061 // Converts the buffer in a stringstream to an std::string, converting NUL
3062 // bytes to "\\0" along the way.
3063 std::string
StringStreamToString(::std::stringstream
* ss
) {
3064 const ::std::string
& str
= ss
->str();
3065 const char* const start
= str
.c_str();
3066 const char* const end
= start
+ str
.length();
3069 result
.reserve(2 * (end
- start
));
3070 for (const char* ch
= start
; ch
!= end
; ++ch
) {
3072 result
+= "\\0"; // Replaces NUL with "\\0";
3081 // Appends the user-supplied message to the Google-Test-generated message.
3082 std::string
AppendUserMessage(const std::string
& gtest_msg
,
3083 const Message
& user_msg
) {
3084 // Appends the user message if it's non-empty.
3085 const std::string user_msg_string
= user_msg
.GetString();
3086 if (user_msg_string
.empty()) {
3090 return gtest_msg
+ "\n" + user_msg_string
;
3093 } // namespace internal
3097 // Creates an empty TestResult.
3098 TestResult::TestResult() : death_test_count_(0), elapsed_time_(0) {}
3101 TestResult::~TestResult() {}
3103 // Returns the i-th test part result among all the results. i can
3104 // range from 0 to total_part_count() - 1. If i is not in that range,
3105 // aborts the program.
3106 const TestPartResult
& TestResult::GetTestPartResult(int i
) const {
3107 if (i
< 0 || i
>= total_part_count()) internal::posix::Abort();
3108 return test_part_results_
.at(i
);
3111 // Returns the i-th test property. i can range from 0 to
3112 // test_property_count() - 1. If i is not in that range, aborts the
3114 const TestProperty
& TestResult::GetTestProperty(int i
) const {
3115 if (i
< 0 || i
>= test_property_count()) internal::posix::Abort();
3116 return test_properties_
.at(i
);
3119 // Clears the test part results.
3120 void TestResult::ClearTestPartResults() { test_part_results_
.clear(); }
3122 // Adds a test part result to the list.
3123 void TestResult::AddTestPartResult(const TestPartResult
& test_part_result
) {
3124 test_part_results_
.push_back(test_part_result
);
3127 // Adds a test property to the list. If a property with the same key as the
3128 // supplied property is already represented, the value of this test_property
3129 // replaces the old value for that key.
3130 void TestResult::RecordProperty(const std::string
& xml_element
,
3131 const TestProperty
& test_property
) {
3132 if (!ValidateTestProperty(xml_element
, test_property
)) {
3135 internal::MutexLock
lock(&test_properites_mutex_
);
3136 const std::vector
<TestProperty
>::iterator property_with_matching_key
=
3137 std::find_if(test_properties_
.begin(), test_properties_
.end(),
3138 internal::TestPropertyKeyIs(test_property
.key()));
3139 if (property_with_matching_key
== test_properties_
.end()) {
3140 test_properties_
.push_back(test_property
);
3143 property_with_matching_key
->SetValue(test_property
.value());
3146 // The list of reserved attributes used in the <testsuites> element of XML
3148 static const char* const kReservedTestSuitesAttributes
[] = {
3149 "disabled", "errors", "failures", "name",
3150 "random_seed", "tests", "time", "timestamp"};
3152 // The list of reserved attributes used in the <testsuite> element of XML
3154 static const char* const kReservedTestSuiteAttributes
[] = {
3155 "disabled", "errors", "failures", "name", "tests", "time"};
3157 // The list of reserved attributes used in the <testcase> element of XML output.
3158 static const char* const kReservedTestCaseAttributes
[] = {
3159 "classname", "name", "status", "time", "type_param", "value_param"};
3161 template <int kSize
>
3162 std::vector
<std::string
> ArrayAsVector(const char* const (&array
)[kSize
]) {
3163 return std::vector
<std::string
>(array
, array
+ kSize
);
3166 static std::vector
<std::string
> GetReservedAttributesForElement(
3167 const std::string
& xml_element
) {
3168 if (xml_element
== "testsuites") {
3169 return ArrayAsVector(kReservedTestSuitesAttributes
);
3170 } else if (xml_element
== "testsuite") {
3171 return ArrayAsVector(kReservedTestSuiteAttributes
);
3172 } else if (xml_element
== "testcase") {
3173 return ArrayAsVector(kReservedTestCaseAttributes
);
3175 GTEST_CHECK_(false) << "Unrecognized xml_element provided: " << xml_element
;
3177 // This code is unreachable but some compilers may not realizes that.
3178 return std::vector
<std::string
>();
3181 static std::string
FormatWordList(const std::vector
<std::string
>& words
) {
3183 for (size_t i
= 0; i
< words
.size(); ++i
) {
3184 if (i
> 0 && words
.size() > 2) {
3187 if (i
== words
.size() - 1) {
3188 word_list
<< "and ";
3190 word_list
<< "'" << words
[i
] << "'";
3192 return word_list
.GetString();
3195 bool ValidateTestPropertyName(const std::string
& property_name
,
3196 const std::vector
<std::string
>& reserved_names
) {
3197 if (std::find(reserved_names
.begin(), reserved_names
.end(), property_name
) !=
3198 reserved_names
.end()) {
3199 ADD_FAILURE() << "Reserved key used in RecordProperty(): " << property_name
3200 << " (" << FormatWordList(reserved_names
)
3201 << " are reserved by " << GTEST_NAME_
<< ")";
3207 // Adds a failure if the key is a reserved attribute of the element named
3208 // xml_element. Returns true if the property is valid.
3209 bool TestResult::ValidateTestProperty(const std::string
& xml_element
,
3210 const TestProperty
& test_property
) {
3211 return ValidateTestPropertyName(test_property
.key(),
3212 GetReservedAttributesForElement(xml_element
));
3215 // Clears the object.
3216 void TestResult::Clear() {
3217 test_part_results_
.clear();
3218 test_properties_
.clear();
3219 death_test_count_
= 0;
3223 // Returns true iff the test failed.
3224 bool TestResult::Failed() const {
3225 for (int i
= 0; i
< total_part_count(); ++i
) {
3226 if (GetTestPartResult(i
).failed()) return true;
3231 // Returns true iff the test part fatally failed.
3232 static bool TestPartFatallyFailed(const TestPartResult
& result
) {
3233 return result
.fatally_failed();
3236 // Returns true iff the test fatally failed.
3237 bool TestResult::HasFatalFailure() const {
3238 return CountIf(test_part_results_
, TestPartFatallyFailed
) > 0;
3241 // Returns true iff the test part non-fatally failed.
3242 static bool TestPartNonfatallyFailed(const TestPartResult
& result
) {
3243 return result
.nonfatally_failed();
3246 // Returns true iff the test has a non-fatal failure.
3247 bool TestResult::HasNonfatalFailure() const {
3248 return CountIf(test_part_results_
, TestPartNonfatallyFailed
) > 0;
3251 // Gets the number of all test parts. This is the sum of the number
3252 // of successful test parts and the number of failed test parts.
3253 int TestResult::total_part_count() const {
3254 return static_cast<int>(test_part_results_
.size());
3257 // Returns the number of the test properties.
3258 int TestResult::test_property_count() const {
3259 return static_cast<int>(test_properties_
.size());
3264 // Creates a Test object.
3266 // The c'tor saves the values of all Google Test flags.
3267 Test::Test() : gtest_flag_saver_(new internal::GTestFlagSaver
) {}
3269 // The d'tor restores the values of all Google Test flags.
3270 Test::~Test() { delete gtest_flag_saver_
; }
3272 // Sets up the test fixture.
3274 // A sub-class may override this.
3275 void Test::SetUp() {}
3277 // Tears down the test fixture.
3279 // A sub-class may override this.
3280 void Test::TearDown() {}
3282 // Allows user supplied key value pairs to be recorded for later output.
3283 void Test::RecordProperty(const std::string
& key
, const std::string
& value
) {
3284 UnitTest::GetInstance()->RecordProperty(key
, value
);
3287 // Allows user supplied key value pairs to be recorded for later output.
3288 void Test::RecordProperty(const std::string
& key
, int value
) {
3289 Message value_message
;
3290 value_message
<< value
;
3291 RecordProperty(key
, value_message
.GetString().c_str());
3294 namespace internal
{
3296 void ReportFailureInUnknownLocation(TestPartResult::Type result_type
,
3297 const std::string
& message
) {
3298 // This function is a friend of UnitTest and as such has access to
3299 // AddTestPartResult.
3300 UnitTest::GetInstance()->AddTestPartResult(
3302 NULL
, // No info about the source file where the exception occurred.
3303 -1, // We have no info on which line caused the exception.
3305 ""); // No stack trace, either.
3308 } // namespace internal
3310 // Google Test requires all tests in the same test case to use the same test
3311 // fixture class. This function checks if the current test has the
3312 // same fixture class as the first test in the current test case. If
3313 // yes, it returns true; otherwise it generates a Google Test failure and
3315 bool Test::HasSameFixtureClass() {
3316 internal::UnitTestImpl
* const impl
= internal::GetUnitTestImpl();
3317 const TestCase
* const test_case
= impl
->current_test_case();
3319 // Info about the first test in the current test case.
3320 const TestInfo
* const first_test_info
= test_case
->test_info_list()[0];
3321 const internal::TypeId first_fixture_id
= first_test_info
->fixture_class_id_
;
3322 const char* const first_test_name
= first_test_info
->name();
3324 // Info about the current test.
3325 const TestInfo
* const this_test_info
= impl
->current_test_info();
3326 const internal::TypeId this_fixture_id
= this_test_info
->fixture_class_id_
;
3327 const char* const this_test_name
= this_test_info
->name();
3329 if (this_fixture_id
!= first_fixture_id
) {
3330 // Is the first test defined using TEST?
3331 const bool first_is_TEST
= first_fixture_id
== internal::GetTestTypeId();
3332 // Is this test defined using TEST?
3333 const bool this_is_TEST
= this_fixture_id
== internal::GetTestTypeId();
3335 if (first_is_TEST
|| this_is_TEST
) {
3336 // The user mixed TEST and TEST_F in this test case - we'll tell
3337 // him/her how to fix it.
3339 // Gets the name of the TEST and the name of the TEST_F. Note
3340 // that first_is_TEST and this_is_TEST cannot both be true, as
3341 // the fixture IDs are different for the two tests.
3342 const char* const TEST_name
=
3343 first_is_TEST
? first_test_name
: this_test_name
;
3344 const char* const TEST_F_name
=
3345 first_is_TEST
? this_test_name
: first_test_name
;
3348 << "All tests in the same test case must use the same test fixture\n"
3349 << "class, so mixing TEST_F and TEST in the same test case is\n"
3350 << "illegal. In test case " << this_test_info
->test_case_name()
3352 << "test " << TEST_F_name
<< " is defined using TEST_F but\n"
3353 << "test " << TEST_name
<< " is defined using TEST. You probably\n"
3354 << "want to change the TEST to TEST_F or move it to another test\n"
3357 // The user defined two fixture classes with the same name in
3358 // two namespaces - we'll tell him/her how to fix it.
3360 << "All tests in the same test case must use the same test fixture\n"
3361 << "class. However, in test case "
3362 << this_test_info
->test_case_name() << ",\n"
3363 << "you defined test " << first_test_name
<< " and test "
3364 << this_test_name
<< "\n"
3365 << "using two different test fixture classes. This can happen if\n"
3366 << "the two classes are from different namespaces or translation\n"
3367 << "units and have the same name. You should probably rename one\n"
3368 << "of the classes to put the tests into different test cases.";
3378 // Adds an "exception thrown" fatal failure to the current test. This
3379 // function returns its result via an output parameter pointer because VC++
3380 // prohibits creation of objects with destructors on stack in functions
3381 // using __try (see error C2712).
3382 static std::string
* FormatSehExceptionMessage(DWORD exception_code
,
3383 const char* location
) {
3385 message
<< "SEH exception with code 0x" << std::setbase(16) << exception_code
3386 << std::setbase(10) << " thrown in " << location
<< ".";
3388 return new std::string(message
.GetString());
3391 #endif // GTEST_HAS_SEH
3393 namespace internal
{
3395 #if GTEST_HAS_EXCEPTIONS
3397 // Adds an "exception thrown" fatal failure to the current test.
3398 static std::string
FormatCxxExceptionMessage(const char* description
,
3399 const char* location
) {
3401 if (description
!= NULL
) {
3402 message
<< "C++ exception with description \"" << description
<< "\"";
3404 message
<< "Unknown C++ exception";
3406 message
<< " thrown in " << location
<< ".";
3408 return message
.GetString();
3411 static std::string
PrintTestPartResultToString(
3412 const TestPartResult
& test_part_result
);
3414 GoogleTestFailureException::GoogleTestFailureException(
3415 const TestPartResult
& failure
)
3416 : ::std::runtime_error(PrintTestPartResultToString(failure
).c_str()) {}
3418 #endif // GTEST_HAS_EXCEPTIONS
3420 // We put these helper functions in the internal namespace as IBM's xlC
3421 // compiler rejects the code if they were declared static.
3423 // Runs the given method and handles SEH exceptions it throws, when
3424 // SEH is supported; returns the 0-value for type Result in case of an
3425 // SEH exception. (Microsoft compilers cannot handle SEH and C++
3426 // exceptions in the same function. Therefore, we provide a separate
3427 // wrapper function for handling SEH exceptions.)
3428 template <class T
, typename Result
>
3429 Result
HandleSehExceptionsInMethodIfSupported(T
* object
, Result (T::*method
)(),
3430 const char* location
) {
3433 return (object
->*method
)();
3434 } __except (internal::UnitTestOptions::GTestShouldProcessSEH( // NOLINT
3435 GetExceptionCode())) {
3436 // We create the exception message on the heap because VC++ prohibits
3437 // creation of objects with destructors on stack in functions using __try
3438 // (see error C2712).
3439 std::string
* exception_message
=
3440 FormatSehExceptionMessage(GetExceptionCode(), location
);
3441 internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure
,
3442 *exception_message
);
3443 delete exception_message
;
3444 return static_cast<Result
>(0);
3448 return (object
->*method
)();
3449 #endif // GTEST_HAS_SEH
3452 // Runs the given method and catches and reports C++ and/or SEH-style
3453 // exceptions, if they are supported; returns the 0-value for type
3454 // Result in case of an SEH exception.
3455 template <class T
, typename Result
>
3456 Result
HandleExceptionsInMethodIfSupported(T
* object
, Result (T::*method
)(),
3457 const char* location
) {
3458 // NOTE: The user code can affect the way in which Google Test handles
3459 // exceptions by setting GTEST_FLAG(catch_exceptions), but only before
3460 // RUN_ALL_TESTS() starts. It is technically possible to check the flag
3461 // after the exception is caught and either report or re-throw the
3462 // exception based on the flag's value:
3465 // // Perform the test method.
3467 // if (GTEST_FLAG(catch_exceptions))
3468 // // Report the exception as failure.
3470 // throw; // Re-throws the original exception.
3473 // However, the purpose of this flag is to allow the program to drop into
3474 // the debugger when the exception is thrown. On most platforms, once the
3475 // control enters the catch block, the exception origin information is
3476 // lost and the debugger will stop the program at the point of the
3477 // re-throw in this function -- instead of at the point of the original
3478 // throw statement in the code under test. For this reason, we perform
3479 // the check early, sacrificing the ability to affect Google Test's
3480 // exception handling in the method where the exception is thrown.
3481 if (internal::GetUnitTestImpl()->catch_exceptions()) {
3482 #if GTEST_HAS_EXCEPTIONS
3484 return HandleSehExceptionsInMethodIfSupported(object
, method
, location
);
3485 } catch (const internal::GoogleTestFailureException
&) { // NOLINT
3486 // This exception type can only be thrown by a failed Google
3487 // Test assertion with the intention of letting another testing
3488 // framework catch it. Therefore we just re-throw it.
3490 } catch (const std::exception
& e
) { // NOLINT
3491 internal::ReportFailureInUnknownLocation(
3492 TestPartResult::kFatalFailure
,
3493 FormatCxxExceptionMessage(e
.what(), location
));
3494 } catch (...) { // NOLINT
3495 internal::ReportFailureInUnknownLocation(
3496 TestPartResult::kFatalFailure
,
3497 FormatCxxExceptionMessage(NULL
, location
));
3499 return static_cast<Result
>(0);
3501 return HandleSehExceptionsInMethodIfSupported(object
, method
, location
);
3502 #endif // GTEST_HAS_EXCEPTIONS
3504 return (object
->*method
)();
3508 } // namespace internal
3510 // Runs the test and updates the test result.
3512 if (!HasSameFixtureClass()) return;
3514 internal::UnitTestImpl
* const impl
= internal::GetUnitTestImpl();
3515 impl
->os_stack_trace_getter()->UponLeavingGTest();
3516 internal::HandleExceptionsInMethodIfSupported(this, &Test::SetUp
, "SetUp()");
3517 // We will run the test only if SetUp() was successful.
3518 if (!HasFatalFailure()) {
3519 impl
->os_stack_trace_getter()->UponLeavingGTest();
3520 internal::HandleExceptionsInMethodIfSupported(this, &Test::TestBody
,
3524 // However, we want to clean up as much as possible. Hence we will
3525 // always call TearDown(), even if SetUp() or the test body has
3527 impl
->os_stack_trace_getter()->UponLeavingGTest();
3528 internal::HandleExceptionsInMethodIfSupported(this, &Test::TearDown
,
3532 // Returns true iff the current test has a fatal failure.
3533 bool Test::HasFatalFailure() {
3534 return internal::GetUnitTestImpl()->current_test_result()->HasFatalFailure();
3537 // Returns true iff the current test has a non-fatal failure.
3538 bool Test::HasNonfatalFailure() {
3539 return internal::GetUnitTestImpl()
3540 ->current_test_result()
3541 ->HasNonfatalFailure();
3546 // Constructs a TestInfo object. It assumes ownership of the test factory
3548 TestInfo::TestInfo(const std::string
& a_test_case_name
,
3549 const std::string
& a_name
, const char* a_type_param
,
3550 const char* a_value_param
, internal::TypeId fixture_class_id
,
3551 internal::TestFactoryBase
* factory
)
3552 : test_case_name_(a_test_case_name
),
3554 type_param_(a_type_param
? new std::string(a_type_param
) : NULL
),
3555 value_param_(a_value_param
? new std::string(a_value_param
) : NULL
),
3556 fixture_class_id_(fixture_class_id
),
3558 is_disabled_(false),
3559 matches_filter_(false),
3563 // Destructs a TestInfo object.
3564 TestInfo::~TestInfo() { delete factory_
; }
3566 namespace internal
{
3568 // Creates a new TestInfo object and registers it with Google Test;
3569 // returns the created object.
3573 // test_case_name: name of the test case
3574 // name: name of the test
3575 // type_param: the name of the test's type parameter, or NULL if
3576 // this is not a typed or a type-parameterized test.
3577 // value_param: text representation of the test's value parameter,
3578 // or NULL if this is not a value-parameterized test.
3579 // fixture_class_id: ID of the test fixture class
3580 // set_up_tc: pointer to the function that sets up the test case
3581 // tear_down_tc: pointer to the function that tears down the test case
3582 // factory: pointer to the factory that creates a test object.
3583 // The newly created TestInfo instance will assume
3584 // ownership of the factory object.
3585 TestInfo
* MakeAndRegisterTestInfo(const char* test_case_name
, const char* name
,
3586 const char* type_param
,
3587 const char* value_param
,
3588 TypeId fixture_class_id
,
3589 SetUpTestCaseFunc set_up_tc
,
3590 TearDownTestCaseFunc tear_down_tc
,
3591 TestFactoryBase
* factory
) {
3592 TestInfo
* const test_info
= new TestInfo(
3593 test_case_name
, name
, type_param
, value_param
, fixture_class_id
, factory
);
3594 GetUnitTestImpl()->AddTestInfo(set_up_tc
, tear_down_tc
, test_info
);
3598 #if GTEST_HAS_PARAM_TEST
3599 void ReportInvalidTestCaseType(const char* test_case_name
, const char* file
,
3603 << "Attempted redefinition of test case " << test_case_name
<< ".\n"
3604 << "All tests in the same test case must use the same test fixture\n"
3605 << "class. However, in test case " << test_case_name
<< ", you tried\n"
3606 << "to define a test using a fixture class different from the one\n"
3607 << "used earlier. This can happen if the two fixture classes are\n"
3608 << "from different namespaces and have the same name. You should\n"
3609 << "probably rename one of the classes to put the tests into different\n"
3612 fprintf(stderr
, "%s %s", FormatFileLocation(file
, line
).c_str(),
3613 errors
.GetString().c_str());
3615 #endif // GTEST_HAS_PARAM_TEST
3617 } // namespace internal
3621 // A predicate that checks the test name of a TestInfo against a known
3624 // This is used for implementation of the TestCase class only. We put
3625 // it in the anonymous namespace to prevent polluting the outer
3628 // TestNameIs is copyable.
3633 // TestNameIs has NO default constructor.
3634 explicit TestNameIs(const char* name
) : name_(name
) {}
3636 // Returns true iff the test name of test_info matches name_.
3637 bool operator()(const TestInfo
* test_info
) const {
3638 return test_info
&& test_info
->name() == name_
;
3647 namespace internal
{
3649 // This method expands all parameterized tests registered with macros TEST_P
3650 // and INSTANTIATE_TEST_CASE_P into regular tests and registers those.
3651 // This will be done just once during the program runtime.
3652 void UnitTestImpl::RegisterParameterizedTests() {
3653 #if GTEST_HAS_PARAM_TEST
3654 if (!parameterized_tests_registered_
) {
3655 parameterized_test_registry_
.RegisterTests();
3656 parameterized_tests_registered_
= true;
3661 } // namespace internal
3663 // Creates the test object, runs it, records its result, and then
3665 void TestInfo::Run() {
3666 if (!should_run_
) return;
3668 // Tells UnitTest where to store test result.
3669 internal::UnitTestImpl
* const impl
= internal::GetUnitTestImpl();
3670 impl
->set_current_test_info(this);
3672 TestEventListener
* repeater
= UnitTest::GetInstance()->listeners().repeater();
3674 // Notifies the unit test event listeners that a test is about to start.
3675 repeater
->OnTestStart(*this);
3677 const TimeInMillis start
= internal::GetTimeInMillis();
3679 impl
->os_stack_trace_getter()->UponLeavingGTest();
3681 // Creates the test object.
3682 Test
* const test
= internal::HandleExceptionsInMethodIfSupported(
3683 factory_
, &internal::TestFactoryBase::CreateTest
,
3684 "the test fixture's constructor");
3686 // Runs the test only if the test object was created and its
3687 // constructor didn't generate a fatal failure.
3688 if ((test
!= NULL
) && !Test::HasFatalFailure()) {
3689 // This doesn't throw as all user code that can throw are wrapped into
3690 // exception handling code.
3694 // Deletes the test object.
3695 impl
->os_stack_trace_getter()->UponLeavingGTest();
3696 internal::HandleExceptionsInMethodIfSupported(
3697 test
, &Test::DeleteSelf_
, "the test fixture's destructor");
3699 result_
.set_elapsed_time(internal::GetTimeInMillis() - start
);
3701 // Notifies the unit test event listener that a test has just finished.
3702 repeater
->OnTestEnd(*this);
3704 // Tells UnitTest to stop associating assertion results to this
3706 impl
->set_current_test_info(NULL
);
3711 // Gets the number of successful tests in this test case.
3712 int TestCase::successful_test_count() const {
3713 return CountIf(test_info_list_
, TestPassed
);
3716 // Gets the number of failed tests in this test case.
3717 int TestCase::failed_test_count() const {
3718 return CountIf(test_info_list_
, TestFailed
);
3721 // Gets the number of disabled tests that will be reported in the XML report.
3722 int TestCase::reportable_disabled_test_count() const {
3723 return CountIf(test_info_list_
, TestReportableDisabled
);
3726 // Gets the number of disabled tests in this test case.
3727 int TestCase::disabled_test_count() const {
3728 return CountIf(test_info_list_
, TestDisabled
);
3731 // Gets the number of tests to be printed in the XML report.
3732 int TestCase::reportable_test_count() const {
3733 return CountIf(test_info_list_
, TestReportable
);
3736 // Get the number of tests in this test case that should run.
3737 int TestCase::test_to_run_count() const {
3738 return CountIf(test_info_list_
, ShouldRunTest
);
3741 // Gets the number of all tests.
3742 int TestCase::total_test_count() const {
3743 return static_cast<int>(test_info_list_
.size());
3746 // Creates a TestCase with the given name.
3750 // name: name of the test case
3751 // a_type_param: the name of the test case's type parameter, or NULL if
3752 // this is not a typed or a type-parameterized test case.
3753 // set_up_tc: pointer to the function that sets up the test case
3754 // tear_down_tc: pointer to the function that tears down the test case
3755 TestCase::TestCase(const char* a_name
, const char* a_type_param
,
3756 Test::SetUpTestCaseFunc set_up_tc
,
3757 Test::TearDownTestCaseFunc tear_down_tc
)
3759 type_param_(a_type_param
? new std::string(a_type_param
) : NULL
),
3760 set_up_tc_(set_up_tc
),
3761 tear_down_tc_(tear_down_tc
),
3765 // Destructor of TestCase.
3766 TestCase::~TestCase() {
3767 // Deletes every Test in the collection.
3768 ForEach(test_info_list_
, internal::Delete
<TestInfo
>);
3771 // Returns the i-th test among all the tests. i can range from 0 to
3772 // total_test_count() - 1. If i is not in that range, returns NULL.
3773 const TestInfo
* TestCase::GetTestInfo(int i
) const {
3774 const int index
= GetElementOr(test_indices_
, i
, -1);
3775 return index
< 0 ? NULL
: test_info_list_
[index
];
3778 // Returns the i-th test among all the tests. i can range from 0 to
3779 // total_test_count() - 1. If i is not in that range, returns NULL.
3780 TestInfo
* TestCase::GetMutableTestInfo(int i
) {
3781 const int index
= GetElementOr(test_indices_
, i
, -1);
3782 return index
< 0 ? NULL
: test_info_list_
[index
];
3785 // Adds a test to this test case. Will delete the test upon
3786 // destruction of the TestCase object.
3787 void TestCase::AddTestInfo(TestInfo
* test_info
) {
3788 test_info_list_
.push_back(test_info
);
3789 test_indices_
.push_back(static_cast<int>(test_indices_
.size()));
3792 // Runs every test in this TestCase.
3793 void TestCase::Run() {
3794 if (!should_run_
) return;
3796 internal::UnitTestImpl
* const impl
= internal::GetUnitTestImpl();
3797 impl
->set_current_test_case(this);
3799 TestEventListener
* repeater
= UnitTest::GetInstance()->listeners().repeater();
3801 repeater
->OnTestCaseStart(*this);
3802 impl
->os_stack_trace_getter()->UponLeavingGTest();
3803 internal::HandleExceptionsInMethodIfSupported(
3804 this, &TestCase::RunSetUpTestCase
, "SetUpTestCase()");
3806 const internal::TimeInMillis start
= internal::GetTimeInMillis();
3807 for (int i
= 0; i
< total_test_count(); i
++) {
3808 GetMutableTestInfo(i
)->Run();
3810 elapsed_time_
= internal::GetTimeInMillis() - start
;
3812 impl
->os_stack_trace_getter()->UponLeavingGTest();
3813 internal::HandleExceptionsInMethodIfSupported(
3814 this, &TestCase::RunTearDownTestCase
, "TearDownTestCase()");
3816 repeater
->OnTestCaseEnd(*this);
3817 impl
->set_current_test_case(NULL
);
3820 // Clears the results of all tests in this test case.
3821 void TestCase::ClearResult() {
3822 ad_hoc_test_result_
.Clear();
3823 ForEach(test_info_list_
, TestInfo::ClearTestResult
);
3826 // Shuffles the tests in this test case.
3827 void TestCase::ShuffleTests(internal::Random
* random
) {
3828 Shuffle(random
, &test_indices_
);
3831 // Restores the test order to before the first shuffle.
3832 void TestCase::UnshuffleTests() {
3833 for (size_t i
= 0; i
< test_indices_
.size(); i
++) {
3834 test_indices_
[i
] = static_cast<int>(i
);
3838 // Formats a countable noun. Depending on its quantity, either the
3839 // singular form or the plural form is used. e.g.
3841 // FormatCountableNoun(1, "formula", "formuli") returns "1 formula".
3842 // FormatCountableNoun(5, "book", "books") returns "5 books".
3843 static std::string
FormatCountableNoun(int count
, const char* singular_form
,
3844 const char* plural_form
) {
3845 return internal::StreamableToString(count
) + " " +
3846 (count
== 1 ? singular_form
: plural_form
);
3849 // Formats the count of tests.
3850 static std::string
FormatTestCount(int test_count
) {
3851 return FormatCountableNoun(test_count
, "test", "tests");
3854 // Formats the count of test cases.
3855 static std::string
FormatTestCaseCount(int test_case_count
) {
3856 return FormatCountableNoun(test_case_count
, "test case", "test cases");
3859 // Converts a TestPartResult::Type enum to human-friendly string
3860 // representation. Both kNonFatalFailure and kFatalFailure are translated
3861 // to "Failure", as the user usually doesn't care about the difference
3862 // between the two when viewing the test result.
3863 static const char* TestPartResultTypeToString(TestPartResult::Type type
) {
3865 case TestPartResult::kSuccess
:
3868 case TestPartResult::kNonFatalFailure
:
3869 case TestPartResult::kFatalFailure
:
3876 return "Unknown result type";
3880 namespace internal
{
3882 // Prints a TestPartResult to an std::string.
3883 static std::string
PrintTestPartResultToString(
3884 const TestPartResult
& test_part_result
) {
3885 return (Message() << internal::FormatFileLocation(
3886 test_part_result
.file_name(),
3887 test_part_result
.line_number())
3889 << TestPartResultTypeToString(test_part_result
.type())
3890 << test_part_result
.message())
3894 // Prints a TestPartResult.
3895 static void PrintTestPartResult(const TestPartResult
& test_part_result
) {
3896 const std::string
& result
= PrintTestPartResultToString(test_part_result
);
3897 printf("%s\n", result
.c_str());
3899 // If the test program runs in Visual Studio or a debugger, the
3900 // following statements add the test part result message to the Output
3901 // window such that the user can double-click on it to jump to the
3902 // corresponding source code location; otherwise they do nothing.
3903 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
3904 // We don't call OutputDebugString*() on Windows Mobile, as printing
3905 // to stdout is done by OutputDebugString() there already - we don't
3906 // want the same message printed twice.
3907 ::OutputDebugStringA(result
.c_str());
3908 ::OutputDebugStringA("\n");
3912 // class PrettyUnitTestResultPrinter
3914 enum GTestColor
{ COLOR_DEFAULT
, COLOR_RED
, COLOR_GREEN
, COLOR_YELLOW
};
3916 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
3918 // Returns the character attribute for the given color.
3919 WORD
GetColorAttribute(GTestColor color
) {
3922 return FOREGROUND_RED
;
3924 return FOREGROUND_GREEN
;
3926 return FOREGROUND_RED
| FOREGROUND_GREEN
;
3934 // Returns the ANSI color code for the given color. COLOR_DEFAULT is
3935 // an invalid input.
3936 const char* GetAnsiColorCode(GTestColor color
) {
3949 #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
3951 // Returns true iff Google Test should use colors in the output.
3952 bool ShouldUseColor(bool stdout_is_tty
) {
3953 const char* const gtest_color
= GTEST_FLAG(color
).c_str();
3955 if (String::CaseInsensitiveCStringEquals(gtest_color
, "auto")) {
3956 #if GTEST_OS_WINDOWS
3957 // On Windows the TERM variable is usually not set, but the
3958 // console there does support colors.
3959 return stdout_is_tty
;
3961 // On non-Windows platforms, we rely on the TERM variable.
3962 const char* const term
= posix::GetEnv("TERM");
3963 const bool term_supports_color
=
3964 String::CStringEquals(term
, "xterm") ||
3965 String::CStringEquals(term
, "xterm-color") ||
3966 String::CStringEquals(term
, "xterm-256color") ||
3967 String::CStringEquals(term
, "screen") ||
3968 String::CStringEquals(term
, "screen-256color") ||
3969 String::CStringEquals(term
, "linux") ||
3970 String::CStringEquals(term
, "cygwin");
3971 return stdout_is_tty
&& term_supports_color
;
3972 #endif // GTEST_OS_WINDOWS
3975 return String::CaseInsensitiveCStringEquals(gtest_color
, "yes") ||
3976 String::CaseInsensitiveCStringEquals(gtest_color
, "true") ||
3977 String::CaseInsensitiveCStringEquals(gtest_color
, "t") ||
3978 String::CStringEquals(gtest_color
, "1");
3979 // We take "yes", "true", "t", and "1" as meaning "yes". If the
3980 // value is neither one of these nor "auto", we treat it as "no" to
3984 // Helpers for printing colored strings to stdout. Note that on Windows, we
3985 // cannot simply emit special characters and have the terminal change colors.
3986 // This routine must actually emit the characters rather than return a string
3987 // that would be colored when printed, as can be done on Linux.
3988 void ColoredPrintf(GTestColor color
, const char* fmt
, ...) {
3990 va_start(args
, fmt
);
3992 #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS || GTEST_OS_IOS
3993 const bool use_color
= false;
3995 static const bool in_color_mode
=
3996 ShouldUseColor(posix::IsATTY(posix::FileNo(stdout
)) != 0);
3997 const bool use_color
= in_color_mode
&& (color
!= COLOR_DEFAULT
);
3998 #endif // GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS
3999 // The '!= 0' comparison is necessary to satisfy MSVC 7.1.
4007 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
4008 const HANDLE stdout_handle
= GetStdHandle(STD_OUTPUT_HANDLE
);
4010 // Gets the current text color.
4011 CONSOLE_SCREEN_BUFFER_INFO buffer_info
;
4012 GetConsoleScreenBufferInfo(stdout_handle
, &buffer_info
);
4013 const WORD old_color_attrs
= buffer_info
.wAttributes
;
4015 // We need to flush the stream buffers into the console before each
4016 // SetConsoleTextAttribute call lest it affect the text that is already
4017 // printed but has not yet reached the console.
4019 SetConsoleTextAttribute(stdout_handle
,
4020 GetColorAttribute(color
) | FOREGROUND_INTENSITY
);
4024 // Restores the text color.
4025 SetConsoleTextAttribute(stdout_handle
, old_color_attrs
);
4027 printf("\033[0;3%sm", GetAnsiColorCode(color
));
4029 printf("\033[m"); // Resets the terminal to default.
4030 #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
4034 // Text printed in Google Test's text output and --gunit_list_tests
4035 // output to label the type parameter and value parameter for a test.
4036 static const char kTypeParamLabel
[] = "TypeParam";
4037 static const char kValueParamLabel
[] = "GetParam()";
4039 void PrintFullTestCommentIfPresent(const TestInfo
& test_info
) {
4040 const char* const type_param
= test_info
.type_param();
4041 const char* const value_param
= test_info
.value_param();
4043 if (type_param
!= NULL
|| value_param
!= NULL
) {
4045 if (type_param
!= NULL
) {
4046 printf("%s = %s", kTypeParamLabel
, type_param
);
4047 if (value_param
!= NULL
) printf(" and ");
4049 if (value_param
!= NULL
) {
4050 printf("%s = %s", kValueParamLabel
, value_param
);
4055 // This class implements the TestEventListener interface.
4057 // Class PrettyUnitTestResultPrinter is copyable.
4058 class PrettyUnitTestResultPrinter
: public TestEventListener
{
4060 PrettyUnitTestResultPrinter() {}
4061 static void PrintTestName(const char* test_case
, const char* test
) {
4062 printf("%s.%s", test_case
, test
);
4065 // The following methods override what's in the TestEventListener class.
4066 virtual void OnTestProgramStart(const UnitTest
& /*unit_test*/) {}
4067 virtual void OnTestIterationStart(const UnitTest
& unit_test
, int iteration
);
4068 virtual void OnEnvironmentsSetUpStart(const UnitTest
& unit_test
);
4069 virtual void OnEnvironmentsSetUpEnd(const UnitTest
& /*unit_test*/) {}
4070 virtual void OnTestCaseStart(const TestCase
& test_case
);
4071 virtual void OnTestStart(const TestInfo
& test_info
);
4072 virtual void OnTestPartResult(const TestPartResult
& result
);
4073 virtual void OnTestEnd(const TestInfo
& test_info
);
4074 virtual void OnTestCaseEnd(const TestCase
& test_case
);
4075 virtual void OnEnvironmentsTearDownStart(const UnitTest
& unit_test
);
4076 virtual void OnEnvironmentsTearDownEnd(const UnitTest
& /*unit_test*/) {}
4077 virtual void OnTestIterationEnd(const UnitTest
& unit_test
, int iteration
);
4078 virtual void OnTestProgramEnd(const UnitTest
& /*unit_test*/) {}
4081 static void PrintFailedTests(const UnitTest
& unit_test
);
4084 // Fired before each iteration of tests starts.
4085 void PrettyUnitTestResultPrinter::OnTestIterationStart(
4086 const UnitTest
& unit_test
, int iteration
) {
4087 if (GTEST_FLAG(repeat
) != 1)
4088 printf("\nRepeating all tests (iteration %d) . . .\n\n", iteration
+ 1);
4090 const char* const filter
= GTEST_FLAG(filter
).c_str();
4092 // Prints the filter if it's not *. This reminds the user that some
4093 // tests may be skipped.
4094 if (!String::CStringEquals(filter
, kUniversalFilter
)) {
4095 ColoredPrintf(COLOR_YELLOW
, "Note: %s filter = %s\n", GTEST_NAME_
, filter
);
4098 if (internal::ShouldShard(kTestTotalShards
, kTestShardIndex
, false)) {
4099 const Int32 shard_index
= Int32FromEnvOrDie(kTestShardIndex
, -1);
4100 ColoredPrintf(COLOR_YELLOW
, "Note: This is test shard %d of %s.\n",
4101 static_cast<int>(shard_index
) + 1,
4102 internal::posix::GetEnv(kTestTotalShards
));
4105 if (GTEST_FLAG(shuffle
)) {
4106 ColoredPrintf(COLOR_YELLOW
,
4107 "Note: Randomizing tests' orders with a seed of %d .\n",
4108 unit_test
.random_seed());
4111 ColoredPrintf(COLOR_GREEN
, "[==========] ");
4112 printf("Running %s from %s.\n",
4113 FormatTestCount(unit_test
.test_to_run_count()).c_str(),
4114 FormatTestCaseCount(unit_test
.test_case_to_run_count()).c_str());
4118 void PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart(
4119 const UnitTest
& /*unit_test*/) {
4120 ColoredPrintf(COLOR_GREEN
, "[----------] ");
4121 printf("Global test environment set-up.\n");
4125 void PrettyUnitTestResultPrinter::OnTestCaseStart(const TestCase
& test_case
) {
4126 const std::string counts
=
4127 FormatCountableNoun(test_case
.test_to_run_count(), "test", "tests");
4128 ColoredPrintf(COLOR_GREEN
, "[----------] ");
4129 printf("%s from %s", counts
.c_str(), test_case
.name());
4130 if (test_case
.type_param() == NULL
) {
4133 printf(", where %s = %s\n", kTypeParamLabel
, test_case
.type_param());
4138 void PrettyUnitTestResultPrinter::OnTestStart(const TestInfo
& test_info
) {
4139 ColoredPrintf(COLOR_GREEN
, "[ RUN ] ");
4140 PrintTestName(test_info
.test_case_name(), test_info
.name());
4145 // Called after an assertion failure.
4146 void PrettyUnitTestResultPrinter::OnTestPartResult(
4147 const TestPartResult
& result
) {
4148 // If the test part succeeded, we don't need to do anything.
4149 if (result
.type() == TestPartResult::kSuccess
) return;
4151 // Print failure message from the assertion (e.g. expected this and got that).
4152 PrintTestPartResult(result
);
4156 void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo
& test_info
) {
4157 if (test_info
.result()->Passed()) {
4158 ColoredPrintf(COLOR_GREEN
, "[ OK ] ");
4160 ColoredPrintf(COLOR_RED
, "[ FAILED ] ");
4162 PrintTestName(test_info
.test_case_name(), test_info
.name());
4163 if (test_info
.result()->Failed()) PrintFullTestCommentIfPresent(test_info
);
4165 if (GTEST_FLAG(print_time
)) {
4166 printf(" (%s ms)\n",
4167 internal::StreamableToString(test_info
.result()->elapsed_time())
4175 void PrettyUnitTestResultPrinter::OnTestCaseEnd(const TestCase
& test_case
) {
4176 if (!GTEST_FLAG(print_time
)) return;
4178 const std::string counts
=
4179 FormatCountableNoun(test_case
.test_to_run_count(), "test", "tests");
4180 ColoredPrintf(COLOR_GREEN
, "[----------] ");
4181 printf("%s from %s (%s ms total)\n\n", counts
.c_str(), test_case
.name(),
4182 internal::StreamableToString(test_case
.elapsed_time()).c_str());
4186 void PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart(
4187 const UnitTest
& /*unit_test*/) {
4188 ColoredPrintf(COLOR_GREEN
, "[----------] ");
4189 printf("Global test environment tear-down\n");
4193 // Internal helper for printing the list of failed tests.
4194 void PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest
& unit_test
) {
4195 const int failed_test_count
= unit_test
.failed_test_count();
4196 if (failed_test_count
== 0) {
4200 for (int i
= 0; i
< unit_test
.total_test_case_count(); ++i
) {
4201 const TestCase
& test_case
= *unit_test
.GetTestCase(i
);
4202 if (!test_case
.should_run() || (test_case
.failed_test_count() == 0)) {
4205 for (int j
= 0; j
< test_case
.total_test_count(); ++j
) {
4206 const TestInfo
& test_info
= *test_case
.GetTestInfo(j
);
4207 if (!test_info
.should_run() || test_info
.result()->Passed()) {
4210 ColoredPrintf(COLOR_RED
, "[ FAILED ] ");
4211 printf("%s.%s", test_case
.name(), test_info
.name());
4212 PrintFullTestCommentIfPresent(test_info
);
4218 void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest
& unit_test
,
4219 int /*iteration*/) {
4220 ColoredPrintf(COLOR_GREEN
, "[==========] ");
4221 printf("%s from %s ran.",
4222 FormatTestCount(unit_test
.test_to_run_count()).c_str(),
4223 FormatTestCaseCount(unit_test
.test_case_to_run_count()).c_str());
4224 if (GTEST_FLAG(print_time
)) {
4225 printf(" (%s ms total)",
4226 internal::StreamableToString(unit_test
.elapsed_time()).c_str());
4229 ColoredPrintf(COLOR_GREEN
, "[ PASSED ] ");
4230 printf("%s.\n", FormatTestCount(unit_test
.successful_test_count()).c_str());
4232 int num_failures
= unit_test
.failed_test_count();
4233 if (!unit_test
.Passed()) {
4234 const int failed_test_count
= unit_test
.failed_test_count();
4235 ColoredPrintf(COLOR_RED
, "[ FAILED ] ");
4236 printf("%s, listed below:\n", FormatTestCount(failed_test_count
).c_str());
4237 PrintFailedTests(unit_test
);
4238 printf("\n%2d FAILED %s\n", num_failures
,
4239 num_failures
== 1 ? "TEST" : "TESTS");
4242 int num_disabled
= unit_test
.reportable_disabled_test_count();
4243 if (num_disabled
&& !GTEST_FLAG(also_run_disabled_tests
)) {
4244 if (!num_failures
) {
4245 printf("\n"); // Add a spacer if no FAILURE banner is displayed.
4247 ColoredPrintf(COLOR_YELLOW
, " YOU HAVE %d DISABLED %s\n\n", num_disabled
,
4248 num_disabled
== 1 ? "TEST" : "TESTS");
4250 // Ensure that Google Test output is printed before, e.g., heapchecker output.
4254 // End PrettyUnitTestResultPrinter
4256 // class TestEventRepeater
4258 // This class forwards events to other event listeners.
4259 class TestEventRepeater
: public TestEventListener
{
4261 TestEventRepeater() : forwarding_enabled_(true) {}
4262 virtual ~TestEventRepeater();
4263 void Append(TestEventListener
* listener
);
4264 TestEventListener
* Release(TestEventListener
* listener
);
4266 // Controls whether events will be forwarded to listeners_. Set to false
4267 // in death test child processes.
4268 bool forwarding_enabled() const { return forwarding_enabled_
; }
4269 void set_forwarding_enabled(bool enable
) { forwarding_enabled_
= enable
; }
4271 virtual void OnTestProgramStart(const UnitTest
& unit_test
);
4272 virtual void OnTestIterationStart(const UnitTest
& unit_test
, int iteration
);
4273 virtual void OnEnvironmentsSetUpStart(const UnitTest
& unit_test
);
4274 virtual void OnEnvironmentsSetUpEnd(const UnitTest
& unit_test
);
4275 virtual void OnTestCaseStart(const TestCase
& test_case
);
4276 virtual void OnTestStart(const TestInfo
& test_info
);
4277 virtual void OnTestPartResult(const TestPartResult
& result
);
4278 virtual void OnTestEnd(const TestInfo
& test_info
);
4279 virtual void OnTestCaseEnd(const TestCase
& test_case
);
4280 virtual void OnEnvironmentsTearDownStart(const UnitTest
& unit_test
);
4281 virtual void OnEnvironmentsTearDownEnd(const UnitTest
& unit_test
);
4282 virtual void OnTestIterationEnd(const UnitTest
& unit_test
, int iteration
);
4283 virtual void OnTestProgramEnd(const UnitTest
& unit_test
);
4286 // Controls whether events will be forwarded to listeners_. Set to false
4287 // in death test child processes.
4288 bool forwarding_enabled_
;
4289 // The list of listeners that receive events.
4290 std::vector
<TestEventListener
*> listeners_
;
4292 GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventRepeater
);
4295 TestEventRepeater::~TestEventRepeater() {
4296 ForEach(listeners_
, Delete
<TestEventListener
>);
4299 void TestEventRepeater::Append(TestEventListener
* listener
) {
4300 listeners_
.push_back(listener
);
4303 // TODO(vladl@google.com): Factor the search functionality into Vector::Find.
4304 TestEventListener
* TestEventRepeater::Release(TestEventListener
* listener
) {
4305 for (size_t i
= 0; i
< listeners_
.size(); ++i
) {
4306 if (listeners_
[i
] == listener
) {
4307 listeners_
.erase(listeners_
.begin() + i
);
4315 // Since most methods are very similar, use macros to reduce boilerplate.
4316 // This defines a member that forwards the call to all listeners.
4317 #define GTEST_REPEATER_METHOD_(Name, Type) \
4318 void TestEventRepeater::Name(const Type& parameter) { \
4319 if (forwarding_enabled_) { \
4320 for (size_t i = 0; i < listeners_.size(); i++) { \
4321 listeners_[i]->Name(parameter); \
4325 // This defines a member that forwards the call to all listeners in reverse
4327 #define GTEST_REVERSE_REPEATER_METHOD_(Name, Type) \
4328 void TestEventRepeater::Name(const Type& parameter) { \
4329 if (forwarding_enabled_) { \
4330 for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) { \
4331 listeners_[i]->Name(parameter); \
4336 GTEST_REPEATER_METHOD_(OnTestProgramStart
, UnitTest
)
4337 GTEST_REPEATER_METHOD_(OnEnvironmentsSetUpStart
, UnitTest
)
4338 GTEST_REPEATER_METHOD_(OnTestCaseStart
, TestCase
)
4339 GTEST_REPEATER_METHOD_(OnTestStart
, TestInfo
)
4340 GTEST_REPEATER_METHOD_(OnTestPartResult
, TestPartResult
)
4341 GTEST_REPEATER_METHOD_(OnEnvironmentsTearDownStart
, UnitTest
)
4342 GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsSetUpEnd
, UnitTest
)
4343 GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsTearDownEnd
, UnitTest
)
4344 GTEST_REVERSE_REPEATER_METHOD_(OnTestEnd
, TestInfo
)
4345 GTEST_REVERSE_REPEATER_METHOD_(OnTestCaseEnd
, TestCase
)
4346 GTEST_REVERSE_REPEATER_METHOD_(OnTestProgramEnd
, UnitTest
)
4348 #undef GTEST_REPEATER_METHOD_
4349 #undef GTEST_REVERSE_REPEATER_METHOD_
4351 void TestEventRepeater::OnTestIterationStart(const UnitTest
& unit_test
,
4353 if (forwarding_enabled_
) {
4354 for (size_t i
= 0; i
< listeners_
.size(); i
++) {
4355 listeners_
[i
]->OnTestIterationStart(unit_test
, iteration
);
4360 void TestEventRepeater::OnTestIterationEnd(const UnitTest
& unit_test
,
4362 if (forwarding_enabled_
) {
4363 for (int i
= static_cast<int>(listeners_
.size()) - 1; i
>= 0; i
--) {
4364 listeners_
[i
]->OnTestIterationEnd(unit_test
, iteration
);
4369 // End TestEventRepeater
4371 // This class generates an XML output file.
4372 class XmlUnitTestResultPrinter
: public EmptyTestEventListener
{
4374 explicit XmlUnitTestResultPrinter(const char* output_file
);
4376 virtual void OnTestIterationEnd(const UnitTest
& unit_test
, int iteration
);
4379 // Is c a whitespace character that is normalized to a space character
4380 // when it appears in an XML attribute value?
4381 static bool IsNormalizableWhitespace(char c
) {
4382 return c
== 0x9 || c
== 0xA || c
== 0xD;
4385 // May c appear in a well-formed XML document?
4386 static bool IsValidXmlCharacter(char c
) {
4387 return IsNormalizableWhitespace(c
) || c
>= 0x20;
4390 // Returns an XML-escaped copy of the input string str. If
4391 // is_attribute is true, the text is meant to appear as an attribute
4392 // value, and normalizable whitespace is preserved by replacing it
4393 // with character references.
4394 static std::string
EscapeXml(const std::string
& str
, bool is_attribute
);
4396 // Returns the given string with all characters invalid in XML removed.
4397 static std::string
RemoveInvalidXmlCharacters(const std::string
& str
);
4399 // Convenience wrapper around EscapeXml when str is an attribute value.
4400 static std::string
EscapeXmlAttribute(const std::string
& str
) {
4401 return EscapeXml(str
, true);
4404 // Convenience wrapper around EscapeXml when str is not an attribute value.
4405 static std::string
EscapeXmlText(const char* str
) {
4406 return EscapeXml(str
, false);
4409 // Verifies that the given attribute belongs to the given element and
4410 // streams the attribute as XML.
4411 static void OutputXmlAttribute(std::ostream
* stream
,
4412 const std::string
& element_name
,
4413 const std::string
& name
,
4414 const std::string
& value
);
4416 // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
4417 static void OutputXmlCDataSection(::std::ostream
* stream
, const char* data
);
4419 // Streams an XML representation of a TestInfo object.
4420 static void OutputXmlTestInfo(::std::ostream
* stream
,
4421 const char* test_case_name
,
4422 const TestInfo
& test_info
);
4424 // Prints an XML representation of a TestCase object
4425 static void PrintXmlTestCase(::std::ostream
* stream
,
4426 const TestCase
& test_case
);
4428 // Prints an XML summary of unit_test to output stream out.
4429 static void PrintXmlUnitTest(::std::ostream
* stream
,
4430 const UnitTest
& unit_test
);
4432 // Produces a string representing the test properties in a result as space
4433 // delimited XML attributes based on the property key="value" pairs.
4434 // When the std::string is not empty, it includes a space at the beginning,
4435 // to delimit this attribute from prior attributes.
4436 static std::string
TestPropertiesAsXmlAttributes(const TestResult
& result
);
4439 const std::string output_file_
;
4441 GTEST_DISALLOW_COPY_AND_ASSIGN_(XmlUnitTestResultPrinter
);
4444 // Creates a new XmlUnitTestResultPrinter.
4445 XmlUnitTestResultPrinter::XmlUnitTestResultPrinter(const char* output_file
)
4446 : output_file_(output_file
) {
4447 if (output_file_
.c_str() == NULL
|| output_file_
.empty()) {
4448 fprintf(stderr
, "XML output file may not be null\n");
4454 // Called after the unit test ends.
4455 void XmlUnitTestResultPrinter::OnTestIterationEnd(const UnitTest
& unit_test
,
4456 int /*iteration*/) {
4457 FILE* xmlout
= NULL
;
4458 FilePath
output_file(output_file_
);
4459 FilePath
output_dir(output_file
.RemoveFileName());
4461 if (output_dir
.CreateDirectoriesRecursively()) {
4462 xmlout
= posix::FOpen(output_file_
.c_str(), "w");
4464 if (xmlout
== NULL
) {
4465 // TODO(wan): report the reason of the failure.
4467 // We don't do it for now as:
4469 // 1. There is no urgent need for it.
4470 // 2. It's a bit involved to make the errno variable thread-safe on
4471 // all three operating systems (Linux, Windows, and Mac OS).
4472 // 3. To interpret the meaning of errno in a thread-safe way,
4473 // we need the strerror_r() function, which is not available on
4475 fprintf(stderr
, "Unable to open file \"%s\"\n", output_file_
.c_str());
4479 std::stringstream stream
;
4480 PrintXmlUnitTest(&stream
, unit_test
);
4481 fprintf(xmlout
, "%s", StringStreamToString(&stream
).c_str());
4485 // Returns an XML-escaped copy of the input string str. If is_attribute
4486 // is true, the text is meant to appear as an attribute value, and
4487 // normalizable whitespace is preserved by replacing it with character
4490 // Invalid XML characters in str, if any, are stripped from the output.
4491 // It is expected that most, if not all, of the text processed by this
4492 // module will consist of ordinary English text.
4493 // If this module is ever modified to produce version 1.1 XML output,
4494 // most invalid characters can be retained using character references.
4495 // TODO(wan): It might be nice to have a minimally invasive, human-readable
4496 // escaping scheme for invalid characters, rather than dropping them.
4497 std::string
XmlUnitTestResultPrinter::EscapeXml(const std::string
& str
,
4498 bool is_attribute
) {
4501 for (size_t i
= 0; i
< str
.size(); ++i
) {
4502 const char ch
= str
[i
];
4526 if (IsValidXmlCharacter(ch
)) {
4527 if (is_attribute
&& IsNormalizableWhitespace(ch
))
4528 m
<< "&#x" << String::FormatByte(static_cast<unsigned char>(ch
))
4537 return m
.GetString();
4540 // Returns the given string with all characters invalid in XML removed.
4541 // Currently invalid characters are dropped from the string. An
4542 // alternative is to replace them with certain characters such as . or ?.
4543 std::string
XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters(
4544 const std::string
& str
) {
4546 output
.reserve(str
.size());
4547 for (std::string::const_iterator it
= str
.begin(); it
!= str
.end(); ++it
)
4548 if (IsValidXmlCharacter(*it
)) output
.push_back(*it
);
4553 // The following routines generate an XML representation of a UnitTest
4556 // This is how Google Test concepts map to the DTD:
4558 // <testsuites name="AllTests"> <-- corresponds to a UnitTest object
4559 // <testsuite name="testcase-name"> <-- corresponds to a TestCase object
4560 // <testcase name="test-name"> <-- corresponds to a TestInfo object
4561 // <failure message="...">...</failure>
4562 // <failure message="...">...</failure>
4563 // <failure message="...">...</failure>
4564 // <-- individual assertion failures
4569 // Formats the given time in milliseconds as seconds.
4570 std::string
FormatTimeInMillisAsSeconds(TimeInMillis ms
) {
4571 ::std::stringstream ss
;
4576 // Converts the given epoch time in milliseconds to a date string in the ISO
4577 // 8601 format, without the timezone information.
4578 std::string
FormatEpochTimeInMillisAsIso8601(TimeInMillis ms
) {
4579 // Using non-reentrant version as localtime_r is not portable.
4580 time_t seconds
= static_cast<time_t>(ms
/ 1000);
4582 # pragma warning(push) // Saves the current warning state.
4583 # pragma warning(disable : 4996) // Temporarily disables warning 4996
4584 // (function or variable may be unsafe).
4585 const struct tm
* const time_struct
= localtime(&seconds
); // NOLINT
4586 # pragma warning(pop) // Restores the warning state again.
4588 const struct tm
* const time_struct
= localtime(&seconds
); // NOLINT
4590 if (time_struct
== NULL
) return ""; // Invalid ms value
4592 // YYYY-MM-DDThh:mm:ss
4593 return StreamableToString(time_struct
->tm_year
+ 1900) + "-" +
4594 String::FormatIntWidth2(time_struct
->tm_mon
+ 1) + "-" +
4595 String::FormatIntWidth2(time_struct
->tm_mday
) + "T" +
4596 String::FormatIntWidth2(time_struct
->tm_hour
) + ":" +
4597 String::FormatIntWidth2(time_struct
->tm_min
) + ":" +
4598 String::FormatIntWidth2(time_struct
->tm_sec
);
4601 // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
4602 void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream
* stream
,
4604 const char* segment
= data
;
4605 *stream
<< "<![CDATA[";
4607 const char* const next_segment
= strstr(segment
, "]]>");
4608 if (next_segment
!= NULL
) {
4609 stream
->write(segment
,
4610 static_cast<std::streamsize
>(next_segment
- segment
));
4611 *stream
<< "]]>]]><![CDATA[";
4612 segment
= next_segment
+ strlen("]]>");
4621 void XmlUnitTestResultPrinter::OutputXmlAttribute(
4622 std::ostream
* stream
, const std::string
& element_name
,
4623 const std::string
& name
, const std::string
& value
) {
4624 const std::vector
<std::string
>& allowed_names
=
4625 GetReservedAttributesForElement(element_name
);
4627 GTEST_CHECK_(std::find(allowed_names
.begin(), allowed_names
.end(), name
) !=
4628 allowed_names
.end())
4629 << "Attribute " << name
<< " is not allowed for element <" << element_name
4632 *stream
<< " " << name
<< "=\"" << EscapeXmlAttribute(value
) << "\"";
4635 // Prints an XML representation of a TestInfo object.
4636 // TODO(wan): There is also value in printing properties with the plain printer.
4637 void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream
* stream
,
4638 const char* test_case_name
,
4639 const TestInfo
& test_info
) {
4640 const TestResult
& result
= *test_info
.result();
4641 const std::string kTestcase
= "testcase";
4643 *stream
<< " <testcase";
4644 OutputXmlAttribute(stream
, kTestcase
, "name", test_info
.name());
4646 if (test_info
.value_param() != NULL
) {
4647 OutputXmlAttribute(stream
, kTestcase
, "value_param",
4648 test_info
.value_param());
4650 if (test_info
.type_param() != NULL
) {
4651 OutputXmlAttribute(stream
, kTestcase
, "type_param", test_info
.type_param());
4654 OutputXmlAttribute(stream
, kTestcase
, "status",
4655 test_info
.should_run() ? "run" : "notrun");
4656 OutputXmlAttribute(stream
, kTestcase
, "time",
4657 FormatTimeInMillisAsSeconds(result
.elapsed_time()));
4658 OutputXmlAttribute(stream
, kTestcase
, "classname", test_case_name
);
4659 *stream
<< TestPropertiesAsXmlAttributes(result
);
4662 for (int i
= 0; i
< result
.total_part_count(); ++i
) {
4663 const TestPartResult
& part
= result
.GetTestPartResult(i
);
4664 if (part
.failed()) {
4665 if (++failures
== 1) {
4668 const string location
= internal::FormatCompilerIndependentFileLocation(
4669 part
.file_name(), part
.line_number());
4670 const string summary
= location
+ "\n" + part
.summary();
4671 *stream
<< " <failure message=\""
4672 << EscapeXmlAttribute(summary
.c_str()) << "\" type=\"\">";
4673 const string detail
= location
+ "\n" + part
.message();
4674 OutputXmlCDataSection(stream
, RemoveInvalidXmlCharacters(detail
).c_str());
4675 *stream
<< "</failure>\n";
4682 *stream
<< " </testcase>\n";
4685 // Prints an XML representation of a TestCase object
4686 void XmlUnitTestResultPrinter::PrintXmlTestCase(std::ostream
* stream
,
4687 const TestCase
& test_case
) {
4688 const std::string kTestsuite
= "testsuite";
4689 *stream
<< " <" << kTestsuite
;
4690 OutputXmlAttribute(stream
, kTestsuite
, "name", test_case
.name());
4691 OutputXmlAttribute(stream
, kTestsuite
, "tests",
4692 StreamableToString(test_case
.reportable_test_count()));
4693 OutputXmlAttribute(stream
, kTestsuite
, "failures",
4694 StreamableToString(test_case
.failed_test_count()));
4696 stream
, kTestsuite
, "disabled",
4697 StreamableToString(test_case
.reportable_disabled_test_count()));
4698 OutputXmlAttribute(stream
, kTestsuite
, "errors", "0");
4699 OutputXmlAttribute(stream
, kTestsuite
, "time",
4700 FormatTimeInMillisAsSeconds(test_case
.elapsed_time()));
4701 *stream
<< TestPropertiesAsXmlAttributes(test_case
.ad_hoc_test_result())
4704 for (int i
= 0; i
< test_case
.total_test_count(); ++i
) {
4705 if (test_case
.GetTestInfo(i
)->is_reportable())
4706 OutputXmlTestInfo(stream
, test_case
.name(), *test_case
.GetTestInfo(i
));
4708 *stream
<< " </" << kTestsuite
<< ">\n";
4711 // Prints an XML summary of unit_test to output stream out.
4712 void XmlUnitTestResultPrinter::PrintXmlUnitTest(std::ostream
* stream
,
4713 const UnitTest
& unit_test
) {
4714 const std::string kTestsuites
= "testsuites";
4716 *stream
<< "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
4717 *stream
<< "<" << kTestsuites
;
4719 OutputXmlAttribute(stream
, kTestsuites
, "tests",
4720 StreamableToString(unit_test
.reportable_test_count()));
4721 OutputXmlAttribute(stream
, kTestsuites
, "failures",
4722 StreamableToString(unit_test
.failed_test_count()));
4724 stream
, kTestsuites
, "disabled",
4725 StreamableToString(unit_test
.reportable_disabled_test_count()));
4726 OutputXmlAttribute(stream
, kTestsuites
, "errors", "0");
4728 stream
, kTestsuites
, "timestamp",
4729 FormatEpochTimeInMillisAsIso8601(unit_test
.start_timestamp()));
4730 OutputXmlAttribute(stream
, kTestsuites
, "time",
4731 FormatTimeInMillisAsSeconds(unit_test
.elapsed_time()));
4733 if (GTEST_FLAG(shuffle
)) {
4734 OutputXmlAttribute(stream
, kTestsuites
, "random_seed",
4735 StreamableToString(unit_test
.random_seed()));
4738 *stream
<< TestPropertiesAsXmlAttributes(unit_test
.ad_hoc_test_result());
4740 OutputXmlAttribute(stream
, kTestsuites
, "name", "AllTests");
4743 for (int i
= 0; i
< unit_test
.total_test_case_count(); ++i
) {
4744 if (unit_test
.GetTestCase(i
)->reportable_test_count() > 0)
4745 PrintXmlTestCase(stream
, *unit_test
.GetTestCase(i
));
4747 *stream
<< "</" << kTestsuites
<< ">\n";
4750 // Produces a string representing the test properties in a result as space
4751 // delimited XML attributes based on the property key="value" pairs.
4752 std::string
XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes(
4753 const TestResult
& result
) {
4755 for (int i
= 0; i
< result
.test_property_count(); ++i
) {
4756 const TestProperty
& property
= result
.GetTestProperty(i
);
4757 attributes
<< " " << property
.key() << "="
4758 << "\"" << EscapeXmlAttribute(property
.value()) << "\"";
4760 return attributes
.GetString();
4763 // End XmlUnitTestResultPrinter
4765 #if GTEST_CAN_STREAM_RESULTS_
4767 // Checks if str contains '=', '&', '%' or '\n' characters. If yes,
4768 // replaces them by "%xx" where xx is their hexadecimal value. For
4769 // example, replaces "=" with "%3D". This algorithm is O(strlen(str))
4770 // in both time and space -- important as the input str may contain an
4771 // arbitrarily long test failure message and stack trace.
4772 string
StreamingListener::UrlEncode(const char* str
) {
4774 result
.reserve(strlen(str
) + 1);
4775 for (char ch
= *str
; ch
!= '\0'; ch
= *++str
) {
4781 result
.append("%" + String::FormatByte(static_cast<unsigned char>(ch
)));
4784 result
.push_back(ch
);
4791 void StreamingListener::SocketWriter::MakeConnection() {
4792 GTEST_CHECK_(sockfd_
== -1)
4793 << "MakeConnection() can't be called when there is already a connection.";
4796 memset(&hints
, 0, sizeof(hints
));
4797 hints
.ai_family
= AF_UNSPEC
; // To allow both IPv4 and IPv6 addresses.
4798 hints
.ai_socktype
= SOCK_STREAM
;
4799 addrinfo
* servinfo
= NULL
;
4801 // Use the getaddrinfo() to get a linked list of IP addresses for
4802 // the given host name.
4803 const int error_num
=
4804 getaddrinfo(host_name_
.c_str(), port_num_
.c_str(), &hints
, &servinfo
);
4805 if (error_num
!= 0) {
4806 GTEST_LOG_(WARNING
) << "stream_result_to: getaddrinfo() failed: "
4807 << gai_strerror(error_num
);
4810 // Loop through all the results and connect to the first we can.
4811 for (addrinfo
* cur_addr
= servinfo
; sockfd_
== -1 && cur_addr
!= NULL
;
4812 cur_addr
= cur_addr
->ai_next
) {
4813 sockfd_
= socket(cur_addr
->ai_family
, cur_addr
->ai_socktype
,
4814 cur_addr
->ai_protocol
);
4815 if (sockfd_
!= -1) {
4816 // Connect the client socket to the server socket.
4817 if (connect(sockfd_
, cur_addr
->ai_addr
, cur_addr
->ai_addrlen
) == -1) {
4824 freeaddrinfo(servinfo
); // all done with this structure
4826 if (sockfd_
== -1) {
4827 GTEST_LOG_(WARNING
) << "stream_result_to: failed to connect to "
4828 << host_name_
<< ":" << port_num_
;
4832 // End of class Streaming Listener
4833 #endif // GTEST_CAN_STREAM_RESULTS__
4835 // Class ScopedTrace
4837 // Pushes the given source file location and message onto a per-thread
4838 // trace stack maintained by Google Test.
4839 ScopedTrace::ScopedTrace(const char* file
, int line
, const Message
& message
)
4840 GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_
) {
4844 trace
.message
= message
.GetString();
4846 UnitTest::GetInstance()->PushGTestTrace(trace
);
4849 // Pops the info pushed by the c'tor.
4850 ScopedTrace::~ScopedTrace() GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_
) {
4851 UnitTest::GetInstance()->PopGTestTrace();
4854 // class OsStackTraceGetter
4856 // Returns the current OS stack trace as an std::string. Parameters:
4858 // max_depth - the maximum number of stack frames to be included
4860 // skip_count - the number of top frames to be skipped; doesn't count
4861 // against max_depth.
4863 string
OsStackTraceGetter::CurrentStackTrace(int /* max_depth */,
4864 int /* skip_count */)
4865 GTEST_LOCK_EXCLUDED_(mutex_
) {
4869 void OsStackTraceGetter::UponLeavingGTest() GTEST_LOCK_EXCLUDED_(mutex_
) {}
4871 const char* const OsStackTraceGetter::kElidedFramesMarker
=
4872 "... " GTEST_NAME_
" internal frames ...";
4874 // A helper class that creates the premature-exit file in its
4875 // constructor and deletes the file in its destructor.
4876 class ScopedPrematureExitFile
{
4878 explicit ScopedPrematureExitFile(const char* premature_exit_filepath
)
4879 : premature_exit_filepath_(premature_exit_filepath
) {
4880 // If a path to the premature-exit file is specified...
4881 if (premature_exit_filepath
!= NULL
&& *premature_exit_filepath
!= '\0') {
4882 // create the file with a single "0" character in it. I/O
4883 // errors are ignored as there's nothing better we can do and we
4884 // don't want to fail the test because of this.
4885 FILE* pfile
= posix::FOpen(premature_exit_filepath
, "w");
4886 fwrite("0", 1, 1, pfile
);
4891 ~ScopedPrematureExitFile() {
4892 if (premature_exit_filepath_
!= NULL
&& *premature_exit_filepath_
!= '\0') {
4893 remove(premature_exit_filepath_
);
4898 const char* const premature_exit_filepath_
;
4900 GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedPrematureExitFile
);
4903 } // namespace internal
4905 // class TestEventListeners
4907 TestEventListeners::TestEventListeners()
4908 : repeater_(new internal::TestEventRepeater()),
4909 default_result_printer_(NULL
),
4910 default_xml_generator_(NULL
) {}
4912 TestEventListeners::~TestEventListeners() { delete repeater_
; }
4914 // Returns the standard listener responsible for the default console
4915 // output. Can be removed from the listeners list to shut down default
4916 // console output. Note that removing this object from the listener list
4917 // with Release transfers its ownership to the user.
4918 void TestEventListeners::Append(TestEventListener
* listener
) {
4919 repeater_
->Append(listener
);
4922 // Removes the given event listener from the list and returns it. It then
4923 // becomes the caller's responsibility to delete the listener. Returns
4924 // NULL if the listener is not found in the list.
4925 TestEventListener
* TestEventListeners::Release(TestEventListener
* listener
) {
4926 if (listener
== default_result_printer_
)
4927 default_result_printer_
= NULL
;
4928 else if (listener
== default_xml_generator_
)
4929 default_xml_generator_
= NULL
;
4930 return repeater_
->Release(listener
);
4933 // Returns repeater that broadcasts the TestEventListener events to all
4935 TestEventListener
* TestEventListeners::repeater() { return repeater_
; }
4937 // Sets the default_result_printer attribute to the provided listener.
4938 // The listener is also added to the listener list and previous
4939 // default_result_printer is removed from it and deleted. The listener can
4940 // also be NULL in which case it will not be added to the list. Does
4941 // nothing if the previous and the current listener objects are the same.
4942 void TestEventListeners::SetDefaultResultPrinter(TestEventListener
* listener
) {
4943 if (default_result_printer_
!= listener
) {
4944 // It is an error to pass this method a listener that is already in the
4946 delete Release(default_result_printer_
);
4947 default_result_printer_
= listener
;
4948 if (listener
!= NULL
) Append(listener
);
4952 // Sets the default_xml_generator attribute to the provided listener. The
4953 // listener is also added to the listener list and previous
4954 // default_xml_generator is removed from it and deleted. The listener can
4955 // also be NULL in which case it will not be added to the list. Does
4956 // nothing if the previous and the current listener objects are the same.
4957 void TestEventListeners::SetDefaultXmlGenerator(TestEventListener
* listener
) {
4958 if (default_xml_generator_
!= listener
) {
4959 // It is an error to pass this method a listener that is already in the
4961 delete Release(default_xml_generator_
);
4962 default_xml_generator_
= listener
;
4963 if (listener
!= NULL
) Append(listener
);
4967 // Controls whether events will be forwarded by the repeater to the
4968 // listeners in the list.
4969 bool TestEventListeners::EventForwardingEnabled() const {
4970 return repeater_
->forwarding_enabled();
4973 void TestEventListeners::SuppressEventForwarding() {
4974 repeater_
->set_forwarding_enabled(false);
4979 // Gets the singleton UnitTest object. The first time this method is
4980 // called, a UnitTest object is constructed and returned. Consecutive
4981 // calls will return the same object.
4983 // We don't protect this under mutex_ as a user is not supposed to
4984 // call this before main() starts, from which point on the return
4985 // value will never change.
4986 UnitTest
* UnitTest::GetInstance() {
4987 // When compiled with MSVC 7.1 in optimized mode, destroying the
4988 // UnitTest object upon exiting the program messes up the exit code,
4989 // causing successful tests to appear failed. We have to use a
4990 // different implementation in this case to bypass the compiler bug.
4991 // This implementation makes the compiler happy, at the cost of
4992 // leaking the UnitTest object.
4994 // CodeGear C++Builder insists on a public destructor for the
4995 // default implementation. Use this implementation to keep good OO
4996 // design with private destructor.
4998 #if (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)
4999 static UnitTest
* const instance
= new UnitTest
;
5002 static UnitTest instance
;
5004 #endif // (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)
5007 // Gets the number of successful test cases.
5008 int UnitTest::successful_test_case_count() const {
5009 return impl()->successful_test_case_count();
5012 // Gets the number of failed test cases.
5013 int UnitTest::failed_test_case_count() const {
5014 return impl()->failed_test_case_count();
5017 // Gets the number of all test cases.
5018 int UnitTest::total_test_case_count() const {
5019 return impl()->total_test_case_count();
5022 // Gets the number of all test cases that contain at least one test
5024 int UnitTest::test_case_to_run_count() const {
5025 return impl()->test_case_to_run_count();
5028 // Gets the number of successful tests.
5029 int UnitTest::successful_test_count() const {
5030 return impl()->successful_test_count();
5033 // Gets the number of failed tests.
5034 int UnitTest::failed_test_count() const { return impl()->failed_test_count(); }
5036 // Gets the number of disabled tests that will be reported in the XML report.
5037 int UnitTest::reportable_disabled_test_count() const {
5038 return impl()->reportable_disabled_test_count();
5041 // Gets the number of disabled tests.
5042 int UnitTest::disabled_test_count() const {
5043 return impl()->disabled_test_count();
5046 // Gets the number of tests to be printed in the XML report.
5047 int UnitTest::reportable_test_count() const {
5048 return impl()->reportable_test_count();
5051 // Gets the number of all tests.
5052 int UnitTest::total_test_count() const { return impl()->total_test_count(); }
5054 // Gets the number of tests that should run.
5055 int UnitTest::test_to_run_count() const { return impl()->test_to_run_count(); }
5057 // Gets the time of the test program start, in ms from the start of the
5059 internal::TimeInMillis
UnitTest::start_timestamp() const {
5060 return impl()->start_timestamp();
5063 // Gets the elapsed time, in milliseconds.
5064 internal::TimeInMillis
UnitTest::elapsed_time() const {
5065 return impl()->elapsed_time();
5068 // Returns true iff the unit test passed (i.e. all test cases passed).
5069 bool UnitTest::Passed() const { return impl()->Passed(); }
5071 // Returns true iff the unit test failed (i.e. some test case failed
5072 // or something outside of all tests failed).
5073 bool UnitTest::Failed() const { return impl()->Failed(); }
5075 // Gets the i-th test case among all the test cases. i can range from 0 to
5076 // total_test_case_count() - 1. If i is not in that range, returns NULL.
5077 const TestCase
* UnitTest::GetTestCase(int i
) const {
5078 return impl()->GetTestCase(i
);
5081 // Returns the TestResult containing information on test failures and
5082 // properties logged outside of individual test cases.
5083 const TestResult
& UnitTest::ad_hoc_test_result() const {
5084 return *impl()->ad_hoc_test_result();
5087 // Gets the i-th test case among all the test cases. i can range from 0 to
5088 // total_test_case_count() - 1. If i is not in that range, returns NULL.
5089 TestCase
* UnitTest::GetMutableTestCase(int i
) {
5090 return impl()->GetMutableTestCase(i
);
5093 // Returns the list of event listeners that can be used to track events
5094 // inside Google Test.
5095 TestEventListeners
& UnitTest::listeners() { return *impl()->listeners(); }
5097 // Registers and returns a global test environment. When a test
5098 // program is run, all global test environments will be set-up in the
5099 // order they were registered. After all tests in the program have
5100 // finished, all global test environments will be torn-down in the
5101 // *reverse* order they were registered.
5103 // The UnitTest object takes ownership of the given environment.
5105 // We don't protect this under mutex_, as we only support calling it
5106 // from the main thread.
5107 Environment
* UnitTest::AddEnvironment(Environment
* env
) {
5112 impl_
->environments().push_back(env
);
5116 // Adds a TestPartResult to the current TestResult object. All Google Test
5117 // assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) eventually call
5118 // this to report their results. The user code should use the
5119 // assertion macros instead of calling this directly.
5120 void UnitTest::AddTestPartResult(TestPartResult::Type result_type
,
5121 const char* file_name
, int line_number
,
5122 const std::string
& message
,
5123 const std::string
& os_stack_trace
)
5124 GTEST_LOCK_EXCLUDED_(mutex_
) {
5128 internal::MutexLock
lock(&mutex_
);
5129 if (impl_
->gtest_trace_stack().size() > 0) {
5130 msg
<< "\n" << GTEST_NAME_
<< " trace:";
5132 for (int i
= static_cast<int>(impl_
->gtest_trace_stack().size()); i
> 0;
5134 const internal::TraceInfo
& trace
= impl_
->gtest_trace_stack()[i
- 1];
5136 << internal::FormatFileLocation(trace
.file
, trace
.line
) << " "
5141 if (os_stack_trace
.c_str() != NULL
&& !os_stack_trace
.empty()) {
5142 msg
<< internal::kStackTraceMarker
<< os_stack_trace
;
5145 const TestPartResult result
= TestPartResult(
5146 result_type
, file_name
, line_number
, msg
.GetString().c_str());
5147 impl_
->GetTestPartResultReporterForCurrentThread()->ReportTestPartResult(
5150 if (result_type
!= TestPartResult::kSuccess
) {
5151 // gtest_break_on_failure takes precedence over
5152 // gtest_throw_on_failure. This allows a user to set the latter
5153 // in the code (perhaps in order to use Google Test assertions
5154 // with another testing framework) and specify the former on the
5155 // command line for debugging.
5156 if (GTEST_FLAG(break_on_failure
)) {
5157 #if GTEST_OS_WINDOWS
5158 // Using DebugBreak on Windows allows gtest to still break into a debugger
5159 // when a failure happens and both the --gtest_break_on_failure and
5160 // the --gtest_catch_exceptions flags are specified.
5163 // Dereference NULL through a volatile pointer to prevent the compiler
5164 // from removing. We use this rather than abort() or __builtin_trap() for
5165 // portability: Symbian doesn't implement abort() well, and some debuggers
5166 // don't correctly trap abort().
5167 *static_cast<volatile int*>(NULL
) = 1;
5168 #endif // GTEST_OS_WINDOWS
5169 } else if (GTEST_FLAG(throw_on_failure
)) {
5170 #if GTEST_HAS_EXCEPTIONS
5171 throw internal::GoogleTestFailureException(result
);
5173 // We cannot call abort() as it generates a pop-up in debug mode
5174 // that cannot be suppressed in VC 7.1 or below.
5181 // Adds a TestProperty to the current TestResult object when invoked from
5182 // inside a test, to current TestCase's ad_hoc_test_result_ when invoked
5183 // from SetUpTestCase or TearDownTestCase, or to the global property set
5184 // when invoked elsewhere. If the result already contains a property with
5185 // the same key, the value will be updated.
5186 void UnitTest::RecordProperty(const std::string
& key
,
5187 const std::string
& value
) {
5188 impl_
->RecordProperty(TestProperty(key
, value
));
5191 // Runs all tests in this UnitTest object and prints the result.
5192 // Returns 0 if successful, or 1 otherwise.
5194 // We don't protect this under mutex_, as we only support calling it
5195 // from the main thread.
5196 int UnitTest::Run() {
5197 const bool in_death_test_child_process
=
5198 internal::GTEST_FLAG(internal_run_death_test
).length() > 0;
5200 // Google Test implements this protocol for catching that a test
5201 // program exits before returning control to Google Test:
5203 // 1. Upon start, Google Test creates a file whose absolute path
5204 // is specified by the environment variable
5205 // TEST_PREMATURE_EXIT_FILE.
5206 // 2. When Google Test has finished its work, it deletes the file.
5208 // This allows a test runner to set TEST_PREMATURE_EXIT_FILE before
5209 // running a Google-Test-based test program and check the existence
5210 // of the file at the end of the test execution to see if it has
5211 // exited prematurely.
5213 // If we are in the child process of a death test, don't
5214 // create/delete the premature exit file, as doing so is unnecessary
5215 // and will confuse the parent process. Otherwise, create/delete
5216 // the file upon entering/leaving this function. If the program
5217 // somehow exits before this function has a chance to return, the
5218 // premature-exit file will be left undeleted, causing a test runner
5219 // that understands the premature-exit-file protocol to report the
5220 // test as having failed.
5221 const internal::ScopedPrematureExitFile
premature_exit_file(
5222 in_death_test_child_process
5224 : internal::posix::GetEnv("TEST_PREMATURE_EXIT_FILE"));
5226 // Captures the value of GTEST_FLAG(catch_exceptions). This value will be
5227 // used for the duration of the program.
5228 impl()->set_catch_exceptions(GTEST_FLAG(catch_exceptions
));
5231 // Either the user wants Google Test to catch exceptions thrown by the
5232 // tests or this is executing in the context of death test child
5233 // process. In either case the user does not want to see pop-up dialogs
5234 // about crashes - they are expected.
5235 if (impl()->catch_exceptions() || in_death_test_child_process
) {
5236 # if !GTEST_OS_WINDOWS_MOBILE
5237 // SetErrorMode doesn't exist on CE.
5238 SetErrorMode(SEM_FAILCRITICALERRORS
| SEM_NOALIGNMENTFAULTEXCEPT
|
5239 SEM_NOGPFAULTERRORBOX
| SEM_NOOPENFILEERRORBOX
);
5240 # endif // !GTEST_OS_WINDOWS_MOBILE
5242 # if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE
5243 // Death test children can be terminated with _abort(). On Windows,
5244 // _abort() can show a dialog with a warning message. This forces the
5245 // abort message to go to stderr instead.
5246 _set_error_mode(_OUT_TO_STDERR
);
5249 # if _MSC_VER >= 1400 && !GTEST_OS_WINDOWS_MOBILE
5250 // In the debug version, Visual Studio pops up a separate dialog
5251 // offering a choice to debug the aborted program. We need to suppress
5252 // this dialog or it will pop up for every EXPECT/ASSERT_DEATH statement
5253 // executed. Google Test will notify the user of any unexpected
5254 // failure via stderr.
5256 // VC++ doesn't define _set_abort_behavior() prior to the version 8.0.
5257 // Users of prior VC versions shall suffer the agony and pain of
5258 // clicking through the countless debug dialogs.
5259 // TODO(vladl@google.com): find a way to suppress the abort dialog() in the
5260 // debug mode when compiled with VC 7.1 or lower.
5261 if (!GTEST_FLAG(break_on_failure
))
5262 _set_abort_behavior(
5263 0x0, // Clear the following flags:
5264 _WRITE_ABORT_MSG
| _CALL_REPORTFAULT
); // pop-up window, core dump.
5267 #endif // GTEST_HAS_SEH
5269 return internal::HandleExceptionsInMethodIfSupported(
5270 impl(), &internal::UnitTestImpl::RunAllTests
,
5271 "auxiliary test code (environments or event listeners)")
5276 // Returns the working directory when the first TEST() or TEST_F() was
5278 const char* UnitTest::original_working_dir() const {
5279 return impl_
->original_working_dir_
.c_str();
5282 // Returns the TestCase object for the test that's currently running,
5283 // or NULL if no test is running.
5284 const TestCase
* UnitTest::current_test_case() const
5285 GTEST_LOCK_EXCLUDED_(mutex_
) {
5286 internal::MutexLock
lock(&mutex_
);
5287 return impl_
->current_test_case();
5290 // Returns the TestInfo object for the test that's currently running,
5291 // or NULL if no test is running.
5292 const TestInfo
* UnitTest::current_test_info() const
5293 GTEST_LOCK_EXCLUDED_(mutex_
) {
5294 internal::MutexLock
lock(&mutex_
);
5295 return impl_
->current_test_info();
5298 // Returns the random seed used at the start of the current test run.
5299 int UnitTest::random_seed() const { return impl_
->random_seed(); }
5301 #if GTEST_HAS_PARAM_TEST
5302 // Returns ParameterizedTestCaseRegistry object used to keep track of
5303 // value-parameterized tests and instantiate and register them.
5304 internal::ParameterizedTestCaseRegistry
& UnitTest::parameterized_test_registry()
5305 GTEST_LOCK_EXCLUDED_(mutex_
) {
5306 return impl_
->parameterized_test_registry();
5308 #endif // GTEST_HAS_PARAM_TEST
5310 // Creates an empty UnitTest.
5311 UnitTest::UnitTest() { impl_
= new internal::UnitTestImpl(this); }
5313 // Destructor of UnitTest.
5314 UnitTest::~UnitTest() { delete impl_
; }
5316 // Pushes a trace defined by SCOPED_TRACE() on to the per-thread
5317 // Google Test trace stack.
5318 void UnitTest::PushGTestTrace(const internal::TraceInfo
& trace
)
5319 GTEST_LOCK_EXCLUDED_(mutex_
) {
5320 internal::MutexLock
lock(&mutex_
);
5321 impl_
->gtest_trace_stack().push_back(trace
);
5324 // Pops a trace from the per-thread Google Test trace stack.
5325 void UnitTest::PopGTestTrace() GTEST_LOCK_EXCLUDED_(mutex_
) {
5326 internal::MutexLock
lock(&mutex_
);
5327 impl_
->gtest_trace_stack().pop_back();
5330 namespace internal
{
5332 UnitTestImpl::UnitTestImpl(UnitTest
* parent
)
5335 # pragma warning(push) // Saves the current warning state.
5336 # pragma warning(disable : 4355) // Temporarily disables warning 4355
5337 // (using this in initializer).
5338 default_global_test_part_result_reporter_(this),
5339 default_per_thread_test_part_result_reporter_(this),
5340 # pragma warning(pop) // Restores the warning state again.
5342 default_global_test_part_result_reporter_(this),
5343 default_per_thread_test_part_result_reporter_(this),
5345 global_test_part_result_repoter_(
5346 &default_global_test_part_result_reporter_
),
5347 per_thread_test_part_result_reporter_(
5348 &default_per_thread_test_part_result_reporter_
),
5349 #if GTEST_HAS_PARAM_TEST
5350 parameterized_test_registry_(),
5351 parameterized_tests_registered_(false),
5352 #endif // GTEST_HAS_PARAM_TEST
5353 last_death_test_case_(-1),
5354 current_test_case_(NULL
),
5355 current_test_info_(NULL
),
5356 ad_hoc_test_result_(),
5357 os_stack_trace_getter_(NULL
),
5358 post_flag_parse_init_performed_(false),
5359 random_seed_(0), // Will be overridden by the flag before first use.
5360 random_(0), // Will be reseeded before first use.
5361 start_timestamp_(0),
5363 #if GTEST_HAS_DEATH_TEST
5364 death_test_factory_(new DefaultDeathTestFactory
),
5366 // Will be overridden by the flag before first use.
5367 catch_exceptions_(false) {
5368 listeners()->SetDefaultResultPrinter(new PrettyUnitTestResultPrinter
);
5371 UnitTestImpl::~UnitTestImpl() {
5372 // Deletes every TestCase.
5373 ForEach(test_cases_
, internal::Delete
<TestCase
>);
5375 // Deletes every Environment.
5376 ForEach(environments_
, internal::Delete
<Environment
>);
5378 delete os_stack_trace_getter_
;
5381 // Adds a TestProperty to the current TestResult object when invoked in a
5382 // context of a test, to current test case's ad_hoc_test_result when invoke
5383 // from SetUpTestCase/TearDownTestCase, or to the global property set
5384 // otherwise. If the result already contains a property with the same key,
5385 // the value will be updated.
5386 void UnitTestImpl::RecordProperty(const TestProperty
& test_property
) {
5387 std::string xml_element
;
5388 TestResult
* test_result
; // TestResult appropriate for property recording.
5390 if (current_test_info_
!= NULL
) {
5391 xml_element
= "testcase";
5392 test_result
= &(current_test_info_
->result_
);
5393 } else if (current_test_case_
!= NULL
) {
5394 xml_element
= "testsuite";
5395 test_result
= &(current_test_case_
->ad_hoc_test_result_
);
5397 xml_element
= "testsuites";
5398 test_result
= &ad_hoc_test_result_
;
5400 test_result
->RecordProperty(xml_element
, test_property
);
5403 #if GTEST_HAS_DEATH_TEST
5404 // Disables event forwarding if the control is currently in a death test
5405 // subprocess. Must not be called before InitGoogleTest.
5406 void UnitTestImpl::SuppressTestEventsIfInSubprocess() {
5407 if (internal_run_death_test_flag_
.get() != NULL
)
5408 listeners()->SuppressEventForwarding();
5410 #endif // GTEST_HAS_DEATH_TEST
5412 // Initializes event listeners performing XML output as specified by
5413 // UnitTestOptions. Must not be called before InitGoogleTest.
5414 void UnitTestImpl::ConfigureXmlOutput() {
5415 const std::string
& output_format
= UnitTestOptions::GetOutputFormat();
5416 if (output_format
== "xml") {
5417 listeners()->SetDefaultXmlGenerator(new XmlUnitTestResultPrinter(
5418 UnitTestOptions::GetAbsolutePathToOutputFile().c_str()));
5419 } else if (output_format
!= "") {
5420 printf("WARNING: unrecognized output format \"%s\" ignored.\n",
5421 output_format
.c_str());
5426 #if GTEST_CAN_STREAM_RESULTS_
5427 // Initializes event listeners for streaming test results in string form.
5428 // Must not be called before InitGoogleTest.
5429 void UnitTestImpl::ConfigureStreamingOutput() {
5430 const std::string
& target
= GTEST_FLAG(stream_result_to
);
5431 if (!target
.empty()) {
5432 const size_t pos
= target
.find(':');
5433 if (pos
!= std::string::npos
) {
5434 listeners()->Append(
5435 new StreamingListener(target
.substr(0, pos
), target
.substr(pos
+ 1)));
5437 printf("WARNING: unrecognized streaming target \"%s\" ignored.\n",
5443 #endif // GTEST_CAN_STREAM_RESULTS_
5445 // Performs initialization dependent upon flag values obtained in
5446 // ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to
5447 // ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest
5448 // this function is also called from RunAllTests. Since this function can be
5449 // called more than once, it has to be idempotent.
5450 void UnitTestImpl::PostFlagParsingInit() {
5451 // Ensures that this function does not execute more than once.
5452 if (!post_flag_parse_init_performed_
) {
5453 post_flag_parse_init_performed_
= true;
5455 #if GTEST_HAS_DEATH_TEST
5456 InitDeathTestSubprocessControlInfo();
5457 SuppressTestEventsIfInSubprocess();
5458 #endif // GTEST_HAS_DEATH_TEST
5460 // Registers parameterized tests. This makes parameterized tests
5461 // available to the UnitTest reflection API without running
5463 RegisterParameterizedTests();
5465 // Configures listeners for XML output. This makes it possible for users
5466 // to shut down the default XML output before invoking RUN_ALL_TESTS.
5467 ConfigureXmlOutput();
5469 #if GTEST_CAN_STREAM_RESULTS_
5470 // Configures listeners for streaming test results to the specified server.
5471 ConfigureStreamingOutput();
5472 #endif // GTEST_CAN_STREAM_RESULTS_
5476 // A predicate that checks the name of a TestCase against a known
5479 // This is used for implementation of the UnitTest class only. We put
5480 // it in the anonymous namespace to prevent polluting the outer
5483 // TestCaseNameIs is copyable.
5484 class TestCaseNameIs
{
5487 explicit TestCaseNameIs(const std::string
& name
) : name_(name
) {}
5489 // Returns true iff the name of test_case matches name_.
5490 bool operator()(const TestCase
* test_case
) const {
5491 return test_case
!= NULL
&& strcmp(test_case
->name(), name_
.c_str()) == 0;
5498 // Finds and returns a TestCase with the given name. If one doesn't
5499 // exist, creates one and returns it. It's the CALLER'S
5500 // RESPONSIBILITY to ensure that this function is only called WHEN THE
5501 // TESTS ARE NOT SHUFFLED.
5505 // test_case_name: name of the test case
5506 // type_param: the name of the test case's type parameter, or NULL if
5507 // this is not a typed or a type-parameterized test case.
5508 // set_up_tc: pointer to the function that sets up the test case
5509 // tear_down_tc: pointer to the function that tears down the test case
5510 TestCase
* UnitTestImpl::GetTestCase(const char* test_case_name
,
5511 const char* type_param
,
5512 Test::SetUpTestCaseFunc set_up_tc
,
5513 Test::TearDownTestCaseFunc tear_down_tc
) {
5514 // Can we find a TestCase with the given name?
5515 const std::vector
<TestCase
*>::const_iterator test_case
= std::find_if(
5516 test_cases_
.begin(), test_cases_
.end(), TestCaseNameIs(test_case_name
));
5518 if (test_case
!= test_cases_
.end()) return *test_case
;
5520 // No. Let's create one.
5521 TestCase
* const new_test_case
=
5522 new TestCase(test_case_name
, type_param
, set_up_tc
, tear_down_tc
);
5524 // Is this a death test case?
5525 if (internal::UnitTestOptions::MatchesFilter(test_case_name
,
5526 kDeathTestCaseFilter
)) {
5527 // Yes. Inserts the test case after the last death test case
5528 // defined so far. This only works when the test cases haven't
5529 // been shuffled. Otherwise we may end up running a death test
5530 // after a non-death test.
5531 ++last_death_test_case_
;
5532 test_cases_
.insert(test_cases_
.begin() + last_death_test_case_
,
5535 // No. Appends to the end of the list.
5536 test_cases_
.push_back(new_test_case
);
5539 test_case_indices_
.push_back(static_cast<int>(test_case_indices_
.size()));
5540 return new_test_case
;
5543 // Helpers for setting up / tearing down the given environment. They
5544 // are for use in the ForEach() function.
5545 static void SetUpEnvironment(Environment
* env
) { env
->SetUp(); }
5546 static void TearDownEnvironment(Environment
* env
) { env
->TearDown(); }
5548 // Runs all tests in this UnitTest object, prints the result, and
5549 // returns true if all tests are successful. If any exception is
5550 // thrown during a test, the test is considered to be failed, but the
5551 // rest of the tests will still be run.
5553 // When parameterized tests are enabled, it expands and registers
5554 // parameterized tests first in RegisterParameterizedTests().
5555 // All other functions called from RunAllTests() may safely assume that
5556 // parameterized tests are ready to be counted and run.
5557 bool UnitTestImpl::RunAllTests() {
5558 // Makes sure InitGoogleTest() was called.
5559 if (!GTestIsInitialized()) {
5561 "\nThis test program did NOT call ::testing::InitGoogleTest "
5562 "before calling RUN_ALL_TESTS(). Please fix it.\n");
5566 // Do not run any test if the --help flag was specified.
5567 if (g_help_flag
) return true;
5569 // Repeats the call to the post-flag parsing initialization in case the
5570 // user didn't call InitGoogleTest.
5571 PostFlagParsingInit();
5573 // Even if sharding is not on, test runners may want to use the
5574 // GTEST_SHARD_STATUS_FILE to query whether the test supports the sharding
5576 internal::WriteToShardStatusFileIfNeeded();
5578 // True iff we are in a subprocess for running a thread-safe-style
5580 bool in_subprocess_for_death_test
= false;
5582 #if GTEST_HAS_DEATH_TEST
5583 in_subprocess_for_death_test
= (internal_run_death_test_flag_
.get() != NULL
);
5584 #endif // GTEST_HAS_DEATH_TEST
5586 const bool should_shard
= ShouldShard(kTestTotalShards
, kTestShardIndex
,
5587 in_subprocess_for_death_test
);
5589 // Compares the full test names with the filter to decide which
5591 const bool has_tests_to_run
=
5592 FilterTests(should_shard
? HONOR_SHARDING_PROTOCOL
5593 : IGNORE_SHARDING_PROTOCOL
) > 0;
5595 // Lists the tests and exits if the --gtest_list_tests flag was specified.
5596 if (GTEST_FLAG(list_tests
)) {
5597 // This must be called *after* FilterTests() has been called.
5598 ListTestsMatchingFilter();
5603 GTEST_FLAG(shuffle
) ? GetRandomSeedFromFlag(GTEST_FLAG(random_seed
)) : 0;
5605 // True iff at least one test has failed.
5606 bool failed
= false;
5608 TestEventListener
* repeater
= listeners()->repeater();
5610 start_timestamp_
= GetTimeInMillis();
5611 repeater
->OnTestProgramStart(*parent_
);
5613 // How many times to repeat the tests? We don't want to repeat them
5614 // when we are inside the subprocess of a death test.
5615 const int repeat
= in_subprocess_for_death_test
? 1 : GTEST_FLAG(repeat
);
5616 // Repeats forever if the repeat count is negative.
5617 const bool forever
= repeat
< 0;
5618 for (int i
= 0; forever
|| i
!= repeat
; i
++) {
5619 // We want to preserve failures generated by ad-hoc test
5620 // assertions executed before RUN_ALL_TESTS().
5621 ClearNonAdHocTestResult();
5623 const TimeInMillis start
= GetTimeInMillis();
5625 // Shuffles test cases and tests if requested.
5626 if (has_tests_to_run
&& GTEST_FLAG(shuffle
)) {
5627 random()->Reseed(random_seed_
);
5628 // This should be done before calling OnTestIterationStart(),
5629 // such that a test event listener can see the actual test order
5634 // Tells the unit test event listeners that the tests are about to start.
5635 repeater
->OnTestIterationStart(*parent_
, i
);
5637 // Runs each test case if there is at least one test to run.
5638 if (has_tests_to_run
) {
5639 // Sets up all environments beforehand.
5640 repeater
->OnEnvironmentsSetUpStart(*parent_
);
5641 ForEach(environments_
, SetUpEnvironment
);
5642 repeater
->OnEnvironmentsSetUpEnd(*parent_
);
5644 // Runs the tests only if there was no fatal failure during global
5646 if (!Test::HasFatalFailure()) {
5647 for (int test_index
= 0; test_index
< total_test_case_count();
5649 GetMutableTestCase(test_index
)->Run();
5653 // Tears down all environments in reverse order afterwards.
5654 repeater
->OnEnvironmentsTearDownStart(*parent_
);
5655 std::for_each(environments_
.rbegin(), environments_
.rend(),
5656 TearDownEnvironment
);
5657 repeater
->OnEnvironmentsTearDownEnd(*parent_
);
5660 elapsed_time_
= GetTimeInMillis() - start
;
5662 // Tells the unit test event listener that the tests have just finished.
5663 repeater
->OnTestIterationEnd(*parent_
, i
);
5665 // Gets the result and clears it.
5670 // Restores the original test order after the iteration. This
5671 // allows the user to quickly repro a failure that happens in the
5672 // N-th iteration without repeating the first (N - 1) iterations.
5673 // This is not enclosed in "if (GTEST_FLAG(shuffle)) { ... }", in
5674 // case the user somehow changes the value of the flag somewhere
5675 // (it's always safe to unshuffle the tests).
5678 if (GTEST_FLAG(shuffle
)) {
5679 // Picks a new random seed for each iteration.
5680 random_seed_
= GetNextRandomSeed(random_seed_
);
5684 repeater
->OnTestProgramEnd(*parent_
);
5689 // Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
5690 // if the variable is present. If a file already exists at this location, this
5691 // function will write over it. If the variable is present, but the file cannot
5692 // be created, prints an error and exits.
5693 void WriteToShardStatusFileIfNeeded() {
5694 const char* const test_shard_file
= posix::GetEnv(kTestShardStatusFile
);
5695 if (test_shard_file
!= NULL
) {
5696 FILE* const file
= posix::FOpen(test_shard_file
, "w");
5698 ColoredPrintf(COLOR_RED
,
5699 "Could not write to the test shard status file \"%s\" "
5700 "specified by the %s environment variable.\n",
5701 test_shard_file
, kTestShardStatusFile
);
5709 // Checks whether sharding is enabled by examining the relevant
5710 // environment variable values. If the variables are present,
5711 // but inconsistent (i.e., shard_index >= total_shards), prints
5712 // an error and exits. If in_subprocess_for_death_test, sharding is
5713 // disabled because it must only be applied to the original test
5714 // process. Otherwise, we could filter out death tests we intended to execute.
5715 bool ShouldShard(const char* total_shards_env
, const char* shard_index_env
,
5716 bool in_subprocess_for_death_test
) {
5717 if (in_subprocess_for_death_test
) {
5721 const Int32 total_shards
= Int32FromEnvOrDie(total_shards_env
, -1);
5722 const Int32 shard_index
= Int32FromEnvOrDie(shard_index_env
, -1);
5724 if (total_shards
== -1 && shard_index
== -1) {
5726 } else if (total_shards
== -1 && shard_index
!= -1) {
5727 const Message msg
= Message() << "Invalid environment variables: you have "
5728 << kTestShardIndex
<< " = " << shard_index
5729 << ", but have left " << kTestTotalShards
5731 ColoredPrintf(COLOR_RED
, msg
.GetString().c_str());
5734 } else if (total_shards
!= -1 && shard_index
== -1) {
5735 const Message msg
= Message()
5736 << "Invalid environment variables: you have "
5737 << kTestTotalShards
<< " = " << total_shards
5738 << ", but have left " << kTestShardIndex
<< " unset.\n";
5739 ColoredPrintf(COLOR_RED
, msg
.GetString().c_str());
5742 } else if (shard_index
< 0 || shard_index
>= total_shards
) {
5744 Message() << "Invalid environment variables: we require 0 <= "
5745 << kTestShardIndex
<< " < " << kTestTotalShards
5746 << ", but you have " << kTestShardIndex
<< "=" << shard_index
5747 << ", " << kTestTotalShards
<< "=" << total_shards
<< ".\n";
5748 ColoredPrintf(COLOR_RED
, msg
.GetString().c_str());
5753 return total_shards
> 1;
5756 // Parses the environment variable var as an Int32. If it is unset,
5757 // returns default_val. If it is not an Int32, prints an error
5759 Int32
Int32FromEnvOrDie(const char* var
, Int32 default_val
) {
5760 const char* str_val
= posix::GetEnv(var
);
5761 if (str_val
== NULL
) {
5766 if (!ParseInt32(Message() << "The value of environment variable " << var
,
5767 str_val
, &result
)) {
5773 // Given the total number of shards, the shard index, and the test id,
5774 // returns true iff the test should be run on this shard. The test id is
5775 // some arbitrary but unique non-negative integer assigned to each test
5776 // method. Assumes that 0 <= shard_index < total_shards.
5777 bool ShouldRunTestOnShard(int total_shards
, int shard_index
, int test_id
) {
5778 return (test_id
% total_shards
) == shard_index
;
5781 // Compares the name of each test with the user-specified filter to
5782 // decide whether the test should be run, then records the result in
5783 // each TestCase and TestInfo object.
5784 // If shard_tests == true, further filters tests based on sharding
5785 // variables in the environment - see
5786 // http://code.google.com/p/googletest/wiki/GoogleTestAdvancedGuide.
5787 // Returns the number of tests that should run.
5788 int UnitTestImpl::FilterTests(ReactionToSharding shard_tests
) {
5789 const Int32 total_shards
= shard_tests
== HONOR_SHARDING_PROTOCOL
5790 ? Int32FromEnvOrDie(kTestTotalShards
, -1)
5792 const Int32 shard_index
= shard_tests
== HONOR_SHARDING_PROTOCOL
5793 ? Int32FromEnvOrDie(kTestShardIndex
, -1)
5796 // num_runnable_tests are the number of tests that will
5797 // run across all shards (i.e., match filter and are not disabled).
5798 // num_selected_tests are the number of tests to be run on
5800 int num_runnable_tests
= 0;
5801 int num_selected_tests
= 0;
5802 for (size_t i
= 0; i
< test_cases_
.size(); i
++) {
5803 TestCase
* const test_case
= test_cases_
[i
];
5804 const std::string
& test_case_name
= test_case
->name();
5805 test_case
->set_should_run(false);
5807 for (size_t j
= 0; j
< test_case
->test_info_list().size(); j
++) {
5808 TestInfo
* const test_info
= test_case
->test_info_list()[j
];
5809 const std::string
test_name(test_info
->name());
5810 // A test is disabled if test case name or test name matches
5811 // kDisableTestFilter.
5812 const bool is_disabled
= internal::UnitTestOptions::MatchesFilter(
5813 test_case_name
, kDisableTestFilter
) ||
5814 internal::UnitTestOptions::MatchesFilter(
5815 test_name
, kDisableTestFilter
);
5816 test_info
->is_disabled_
= is_disabled
;
5818 const bool matches_filter
= internal::UnitTestOptions::FilterMatchesTest(
5819 test_case_name
, test_name
);
5820 test_info
->matches_filter_
= matches_filter
;
5822 const bool is_runnable
=
5823 (GTEST_FLAG(also_run_disabled_tests
) || !is_disabled
) &&
5826 const bool is_selected
=
5828 (shard_tests
== IGNORE_SHARDING_PROTOCOL
||
5829 ShouldRunTestOnShard(total_shards
, shard_index
, num_runnable_tests
));
5831 num_runnable_tests
+= is_runnable
;
5832 num_selected_tests
+= is_selected
;
5834 test_info
->should_run_
= is_selected
;
5835 test_case
->set_should_run(test_case
->should_run() || is_selected
);
5838 return num_selected_tests
;
5841 // Prints the given C-string on a single line by replacing all '\n'
5842 // characters with string "\\n". If the output takes more than
5843 // max_length characters, only prints the first max_length characters
5845 static void PrintOnOneLine(const char* str
, int max_length
) {
5847 for (int i
= 0; *str
!= '\0'; ++str
) {
5848 if (i
>= max_length
) {
5863 // Prints the names of the tests matching the user-specified filter flag.
5864 void UnitTestImpl::ListTestsMatchingFilter() {
5865 // Print at most this many characters for each type/value parameter.
5866 const int kMaxParamLength
= 250;
5868 for (size_t i
= 0; i
< test_cases_
.size(); i
++) {
5869 const TestCase
* const test_case
= test_cases_
[i
];
5870 bool printed_test_case_name
= false;
5872 for (size_t j
= 0; j
< test_case
->test_info_list().size(); j
++) {
5873 const TestInfo
* const test_info
= test_case
->test_info_list()[j
];
5874 if (test_info
->matches_filter_
) {
5875 if (!printed_test_case_name
) {
5876 printed_test_case_name
= true;
5877 printf("%s.", test_case
->name());
5878 if (test_case
->type_param() != NULL
) {
5879 printf(" # %s = ", kTypeParamLabel
);
5880 // We print the type parameter on a single line to make
5881 // the output easy to parse by a program.
5882 PrintOnOneLine(test_case
->type_param(), kMaxParamLength
);
5886 printf(" %s", test_info
->name());
5887 if (test_info
->value_param() != NULL
) {
5888 printf(" # %s = ", kValueParamLabel
);
5889 // We print the value parameter on a single line to make the
5890 // output easy to parse by a program.
5891 PrintOnOneLine(test_info
->value_param(), kMaxParamLength
);
5900 // Sets the OS stack trace getter.
5902 // Does nothing if the input and the current OS stack trace getter are
5903 // the same; otherwise, deletes the old getter and makes the input the
5905 void UnitTestImpl::set_os_stack_trace_getter(
5906 OsStackTraceGetterInterface
* getter
) {
5907 if (os_stack_trace_getter_
!= getter
) {
5908 delete os_stack_trace_getter_
;
5909 os_stack_trace_getter_
= getter
;
5913 // Returns the current OS stack trace getter if it is not NULL;
5914 // otherwise, creates an OsStackTraceGetter, makes it the current
5915 // getter, and returns it.
5916 OsStackTraceGetterInterface
* UnitTestImpl::os_stack_trace_getter() {
5917 if (os_stack_trace_getter_
== NULL
) {
5918 os_stack_trace_getter_
= new OsStackTraceGetter
;
5921 return os_stack_trace_getter_
;
5924 // Returns the TestResult for the test that's currently running, or
5925 // the TestResult for the ad hoc test if no test is running.
5926 TestResult
* UnitTestImpl::current_test_result() {
5927 return current_test_info_
? &(current_test_info_
->result_
)
5928 : &ad_hoc_test_result_
;
5931 // Shuffles all test cases, and the tests within each test case,
5932 // making sure that death tests are still run first.
5933 void UnitTestImpl::ShuffleTests() {
5934 // Shuffles the death test cases.
5935 ShuffleRange(random(), 0, last_death_test_case_
+ 1, &test_case_indices_
);
5937 // Shuffles the non-death test cases.
5938 ShuffleRange(random(), last_death_test_case_
+ 1,
5939 static_cast<int>(test_cases_
.size()), &test_case_indices_
);
5941 // Shuffles the tests inside each test case.
5942 for (size_t i
= 0; i
< test_cases_
.size(); i
++) {
5943 test_cases_
[i
]->ShuffleTests(random());
5947 // Restores the test cases and tests to their order before the first shuffle.
5948 void UnitTestImpl::UnshuffleTests() {
5949 for (size_t i
= 0; i
< test_cases_
.size(); i
++) {
5950 // Unshuffles the tests in each test case.
5951 test_cases_
[i
]->UnshuffleTests();
5952 // Resets the index of each test case.
5953 test_case_indices_
[i
] = static_cast<int>(i
);
5957 // Returns the current OS stack trace as an std::string.
5959 // The maximum number of stack frames to be included is specified by
5960 // the gtest_stack_trace_depth flag. The skip_count parameter
5961 // specifies the number of top frames to be skipped, which doesn't
5962 // count against the number of frames to be included.
5964 // For example, if Foo() calls Bar(), which in turn calls
5965 // GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in
5966 // the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.
5967 std::string
GetCurrentOsStackTraceExceptTop(UnitTest
* /*unit_test*/,
5969 // We pass skip_count + 1 to skip this wrapper function in addition
5970 // to what the user really wants to skip.
5971 return GetUnitTestImpl()->CurrentOsStackTraceExceptTop(skip_count
+ 1);
5974 // Used by the GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_ macro to
5975 // suppress unreachable code warnings.
5977 class ClassUniqueToAlwaysTrue
{};
5980 bool IsTrue(bool condition
) { return condition
; }
5983 #if GTEST_HAS_EXCEPTIONS
5984 // This condition is always false so AlwaysTrue() never actually throws,
5985 // but it makes the compiler think that it may throw.
5986 if (IsTrue(false)) throw ClassUniqueToAlwaysTrue();
5987 #endif // GTEST_HAS_EXCEPTIONS
5991 // If *pstr starts with the given prefix, modifies *pstr to be right
5992 // past the prefix and returns true; otherwise leaves *pstr unchanged
5993 // and returns false. None of pstr, *pstr, and prefix can be NULL.
5994 bool SkipPrefix(const char* prefix
, const char** pstr
) {
5995 const size_t prefix_len
= strlen(prefix
);
5996 if (strncmp(*pstr
, prefix
, prefix_len
) == 0) {
5997 *pstr
+= prefix_len
;
6003 // Parses a string as a command line flag. The string should have
6004 // the format "--flag=value". When def_optional is true, the "=value"
6005 // part can be omitted.
6007 // Returns the value of the flag, or NULL if the parsing failed.
6008 const char* ParseFlagValue(const char* str
, const char* flag
,
6009 bool def_optional
) {
6010 // str and flag must not be NULL.
6011 if (str
== NULL
|| flag
== NULL
) return NULL
;
6013 // The flag must start with "--" followed by GTEST_FLAG_PREFIX_.
6014 const std::string flag_str
= std::string("--") + GTEST_FLAG_PREFIX_
+ flag
;
6015 const size_t flag_len
= flag_str
.length();
6016 if (strncmp(str
, flag_str
.c_str(), flag_len
) != 0) return NULL
;
6018 // Skips the flag name.
6019 const char* flag_end
= str
+ flag_len
;
6021 // When def_optional is true, it's OK to not have a "=value" part.
6022 if (def_optional
&& (flag_end
[0] == '\0')) {
6026 // If def_optional is true and there are more characters after the
6027 // flag name, or if def_optional is false, there must be a '=' after
6029 if (flag_end
[0] != '=') return NULL
;
6031 // Returns the string after "=".
6032 return flag_end
+ 1;
6035 // Parses a string for a bool flag, in the form of either
6036 // "--flag=value" or "--flag".
6038 // In the former case, the value is taken as true as long as it does
6039 // not start with '0', 'f', or 'F'.
6041 // In the latter case, the value is taken as true.
6043 // On success, stores the value of the flag in *value, and returns
6044 // true. On failure, returns false without changing *value.
6045 bool ParseBoolFlag(const char* str
, const char* flag
, bool* value
) {
6046 // Gets the value of the flag as a string.
6047 const char* const value_str
= ParseFlagValue(str
, flag
, true);
6049 // Aborts if the parsing failed.
6050 if (value_str
== NULL
) return false;
6052 // Converts the string value to a bool.
6053 *value
= !(*value_str
== '0' || *value_str
== 'f' || *value_str
== 'F');
6057 // Parses a string for an Int32 flag, in the form of
6060 // On success, stores the value of the flag in *value, and returns
6061 // true. On failure, returns false without changing *value.
6062 bool ParseInt32Flag(const char* str
, const char* flag
, Int32
* value
) {
6063 // Gets the value of the flag as a string.
6064 const char* const value_str
= ParseFlagValue(str
, flag
, false);
6066 // Aborts if the parsing failed.
6067 if (value_str
== NULL
) return false;
6069 // Sets *value to the value of the flag.
6070 return ParseInt32(Message() << "The value of flag --" << flag
, value_str
,
6074 // Parses a string for a string flag, in the form of
6077 // On success, stores the value of the flag in *value, and returns
6078 // true. On failure, returns false without changing *value.
6079 bool ParseStringFlag(const char* str
, const char* flag
, std::string
* value
) {
6080 // Gets the value of the flag as a string.
6081 const char* const value_str
= ParseFlagValue(str
, flag
, false);
6083 // Aborts if the parsing failed.
6084 if (value_str
== NULL
) return false;
6086 // Sets *value to the value of the flag.
6091 // Determines whether a string has a prefix that Google Test uses for its
6092 // flags, i.e., starts with GTEST_FLAG_PREFIX_ or GTEST_FLAG_PREFIX_DASH_.
6093 // If Google Test detects that a command line flag has its prefix but is not
6094 // recognized, it will print its help message. Flags starting with
6095 // GTEST_INTERNAL_PREFIX_ followed by "internal_" are considered Google Test
6096 // internal flags and do not trigger the help message.
6097 static bool HasGoogleTestFlagPrefix(const char* str
) {
6098 return (SkipPrefix("--", &str
) || SkipPrefix("-", &str
) ||
6099 SkipPrefix("/", &str
)) &&
6100 !SkipPrefix(GTEST_FLAG_PREFIX_
"internal_", &str
) &&
6101 (SkipPrefix(GTEST_FLAG_PREFIX_
, &str
) ||
6102 SkipPrefix(GTEST_FLAG_PREFIX_DASH_
, &str
));
6105 // Prints a string containing code-encoded text. The following escape
6106 // sequences can be used in the string to control the text color:
6108 // @@ prints a single '@' character.
6109 // @R changes the color to red.
6110 // @G changes the color to green.
6111 // @Y changes the color to yellow.
6112 // @D changes to the default terminal text color.
6114 // TODO(wan@google.com): Write tests for this once we add stdout
6115 // capturing to Google Test.
6116 static void PrintColorEncoded(const char* str
) {
6117 GTestColor color
= COLOR_DEFAULT
; // The current color.
6119 // Conceptually, we split the string into segments divided by escape
6120 // sequences. Then we print one segment at a time. At the end of
6121 // each iteration, the str pointer advances to the beginning of the
6124 const char* p
= strchr(str
, '@');
6126 ColoredPrintf(color
, "%s", str
);
6130 ColoredPrintf(color
, "%s", std::string(str
, p
).c_str());
6132 const char ch
= p
[1];
6135 ColoredPrintf(color
, "@");
6136 } else if (ch
== 'D') {
6137 color
= COLOR_DEFAULT
;
6138 } else if (ch
== 'R') {
6140 } else if (ch
== 'G') {
6141 color
= COLOR_GREEN
;
6142 } else if (ch
== 'Y') {
6143 color
= COLOR_YELLOW
;
6150 static const char kColorEncodedHelpMessage
[] =
6151 "This program contains tests written using " GTEST_NAME_
6152 ". You can use the\n"
6153 "following command line flags to control its behavior:\n"
6156 " @G--" GTEST_FLAG_PREFIX_
6158 " List the names of all tests instead of running them. The name of\n"
6159 " TEST(Foo, Bar) is \"Foo.Bar\".\n"
6160 " @G--" GTEST_FLAG_PREFIX_
6161 "filter=@YPOSTIVE_PATTERNS"
6162 "[@G-@YNEGATIVE_PATTERNS]@D\n"
6163 " Run only the tests whose name matches one of the positive patterns "
6165 " none of the negative patterns. '?' matches any single character; "
6167 " matches any substring; ':' separates two patterns.\n"
6168 " @G--" GTEST_FLAG_PREFIX_
6169 "also_run_disabled_tests@D\n"
6170 " Run all disabled tests too.\n"
6173 " @G--" GTEST_FLAG_PREFIX_
6174 "repeat=@Y[COUNT]@D\n"
6175 " Run the tests repeatedly; use a negative count to repeat forever.\n"
6176 " @G--" GTEST_FLAG_PREFIX_
6178 " Randomize tests' orders on every iteration.\n"
6179 " @G--" GTEST_FLAG_PREFIX_
6180 "random_seed=@Y[NUMBER]@D\n"
6181 " Random number seed to use for shuffling test orders (between 1 and\n"
6182 " 99999, or 0 to use a seed based on the current time).\n"
6185 " @G--" GTEST_FLAG_PREFIX_
6186 "color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\n"
6187 " Enable/disable colored output. The default is @Gauto@D.\n"
6188 " -@G-" GTEST_FLAG_PREFIX_
6190 " Don't print the elapsed time of each test.\n"
6191 " @G--" GTEST_FLAG_PREFIX_
6192 "output=xml@Y[@G:@YDIRECTORY_PATH@G" GTEST_PATH_SEP_
6193 "@Y|@G:@YFILE_PATH]@D\n"
6194 " Generate an XML report in the given directory or with the given "
6196 " name. @YFILE_PATH@D defaults to @Gtest_details.xml@D.\n"
6197 #if GTEST_CAN_STREAM_RESULTS_
6198 " @G--" GTEST_FLAG_PREFIX_
6199 "stream_result_to=@YHOST@G:@YPORT@D\n"
6200 " Stream test results to the given server.\n"
6201 #endif // GTEST_CAN_STREAM_RESULTS_
6203 "Assertion Behavior:\n"
6204 #if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
6205 " @G--" GTEST_FLAG_PREFIX_
6206 "death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n"
6207 " Set the default death test style.\n"
6208 #endif // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
6209 " @G--" GTEST_FLAG_PREFIX_
6210 "break_on_failure@D\n"
6211 " Turn assertion failures into debugger break-points.\n"
6212 " @G--" GTEST_FLAG_PREFIX_
6213 "throw_on_failure@D\n"
6214 " Turn assertion failures into C++ exceptions.\n"
6215 " @G--" GTEST_FLAG_PREFIX_
6216 "catch_exceptions=0@D\n"
6217 " Do not report exceptions as test failures. Instead, allow them\n"
6218 " to crash the program or throw a pop-up (on Windows).\n"
6220 "Except for @G--" GTEST_FLAG_PREFIX_
6221 "list_tests@D, you can alternatively set "
6222 "the corresponding\n"
6223 "environment variable of a flag (all letters in upper-case). For example, "
6225 "disable colored text output, you can either specify "
6226 "@G--" GTEST_FLAG_PREFIX_
6227 "color=no@D or set\n"
6228 "the @G" GTEST_FLAG_PREFIX_UPPER_
6229 "COLOR@D environment variable to @Gno@D.\n"
6231 "For more information, please read the " GTEST_NAME_
6232 " documentation at\n"
6233 "@G" GTEST_PROJECT_URL_
"@D. If you find a bug in " GTEST_NAME_
6235 "(not one in your own code or tests), please report it to\n"
6236 "@G<" GTEST_DEV_EMAIL_
">@D.\n";
6238 // Parses the command line for Google Test flags, without initializing
6239 // other parts of Google Test. The type parameter CharType can be
6240 // instantiated to either char or wchar_t.
6241 template <typename CharType
>
6242 void ParseGoogleTestFlagsOnlyImpl(int* argc
, CharType
** argv
) {
6243 for (int i
= 1; i
< *argc
; i
++) {
6244 const std::string arg_string
= StreamableToString(argv
[i
]);
6245 const char* const arg
= arg_string
.c_str();
6247 using internal::ParseBoolFlag
;
6248 using internal::ParseInt32Flag
;
6249 using internal::ParseStringFlag
;
6251 // Do we see a Google Test flag?
6252 if (ParseBoolFlag(arg
, kAlsoRunDisabledTestsFlag
,
6253 >EST_FLAG(also_run_disabled_tests
)) ||
6254 ParseBoolFlag(arg
, kBreakOnFailureFlag
,
6255 >EST_FLAG(break_on_failure
)) ||
6256 ParseBoolFlag(arg
, kCatchExceptionsFlag
,
6257 >EST_FLAG(catch_exceptions
)) ||
6258 ParseStringFlag(arg
, kColorFlag
, >EST_FLAG(color
)) ||
6259 ParseStringFlag(arg
, kDeathTestStyleFlag
,
6260 >EST_FLAG(death_test_style
)) ||
6261 ParseBoolFlag(arg
, kDeathTestUseFork
,
6262 >EST_FLAG(death_test_use_fork
)) ||
6263 ParseStringFlag(arg
, kFilterFlag
, >EST_FLAG(filter
)) ||
6264 ParseStringFlag(arg
, kInternalRunDeathTestFlag
,
6265 >EST_FLAG(internal_run_death_test
)) ||
6266 ParseBoolFlag(arg
, kListTestsFlag
, >EST_FLAG(list_tests
)) ||
6267 ParseStringFlag(arg
, kOutputFlag
, >EST_FLAG(output
)) ||
6268 ParseBoolFlag(arg
, kPrintTimeFlag
, >EST_FLAG(print_time
)) ||
6269 ParseInt32Flag(arg
, kRandomSeedFlag
, >EST_FLAG(random_seed
)) ||
6270 ParseInt32Flag(arg
, kRepeatFlag
, >EST_FLAG(repeat
)) ||
6271 ParseBoolFlag(arg
, kShuffleFlag
, >EST_FLAG(shuffle
)) ||
6272 ParseInt32Flag(arg
, kStackTraceDepthFlag
,
6273 >EST_FLAG(stack_trace_depth
)) ||
6274 ParseStringFlag(arg
, kStreamResultToFlag
,
6275 >EST_FLAG(stream_result_to
)) ||
6276 ParseBoolFlag(arg
, kThrowOnFailureFlag
,
6277 >EST_FLAG(throw_on_failure
))) {
6278 // Yes. Shift the remainder of the argv list left by one. Note
6279 // that argv has (*argc + 1) elements, the last one always being
6280 // NULL. The following loop moves the trailing NULL element as
6282 for (int j
= i
; j
!= *argc
; j
++) {
6283 argv
[j
] = argv
[j
+ 1];
6286 // Decrements the argument count.
6289 // We also need to decrement the iterator as we just removed
6292 } else if (arg_string
== "--help" || arg_string
== "-h" ||
6293 arg_string
== "-?" || arg_string
== "/?" ||
6294 HasGoogleTestFlagPrefix(arg
)) {
6295 // Both help flag and unrecognized Google Test flags (excluding
6296 // internal ones) trigger help display.
6302 // We print the help here instead of in RUN_ALL_TESTS(), as the
6303 // latter may not be called at all if the user is using Google
6304 // Test with another testing framework.
6305 PrintColorEncoded(kColorEncodedHelpMessage
);
6309 // Parses the command line for Google Test flags, without initializing
6310 // other parts of Google Test.
6311 void ParseGoogleTestFlagsOnly(int* argc
, char** argv
) {
6312 ParseGoogleTestFlagsOnlyImpl(argc
, argv
);
6314 void ParseGoogleTestFlagsOnly(int* argc
, wchar_t** argv
) {
6315 ParseGoogleTestFlagsOnlyImpl(argc
, argv
);
6318 // The internal implementation of InitGoogleTest().
6320 // The type parameter CharType can be instantiated to either char or
6322 template <typename CharType
>
6323 void InitGoogleTestImpl(int* argc
, CharType
** argv
) {
6324 g_init_gtest_count
++;
6326 // We don't want to run the initialization code twice.
6327 if (g_init_gtest_count
!= 1) return;
6329 if (*argc
<= 0) return;
6331 internal::g_executable_path
= internal::StreamableToString(argv
[0]);
6333 #if GTEST_HAS_DEATH_TEST
6336 for (int i
= 0; i
!= *argc
; i
++) {
6337 g_argvs
.push_back(StreamableToString(argv
[i
]));
6340 #endif // GTEST_HAS_DEATH_TEST
6342 ParseGoogleTestFlagsOnly(argc
, argv
);
6343 GetUnitTestImpl()->PostFlagParsingInit();
6346 } // namespace internal
6348 // Initializes Google Test. This must be called before calling
6349 // RUN_ALL_TESTS(). In particular, it parses a command line for the
6350 // flags that Google Test recognizes. Whenever a Google Test flag is
6351 // seen, it is removed from argv, and *argc is decremented.
6353 // No value is returned. Instead, the Google Test flag variables are
6356 // Calling the function for the second time has no user-visible effect.
6357 void InitGoogleTest(int* argc
, char** argv
) {
6358 internal::InitGoogleTestImpl(argc
, argv
);
6361 // This overloaded version can be used in Windows programs compiled in
6363 void InitGoogleTest(int* argc
, wchar_t** argv
) {
6364 internal::InitGoogleTestImpl(argc
, argv
);
6367 } // namespace testing
6368 // Copyright 2005, Google Inc.
6369 // All rights reserved.
6371 // Redistribution and use in source and binary forms, with or without
6372 // modification, are permitted provided that the following conditions are
6375 // * Redistributions of source code must retain the above copyright
6376 // notice, this list of conditions and the following disclaimer.
6377 // * Redistributions in binary form must reproduce the above
6378 // copyright notice, this list of conditions and the following disclaimer
6379 // in the documentation and/or other materials provided with the
6381 // * Neither the name of Google Inc. nor the names of its
6382 // contributors may be used to endorse or promote products derived from
6383 // this software without specific prior written permission.
6385 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
6386 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
6387 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
6388 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
6389 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
6390 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
6391 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
6392 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
6393 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
6394 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
6395 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
6397 // Author: wan@google.com (Zhanyong Wan), vladl@google.com (Vlad Losev)
6399 // This file implements death tests.
6401 #if GTEST_HAS_DEATH_TEST
6404 # include <crt_externs.h>
6405 # endif // GTEST_OS_MAC
6409 # include <limits.h>
6412 # include <signal.h>
6413 # endif // GTEST_OS_LINUX
6415 # include <stdarg.h>
6417 # if GTEST_OS_WINDOWS
6418 # include <windows.h>
6420 # include <sys/mman.h>
6421 # include <sys/wait.h>
6422 # endif // GTEST_OS_WINDOWS
6426 # endif // GTEST_OS_QNX
6428 #endif // GTEST_HAS_DEATH_TEST
6430 // Indicates that this translation unit is part of Google Test's
6431 // implementation. It must come before gtest-internal-inl.h is
6432 // included, or there will be a compiler error. This trick is to
6433 // prevent a user from accidentally including gtest-internal-inl.h in
6435 #define GTEST_IMPLEMENTATION_ 1
6436 #undef GTEST_IMPLEMENTATION_
6442 // The default death test style.
6443 static const char kDefaultDeathTestStyle
[] = "fast";
6445 GTEST_DEFINE_string_(
6447 internal::StringFromGTestEnv("death_test_style", kDefaultDeathTestStyle
),
6448 "Indicates how to run a death test in a forked child process: "
6449 "\"threadsafe\" (child process re-executes the test binary "
6450 "from the beginning, running only the specific death test) or "
6451 "\"fast\" (child process runs the death test immediately "
6455 death_test_use_fork
,
6456 internal::BoolFromGTestEnv("death_test_use_fork", false),
6457 "Instructs to use fork()/_exit() instead of clone() in death tests. "
6458 "Ignored and always uses fork() on POSIX systems where clone() is not "
6459 "implemented. Useful when running under valgrind or similar tools if "
6460 "those do not support clone(). Valgrind 3.3.1 will just fail if "
6461 "it sees an unsupported combination of clone() flags. "
6462 "It is not recommended to use this flag w/o valgrind though it will "
6463 "work in 99% of the cases. Once valgrind is fixed, this flag will "
6464 "most likely be removed.");
6466 namespace internal
{
6467 GTEST_DEFINE_string_(
6468 internal_run_death_test
, "",
6469 "Indicates the file, line number, temporal index of "
6470 "the single death test to run, and a file descriptor to "
6471 "which a success code may be sent, all separated by "
6472 "the '|' characters. This flag is specified if and only if the current "
6473 "process is a sub-process launched for running a thread-safe "
6474 "death test. FOR INTERNAL USE ONLY.");
6475 } // namespace internal
6477 #if GTEST_HAS_DEATH_TEST
6479 namespace internal
{
6481 // Valid only for fast death tests. Indicates the code is running in the
6482 // child process of a fast style death test.
6483 static bool g_in_fast_death_test_child
= false;
6485 // Returns a Boolean value indicating whether the caller is currently
6486 // executing in the context of the death test child process. Tools such as
6487 // Valgrind heap checkers may need this to modify their behavior in death
6488 // tests. IMPORTANT: This is an internal utility. Using it may break the
6489 // implementation of death tests. User code MUST NOT use it.
6490 bool InDeathTestChild() {
6491 # if GTEST_OS_WINDOWS
6493 // On Windows, death tests are thread-safe regardless of the value of the
6494 // death_test_style flag.
6495 return !GTEST_FLAG(internal_run_death_test
).empty();
6499 if (GTEST_FLAG(death_test_style
) == "threadsafe")
6500 return !GTEST_FLAG(internal_run_death_test
).empty();
6502 return g_in_fast_death_test_child
;
6506 } // namespace internal
6508 // ExitedWithCode constructor.
6509 ExitedWithCode::ExitedWithCode(int exit_code
) : exit_code_(exit_code
) {}
6511 // ExitedWithCode function-call operator.
6512 bool ExitedWithCode::operator()(int exit_status
) const {
6513 # if GTEST_OS_WINDOWS
6515 return exit_status
== exit_code_
;
6519 return WIFEXITED(exit_status
) && WEXITSTATUS(exit_status
) == exit_code_
;
6521 # endif // GTEST_OS_WINDOWS
6524 # if !GTEST_OS_WINDOWS
6525 // KilledBySignal constructor.
6526 KilledBySignal::KilledBySignal(int signum
) : signum_(signum
) {}
6528 // KilledBySignal function-call operator.
6529 bool KilledBySignal::operator()(int exit_status
) const {
6530 return WIFSIGNALED(exit_status
) && WTERMSIG(exit_status
) == signum_
;
6532 # endif // !GTEST_OS_WINDOWS
6534 namespace internal
{
6536 // Utilities needed for death tests.
6538 // Generates a textual description of a given exit code, in the format
6539 // specified by wait(2).
6540 static std::string
ExitSummary(int exit_code
) {
6543 # if GTEST_OS_WINDOWS
6545 m
<< "Exited with exit status " << exit_code
;
6549 if (WIFEXITED(exit_code
)) {
6550 m
<< "Exited with exit status " << WEXITSTATUS(exit_code
);
6551 } else if (WIFSIGNALED(exit_code
)) {
6552 m
<< "Terminated by signal " << WTERMSIG(exit_code
);
6555 if (WCOREDUMP(exit_code
)) {
6556 m
<< " (core dumped)";
6559 # endif // GTEST_OS_WINDOWS
6561 return m
.GetString();
6564 // Returns true if exit_status describes a process that was terminated
6565 // by a signal, or exited normally with a nonzero exit code.
6566 bool ExitedUnsuccessfully(int exit_status
) {
6567 return !ExitedWithCode(0)(exit_status
);
6570 # if !GTEST_OS_WINDOWS
6571 // Generates a textual failure message when a death test finds more than
6572 // one thread running, or cannot determine the number of threads, prior
6573 // to executing the given statement. It is the responsibility of the
6574 // caller not to pass a thread_count of 1.
6575 static std::string
DeathTestThreadWarning(size_t thread_count
) {
6577 msg
<< "Death tests use fork(), which is unsafe particularly"
6578 << " in a threaded context. For this test, " << GTEST_NAME_
<< " ";
6579 if (thread_count
== 0)
6580 msg
<< "couldn't detect the number of threads.";
6582 msg
<< "detected " << thread_count
<< " threads.";
6583 return msg
.GetString();
6585 # endif // !GTEST_OS_WINDOWS
6587 // Flag characters for reporting a death test that did not die.
6588 static const char kDeathTestLived
= 'L';
6589 static const char kDeathTestReturned
= 'R';
6590 static const char kDeathTestThrew
= 'T';
6591 static const char kDeathTestInternalError
= 'I';
6593 // An enumeration describing all of the possible ways that a death test can
6594 // conclude. DIED means that the process died while executing the test
6595 // code; LIVED means that process lived beyond the end of the test code;
6596 // RETURNED means that the test statement attempted to execute a return
6597 // statement, which is not allowed; THREW means that the test statement
6598 // returned control by throwing an exception. IN_PROGRESS means the test
6599 // has not yet concluded.
6600 // TODO(vladl@google.com): Unify names and possibly values for
6601 // AbortReason, DeathTestOutcome, and flag characters above.
6602 enum DeathTestOutcome
{ IN_PROGRESS
, DIED
, LIVED
, RETURNED
, THREW
};
6604 // Routine for aborting the program which is safe to call from an
6605 // exec-style death test child process, in which case the error
6606 // message is propagated back to the parent process. Otherwise, the
6607 // message is simply printed to stderr. In either case, the program
6608 // then exits with status 1.
6609 void DeathTestAbort(const std::string
& message
) {
6610 // On a POSIX system, this function may be called from a threadsafe-style
6611 // death test child process, which operates on a very small stack. Use
6612 // the heap for any additional non-minuscule memory requirements.
6613 const InternalRunDeathTestFlag
* const flag
=
6614 GetUnitTestImpl()->internal_run_death_test_flag();
6616 FILE* parent
= posix::FDOpen(flag
->write_fd(), "w");
6617 fputc(kDeathTestInternalError
, parent
);
6618 fprintf(parent
, "%s", message
.c_str());
6622 fprintf(stderr
, "%s", message
.c_str());
6628 // A replacement for CHECK that calls DeathTestAbort if the assertion
6630 # define GTEST_DEATH_TEST_CHECK_(expression) \
6632 if (!::testing::internal::IsTrue(expression)) { \
6633 DeathTestAbort(::std::string("CHECK failed: File ") + __FILE__ + \
6635 ::testing::internal::StreamableToString(__LINE__) + \
6636 ": " + #expression); \
6638 } while (::testing::internal::AlwaysFalse())
6640 // This macro is similar to GTEST_DEATH_TEST_CHECK_, but it is meant for
6641 // evaluating any system call that fulfills two conditions: it must return
6642 // -1 on failure, and set errno to EINTR when it is interrupted and
6643 // should be tried again. The macro expands to a loop that repeatedly
6644 // evaluates the expression as long as it evaluates to -1 and sets
6645 // errno to EINTR. If the expression evaluates to -1 but errno is
6646 // something other than EINTR, DeathTestAbort is called.
6647 # define GTEST_DEATH_TEST_CHECK_SYSCALL_(expression) \
6651 gtest_retval = (expression); \
6652 } while (gtest_retval == -1 && errno == EINTR); \
6653 if (gtest_retval == -1) { \
6654 DeathTestAbort(::std::string("CHECK failed: File ") + __FILE__ + \
6656 ::testing::internal::StreamableToString(__LINE__) + \
6657 ": " + #expression + " != -1"); \
6659 } while (::testing::internal::AlwaysFalse())
6661 // Returns the message describing the last system error in errno.
6662 std::string
GetLastErrnoDescription() {
6663 return errno
== 0 ? "" : posix::StrError(errno
);
6666 // This is called from a death test parent process to read a failure
6667 // message from the death test child process and log it with the FATAL
6668 // severity. On Windows, the message is read from a pipe handle. On other
6669 // platforms, it is read from a file descriptor.
6670 static void FailFromInternalError(int fd
) {
6676 while ((num_read
= posix::Read(fd
, buffer
, 255)) > 0) {
6677 buffer
[num_read
] = '\0';
6680 } while (num_read
== -1 && errno
== EINTR
);
6682 if (num_read
== 0) {
6683 GTEST_LOG_(FATAL
) << error
.GetString();
6685 const int last_error
= errno
;
6686 GTEST_LOG_(FATAL
) << "Error while reading death test internal: "
6687 << GetLastErrnoDescription() << " [" << last_error
<< "]";
6691 // Death test constructor. Increments the running death test count
6692 // for the current test.
6693 DeathTest::DeathTest() {
6694 TestInfo
* const info
= GetUnitTestImpl()->current_test_info();
6697 "Cannot run a death test outside of a TEST or "
6698 "TEST_F construct");
6702 // Creates and returns a death test by dispatching to the current
6703 // death test factory.
6704 bool DeathTest::Create(const char* statement
, const RE
* regex
, const char* file
,
6705 int line
, DeathTest
** test
) {
6706 return GetUnitTestImpl()->death_test_factory()->Create(statement
, regex
, file
,
6710 const char* DeathTest::LastMessage() {
6711 return last_death_test_message_
.c_str();
6714 void DeathTest::set_last_death_test_message(const std::string
& message
) {
6715 last_death_test_message_
= message
;
6718 std::string
DeathTest::last_death_test_message_
;
6720 // Provides cross platform implementation for some death functionality.
6721 class DeathTestImpl
: public DeathTest
{
6723 DeathTestImpl(const char* a_statement
, const RE
* a_regex
)
6724 : statement_(a_statement
),
6728 outcome_(IN_PROGRESS
),
6732 // read_fd_ is expected to be closed and cleared by a derived class.
6733 ~DeathTestImpl() { GTEST_DEATH_TEST_CHECK_(read_fd_
== -1); }
6735 void Abort(AbortReason reason
);
6736 virtual bool Passed(bool status_ok
);
6738 const char* statement() const { return statement_
; }
6739 const RE
* regex() const { return regex_
; }
6740 bool spawned() const { return spawned_
; }
6741 void set_spawned(bool is_spawned
) { spawned_
= is_spawned
; }
6742 int status() const { return status_
; }
6743 void set_status(int a_status
) { status_
= a_status
; }
6744 DeathTestOutcome
outcome() const { return outcome_
; }
6745 void set_outcome(DeathTestOutcome an_outcome
) { outcome_
= an_outcome
; }
6746 int read_fd() const { return read_fd_
; }
6747 void set_read_fd(int fd
) { read_fd_
= fd
; }
6748 int write_fd() const { return write_fd_
; }
6749 void set_write_fd(int fd
) { write_fd_
= fd
; }
6751 // Called in the parent process only. Reads the result code of the death
6752 // test child process via a pipe, interprets it to set the outcome_
6753 // member, and closes read_fd_. Outputs diagnostics and terminates in
6754 // case of unexpected codes.
6755 void ReadAndInterpretStatusByte();
6758 // The textual content of the code this object is testing. This class
6759 // doesn't own this string and should not attempt to delete it.
6760 const char* const statement_
;
6761 // The regular expression which test output must match. DeathTestImpl
6762 // doesn't own this object and should not attempt to delete it.
6763 const RE
* const regex_
;
6764 // True if the death test child process has been successfully spawned.
6766 // The exit status of the child process.
6768 // How the death test concluded.
6769 DeathTestOutcome outcome_
;
6770 // Descriptor to the read end of the pipe to the child process. It is
6771 // always -1 in the child process. The child keeps its write end of the
6772 // pipe in write_fd_.
6774 // Descriptor to the child's write end of the pipe to the parent process.
6775 // It is always -1 in the parent process. The parent keeps its end of the
6776 // pipe in read_fd_.
6780 // Called in the parent process only. Reads the result code of the death
6781 // test child process via a pipe, interprets it to set the outcome_
6782 // member, and closes read_fd_. Outputs diagnostics and terminates in
6783 // case of unexpected codes.
6784 void DeathTestImpl::ReadAndInterpretStatusByte() {
6788 // The read() here blocks until data is available (signifying the
6789 // failure of the death test) or until the pipe is closed (signifying
6790 // its success), so it's okay to call this in the parent before
6791 // the child process has exited.
6793 bytes_read
= posix::Read(read_fd(), &flag
, 1);
6794 } while (bytes_read
== -1 && errno
== EINTR
);
6796 if (bytes_read
== 0) {
6798 } else if (bytes_read
== 1) {
6800 case kDeathTestReturned
:
6801 set_outcome(RETURNED
);
6803 case kDeathTestThrew
:
6806 case kDeathTestLived
:
6809 case kDeathTestInternalError
:
6810 FailFromInternalError(read_fd()); // Does not return.
6813 GTEST_LOG_(FATAL
) << "Death test child process reported "
6814 << "unexpected status byte ("
6815 << static_cast<unsigned int>(flag
) << ")";
6818 GTEST_LOG_(FATAL
) << "Read from death test child process failed: "
6819 << GetLastErrnoDescription();
6821 GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Close(read_fd()));
6825 // Signals that the death test code which should have exited, didn't.
6826 // Should be called only in a death test child process.
6827 // Writes a status byte to the child's status file descriptor, then
6829 void DeathTestImpl::Abort(AbortReason reason
) {
6830 // The parent process considers the death test to be a failure if
6831 // it finds any data in our pipe. So, here we write a single flag byte
6832 // to the pipe, then exit.
6833 const char status_ch
= reason
== TEST_DID_NOT_DIE
6835 : reason
== TEST_THREW_EXCEPTION
6837 : kDeathTestReturned
;
6839 GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Write(write_fd(), &status_ch
, 1));
6840 // We are leaking the descriptor here because on some platforms (i.e.,
6841 // when built as Windows DLL), destructors of global objects will still
6842 // run after calling _exit(). On such systems, write_fd_ will be
6843 // indirectly closed from the destructor of UnitTestImpl, causing double
6844 // close if it is also closed here. On debug configurations, double close
6845 // may assert. As there are no in-process buffers to flush here, we are
6846 // relying on the OS to close the descriptor after the process terminates
6847 // when the destructors are not run.
6848 _exit(1); // Exits w/o any normal exit hooks (we were supposed to crash)
6851 // Returns an indented copy of stderr output for a death test.
6852 // This makes distinguishing death test output lines from regular log lines
6854 static ::std::string
FormatDeathTestOutput(const ::std::string
& output
) {
6856 for (size_t at
= 0;;) {
6857 const size_t line_end
= output
.find('\n', at
);
6858 ret
+= "[ DEATH ] ";
6859 if (line_end
== ::std::string::npos
) {
6860 ret
+= output
.substr(at
);
6863 ret
+= output
.substr(at
, line_end
+ 1 - at
);
6869 // Assesses the success or failure of a death test, using both private
6870 // members which have previously been set, and one argument:
6872 // Private data members:
6873 // outcome: An enumeration describing how the death test
6874 // concluded: DIED, LIVED, THREW, or RETURNED. The death test
6875 // fails in the latter three cases.
6876 // status: The exit status of the child process. On *nix, it is in the
6877 // in the format specified by wait(2). On Windows, this is the
6878 // value supplied to the ExitProcess() API or a numeric code
6879 // of the exception that terminated the program.
6880 // regex: A regular expression object to be applied to
6881 // the test's captured standard error output; the death test
6882 // fails if it does not match.
6885 // status_ok: true if exit_status is acceptable in the context of
6886 // this particular death test, which fails if it is false
6888 // Returns true iff all of the above conditions are met. Otherwise, the
6889 // first failing condition, in the order given above, is the one that is
6890 // reported. Also sets the last death test message string.
6891 bool DeathTestImpl::Passed(bool status_ok
) {
6892 if (!spawned()) return false;
6894 const std::string error_message
= GetCapturedStderr();
6896 bool success
= false;
6899 buffer
<< "Death test: " << statement() << "\n";
6900 switch (outcome()) {
6902 buffer
<< " Result: failed to die.\n"
6904 << FormatDeathTestOutput(error_message
);
6907 buffer
<< " Result: threw an exception.\n"
6909 << FormatDeathTestOutput(error_message
);
6912 buffer
<< " Result: illegal return in test statement.\n"
6914 << FormatDeathTestOutput(error_message
);
6918 const bool matched
= RE::PartialMatch(error_message
.c_str(), *regex());
6922 buffer
<< " Result: died but not with expected error.\n"
6923 << " Expected: " << regex()->pattern() << "\n"
6925 << FormatDeathTestOutput(error_message
);
6928 buffer
<< " Result: died but not with expected exit code:\n"
6929 << " " << ExitSummary(status()) << "\n"
6931 << FormatDeathTestOutput(error_message
);
6937 << "DeathTest::Passed somehow called before conclusion of test";
6940 DeathTest::set_last_death_test_message(buffer
.GetString());
6944 # if GTEST_OS_WINDOWS
6945 // WindowsDeathTest implements death tests on Windows. Due to the
6946 // specifics of starting new processes on Windows, death tests there are
6947 // always threadsafe, and Google Test considers the
6948 // --gtest_death_test_style=fast setting to be equivalent to
6949 // --gtest_death_test_style=threadsafe there.
6951 // A few implementation notes: Like the Linux version, the Windows
6952 // implementation uses pipes for child-to-parent communication. But due to
6953 // the specifics of pipes on Windows, some extra steps are required:
6955 // 1. The parent creates a communication pipe and stores handles to both
6957 // 2. The parent starts the child and provides it with the information
6958 // necessary to acquire the handle to the write end of the pipe.
6959 // 3. The child acquires the write end of the pipe and signals the parent
6960 // using a Windows event.
6961 // 4. Now the parent can release the write end of the pipe on its side. If
6962 // this is done before step 3, the object's reference count goes down to
6963 // 0 and it is destroyed, preventing the child from acquiring it. The
6964 // parent now has to release it, or read operations on the read end of
6965 // the pipe will not return when the child terminates.
6966 // 5. The parent reads child's output through the pipe (outcome code and
6967 // any possible error messages) from the pipe, and its stderr and then
6968 // determines whether to fail the test.
6970 // Note: to distinguish Win32 API calls from the local method and function
6971 // calls, the former are explicitly resolved in the global namespace.
6973 class WindowsDeathTest
: public DeathTestImpl
{
6975 WindowsDeathTest(const char* a_statement
, const RE
* a_regex
, const char* file
,
6977 : DeathTestImpl(a_statement
, a_regex
), file_(file
), line_(line
) {}
6979 // All of these virtual functions are inherited from DeathTest.
6981 virtual TestRole
AssumeRole();
6984 // The name of the file in which the death test is located.
6985 const char* const file_
;
6986 // The line number on which the death test is located.
6988 // Handle to the write end of the pipe to the child process.
6989 AutoHandle write_handle_
;
6990 // Child process handle.
6991 AutoHandle child_handle_
;
6992 // Event the child process uses to signal the parent that it has
6993 // acquired the handle to the write end of the pipe. After seeing this
6994 // event the parent can release its own handles to make sure its
6995 // ReadFile() calls return when the child terminates.
6996 AutoHandle event_handle_
;
6999 // Waits for the child in a death test to exit, returning its exit
7000 // status, or 0 if no child process exists. As a side effect, sets the
7001 // outcome data member.
7002 int WindowsDeathTest::Wait() {
7003 if (!spawned()) return 0;
7005 // Wait until the child either signals that it has acquired the write end
7006 // of the pipe or it dies.
7007 const HANDLE wait_handles
[2] = {child_handle_
.Get(), event_handle_
.Get()};
7008 switch (::WaitForMultipleObjects(2, wait_handles
,
7009 FALSE
, // Waits for any of the handles.
7012 case WAIT_OBJECT_0
+ 1:
7015 GTEST_DEATH_TEST_CHECK_(false); // Should not get here.
7018 // The child has acquired the write end of the pipe or exited.
7019 // We release the handle on our side and continue.
7020 write_handle_
.Reset();
7021 event_handle_
.Reset();
7023 ReadAndInterpretStatusByte();
7025 // Waits for the child process to exit if it haven't already. This
7026 // returns immediately if the child has already exited, regardless of
7027 // whether previous calls to WaitForMultipleObjects synchronized on this
7029 GTEST_DEATH_TEST_CHECK_(WAIT_OBJECT_0
==
7030 ::WaitForSingleObject(child_handle_
.Get(), INFINITE
));
7032 GTEST_DEATH_TEST_CHECK_(
7033 ::GetExitCodeProcess(child_handle_
.Get(), &status_code
) != FALSE
);
7034 child_handle_
.Reset();
7035 set_status(static_cast<int>(status_code
));
7039 // The AssumeRole process for a Windows death test. It creates a child
7040 // process with the same executable as the current process to run the
7041 // death test. The child process is given the --gtest_filter and
7042 // --gtest_internal_run_death_test flags such that it knows to run the
7043 // current death test only.
7044 DeathTest::TestRole
WindowsDeathTest::AssumeRole() {
7045 const UnitTestImpl
* const impl
= GetUnitTestImpl();
7046 const InternalRunDeathTestFlag
* const flag
=
7047 impl
->internal_run_death_test_flag();
7048 const TestInfo
* const info
= impl
->current_test_info();
7049 const int death_test_index
= info
->result()->death_test_count();
7052 // ParseInternalRunDeathTestFlag() has performed all the necessary
7054 set_write_fd(flag
->write_fd());
7055 return EXECUTE_TEST
;
7058 // WindowsDeathTest uses an anonymous pipe to communicate results of
7060 SECURITY_ATTRIBUTES handles_are_inheritable
= {sizeof(SECURITY_ATTRIBUTES
),
7062 HANDLE read_handle
, write_handle
;
7063 GTEST_DEATH_TEST_CHECK_(::CreatePipe(&read_handle
, &write_handle
,
7064 &handles_are_inheritable
,
7065 0) // Default buffer size.
7068 ::_open_osfhandle(reinterpret_cast<intptr_t>(read_handle
), O_RDONLY
));
7069 write_handle_
.Reset(write_handle
);
7070 event_handle_
.Reset(::CreateEvent(
7071 &handles_are_inheritable
,
7072 TRUE
, // The event will automatically reset to non-signaled state.
7073 FALSE
, // The initial state is non-signalled.
7074 NULL
)); // The even is unnamed.
7075 GTEST_DEATH_TEST_CHECK_(event_handle_
.Get() != NULL
);
7076 const std::string filter_flag
= std::string("--") + GTEST_FLAG_PREFIX_
+
7077 kFilterFlag
+ "=" + info
->test_case_name() +
7079 const std::string internal_flag
=
7080 std::string("--") + GTEST_FLAG_PREFIX_
+ kInternalRunDeathTestFlag
+ "=" +
7081 file_
+ "|" + StreamableToString(line_
) + "|" +
7082 StreamableToString(death_test_index
) + "|" +
7083 StreamableToString(static_cast<unsigned int>(::GetCurrentProcessId())) +
7084 // size_t has the same width as pointers on both 32-bit and 64-bit
7085 // Windows platforms.
7086 // See http://msdn.microsoft.com/en-us/library/tcxf1dw6.aspx.
7087 "|" + StreamableToString(reinterpret_cast<size_t>(write_handle
)) + "|" +
7088 StreamableToString(reinterpret_cast<size_t>(event_handle_
.Get()));
7090 char executable_path
[_MAX_PATH
+ 1]; // NOLINT
7091 GTEST_DEATH_TEST_CHECK_(
7092 _MAX_PATH
+ 1 != ::GetModuleFileNameA(NULL
, executable_path
, _MAX_PATH
));
7094 std::string command_line
= std::string(::GetCommandLineA()) + " " +
7095 filter_flag
+ " \"" + internal_flag
+ "\"";
7097 DeathTest::set_last_death_test_message("");
7100 // Flush the log buffers since the log streams are shared with the child.
7103 // The child process will share the standard handles with the parent.
7104 STARTUPINFOA startup_info
;
7105 memset(&startup_info
, 0, sizeof(STARTUPINFO
));
7106 startup_info
.dwFlags
= STARTF_USESTDHANDLES
;
7107 startup_info
.hStdInput
= ::GetStdHandle(STD_INPUT_HANDLE
);
7108 startup_info
.hStdOutput
= ::GetStdHandle(STD_OUTPUT_HANDLE
);
7109 startup_info
.hStdError
= ::GetStdHandle(STD_ERROR_HANDLE
);
7111 PROCESS_INFORMATION process_info
;
7112 GTEST_DEATH_TEST_CHECK_(
7114 executable_path
, const_cast<char*>(command_line
.c_str()),
7115 NULL
, // Retuned process handle is not inheritable.
7116 NULL
, // Retuned thread handle is not inheritable.
7117 TRUE
, // Child inherits all inheritable handles (for write_handle_).
7118 0x0, // Default creation flags.
7119 NULL
, // Inherit the parent's environment.
7120 UnitTest::GetInstance()->original_working_dir(), &startup_info
,
7121 &process_info
) != FALSE
);
7122 child_handle_
.Reset(process_info
.hProcess
);
7123 ::CloseHandle(process_info
.hThread
);
7125 return OVERSEE_TEST
;
7127 # else // We are not on Windows.
7129 // ForkingDeathTest provides implementations for most of the abstract
7130 // methods of the DeathTest interface. Only the AssumeRole method is
7132 class ForkingDeathTest
: public DeathTestImpl
{
7134 ForkingDeathTest(const char* statement
, const RE
* regex
);
7136 // All of these virtual functions are inherited from DeathTest.
7140 void set_child_pid(pid_t child_pid
) { child_pid_
= child_pid
; }
7143 // PID of child process during death test; 0 in the child process itself.
7147 // Constructs a ForkingDeathTest.
7148 ForkingDeathTest::ForkingDeathTest(const char* a_statement
, const RE
* a_regex
)
7149 : DeathTestImpl(a_statement
, a_regex
), child_pid_(-1) {}
7151 // Waits for the child in a death test to exit, returning its exit
7152 // status, or 0 if no child process exists. As a side effect, sets the
7153 // outcome data member.
7154 int ForkingDeathTest::Wait() {
7155 if (!spawned()) return 0;
7157 ReadAndInterpretStatusByte();
7160 GTEST_DEATH_TEST_CHECK_SYSCALL_(waitpid(child_pid_
, &status_value
, 0));
7161 set_status(status_value
);
7162 return status_value
;
7165 // A concrete death test class that forks, then immediately runs the test
7166 // in the child process.
7167 class NoExecDeathTest
: public ForkingDeathTest
{
7169 NoExecDeathTest(const char* a_statement
, const RE
* a_regex
)
7170 : ForkingDeathTest(a_statement
, a_regex
) {}
7171 virtual TestRole
AssumeRole();
7174 // The AssumeRole process for a fork-and-run death test. It implements a
7175 // straightforward fork, with a simple pipe to transmit the status byte.
7176 DeathTest::TestRole
NoExecDeathTest::AssumeRole() {
7177 const size_t thread_count
= GetThreadCount();
7178 if (thread_count
!= 1) {
7179 GTEST_LOG_(WARNING
) << DeathTestThreadWarning(thread_count
);
7183 GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd
) != -1);
7185 DeathTest::set_last_death_test_message("");
7187 // When we fork the process below, the log file buffers are copied, but the
7188 // file descriptors are shared. We flush all log files here so that closing
7189 // the file descriptors in the child process doesn't throw off the
7190 // synchronization between descriptors and buffers in the parent process.
7191 // This is as close to the fork as possible to avoid a race condition in case
7192 // there are multiple threads running before the death test, and another
7193 // thread writes to the log file.
7196 const pid_t child_pid
= fork();
7197 GTEST_DEATH_TEST_CHECK_(child_pid
!= -1);
7198 set_child_pid(child_pid
);
7199 if (child_pid
== 0) {
7200 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd
[0]));
7201 set_write_fd(pipe_fd
[1]);
7202 // Redirects all logging to stderr in the child process to prevent
7203 // concurrent writes to the log files. We capture stderr in the parent
7204 // process and append the child process' output to a log.
7206 // Event forwarding to the listeners of event listener API mush be shut
7207 // down in death test subprocesses.
7208 GetUnitTestImpl()->listeners()->SuppressEventForwarding();
7209 g_in_fast_death_test_child
= true;
7210 return EXECUTE_TEST
;
7212 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd
[1]));
7213 set_read_fd(pipe_fd
[0]);
7215 return OVERSEE_TEST
;
7219 // A concrete death test class that forks and re-executes the main
7220 // program from the beginning, with command-line flags set that cause
7221 // only this specific death test to be run.
7222 class ExecDeathTest
: public ForkingDeathTest
{
7224 ExecDeathTest(const char* a_statement
, const RE
* a_regex
, const char* file
,
7226 : ForkingDeathTest(a_statement
, a_regex
), file_(file
), line_(line
) {}
7227 virtual TestRole
AssumeRole();
7230 static ::std::vector
<testing::internal::string
>
7231 GetArgvsForDeathTestChildProcess() {
7232 ::std::vector
<testing::internal::string
> args
= GetInjectableArgvs();
7235 // The name of the file in which the death test is located.
7236 const char* const file_
;
7237 // The line number on which the death test is located.
7241 // Utility class for accumulating command-line arguments.
7244 Arguments() { args_
.push_back(NULL
); }
7247 for (std::vector
<char*>::iterator i
= args_
.begin(); i
!= args_
.end();
7252 void AddArgument(const char* argument
) {
7253 args_
.insert(args_
.end() - 1, posix::StrDup(argument
));
7256 template <typename Str
>
7257 void AddArguments(const ::std::vector
<Str
>& arguments
) {
7258 for (typename ::std::vector
<Str
>::const_iterator i
= arguments
.begin();
7259 i
!= arguments
.end(); ++i
) {
7260 args_
.insert(args_
.end() - 1, posix::StrDup(i
->c_str()));
7263 char* const* Argv() { return &args_
[0]; }
7266 std::vector
<char*> args_
;
7269 // A struct that encompasses the arguments to the child process of a
7270 // threadsafe-style death test process.
7271 struct ExecDeathTestArgs
{
7272 char* const* argv
; // Command-line arguments for the child's call to exec
7273 int close_fd
; // File descriptor to close; the read end of a pipe
7277 inline char** GetEnviron() {
7278 // When Google Test is built as a framework on MacOS X, the environ variable
7279 // is unavailable. Apple's documentation (man environ) recommends using
7280 // _NSGetEnviron() instead.
7281 return *_NSGetEnviron();
7284 // Some POSIX platforms expect you to declare environ. extern "C" makes
7285 // it reside in the global namespace.
7286 extern "C" char** environ
;
7287 inline char** GetEnviron() { return environ
; }
7288 # endif // GTEST_OS_MAC
7291 // The main function for a threadsafe-style death test child process.
7292 // This function is called in a clone()-ed process and thus must avoid
7293 // any potentially unsafe operations like malloc or libc functions.
7294 static int ExecDeathTestChildMain(void* child_arg
) {
7295 ExecDeathTestArgs
* const args
= static_cast<ExecDeathTestArgs
*>(child_arg
);
7296 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(args
->close_fd
));
7298 // We need to execute the test program in the same environment where
7299 // it was originally invoked. Therefore we change to the original
7300 // working directory first.
7301 const char* const original_dir
=
7302 UnitTest::GetInstance()->original_working_dir();
7303 // We can safely call chdir() as it's a direct system call.
7304 if (chdir(original_dir
) != 0) {
7305 DeathTestAbort(std::string("chdir(\"") + original_dir
+
7306 "\") failed: " + GetLastErrnoDescription());
7307 return EXIT_FAILURE
;
7310 // We can safely call execve() as it's a direct system call. We
7311 // cannot use execvp() as it's a libc function and thus potentially
7312 // unsafe. Since execve() doesn't search the PATH, the user must
7313 // invoke the test program via a valid path that contains at least
7314 // one path separator.
7315 execve(args
->argv
[0], args
->argv
, GetEnviron());
7316 DeathTestAbort(std::string("execve(") + args
->argv
[0] + ", ...) in " +
7317 original_dir
+ " failed: " + GetLastErrnoDescription());
7318 return EXIT_FAILURE
;
7320 # endif // !GTEST_OS_QNX
7322 // Two utility routines that together determine the direction the stack
7324 // This could be accomplished more elegantly by a single recursive
7325 // function, but we want to guard against the unlikely possibility of
7326 // a smart compiler optimizing the recursion away.
7328 // GTEST_NO_INLINE_ is required to prevent GCC 4.6 from inlining
7329 // StackLowerThanAddress into StackGrowsDown, which then doesn't give
7331 void StackLowerThanAddress(const void* ptr
, bool* result
) GTEST_NO_INLINE_
;
7332 void StackLowerThanAddress(const void* ptr
, bool* result
) {
7334 *result
= (&dummy
< ptr
);
7337 bool StackGrowsDown() {
7340 StackLowerThanAddress(&dummy
, &result
);
7344 // Spawns a child process with the same executable as the current process in
7345 // a thread-safe manner and instructs it to run the death test. The
7346 // implementation uses fork(2) + exec. On systems where clone(2) is
7347 // available, it is used instead, being slightly more thread-safe. On QNX,
7348 // fork supports only single-threaded environments, so this function uses
7349 // spawn(2) there instead. The function dies with an error message if
7350 // anything goes wrong.
7351 static pid_t
ExecDeathTestSpawnChild(char* const* argv
, int close_fd
) {
7352 ExecDeathTestArgs args
= {argv
, close_fd
};
7353 pid_t child_pid
= -1;
7356 // Obtains the current directory and sets it to be closed in the child
7358 const int cwd_fd
= open(".", O_RDONLY
);
7359 GTEST_DEATH_TEST_CHECK_(cwd_fd
!= -1);
7360 GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(cwd_fd
, F_SETFD
, FD_CLOEXEC
));
7361 // We need to execute the test program in the same environment where
7362 // it was originally invoked. Therefore we change to the original
7363 // working directory first.
7364 const char* const original_dir
=
7365 UnitTest::GetInstance()->original_working_dir();
7366 // We can safely call chdir() as it's a direct system call.
7367 if (chdir(original_dir
) != 0) {
7368 DeathTestAbort(std::string("chdir(\"") + original_dir
+
7369 "\") failed: " + GetLastErrnoDescription());
7370 return EXIT_FAILURE
;
7374 // Set close_fd to be closed after spawn.
7375 GTEST_DEATH_TEST_CHECK_SYSCALL_(fd_flags
= fcntl(close_fd
, F_GETFD
));
7376 GTEST_DEATH_TEST_CHECK_SYSCALL_(
7377 fcntl(close_fd
, F_SETFD
, fd_flags
| FD_CLOEXEC
));
7378 struct inheritance inherit
= {0};
7379 // spawn is a system call.
7380 child_pid
= spawn(args
.argv
[0], 0, NULL
, &inherit
, args
.argv
, GetEnviron());
7381 // Restores the current working directory.
7382 GTEST_DEATH_TEST_CHECK_(fchdir(cwd_fd
) != -1);
7383 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(cwd_fd
));
7385 # else // GTEST_OS_QNX
7387 // When a SIGPROF signal is received while fork() or clone() are executing,
7388 // the process may hang. To avoid this, we ignore SIGPROF here and re-enable
7389 // it after the call to fork()/clone() is complete.
7390 struct sigaction saved_sigprof_action
;
7391 struct sigaction ignore_sigprof_action
;
7392 memset(&ignore_sigprof_action
, 0, sizeof(ignore_sigprof_action
));
7393 sigemptyset(&ignore_sigprof_action
.sa_mask
);
7394 ignore_sigprof_action
.sa_handler
= SIG_IGN
;
7395 GTEST_DEATH_TEST_CHECK_SYSCALL_(
7396 sigaction(SIGPROF
, &ignore_sigprof_action
, &saved_sigprof_action
));
7397 # endif // GTEST_OS_LINUX
7399 # if GTEST_HAS_CLONE
7400 const bool use_fork
= GTEST_FLAG(death_test_use_fork
);
7403 static const bool stack_grows_down
= StackGrowsDown();
7404 const size_t stack_size
= getpagesize();
7405 // MMAP_ANONYMOUS is not defined on Mac, so we use MAP_ANON instead.
7406 void* const stack
= mmap(NULL
, stack_size
, PROT_READ
| PROT_WRITE
,
7407 MAP_ANON
| MAP_PRIVATE
, -1, 0);
7408 GTEST_DEATH_TEST_CHECK_(stack
!= MAP_FAILED
);
7410 // Maximum stack alignment in bytes: For a downward-growing stack, this
7411 // amount is subtracted from size of the stack space to get an address
7412 // that is within the stack space and is aligned on all systems we care
7413 // about. As far as I know there is no ABI with stack alignment greater
7414 // than 64. We assume stack and stack_size already have alignment of
7415 // kMaxStackAlignment.
7416 const size_t kMaxStackAlignment
= 64;
7417 void* const stack_top
=
7418 static_cast<char*>(stack
) +
7419 (stack_grows_down
? stack_size
- kMaxStackAlignment
: 0);
7420 GTEST_DEATH_TEST_CHECK_(
7421 stack_size
> kMaxStackAlignment
&&
7422 reinterpret_cast<intptr_t>(stack_top
) % kMaxStackAlignment
== 0);
7424 child_pid
= clone(&ExecDeathTestChildMain
, stack_top
, SIGCHLD
, &args
);
7426 GTEST_DEATH_TEST_CHECK_(munmap(stack
, stack_size
) != -1);
7429 const bool use_fork
= true;
7430 # endif // GTEST_HAS_CLONE
7432 if (use_fork
&& (child_pid
= fork()) == 0) {
7433 ExecDeathTestChildMain(&args
);
7436 # endif // GTEST_OS_QNX
7438 GTEST_DEATH_TEST_CHECK_SYSCALL_(
7439 sigaction(SIGPROF
, &saved_sigprof_action
, NULL
));
7440 # endif // GTEST_OS_LINUX
7442 GTEST_DEATH_TEST_CHECK_(child_pid
!= -1);
7446 // The AssumeRole process for a fork-and-exec death test. It re-executes the
7447 // main program from the beginning, setting the --gtest_filter
7448 // and --gtest_internal_run_death_test flags to cause only the current
7449 // death test to be re-run.
7450 DeathTest::TestRole
ExecDeathTest::AssumeRole() {
7451 const UnitTestImpl
* const impl
= GetUnitTestImpl();
7452 const InternalRunDeathTestFlag
* const flag
=
7453 impl
->internal_run_death_test_flag();
7454 const TestInfo
* const info
= impl
->current_test_info();
7455 const int death_test_index
= info
->result()->death_test_count();
7458 set_write_fd(flag
->write_fd());
7459 return EXECUTE_TEST
;
7463 GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd
) != -1);
7464 // Clear the close-on-exec flag on the write end of the pipe, lest
7465 // it be closed when the child process does an exec:
7466 GTEST_DEATH_TEST_CHECK_(fcntl(pipe_fd
[1], F_SETFD
, 0) != -1);
7468 const std::string filter_flag
= std::string("--") + GTEST_FLAG_PREFIX_
+
7469 kFilterFlag
+ "=" + info
->test_case_name() +
7471 const std::string internal_flag
= std::string("--") + GTEST_FLAG_PREFIX_
+
7472 kInternalRunDeathTestFlag
+ "=" + file_
+
7473 "|" + StreamableToString(line_
) + "|" +
7474 StreamableToString(death_test_index
) + "|" +
7475 StreamableToString(pipe_fd
[1]);
7477 args
.AddArguments(GetArgvsForDeathTestChildProcess());
7478 args
.AddArgument(filter_flag
.c_str());
7479 args
.AddArgument(internal_flag
.c_str());
7481 DeathTest::set_last_death_test_message("");
7484 // See the comment in NoExecDeathTest::AssumeRole for why the next line
7488 const pid_t child_pid
= ExecDeathTestSpawnChild(args
.Argv(), pipe_fd
[0]);
7489 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd
[1]));
7490 set_child_pid(child_pid
);
7491 set_read_fd(pipe_fd
[0]);
7493 return OVERSEE_TEST
;
7496 # endif // !GTEST_OS_WINDOWS
7498 // Creates a concrete DeathTest-derived class that depends on the
7499 // --gtest_death_test_style flag, and sets the pointer pointed to
7500 // by the "test" argument to its address. If the test should be
7501 // skipped, sets that pointer to NULL. Returns true, unless the
7502 // flag is set to an invalid value.
7503 bool DefaultDeathTestFactory::Create(const char* statement
, const RE
* regex
,
7504 const char* file
, int line
,
7506 UnitTestImpl
* const impl
= GetUnitTestImpl();
7507 const InternalRunDeathTestFlag
* const flag
=
7508 impl
->internal_run_death_test_flag();
7509 const int death_test_index
=
7510 impl
->current_test_info()->increment_death_test_count();
7513 if (death_test_index
> flag
->index()) {
7514 DeathTest::set_last_death_test_message(
7515 "Death test count (" + StreamableToString(death_test_index
) +
7516 ") somehow exceeded expected maximum (" +
7517 StreamableToString(flag
->index()) + ")");
7521 if (!(flag
->file() == file
&& flag
->line() == line
&&
7522 flag
->index() == death_test_index
)) {
7528 # if GTEST_OS_WINDOWS
7530 if (GTEST_FLAG(death_test_style
) == "threadsafe" ||
7531 GTEST_FLAG(death_test_style
) == "fast") {
7532 *test
= new WindowsDeathTest(statement
, regex
, file
, line
);
7537 if (GTEST_FLAG(death_test_style
) == "threadsafe") {
7538 *test
= new ExecDeathTest(statement
, regex
, file
, line
);
7539 } else if (GTEST_FLAG(death_test_style
) == "fast") {
7540 *test
= new NoExecDeathTest(statement
, regex
);
7543 # endif // GTEST_OS_WINDOWS
7545 else { // NOLINT - this is more readable than unbalanced brackets inside #if.
7546 DeathTest::set_last_death_test_message("Unknown death test style \"" +
7547 GTEST_FLAG(death_test_style
) +
7555 // Splits a given string on a given delimiter, populating a given
7556 // vector with the fields. GTEST_HAS_DEATH_TEST implies that we have
7557 // ::std::string, so we can use it here.
7558 static void SplitString(const ::std::string
& str
, char delimiter
,
7559 ::std::vector
< ::std::string
>* dest
) {
7560 ::std::vector
< ::std::string
> parsed
;
7561 ::std::string::size_type pos
= 0;
7562 while (::testing::internal::AlwaysTrue()) {
7563 const ::std::string::size_type colon
= str
.find(delimiter
, pos
);
7564 if (colon
== ::std::string::npos
) {
7565 parsed
.push_back(str
.substr(pos
));
7568 parsed
.push_back(str
.substr(pos
, colon
- pos
));
7575 # if GTEST_OS_WINDOWS
7576 // Recreates the pipe and event handles from the provided parameters,
7577 // signals the event, and returns a file descriptor wrapped around the pipe
7578 // handle. This function is called in the child process only.
7579 int GetStatusFileDescriptor(unsigned int parent_process_id
,
7580 size_t write_handle_as_size_t
,
7581 size_t event_handle_as_size_t
) {
7582 AutoHandle
parent_process_handle(::OpenProcess(PROCESS_DUP_HANDLE
,
7583 FALSE
, // Non-inheritable.
7584 parent_process_id
));
7585 if (parent_process_handle
.Get() == INVALID_HANDLE_VALUE
) {
7586 DeathTestAbort("Unable to open parent process " +
7587 StreamableToString(parent_process_id
));
7590 // TODO(vladl@google.com): Replace the following check with a
7591 // compile-time assertion when available.
7592 GTEST_CHECK_(sizeof(HANDLE
) <= sizeof(size_t));
7594 const HANDLE write_handle
= reinterpret_cast<HANDLE
>(write_handle_as_size_t
);
7595 HANDLE dup_write_handle
;
7597 // The newly initialized handle is accessible only in in the parent
7598 // process. To obtain one accessible within the child, we need to use
7600 if (!::DuplicateHandle(parent_process_handle
.Get(), write_handle
,
7601 ::GetCurrentProcess(), &dup_write_handle
,
7602 0x0, // Requested privileges ignored since
7603 // DUPLICATE_SAME_ACCESS is used.
7604 FALSE
, // Request non-inheritable handler.
7605 DUPLICATE_SAME_ACCESS
)) {
7606 DeathTestAbort("Unable to duplicate the pipe handle " +
7607 StreamableToString(write_handle_as_size_t
) +
7608 " from the parent process " +
7609 StreamableToString(parent_process_id
));
7612 const HANDLE event_handle
= reinterpret_cast<HANDLE
>(event_handle_as_size_t
);
7613 HANDLE dup_event_handle
;
7615 if (!::DuplicateHandle(parent_process_handle
.Get(), event_handle
,
7616 ::GetCurrentProcess(), &dup_event_handle
, 0x0, FALSE
,
7617 DUPLICATE_SAME_ACCESS
)) {
7618 DeathTestAbort("Unable to duplicate the event handle " +
7619 StreamableToString(event_handle_as_size_t
) +
7620 " from the parent process " +
7621 StreamableToString(parent_process_id
));
7624 const int write_fd
=
7625 ::_open_osfhandle(reinterpret_cast<intptr_t>(dup_write_handle
), O_APPEND
);
7626 if (write_fd
== -1) {
7627 DeathTestAbort("Unable to convert pipe handle " +
7628 StreamableToString(write_handle_as_size_t
) +
7629 " to a file descriptor");
7632 // Signals the parent that the write end of the pipe has been acquired
7633 // so the parent can release its own write end.
7634 ::SetEvent(dup_event_handle
);
7638 # endif // GTEST_OS_WINDOWS
7640 // Returns a newly created InternalRunDeathTestFlag object with fields
7641 // initialized from the GTEST_FLAG(internal_run_death_test) flag if
7642 // the flag is specified; otherwise returns NULL.
7643 InternalRunDeathTestFlag
* ParseInternalRunDeathTestFlag() {
7644 if (GTEST_FLAG(internal_run_death_test
) == "") return NULL
;
7646 // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we
7650 ::std::vector
< ::std::string
> fields
;
7651 SplitString(GTEST_FLAG(internal_run_death_test
).c_str(), '|', &fields
);
7654 # if GTEST_OS_WINDOWS
7656 unsigned int parent_process_id
= 0;
7657 size_t write_handle_as_size_t
= 0;
7658 size_t event_handle_as_size_t
= 0;
7660 if (fields
.size() != 6 || !ParseNaturalNumber(fields
[1], &line
) ||
7661 !ParseNaturalNumber(fields
[2], &index
) ||
7662 !ParseNaturalNumber(fields
[3], &parent_process_id
) ||
7663 !ParseNaturalNumber(fields
[4], &write_handle_as_size_t
) ||
7664 !ParseNaturalNumber(fields
[5], &event_handle_as_size_t
)) {
7665 DeathTestAbort("Bad --gtest_internal_run_death_test flag: " +
7666 GTEST_FLAG(internal_run_death_test
));
7668 write_fd
= GetStatusFileDescriptor(parent_process_id
, write_handle_as_size_t
,
7669 event_handle_as_size_t
);
7672 if (fields
.size() != 4 || !ParseNaturalNumber(fields
[1], &line
) ||
7673 !ParseNaturalNumber(fields
[2], &index
) ||
7674 !ParseNaturalNumber(fields
[3], &write_fd
)) {
7675 DeathTestAbort("Bad --gtest_internal_run_death_test flag: " +
7676 GTEST_FLAG(internal_run_death_test
));
7679 # endif // GTEST_OS_WINDOWS
7681 return new InternalRunDeathTestFlag(fields
[0], line
, index
, write_fd
);
7684 } // namespace internal
7686 #endif // GTEST_HAS_DEATH_TEST
7688 } // namespace testing
7689 // Copyright 2008, Google Inc.
7690 // All rights reserved.
7692 // Redistribution and use in source and binary forms, with or without
7693 // modification, are permitted provided that the following conditions are
7696 // * Redistributions of source code must retain the above copyright
7697 // notice, this list of conditions and the following disclaimer.
7698 // * Redistributions in binary form must reproduce the above
7699 // copyright notice, this list of conditions and the following disclaimer
7700 // in the documentation and/or other materials provided with the
7702 // * Neither the name of Google Inc. nor the names of its
7703 // contributors may be used to endorse or promote products derived from
7704 // this software without specific prior written permission.
7706 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
7707 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
7708 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
7709 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
7710 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
7711 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
7712 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
7713 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
7714 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
7715 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
7716 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
7718 // Authors: keith.ray@gmail.com (Keith Ray)
7722 #if GTEST_OS_WINDOWS_MOBILE
7723 # include <windows.h>
7724 #elif GTEST_OS_WINDOWS
7725 # include <direct.h>
7727 #elif GTEST_OS_SYMBIAN
7728 // Symbian OpenC has PATH_MAX in sys/syslimits.h
7729 # include <sys/syslimits.h>
7731 # include <limits.h>
7733 # include <climits> // Some Linux distributions define PATH_MAX here.
7734 #endif // GTEST_OS_WINDOWS_MOBILE
7736 #if GTEST_OS_WINDOWS
7737 # define GTEST_PATH_MAX_ _MAX_PATH
7738 #elif defined(PATH_MAX)
7739 # define GTEST_PATH_MAX_ PATH_MAX
7740 #elif defined(_XOPEN_PATH_MAX)
7741 # define GTEST_PATH_MAX_ _XOPEN_PATH_MAX
7743 # define GTEST_PATH_MAX_ _POSIX_PATH_MAX
7744 #endif // GTEST_OS_WINDOWS
7747 namespace internal
{
7749 #if GTEST_OS_WINDOWS
7750 // On Windows, '\\' is the standard path separator, but many tools and the
7751 // Windows API also accept '/' as an alternate path separator. Unless otherwise
7752 // noted, a file path can contain either kind of path separators, or a mixture
7754 const char kPathSeparator
= '\\';
7755 const char kAlternatePathSeparator
= '/';
7756 const char kPathSeparatorString
[] = "\\";
7757 const char kAlternatePathSeparatorString
[] = "/";
7758 # if GTEST_OS_WINDOWS_MOBILE
7759 // Windows CE doesn't have a current directory. You should not use
7760 // the current directory in tests on Windows CE, but this at least
7761 // provides a reasonable fallback.
7762 const char kCurrentDirectoryString
[] = "\\";
7763 // Windows CE doesn't define INVALID_FILE_ATTRIBUTES
7764 const DWORD kInvalidFileAttributes
= 0xffffffff;
7766 const char kCurrentDirectoryString
[] = ".\\";
7767 # endif // GTEST_OS_WINDOWS_MOBILE
7769 const char kPathSeparator
= '/';
7770 const char kPathSeparatorString
[] = "/";
7771 const char kCurrentDirectoryString
[] = "./";
7772 #endif // GTEST_OS_WINDOWS
7774 // Returns whether the given character is a valid path separator.
7775 static bool IsPathSeparator(char c
) {
7776 #if GTEST_HAS_ALT_PATH_SEP_
7777 return (c
== kPathSeparator
) || (c
== kAlternatePathSeparator
);
7779 return c
== kPathSeparator
;
7783 // Returns the current working directory, or "" if unsuccessful.
7784 FilePath
FilePath::GetCurrentDir() {
7785 #if GTEST_OS_WINDOWS_MOBILE
7786 // Windows CE doesn't have a current directory, so we just return
7787 // something reasonable.
7788 return FilePath(kCurrentDirectoryString
);
7789 #elif GTEST_OS_WINDOWS
7790 char cwd
[GTEST_PATH_MAX_
+ 1] = {'\0'};
7791 return FilePath(_getcwd(cwd
, sizeof(cwd
)) == NULL
? "" : cwd
);
7793 char cwd
[GTEST_PATH_MAX_
+ 1] = {'\0'};
7794 return FilePath(getcwd(cwd
, sizeof(cwd
)) == NULL
? "" : cwd
);
7795 #endif // GTEST_OS_WINDOWS_MOBILE
7798 // Returns a copy of the FilePath with the case-insensitive extension removed.
7799 // Example: FilePath("dir/file.exe").RemoveExtension("EXE") returns
7800 // FilePath("dir/file"). If a case-insensitive extension is not
7801 // found, returns a copy of the original FilePath.
7802 FilePath
FilePath::RemoveExtension(const char* extension
) const {
7803 const std::string dot_extension
= std::string(".") + extension
;
7804 if (String::EndsWithCaseInsensitive(pathname_
, dot_extension
)) {
7806 pathname_
.substr(0, pathname_
.length() - dot_extension
.length()));
7811 // Returns a pointer to the last occurence of a valid path separator in
7812 // the FilePath. On Windows, for example, both '/' and '\' are valid path
7813 // separators. Returns NULL if no path separator was found.
7814 const char* FilePath::FindLastPathSeparator() const {
7815 const char* const last_sep
= strrchr(c_str(), kPathSeparator
);
7816 #if GTEST_HAS_ALT_PATH_SEP_
7817 const char* const last_alt_sep
= strrchr(c_str(), kAlternatePathSeparator
);
7818 // Comparing two pointers of which only one is NULL is undefined.
7819 if (last_alt_sep
!= NULL
&& (last_sep
== NULL
|| last_alt_sep
> last_sep
)) {
7820 return last_alt_sep
;
7826 // Returns a copy of the FilePath with the directory part removed.
7827 // Example: FilePath("path/to/file").RemoveDirectoryName() returns
7828 // FilePath("file"). If there is no directory part ("just_a_file"), it returns
7829 // the FilePath unmodified. If there is no file part ("just_a_dir/") it
7830 // returns an empty FilePath ("").
7831 // On Windows platform, '\' is the path separator, otherwise it is '/'.
7832 FilePath
FilePath::RemoveDirectoryName() const {
7833 const char* const last_sep
= FindLastPathSeparator();
7834 return last_sep
? FilePath(last_sep
+ 1) : *this;
7837 // RemoveFileName returns the directory path with the filename removed.
7838 // Example: FilePath("path/to/file").RemoveFileName() returns "path/to/".
7839 // If the FilePath is "a_file" or "/a_file", RemoveFileName returns
7840 // FilePath("./") or, on Windows, FilePath(".\\"). If the filepath does
7841 // not have a file, like "just/a/dir/", it returns the FilePath unmodified.
7842 // On Windows platform, '\' is the path separator, otherwise it is '/'.
7843 FilePath
FilePath::RemoveFileName() const {
7844 const char* const last_sep
= FindLastPathSeparator();
7847 dir
= std::string(c_str(), last_sep
+ 1 - c_str());
7849 dir
= kCurrentDirectoryString
;
7851 return FilePath(dir
);
7854 // Helper functions for naming files in a directory for xml output.
7856 // Given directory = "dir", base_name = "test", number = 0,
7857 // extension = "xml", returns "dir/test.xml". If number is greater
7858 // than zero (e.g., 12), returns "dir/test_12.xml".
7859 // On Windows platform, uses \ as the separator rather than /.
7860 FilePath
FilePath::MakeFileName(const FilePath
& directory
,
7861 const FilePath
& base_name
, int number
,
7862 const char* extension
) {
7865 file
= base_name
.string() + "." + extension
;
7868 base_name
.string() + "_" + StreamableToString(number
) + "." + extension
;
7870 return ConcatPaths(directory
, FilePath(file
));
7873 // Given directory = "dir", relative_path = "test.xml", returns "dir/test.xml".
7874 // On Windows, uses \ as the separator rather than /.
7875 FilePath
FilePath::ConcatPaths(const FilePath
& directory
,
7876 const FilePath
& relative_path
) {
7877 if (directory
.IsEmpty()) return relative_path
;
7878 const FilePath
dir(directory
.RemoveTrailingPathSeparator());
7879 return FilePath(dir
.string() + kPathSeparator
+ relative_path
.string());
7882 // Returns true if pathname describes something findable in the file-system,
7883 // either a file, directory, or whatever.
7884 bool FilePath::FileOrDirectoryExists() const {
7885 #if GTEST_OS_WINDOWS_MOBILE
7886 LPCWSTR unicode
= String::AnsiToUtf16(pathname_
.c_str());
7887 const DWORD attributes
= GetFileAttributes(unicode
);
7889 return attributes
!= kInvalidFileAttributes
;
7891 posix::StatStruct file_stat
;
7892 return posix::Stat(pathname_
.c_str(), &file_stat
) == 0;
7893 #endif // GTEST_OS_WINDOWS_MOBILE
7896 // Returns true if pathname describes a directory in the file-system
7898 bool FilePath::DirectoryExists() const {
7899 bool result
= false;
7900 #if GTEST_OS_WINDOWS
7901 // Don't strip off trailing separator if path is a root directory on
7902 // Windows (like "C:\\").
7903 const FilePath
& path(IsRootDirectory() ? *this
7904 : RemoveTrailingPathSeparator());
7906 const FilePath
& path(*this);
7909 #if GTEST_OS_WINDOWS_MOBILE
7910 LPCWSTR unicode
= String::AnsiToUtf16(path
.c_str());
7911 const DWORD attributes
= GetFileAttributes(unicode
);
7913 if ((attributes
!= kInvalidFileAttributes
) &&
7914 (attributes
& FILE_ATTRIBUTE_DIRECTORY
)) {
7918 posix::StatStruct file_stat
;
7920 posix::Stat(path
.c_str(), &file_stat
) == 0 && posix::IsDir(file_stat
);
7921 #endif // GTEST_OS_WINDOWS_MOBILE
7926 // Returns true if pathname describes a root directory. (Windows has one
7927 // root directory per disk drive.)
7928 bool FilePath::IsRootDirectory() const {
7929 #if GTEST_OS_WINDOWS
7930 // TODO(wan@google.com): on Windows a network share like
7931 // \\server\share can be a root directory, although it cannot be the
7932 // current directory. Handle this properly.
7933 return pathname_
.length() == 3 && IsAbsolutePath();
7935 return pathname_
.length() == 1 && IsPathSeparator(pathname_
.c_str()[0]);
7939 // Returns true if pathname describes an absolute path.
7940 bool FilePath::IsAbsolutePath() const {
7941 const char* const name
= pathname_
.c_str();
7942 #if GTEST_OS_WINDOWS
7943 return pathname_
.length() >= 3 &&
7944 ((name
[0] >= 'a' && name
[0] <= 'z') ||
7945 (name
[0] >= 'A' && name
[0] <= 'Z')) &&
7946 name
[1] == ':' && IsPathSeparator(name
[2]);
7948 return IsPathSeparator(name
[0]);
7952 // Returns a pathname for a file that does not currently exist. The pathname
7953 // will be directory/base_name.extension or
7954 // directory/base_name_<number>.extension if directory/base_name.extension
7955 // already exists. The number will be incremented until a pathname is found
7956 // that does not already exist.
7957 // Examples: 'dir/foo_test.xml' or 'dir/foo_test_1.xml'.
7958 // There could be a race condition if two or more processes are calling this
7959 // function at the same time -- they could both pick the same filename.
7960 FilePath
FilePath::GenerateUniqueFileName(const FilePath
& directory
,
7961 const FilePath
& base_name
,
7962 const char* extension
) {
7963 FilePath full_pathname
;
7966 full_pathname
.Set(MakeFileName(directory
, base_name
, number
++, extension
));
7967 } while (full_pathname
.FileOrDirectoryExists());
7968 return full_pathname
;
7971 // Returns true if FilePath ends with a path separator, which indicates that
7972 // it is intended to represent a directory. Returns false otherwise.
7973 // This does NOT check that a directory (or file) actually exists.
7974 bool FilePath::IsDirectory() const {
7975 return !pathname_
.empty() &&
7976 IsPathSeparator(pathname_
.c_str()[pathname_
.length() - 1]);
7979 // Create directories so that path exists. Returns true if successful or if
7980 // the directories already exist; returns false if unable to create directories
7982 bool FilePath::CreateDirectoriesRecursively() const {
7983 if (!this->IsDirectory()) {
7987 if (pathname_
.length() == 0 || this->DirectoryExists()) {
7991 const FilePath
parent(this->RemoveTrailingPathSeparator().RemoveFileName());
7992 return parent
.CreateDirectoriesRecursively() && this->CreateFolder();
7995 // Create the directory so that path exists. Returns true if successful or
7996 // if the directory already exists; returns false if unable to create the
7997 // directory for any reason, including if the parent directory does not
7998 // exist. Not named "CreateDirectory" because that's a macro on Windows.
7999 bool FilePath::CreateFolder() const {
8000 #if GTEST_OS_WINDOWS_MOBILE
8001 FilePath
removed_sep(this->RemoveTrailingPathSeparator());
8002 LPCWSTR unicode
= String::AnsiToUtf16(removed_sep
.c_str());
8003 int result
= CreateDirectory(unicode
, NULL
) ? 0 : -1;
8005 #elif GTEST_OS_WINDOWS
8006 int result
= _mkdir(pathname_
.c_str());
8008 int result
= mkdir(pathname_
.c_str(), 0777);
8009 #endif // GTEST_OS_WINDOWS_MOBILE
8012 return this->DirectoryExists(); // An error is OK if the directory exists.
8014 return true; // No error.
8017 // If input name has a trailing separator character, remove it and return the
8018 // name, otherwise return the name string unmodified.
8019 // On Windows platform, uses \ as the separator, other platforms use /.
8020 FilePath
FilePath::RemoveTrailingPathSeparator() const {
8021 return IsDirectory() ? FilePath(pathname_
.substr(0, pathname_
.length() - 1))
8025 // Removes any redundant separators that might be in the pathname.
8026 // For example, "bar///foo" becomes "bar/foo". Does not eliminate other
8027 // redundancies that might be in a pathname involving "." or "..".
8028 // TODO(wan@google.com): handle Windows network shares (e.g. \\server\share).
8029 void FilePath::Normalize() {
8030 if (pathname_
.c_str() == NULL
) {
8034 const char* src
= pathname_
.c_str();
8035 char* const dest
= new char[pathname_
.length() + 1];
8036 char* dest_ptr
= dest
;
8037 memset(dest_ptr
, 0, pathname_
.length() + 1);
8039 while (*src
!= '\0') {
8041 if (!IsPathSeparator(*src
)) {
8044 #if GTEST_HAS_ALT_PATH_SEP_
8045 if (*dest_ptr
== kAlternatePathSeparator
) {
8046 *dest_ptr
= kPathSeparator
;
8049 while (IsPathSeparator(*src
)) src
++;
8058 } // namespace internal
8059 } // namespace testing
8060 // Copyright 2008, Google Inc.
8061 // All rights reserved.
8063 // Redistribution and use in source and binary forms, with or without
8064 // modification, are permitted provided that the following conditions are
8067 // * Redistributions of source code must retain the above copyright
8068 // notice, this list of conditions and the following disclaimer.
8069 // * Redistributions in binary form must reproduce the above
8070 // copyright notice, this list of conditions and the following disclaimer
8071 // in the documentation and/or other materials provided with the
8073 // * Neither the name of Google Inc. nor the names of its
8074 // contributors may be used to endorse or promote products derived from
8075 // this software without specific prior written permission.
8077 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
8078 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
8079 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
8080 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
8081 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
8082 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
8083 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
8084 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
8085 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
8086 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
8087 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
8089 // Author: wan@google.com (Zhanyong Wan)
8096 #if GTEST_OS_WINDOWS_MOBILE
8097 # include <windows.h> // For TerminateProcess()
8098 #elif GTEST_OS_WINDOWS
8100 # include <sys/stat.h>
8102 # include <unistd.h>
8103 #endif // GTEST_OS_WINDOWS_MOBILE
8106 # include <mach/mach_init.h>
8107 # include <mach/task.h>
8108 # include <mach/vm_map.h>
8109 #endif // GTEST_OS_MAC
8112 # include <devctl.h>
8113 # include <sys/procfs.h>
8114 #endif // GTEST_OS_QNX
8116 // Indicates that this translation unit is part of Google Test's
8117 // implementation. It must come before gtest-internal-inl.h is
8118 // included, or there will be a compiler error. This trick is to
8119 // prevent a user from accidentally including gtest-internal-inl.h in
8121 #define GTEST_IMPLEMENTATION_ 1
8122 #undef GTEST_IMPLEMENTATION_
8125 namespace internal
{
8127 #if defined(_MSC_VER) || defined(__BORLANDC__)
8128 // MSVC and C++Builder do not provide a definition of STDERR_FILENO.
8129 const int kStdOutFileno
= 1;
8130 const int kStdErrFileno
= 2;
8132 const int kStdOutFileno
= STDOUT_FILENO
;
8133 const int kStdErrFileno
= STDERR_FILENO
;
8138 // Returns the number of threads running in the process, or 0 to indicate that
8139 // we cannot detect it.
8140 size_t GetThreadCount() {
8141 const task_t task
= mach_task_self();
8142 mach_msg_type_number_t thread_count
;
8143 thread_act_array_t thread_list
;
8144 const kern_return_t status
= task_threads(task
, &thread_list
, &thread_count
);
8145 if (status
== KERN_SUCCESS
) {
8146 // task_threads allocates resources in thread_list and we need to free them
8148 vm_deallocate(task
, reinterpret_cast<vm_address_t
>(thread_list
),
8149 sizeof(thread_t
) * thread_count
);
8150 return static_cast<size_t>(thread_count
);
8158 // Returns the number of threads running in the process, or 0 to indicate that
8159 // we cannot detect it.
8160 size_t GetThreadCount() {
8161 const int fd
= open("/proc/self/as", O_RDONLY
);
8165 procfs_info process_info
;
8167 devctl(fd
, DCMD_PROC_INFO
, &process_info
, sizeof(process_info
), NULL
);
8169 if (status
== EOK
) {
8170 return static_cast<size_t>(process_info
.num_threads
);
8178 size_t GetThreadCount() {
8179 // There's no portable way to detect the number of threads, so we just
8180 // return 0 to indicate that we cannot detect it.
8184 #endif // GTEST_OS_MAC
8186 #if GTEST_USES_POSIX_RE
8188 // Implements RE. Currently only needed for death tests.
8192 // regfree'ing an invalid regex might crash because the content
8193 // of the regex is undefined. Since the regex's are essentially
8194 // the same, one cannot be valid (or invalid) without the other
8196 regfree(&partial_regex_
);
8197 regfree(&full_regex_
);
8199 free(const_cast<char*>(pattern_
));
8202 // Returns true iff regular expression re matches the entire str.
8203 bool RE::FullMatch(const char* str
, const RE
& re
) {
8204 if (!re
.is_valid_
) return false;
8207 return regexec(&re
.full_regex_
, str
, 1, &match
, 0) == 0;
8210 // Returns true iff regular expression re matches a substring of str
8211 // (including str itself).
8212 bool RE::PartialMatch(const char* str
, const RE
& re
) {
8213 if (!re
.is_valid_
) return false;
8216 return regexec(&re
.partial_regex_
, str
, 1, &match
, 0) == 0;
8219 // Initializes an RE from its string representation.
8220 void RE::Init(const char* regex
) {
8221 pattern_
= posix::StrDup(regex
);
8223 // Reserves enough bytes to hold the regular expression used for a
8225 const size_t full_regex_len
= strlen(regex
) + 10;
8226 char* const full_pattern
= new char[full_regex_len
];
8228 snprintf(full_pattern
, full_regex_len
, "^(%s)$", regex
);
8229 is_valid_
= regcomp(&full_regex_
, full_pattern
, REG_EXTENDED
) == 0;
8230 // We want to call regcomp(&partial_regex_, ...) even if the
8231 // previous expression returns false. Otherwise partial_regex_ may
8232 // not be properly initialized can may cause trouble when it's
8235 // Some implementation of POSIX regex (e.g. on at least some
8236 // versions of Cygwin) doesn't accept the empty string as a valid
8237 // regex. We change it to an equivalent form "()" to be safe.
8239 const char* const partial_regex
= (*regex
== '\0') ? "()" : regex
;
8240 is_valid_
= regcomp(&partial_regex_
, partial_regex
, REG_EXTENDED
) == 0;
8242 EXPECT_TRUE(is_valid_
)
8243 << "Regular expression \"" << regex
8244 << "\" is not a valid POSIX Extended regular expression.";
8246 delete[] full_pattern
;
8249 #elif GTEST_USES_SIMPLE_RE
8251 // Returns true iff ch appears anywhere in str (excluding the
8252 // terminating '\0' character).
8253 bool IsInSet(char ch
, const char* str
) {
8254 return ch
!= '\0' && strchr(str
, ch
) != NULL
;
8257 // Returns true iff ch belongs to the given classification. Unlike
8258 // similar functions in <ctype.h>, these aren't affected by the
8260 bool IsAsciiDigit(char ch
) { return '0' <= ch
&& ch
<= '9'; }
8261 bool IsAsciiPunct(char ch
) {
8262 return IsInSet(ch
, "^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~");
8264 bool IsRepeat(char ch
) { return IsInSet(ch
, "?*+"); }
8265 bool IsAsciiWhiteSpace(char ch
) { return IsInSet(ch
, " \f\n\r\t\v"); }
8266 bool IsAsciiWordChar(char ch
) {
8267 return ('a' <= ch
&& ch
<= 'z') || ('A' <= ch
&& ch
<= 'Z') ||
8268 ('0' <= ch
&& ch
<= '9') || ch
== '_';
8271 // Returns true iff "\\c" is a supported escape sequence.
8272 bool IsValidEscape(char c
) {
8273 return (IsAsciiPunct(c
) || IsInSet(c
, "dDfnrsStvwW"));
8276 // Returns true iff the given atom (specified by escaped and pattern)
8277 // matches ch. The result is undefined if the atom is invalid.
8278 bool AtomMatchesChar(bool escaped
, char pattern_char
, char ch
) {
8279 if (escaped
) { // "\\p" where p is pattern_char.
8280 switch (pattern_char
) {
8282 return IsAsciiDigit(ch
);
8284 return !IsAsciiDigit(ch
);
8292 return IsAsciiWhiteSpace(ch
);
8294 return !IsAsciiWhiteSpace(ch
);
8300 return IsAsciiWordChar(ch
);
8302 return !IsAsciiWordChar(ch
);
8304 return IsAsciiPunct(pattern_char
) && pattern_char
== ch
;
8307 return (pattern_char
== '.' && ch
!= '\n') || pattern_char
== ch
;
8310 // Helper function used by ValidateRegex() to format error messages.
8311 std::string
FormatRegexSyntaxError(const char* regex
, int index
) {
8312 return (Message() << "Syntax error at index " << index
8313 << " in simple regular expression \"" << regex
<< "\": ")
8317 // Generates non-fatal failures and returns false if regex is invalid;
8318 // otherwise returns true.
8319 bool ValidateRegex(const char* regex
) {
8320 if (regex
== NULL
) {
8321 // TODO(wan@google.com): fix the source file location in the
8322 // assertion failures to match where the regex is used in user
8324 ADD_FAILURE() << "NULL is not a valid simple regular expression.";
8328 bool is_valid
= true;
8330 // True iff ?, *, or + can follow the previous atom.
8331 bool prev_repeatable
= false;
8332 for (int i
= 0; regex
[i
]; i
++) {
8333 if (regex
[i
] == '\\') { // An escape sequence
8335 if (regex
[i
] == '\0') {
8336 ADD_FAILURE() << FormatRegexSyntaxError(regex
, i
- 1)
8337 << "'\\' cannot appear at the end.";
8341 if (!IsValidEscape(regex
[i
])) {
8342 ADD_FAILURE() << FormatRegexSyntaxError(regex
, i
- 1)
8343 << "invalid escape sequence \"\\" << regex
[i
] << "\".";
8346 prev_repeatable
= true;
8347 } else { // Not an escape sequence.
8348 const char ch
= regex
[i
];
8350 if (ch
== '^' && i
> 0) {
8351 ADD_FAILURE() << FormatRegexSyntaxError(regex
, i
)
8352 << "'^' can only appear at the beginning.";
8354 } else if (ch
== '$' && regex
[i
+ 1] != '\0') {
8355 ADD_FAILURE() << FormatRegexSyntaxError(regex
, i
)
8356 << "'$' can only appear at the end.";
8358 } else if (IsInSet(ch
, "()[]{}|")) {
8359 ADD_FAILURE() << FormatRegexSyntaxError(regex
, i
) << "'" << ch
8360 << "' is unsupported.";
8362 } else if (IsRepeat(ch
) && !prev_repeatable
) {
8363 ADD_FAILURE() << FormatRegexSyntaxError(regex
, i
) << "'" << ch
8364 << "' can only follow a repeatable token.";
8368 prev_repeatable
= !IsInSet(ch
, "^$?*+");
8375 // Matches a repeated regex atom followed by a valid simple regular
8376 // expression. The regex atom is defined as c if escaped is false,
8377 // or \c otherwise. repeat is the repetition meta character (?, *,
8378 // or +). The behavior is undefined if str contains too many
8379 // characters to be indexable by size_t, in which case the test will
8380 // probably time out anyway. We are fine with this limitation as
8381 // std::string has it too.
8382 bool MatchRepetitionAndRegexAtHead(bool escaped
, char c
, char repeat
,
8383 const char* regex
, const char* str
) {
8384 const size_t min_count
= (repeat
== '+') ? 1 : 0;
8385 const size_t max_count
= (repeat
== '?') ? 1 : static_cast<size_t>(-1) - 1;
8386 // We cannot call numeric_limits::max() as it conflicts with the
8387 // max() macro on Windows.
8389 for (size_t i
= 0; i
<= max_count
; ++i
) {
8390 // We know that the atom matches each of the first i characters in str.
8391 if (i
>= min_count
&& MatchRegexAtHead(regex
, str
+ i
)) {
8392 // We have enough matches at the head, and the tail matches too.
8393 // Since we only care about *whether* the pattern matches str
8394 // (as opposed to *how* it matches), there is no need to find a
8398 if (str
[i
] == '\0' || !AtomMatchesChar(escaped
, c
, str
[i
])) return false;
8403 // Returns true iff regex matches a prefix of str. regex must be a
8404 // valid simple regular expression and not start with "^", or the
8405 // result is undefined.
8406 bool MatchRegexAtHead(const char* regex
, const char* str
) {
8407 if (*regex
== '\0') // An empty regex matches a prefix of anything.
8410 // "$" only matches the end of a string. Note that regex being
8411 // valid guarantees that there's nothing after "$" in it.
8412 if (*regex
== '$') return *str
== '\0';
8414 // Is the first thing in regex an escape sequence?
8415 const bool escaped
= *regex
== '\\';
8416 if (escaped
) ++regex
;
8417 if (IsRepeat(regex
[1])) {
8418 // MatchRepetitionAndRegexAtHead() calls MatchRegexAtHead(), so
8419 // here's an indirect recursion. It terminates as the regex gets
8420 // shorter in each recursion.
8421 return MatchRepetitionAndRegexAtHead(escaped
, regex
[0], regex
[1], regex
+ 2,
8424 // regex isn't empty, isn't "$", and doesn't start with a
8425 // repetition. We match the first atom of regex with the first
8426 // character of str and recurse.
8427 return (*str
!= '\0') && AtomMatchesChar(escaped
, *regex
, *str
) &&
8428 MatchRegexAtHead(regex
+ 1, str
+ 1);
8432 // Returns true iff regex matches any substring of str. regex must be
8433 // a valid simple regular expression, or the result is undefined.
8435 // The algorithm is recursive, but the recursion depth doesn't exceed
8436 // the regex length, so we won't need to worry about running out of
8437 // stack space normally. In rare cases the time complexity can be
8438 // exponential with respect to the regex length + the string length,
8439 // but usually it's must faster (often close to linear).
8440 bool MatchRegexAnywhere(const char* regex
, const char* str
) {
8441 if (regex
== NULL
|| str
== NULL
) return false;
8443 if (*regex
== '^') return MatchRegexAtHead(regex
+ 1, str
);
8445 // A successful match can be anywhere in str.
8447 if (MatchRegexAtHead(regex
, str
)) return true;
8448 } while (*str
++ != '\0');
8452 // Implements the RE class.
8455 free(const_cast<char*>(pattern_
));
8456 free(const_cast<char*>(full_pattern_
));
8459 // Returns true iff regular expression re matches the entire str.
8460 bool RE::FullMatch(const char* str
, const RE
& re
) {
8461 return re
.is_valid_
&& MatchRegexAnywhere(re
.full_pattern_
, str
);
8464 // Returns true iff regular expression re matches a substring of str
8465 // (including str itself).
8466 bool RE::PartialMatch(const char* str
, const RE
& re
) {
8467 return re
.is_valid_
&& MatchRegexAnywhere(re
.pattern_
, str
);
8470 // Initializes an RE from its string representation.
8471 void RE::Init(const char* regex
) {
8472 pattern_
= full_pattern_
= NULL
;
8473 if (regex
!= NULL
) {
8474 pattern_
= posix::StrDup(regex
);
8477 is_valid_
= ValidateRegex(regex
);
8479 // No need to calculate the full pattern when the regex is invalid.
8483 const size_t len
= strlen(regex
);
8484 // Reserves enough bytes to hold the regular expression used for a
8485 // full match: we need space to prepend a '^', append a '$', and
8486 // terminate the string with '\0'.
8487 char* buffer
= static_cast<char*>(malloc(len
+ 3));
8488 full_pattern_
= buffer
;
8491 *buffer
++ = '^'; // Makes sure full_pattern_ starts with '^'.
8493 // We don't use snprintf or strncpy, as they trigger a warning when
8494 // compiled with VC++ 8.0.
8495 memcpy(buffer
, regex
, len
);
8498 if (len
== 0 || regex
[len
- 1] != '$')
8499 *buffer
++ = '$'; // Makes sure full_pattern_ ends with '$'.
8504 #endif // GTEST_USES_POSIX_RE
8506 const char kUnknownFile
[] = "unknown file";
8508 // Formats a source file path and a line number as they would appear
8509 // in an error message from the compiler used to compile this code.
8510 GTEST_API_ ::std::string
FormatFileLocation(const char* file
, int line
) {
8511 const std::string
file_name(file
== NULL
? kUnknownFile
: file
);
8514 return file_name
+ ":";
8517 return file_name
+ "(" + StreamableToString(line
) + "):";
8519 return file_name
+ ":" + StreamableToString(line
) + ":";
8523 // Formats a file location for compiler-independent XML output.
8524 // Although this function is not platform dependent, we put it next to
8525 // FormatFileLocation in order to contrast the two functions.
8526 // Note that FormatCompilerIndependentFileLocation() does NOT append colon
8527 // to the file location it produces, unlike FormatFileLocation().
8528 GTEST_API_ ::std::string
FormatCompilerIndependentFileLocation(const char* file
,
8530 const std::string
file_name(file
== NULL
? kUnknownFile
: file
);
8535 return file_name
+ ":" + StreamableToString(line
);
8538 GTestLog::GTestLog(GTestLogSeverity severity
, const char* file
, int line
)
8539 : severity_(severity
) {
8540 const char* const marker
=
8541 severity
== GTEST_INFO
8543 : severity
== GTEST_WARNING
8545 : severity
== GTEST_ERROR
? "[ ERROR ]" : "[ FATAL ]";
8546 GetStream() << ::std::endl
8547 << marker
<< " " << FormatFileLocation(file
, line
).c_str()
8551 // Flushes the buffers and, if severity is GTEST_FATAL, aborts the program.
8552 GTestLog::~GTestLog() {
8553 GetStream() << ::std::endl
;
8554 if (severity_
== GTEST_FATAL
) {
8559 // Disable Microsoft deprecation warnings for POSIX functions called from
8560 // this class (creat, dup, dup2, and close)
8562 # pragma warning(push)
8563 # pragma warning(disable : 4996)
8566 #if GTEST_HAS_STREAM_REDIRECTION
8568 // Object that captures an output stream (stdout/stderr).
8569 class CapturedStream
{
8571 // The ctor redirects the stream to a temporary file.
8572 explicit CapturedStream(int fd
) : fd_(fd
), uncaptured_fd_(dup(fd
)) {
8573 # if GTEST_OS_WINDOWS
8574 char temp_dir_path
[MAX_PATH
+ 1] = {'\0'}; // NOLINT
8575 char temp_file_path
[MAX_PATH
+ 1] = {'\0'}; // NOLINT
8577 ::GetTempPathA(sizeof(temp_dir_path
), temp_dir_path
);
8578 const UINT success
= ::GetTempFileNameA(temp_dir_path
, "gtest_redir",
8579 0, // Generate unique file name.
8581 GTEST_CHECK_(success
!= 0)
8582 << "Unable to create a temporary file in " << temp_dir_path
;
8583 const int captured_fd
= creat(temp_file_path
, _S_IREAD
| _S_IWRITE
);
8584 GTEST_CHECK_(captured_fd
!= -1)
8585 << "Unable to open temporary file " << temp_file_path
;
8586 filename_
= temp_file_path
;
8588 // There's no guarantee that a test has write access to the current
8589 // directory, so we create the temporary file in the /tmp directory
8590 // instead. We use /tmp on most systems, and /sdcard on Android.
8591 // That's because Android doesn't have /tmp.
8592 # if GTEST_OS_LINUX_ANDROID
8593 // Note: Android applications are expected to call the framework's
8594 // Context.getExternalStorageDirectory() method through JNI to get
8595 // the location of the world-writable SD Card directory. However,
8596 // this requires a Context handle, which cannot be retrieved
8597 // globally from native code. Doing so also precludes running the
8598 // code as part of a regular standalone executable, which doesn't
8599 // run in a Dalvik process (e.g. when running it through 'adb shell').
8601 // The location /sdcard is directly accessible from native code
8602 // and is the only location (unofficially) supported by the Android
8603 // team. It's generally a symlink to the real SD Card mount point
8604 // which can be /mnt/sdcard, /mnt/sdcard0, /system/media/sdcard, or
8605 // other OEM-customized locations. Never rely on these, and always
8607 char name_template
[] = "/sdcard/gtest_captured_stream.XXXXXX";
8609 char name_template
[] = "/tmp/captured_stream.XXXXXX";
8610 # endif // GTEST_OS_LINUX_ANDROID
8611 const int captured_fd
= mkstemp(name_template
);
8612 filename_
= name_template
;
8613 # endif // GTEST_OS_WINDOWS
8615 dup2(captured_fd
, fd_
);
8619 ~CapturedStream() { remove(filename_
.c_str()); }
8621 std::string
GetCapturedString() {
8622 if (uncaptured_fd_
!= -1) {
8623 // Restores the original stream.
8625 dup2(uncaptured_fd_
, fd_
);
8626 close(uncaptured_fd_
);
8627 uncaptured_fd_
= -1;
8630 FILE* const file
= posix::FOpen(filename_
.c_str(), "r");
8631 const std::string content
= ReadEntireFile(file
);
8632 posix::FClose(file
);
8637 // Reads the entire content of a file as an std::string.
8638 static std::string
ReadEntireFile(FILE* file
);
8640 // Returns the size (in bytes) of a file.
8641 static size_t GetFileSize(FILE* file
);
8643 const int fd_
; // A stream to capture.
8645 // Name of the temporary file holding the stderr output.
8646 ::std::string filename_
;
8648 GTEST_DISALLOW_COPY_AND_ASSIGN_(CapturedStream
);
8651 // Returns the size (in bytes) of a file.
8652 size_t CapturedStream::GetFileSize(FILE* file
) {
8653 fseek(file
, 0, SEEK_END
);
8654 return static_cast<size_t>(ftell(file
));
8657 // Reads the entire content of a file as a string.
8658 std::string
CapturedStream::ReadEntireFile(FILE* file
) {
8659 const size_t file_size
= GetFileSize(file
);
8660 char* const buffer
= new char[file_size
];
8662 size_t bytes_last_read
= 0; // # of bytes read in the last fread()
8663 size_t bytes_read
= 0; // # of bytes read so far
8665 fseek(file
, 0, SEEK_SET
);
8667 // Keeps reading the file until we cannot read further or the
8668 // pre-determined file size is reached.
8671 fread(buffer
+ bytes_read
, 1, file_size
- bytes_read
, file
);
8672 bytes_read
+= bytes_last_read
;
8673 } while (bytes_last_read
> 0 && bytes_read
< file_size
);
8675 const std::string
content(buffer
, bytes_read
);
8682 # pragma warning(pop)
8685 static CapturedStream
* g_captured_stderr
= NULL
;
8686 static CapturedStream
* g_captured_stdout
= NULL
;
8688 // Starts capturing an output stream (stdout/stderr).
8689 void CaptureStream(int fd
, const char* stream_name
, CapturedStream
** stream
) {
8690 if (*stream
!= NULL
) {
8691 GTEST_LOG_(FATAL
) << "Only one " << stream_name
8692 << " capturer can exist at a time.";
8694 *stream
= new CapturedStream(fd
);
8697 // Stops capturing the output stream and returns the captured string.
8698 std::string
GetCapturedStream(CapturedStream
** captured_stream
) {
8699 const std::string content
= (*captured_stream
)->GetCapturedString();
8701 delete *captured_stream
;
8702 *captured_stream
= NULL
;
8707 // Starts capturing stdout.
8708 void CaptureStdout() {
8709 CaptureStream(kStdOutFileno
, "stdout", &g_captured_stdout
);
8712 // Starts capturing stderr.
8713 void CaptureStderr() {
8714 CaptureStream(kStdErrFileno
, "stderr", &g_captured_stderr
);
8717 // Stops capturing stdout and returns the captured string.
8718 std::string
GetCapturedStdout() {
8719 return GetCapturedStream(&g_captured_stdout
);
8722 // Stops capturing stderr and returns the captured string.
8723 std::string
GetCapturedStderr() {
8724 return GetCapturedStream(&g_captured_stderr
);
8727 #endif // GTEST_HAS_STREAM_REDIRECTION
8729 #if GTEST_HAS_DEATH_TEST
8731 // A copy of all command line arguments. Set by InitGoogleTest().
8732 ::std::vector
<testing::internal::string
> g_argvs
;
8734 static const ::std::vector
<testing::internal::string
>* g_injected_test_argvs
=
8737 void SetInjectableArgvs(const ::std::vector
<testing::internal::string
>* argvs
) {
8738 if (g_injected_test_argvs
!= argvs
) delete g_injected_test_argvs
;
8739 g_injected_test_argvs
= argvs
;
8742 const ::std::vector
<testing::internal::string
>& GetInjectableArgvs() {
8743 if (g_injected_test_argvs
!= NULL
) {
8744 return *g_injected_test_argvs
;
8748 #endif // GTEST_HAS_DEATH_TEST
8750 #if GTEST_OS_WINDOWS_MOBILE
8754 TerminateProcess(GetCurrentProcess(), 1);
8756 } // namespace posix
8757 #endif // GTEST_OS_WINDOWS_MOBILE
8759 // Returns the name of the environment variable corresponding to the
8760 // given flag. For example, FlagToEnvVar("foo") will return
8761 // "GTEST_FOO" in the open-source version.
8762 static std::string
FlagToEnvVar(const char* flag
) {
8763 const std::string full_flag
=
8764 (Message() << GTEST_FLAG_PREFIX_
<< flag
).GetString();
8767 for (size_t i
= 0; i
!= full_flag
.length(); i
++) {
8768 env_var
<< ToUpper(full_flag
.c_str()[i
]);
8771 return env_var
.GetString();
8774 // Parses 'str' for a 32-bit signed integer. If successful, writes
8775 // the result to *value and returns true; otherwise leaves *value
8776 // unchanged and returns false.
8777 bool ParseInt32(const Message
& src_text
, const char* str
, Int32
* value
) {
8778 // Parses the environment variable as a decimal integer.
8780 const long long_value
= strtol(str
, &end
, 10); // NOLINT
8782 // Has strtol() consumed all characters in the string?
8784 // No - an invalid character was encountered.
8786 msg
<< "WARNING: " << src_text
8787 << " is expected to be a 32-bit integer, but actually"
8788 << " has value \"" << str
<< "\".\n";
8789 printf("%s", msg
.GetString().c_str());
8794 // Is the parsed value in the range of an Int32?
8795 const Int32 result
= static_cast<Int32
>(long_value
);
8796 if (long_value
== LONG_MAX
|| long_value
== LONG_MIN
||
8797 // The parsed value overflows as a long. (strtol() returns
8798 // LONG_MAX or LONG_MIN when the input overflows.)
8799 result
!= long_value
8800 // The parsed value overflows as an Int32.
8803 msg
<< "WARNING: " << src_text
8804 << " is expected to be a 32-bit integer, but actually"
8805 << " has value " << str
<< ", which overflows.\n";
8806 printf("%s", msg
.GetString().c_str());
8815 // Reads and returns the Boolean environment variable corresponding to
8816 // the given flag; if it's not set, returns default_value.
8818 // The value is considered true iff it's not "0".
8819 bool BoolFromGTestEnv(const char* flag
, bool default_value
) {
8820 const std::string env_var
= FlagToEnvVar(flag
);
8821 const char* const string_value
= posix::GetEnv(env_var
.c_str());
8822 return string_value
== NULL
? default_value
: strcmp(string_value
, "0") != 0;
8825 // Reads and returns a 32-bit integer stored in the environment
8826 // variable corresponding to the given flag; if it isn't set or
8827 // doesn't represent a valid 32-bit integer, returns default_value.
8828 Int32
Int32FromGTestEnv(const char* flag
, Int32 default_value
) {
8829 const std::string env_var
= FlagToEnvVar(flag
);
8830 const char* const string_value
= posix::GetEnv(env_var
.c_str());
8831 if (string_value
== NULL
) {
8832 // The environment variable is not set.
8833 return default_value
;
8836 Int32 result
= default_value
;
8837 if (!ParseInt32(Message() << "Environment variable " << env_var
, string_value
,
8839 printf("The default value %s is used.\n",
8840 (Message() << default_value
).GetString().c_str());
8842 return default_value
;
8848 // Reads and returns the string environment variable corresponding to
8849 // the given flag; if it's not set, returns default_value.
8850 const char* StringFromGTestEnv(const char* flag
, const char* default_value
) {
8851 const std::string env_var
= FlagToEnvVar(flag
);
8852 const char* const value
= posix::GetEnv(env_var
.c_str());
8853 return value
== NULL
? default_value
: value
;
8856 } // namespace internal
8857 } // namespace testing
8858 // Copyright 2007, Google Inc.
8859 // All rights reserved.
8861 // Redistribution and use in source and binary forms, with or without
8862 // modification, are permitted provided that the following conditions are
8865 // * Redistributions of source code must retain the above copyright
8866 // notice, this list of conditions and the following disclaimer.
8867 // * Redistributions in binary form must reproduce the above
8868 // copyright notice, this list of conditions and the following disclaimer
8869 // in the documentation and/or other materials provided with the
8871 // * Neither the name of Google Inc. nor the names of its
8872 // contributors may be used to endorse or promote products derived from
8873 // this software without specific prior written permission.
8875 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
8876 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
8877 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
8878 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
8879 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
8880 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
8881 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
8882 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
8883 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
8884 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
8885 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
8887 // Author: wan@google.com (Zhanyong Wan)
8889 // Google Test - The Google C++ Testing Framework
8891 // This file implements a universal value printer that can print a
8892 // value of any type T:
8894 // void ::testing::internal::UniversalPrinter<T>::Print(value, ostream_ptr);
8896 // It uses the << operator when possible, and prints the bytes in the
8897 // object otherwise. A user can override its behavior for a class
8898 // type Foo by defining either operator<<(::std::ostream&, const Foo&)
8899 // or void PrintTo(const Foo&, ::std::ostream*) in the namespace that
8905 #include <ostream> // NOLINT
8912 using ::std::ostream
;
8914 // Prints a segment of bytes in the given object.
8915 void PrintByteSegmentInObjectTo(const unsigned char* obj_bytes
, size_t start
,
8916 size_t count
, ostream
* os
) {
8918 for (size_t i
= 0; i
!= count
; i
++) {
8919 const size_t j
= start
+ i
;
8921 // Organizes the bytes into groups of 2 for easy parsing by
8928 GTEST_SNPRINTF_(text
, sizeof(text
), "%02X", obj_bytes
[j
]);
8933 // Prints the bytes in the given value to the given ostream.
8934 void PrintBytesInObjectToImpl(const unsigned char* obj_bytes
, size_t count
,
8936 // Tells the user how big the object is.
8937 *os
<< count
<< "-byte object <";
8939 const size_t kThreshold
= 132;
8940 const size_t kChunkSize
= 64;
8941 // If the object size is bigger than kThreshold, we'll have to omit
8942 // some details by printing only the first and the last kChunkSize
8944 // TODO(wan): let the user control the threshold using a flag.
8945 if (count
< kThreshold
) {
8946 PrintByteSegmentInObjectTo(obj_bytes
, 0, count
, os
);
8948 PrintByteSegmentInObjectTo(obj_bytes
, 0, kChunkSize
, os
);
8950 // Rounds up to 2-byte boundary.
8951 const size_t resume_pos
= (count
- kChunkSize
+ 1) / 2 * 2;
8952 PrintByteSegmentInObjectTo(obj_bytes
, resume_pos
, count
- resume_pos
, os
);
8959 namespace internal2
{
8961 // Delegates to PrintBytesInObjectToImpl() to print the bytes in the
8962 // given object. The delegation simplifies the implementation, which
8963 // uses the << operator and thus is easier done outside of the
8964 // ::testing::internal namespace, which contains a << operator that
8965 // sometimes conflicts with the one in STL.
8966 void PrintBytesInObjectTo(const unsigned char* obj_bytes
, size_t count
,
8968 PrintBytesInObjectToImpl(obj_bytes
, count
, os
);
8971 } // namespace internal2
8973 namespace internal
{
8975 // Depending on the value of a char (or wchar_t), we print it in one
8976 // of three formats:
8977 // - as is if it's a printable ASCII (e.g. 'a', '2', ' '),
8978 // - as a hexidecimal escape sequence (e.g. '\x7F'), or
8979 // - as a special escape sequence (e.g. '\r', '\n').
8980 enum CharFormat
{ kAsIs
, kHexEscape
, kSpecialEscape
};
8982 // Returns true if c is a printable ASCII character. We test the
8983 // value of c directly instead of calling isprint(), which is buggy on
8985 inline bool IsPrintableAscii(wchar_t c
) { return 0x20 <= c
&& c
<= 0x7E; }
8987 // Prints a wide or narrow char c as a character literal without the
8988 // quotes, escaping it when necessary; returns how c was formatted.
8989 // The template argument UnsignedChar is the unsigned version of Char,
8990 // which is the type of c.
8991 template <typename UnsignedChar
, typename Char
>
8992 static CharFormat
PrintAsCharLiteralTo(Char c
, ostream
* os
) {
8993 switch (static_cast<wchar_t>(c
)) {
9025 if (IsPrintableAscii(c
)) {
9026 *os
<< static_cast<char>(c
);
9029 *os
<< "\\x" + String::FormatHexInt(static_cast<UnsignedChar
>(c
));
9033 return kSpecialEscape
;
9036 // Prints a wchar_t c as if it's part of a string literal, escaping it when
9037 // necessary; returns how c was formatted.
9038 static CharFormat
PrintAsStringLiteralTo(wchar_t c
, ostream
* os
) {
9045 return kSpecialEscape
;
9047 return PrintAsCharLiteralTo
<wchar_t>(c
, os
);
9051 // Prints a char c as if it's part of a string literal, escaping it when
9052 // necessary; returns how c was formatted.
9053 static CharFormat
PrintAsStringLiteralTo(char c
, ostream
* os
) {
9054 return PrintAsStringLiteralTo(
9055 static_cast<wchar_t>(static_cast<unsigned char>(c
)), os
);
9058 // Prints a wide or narrow character c and its code. '\0' is printed
9059 // as "'\\0'", other unprintable characters are also properly escaped
9060 // using the standard C++ escape sequence. The template argument
9061 // UnsignedChar is the unsigned version of Char, which is the type of c.
9062 template <typename UnsignedChar
, typename Char
>
9063 void PrintCharAndCodeTo(Char c
, ostream
* os
) {
9064 // First, print c as a literal in the most readable form we can find.
9065 *os
<< ((sizeof(c
) > 1) ? "L'" : "'");
9066 const CharFormat format
= PrintAsCharLiteralTo
<UnsignedChar
>(c
, os
);
9069 // To aid user debugging, we also print c's code in decimal, unless
9070 // it's 0 (in which case c was printed as '\\0', making the code
9073 *os
<< " (" << static_cast<int>(c
);
9075 // For more convenience, we print c's code again in hexidecimal,
9076 // unless c was already printed in the form '\x##' or the code is in
9078 if (format
== kHexEscape
|| (1 <= c
&& c
<= 9)) {
9081 *os
<< ", 0x" << String::FormatHexInt(static_cast<UnsignedChar
>(c
));
9086 void PrintTo(unsigned char c
, ::std::ostream
* os
) {
9087 PrintCharAndCodeTo
<unsigned char>(c
, os
);
9089 void PrintTo(signed char c
, ::std::ostream
* os
) {
9090 PrintCharAndCodeTo
<unsigned char>(c
, os
);
9093 // Prints a wchar_t as a symbol if it is printable or as its internal
9094 // code otherwise and also as its code. L'\0' is printed as "L'\\0'".
9095 void PrintTo(wchar_t wc
, ostream
* os
) { PrintCharAndCodeTo
<wchar_t>(wc
, os
); }
9097 // Prints the given array of characters to the ostream. CharType must be either
9099 // The array starts at begin, the length is len, it may include '\0' characters
9100 // and may not be NUL-terminated.
9101 template <typename CharType
>
9102 static void PrintCharsAsStringTo(const CharType
* begin
, size_t len
,
9104 const char* const kQuoteBegin
= sizeof(CharType
) == 1 ? "\"" : "L\"";
9106 bool is_previous_hex
= false;
9107 for (size_t index
= 0; index
< len
; ++index
) {
9108 const CharType cur
= begin
[index
];
9109 if (is_previous_hex
&& IsXDigit(cur
)) {
9110 // Previous character is of '\x..' form and this character can be
9111 // interpreted as another hexadecimal digit in its number. Break string to
9113 *os
<< "\" " << kQuoteBegin
;
9115 is_previous_hex
= PrintAsStringLiteralTo(cur
, os
) == kHexEscape
;
9120 // Prints a (const) char/wchar_t array of 'len' elements, starting at address
9121 // 'begin'. CharType must be either char or wchar_t.
9122 template <typename CharType
>
9123 static void UniversalPrintCharArray(const CharType
* begin
, size_t len
,
9126 // const char kFoo[] = "foo";
9127 // generates an array of 4, not 3, elements, with the last one being '\0'.
9129 // Therefore when printing a char array, we don't print the last element if
9130 // it's '\0', such that the output matches the string literal as it's
9131 // written in the source code.
9132 if (len
> 0 && begin
[len
- 1] == '\0') {
9133 PrintCharsAsStringTo(begin
, len
- 1, os
);
9137 // If, however, the last element in the array is not '\0', e.g.
9138 // const char kFoo[] = { 'f', 'o', 'o' };
9139 // we must print the entire array. We also print a message to indicate
9140 // that the array is not NUL-terminated.
9141 PrintCharsAsStringTo(begin
, len
, os
);
9142 *os
<< " (no terminating NUL)";
9145 // Prints a (const) char array of 'len' elements, starting at address 'begin'.
9146 void UniversalPrintArray(const char* begin
, size_t len
, ostream
* os
) {
9147 UniversalPrintCharArray(begin
, len
, os
);
9150 // Prints a (const) wchar_t array of 'len' elements, starting at address
9152 void UniversalPrintArray(const wchar_t* begin
, size_t len
, ostream
* os
) {
9153 UniversalPrintCharArray(begin
, len
, os
);
9156 // Prints the given C string to the ostream.
9157 void PrintTo(const char* s
, ostream
* os
) {
9161 *os
<< ImplicitCast_
<const void*>(s
) << " pointing to ";
9162 PrintCharsAsStringTo(s
, strlen(s
), os
);
9166 // MSVC compiler can be configured to define whar_t as a typedef
9167 // of unsigned short. Defining an overload for const wchar_t* in that case
9168 // would cause pointers to unsigned shorts be printed as wide strings,
9169 // possibly accessing more memory than intended and causing invalid
9170 // memory accesses. MSVC defines _NATIVE_WCHAR_T_DEFINED symbol when
9171 // wchar_t is implemented as a native type.
9172 #if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED)
9173 // Prints the given wide C string to the ostream.
9174 void PrintTo(const wchar_t* s
, ostream
* os
) {
9178 *os
<< ImplicitCast_
<const void*>(s
) << " pointing to ";
9179 PrintCharsAsStringTo(s
, wcslen(s
), os
);
9182 #endif // wchar_t is native
9184 // Prints a ::string object.
9185 #if GTEST_HAS_GLOBAL_STRING
9186 void PrintStringTo(const ::string
& s
, ostream
* os
) {
9187 PrintCharsAsStringTo(s
.data(), s
.size(), os
);
9189 #endif // GTEST_HAS_GLOBAL_STRING
9191 void PrintStringTo(const ::std::string
& s
, ostream
* os
) {
9192 PrintCharsAsStringTo(s
.data(), s
.size(), os
);
9195 // Prints a ::wstring object.
9196 #if GTEST_HAS_GLOBAL_WSTRING
9197 void PrintWideStringTo(const ::wstring
& s
, ostream
* os
) {
9198 PrintCharsAsStringTo(s
.data(), s
.size(), os
);
9200 #endif // GTEST_HAS_GLOBAL_WSTRING
9202 #if GTEST_HAS_STD_WSTRING
9203 void PrintWideStringTo(const ::std::wstring
& s
, ostream
* os
) {
9204 PrintCharsAsStringTo(s
.data(), s
.size(), os
);
9206 #endif // GTEST_HAS_STD_WSTRING
9208 } // namespace internal
9210 } // namespace testing
9211 // Copyright 2008, Google Inc.
9212 // All rights reserved.
9214 // Redistribution and use in source and binary forms, with or without
9215 // modification, are permitted provided that the following conditions are
9218 // * Redistributions of source code must retain the above copyright
9219 // notice, this list of conditions and the following disclaimer.
9220 // * Redistributions in binary form must reproduce the above
9221 // copyright notice, this list of conditions and the following disclaimer
9222 // in the documentation and/or other materials provided with the
9224 // * Neither the name of Google Inc. nor the names of its
9225 // contributors may be used to endorse or promote products derived from
9226 // this software without specific prior written permission.
9228 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
9229 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
9230 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
9231 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9232 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
9233 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9234 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
9235 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
9236 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
9237 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
9238 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
9240 // Author: mheule@google.com (Markus Heule)
9242 // The Google C++ Testing Framework (Google Test)
9244 // Indicates that this translation unit is part of Google Test's
9245 // implementation. It must come before gtest-internal-inl.h is
9246 // included, or there will be a compiler error. This trick is to
9247 // prevent a user from accidentally including gtest-internal-inl.h in
9249 #define GTEST_IMPLEMENTATION_ 1
9250 #undef GTEST_IMPLEMENTATION_
9254 using internal::GetUnitTestImpl
;
9256 // Gets the summary of the failure message by omitting the stack trace
9258 std::string
TestPartResult::ExtractSummary(const char* message
) {
9259 const char* const stack_trace
= strstr(message
, internal::kStackTraceMarker
);
9260 return stack_trace
== NULL
? message
: std::string(message
, stack_trace
);
9263 // Prints a TestPartResult object.
9264 std::ostream
& operator<<(std::ostream
& os
, const TestPartResult
& result
) {
9265 return os
<< result
.file_name() << ":" << result
.line_number() << ": "
9266 << (result
.type() == TestPartResult::kSuccess
9268 : result
.type() == TestPartResult::kFatalFailure
9270 : "Non-fatal failure")
9272 << result
.message() << std::endl
;
9275 // Appends a TestPartResult to the array.
9276 void TestPartResultArray::Append(const TestPartResult
& result
) {
9277 array_
.push_back(result
);
9280 // Returns the TestPartResult at the given index (0-based).
9281 const TestPartResult
& TestPartResultArray::GetTestPartResult(int index
) const {
9282 if (index
< 0 || index
>= size()) {
9283 printf("\nInvalid index (%d) into TestPartResultArray.\n", index
);
9284 internal::posix::Abort();
9287 return array_
[index
];
9290 // Returns the number of TestPartResult objects in the array.
9291 int TestPartResultArray::size() const {
9292 return static_cast<int>(array_
.size());
9295 namespace internal
{
9297 HasNewFatalFailureHelper::HasNewFatalFailureHelper()
9298 : has_new_fatal_failure_(false),
9300 GetUnitTestImpl()->GetTestPartResultReporterForCurrentThread()) {
9301 GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(this);
9304 HasNewFatalFailureHelper::~HasNewFatalFailureHelper() {
9305 GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(
9306 original_reporter_
);
9309 void HasNewFatalFailureHelper::ReportTestPartResult(
9310 const TestPartResult
& result
) {
9311 if (result
.fatally_failed()) has_new_fatal_failure_
= true;
9312 original_reporter_
->ReportTestPartResult(result
);
9315 } // namespace internal
9317 } // namespace testing
9318 // Copyright 2008 Google Inc.
9319 // All Rights Reserved.
9321 // Redistribution and use in source and binary forms, with or without
9322 // modification, are permitted provided that the following conditions are
9325 // * Redistributions of source code must retain the above copyright
9326 // notice, this list of conditions and the following disclaimer.
9327 // * Redistributions in binary form must reproduce the above
9328 // copyright notice, this list of conditions and the following disclaimer
9329 // in the documentation and/or other materials provided with the
9331 // * Neither the name of Google Inc. nor the names of its
9332 // contributors may be used to endorse or promote products derived from
9333 // this software without specific prior written permission.
9335 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
9336 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
9337 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
9338 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9339 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
9340 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9341 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
9342 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
9343 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
9344 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
9345 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
9347 // Author: wan@google.com (Zhanyong Wan)
9350 namespace internal
{
9352 #if GTEST_HAS_TYPED_TEST_P
9354 // Skips to the first non-space char in str. Returns an empty string if str
9355 // contains only whitespace characters.
9356 static const char* SkipSpaces(const char* str
) {
9357 while (IsSpace(*str
)) str
++;
9361 // Verifies that registered_tests match the test names in
9362 // defined_test_names_; returns registered_tests if successful, or
9363 // aborts the program otherwise.
9364 const char* TypedTestCasePState::VerifyRegisteredTestNames(
9365 const char* file
, int line
, const char* registered_tests
) {
9366 typedef ::std::set
<const char*>::const_iterator DefinedTestIter
;
9369 // Skip initial whitespace in registered_tests since some
9370 // preprocessors prefix stringizied literals with whitespace.
9371 registered_tests
= SkipSpaces(registered_tests
);
9374 ::std::set
<std::string
> tests
;
9375 for (const char* names
= registered_tests
; names
!= NULL
;
9376 names
= SkipComma(names
)) {
9377 const std::string name
= GetPrefixUntilComma(names
);
9378 if (tests
.count(name
) != 0) {
9379 errors
<< "Test " << name
<< " is listed more than once.\n";
9384 for (DefinedTestIter it
= defined_test_names_
.begin();
9385 it
!= defined_test_names_
.end(); ++it
) {
9395 errors
<< "No test named " << name
9396 << " can be found in this test case.\n";
9400 for (DefinedTestIter it
= defined_test_names_
.begin();
9401 it
!= defined_test_names_
.end(); ++it
) {
9402 if (tests
.count(*it
) == 0) {
9403 errors
<< "You forgot to list test " << *it
<< ".\n";
9407 const std::string
& errors_str
= errors
.GetString();
9408 if (errors_str
!= "") {
9409 fprintf(stderr
, "%s %s", FormatFileLocation(file
, line
).c_str(),
9410 errors_str
.c_str());
9415 return registered_tests
;
9418 #endif // GTEST_HAS_TYPED_TEST_P
9420 } // namespace internal
9421 } // namespace testing
9422 // Copyright 2008, Google Inc.
9423 // All rights reserved.
9425 // Redistribution and use in source and binary forms, with or without
9426 // modification, are permitted provided that the following conditions are
9429 // * Redistributions of source code must retain the above copyright
9430 // notice, this list of conditions and the following disclaimer.
9431 // * Redistributions in binary form must reproduce the above
9432 // copyright notice, this list of conditions and the following disclaimer
9433 // in the documentation and/or other materials provided with the
9435 // * Neither the name of Google Inc. nor the names of its
9436 // contributors may be used to endorse or promote products derived from
9437 // this software without specific prior written permission.
9439 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
9440 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
9441 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
9442 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9443 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
9444 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9445 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
9446 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
9447 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
9448 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
9449 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
9451 // Author: wan@google.com (Zhanyong Wan)
9453 // Google C++ Mocking Framework (Google Mock)
9455 // This file #includes all Google Mock implementation .cc files. The
9456 // purpose is to allow a user to build Google Mock by compiling this
9459 // This line ensures that gmock.h can be compiled on its own, even
9461 #include "gmock/gmock.h"
9463 // The following lines pull in the real gmock *.cc files.
9464 // Copyright 2007, Google Inc.
9465 // All rights reserved.
9467 // Redistribution and use in source and binary forms, with or without
9468 // modification, are permitted provided that the following conditions are
9471 // * Redistributions of source code must retain the above copyright
9472 // notice, this list of conditions and the following disclaimer.
9473 // * Redistributions in binary form must reproduce the above
9474 // copyright notice, this list of conditions and the following disclaimer
9475 // in the documentation and/or other materials provided with the
9477 // * Neither the name of Google Inc. nor the names of its
9478 // contributors may be used to endorse or promote products derived from
9479 // this software without specific prior written permission.
9481 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
9482 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
9483 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
9484 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9485 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
9486 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9487 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
9488 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
9489 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
9490 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
9491 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
9493 // Author: wan@google.com (Zhanyong Wan)
9495 // Google Mock - a framework for writing C++ mock classes.
9497 // This file implements cardinalities.
9501 #include <ostream> // NOLINT
9509 // Implements the Between(m, n) cardinality.
9510 class BetweenCardinalityImpl
: public CardinalityInterface
{
9512 BetweenCardinalityImpl(int min
, int max
)
9513 : min_(min
>= 0 ? min
: 0), max_(max
>= min_
? max
: min_
) {
9514 std::stringstream ss
;
9516 ss
<< "The invocation lower bound must be >= 0, "
9517 << "but is actually " << min
<< ".";
9518 internal::Expect(false, __FILE__
, __LINE__
, ss
.str());
9519 } else if (max
< 0) {
9520 ss
<< "The invocation upper bound must be >= 0, "
9521 << "but is actually " << max
<< ".";
9522 internal::Expect(false, __FILE__
, __LINE__
, ss
.str());
9523 } else if (min
> max
) {
9524 ss
<< "The invocation upper bound (" << max
9525 << ") must be >= the invocation lower bound (" << min
<< ").";
9526 internal::Expect(false, __FILE__
, __LINE__
, ss
.str());
9530 // Conservative estimate on the lower/upper bound of the number of
9532 virtual int ConservativeLowerBound() const { return min_
; }
9533 virtual int ConservativeUpperBound() const { return max_
; }
9535 virtual bool IsSatisfiedByCallCount(int call_count
) const {
9536 return min_
<= call_count
&& call_count
<= max_
;
9539 virtual bool IsSaturatedByCallCount(int call_count
) const {
9540 return call_count
>= max_
;
9543 virtual void DescribeTo(::std::ostream
* os
) const;
9549 GTEST_DISALLOW_COPY_AND_ASSIGN_(BetweenCardinalityImpl
);
9552 // Formats "n times" in a human-friendly way.
9553 inline internal::string
FormatTimes(int n
) {
9556 } else if (n
== 2) {
9559 std::stringstream ss
;
9560 ss
<< n
<< " times";
9565 // Describes the Between(m, n) cardinality in human-friendly text.
9566 void BetweenCardinalityImpl::DescribeTo(::std::ostream
* os
) const {
9569 *os
<< "never called";
9570 } else if (max_
== INT_MAX
) {
9571 *os
<< "called any number of times";
9573 *os
<< "called at most " << FormatTimes(max_
);
9575 } else if (min_
== max_
) {
9576 *os
<< "called " << FormatTimes(min_
);
9577 } else if (max_
== INT_MAX
) {
9578 *os
<< "called at least " << FormatTimes(min_
);
9580 // 0 < min_ < max_ < INT_MAX
9581 *os
<< "called between " << min_
<< " and " << max_
<< " times";
9585 } // Unnamed namespace
9587 // Describes the given call count to an ostream.
9588 void Cardinality::DescribeActualCallCountTo(int actual_call_count
,
9589 ::std::ostream
* os
) {
9590 if (actual_call_count
> 0) {
9591 *os
<< "called " << FormatTimes(actual_call_count
);
9593 *os
<< "never called";
9597 // Creates a cardinality that allows at least n calls.
9598 GTEST_API_ Cardinality
AtLeast(int n
) { return Between(n
, INT_MAX
); }
9600 // Creates a cardinality that allows at most n calls.
9601 GTEST_API_ Cardinality
AtMost(int n
) { return Between(0, n
); }
9603 // Creates a cardinality that allows any number of calls.
9604 GTEST_API_ Cardinality
AnyNumber() { return AtLeast(0); }
9606 // Creates a cardinality that allows between min and max calls.
9607 GTEST_API_ Cardinality
Between(int min
, int max
) {
9608 return Cardinality(new BetweenCardinalityImpl(min
, max
));
9611 // Creates a cardinality that allows exactly n calls.
9612 GTEST_API_ Cardinality
Exactly(int n
) { return Between(n
, n
); }
9614 } // namespace testing
9615 // Copyright 2007, Google Inc.
9616 // All rights reserved.
9618 // Redistribution and use in source and binary forms, with or without
9619 // modification, are permitted provided that the following conditions are
9622 // * Redistributions of source code must retain the above copyright
9623 // notice, this list of conditions and the following disclaimer.
9624 // * Redistributions in binary form must reproduce the above
9625 // copyright notice, this list of conditions and the following disclaimer
9626 // in the documentation and/or other materials provided with the
9628 // * Neither the name of Google Inc. nor the names of its
9629 // contributors may be used to endorse or promote products derived from
9630 // this software without specific prior written permission.
9632 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
9633 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
9634 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
9635 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9636 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
9637 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9638 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
9639 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
9640 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
9641 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
9642 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
9644 // Author: wan@google.com (Zhanyong Wan)
9646 // Google Mock - a framework for writing C++ mock classes.
9648 // This file defines some utilities useful for implementing Google
9649 // Mock. They are subject to change without notice, so please DO NOT
9650 // USE THEM IN USER CODE.
9654 #include <ostream> // NOLINT
9658 namespace internal
{
9660 // Converts an identifier name to a space-separated list of lower-case
9661 // words. Each maximum substring of the form [A-Za-z][a-z]*|\d+ is
9662 // treated as one word. For example, both "FooBar123" and
9663 // "foo_bar_123" are converted to "foo bar 123".
9664 GTEST_API_ string
ConvertIdentifierNameToWords(const char* id_name
) {
9666 char prev_char
= '\0';
9667 for (const char* p
= id_name
; *p
!= '\0'; prev_char
= *(p
++)) {
9668 // We don't care about the current locale as the input is
9669 // guaranteed to be a valid C++ identifier name.
9670 const bool starts_new_word
= IsUpper(*p
) ||
9671 (!IsAlpha(prev_char
) && IsLower(*p
)) ||
9672 (!IsDigit(prev_char
) && IsDigit(*p
));
9675 if (starts_new_word
&& result
!= "") result
+= ' ';
9676 result
+= ToLower(*p
);
9682 // This class reports Google Mock failures as Google Test failures. A
9683 // user can define another class in a similar fashion if he intends to
9684 // use Google Mock with a testing framework other than Google Test.
9685 class GoogleTestFailureReporter
: public FailureReporterInterface
{
9687 virtual void ReportFailure(FailureType type
, const char* file
, int line
,
9688 const string
& message
) {
9689 AssertHelper(type
== kFatal
? TestPartResult::kFatalFailure
9690 : TestPartResult::kNonFatalFailure
,
9691 file
, line
, message
.c_str()) = Message();
9692 if (type
== kFatal
) {
9698 // Returns the global failure reporter. Will create a
9699 // GoogleTestFailureReporter and return it the first time called.
9700 GTEST_API_ FailureReporterInterface
* GetFailureReporter() {
9701 // Points to the global failure reporter used by Google Mock. gcc
9702 // guarantees that the following use of failure_reporter is
9703 // thread-safe. We may need to add additional synchronization to
9704 // protect failure_reporter if we port Google Mock to other
9706 static FailureReporterInterface
* const failure_reporter
=
9707 new GoogleTestFailureReporter();
9708 return failure_reporter
;
9711 // Protects global resources (stdout in particular) used by Log().
9712 static GTEST_DEFINE_STATIC_MUTEX_(g_log_mutex
);
9714 // Returns true iff a log with the given severity is visible according
9715 // to the --gmock_verbose flag.
9716 GTEST_API_
bool LogIsVisible(LogSeverity severity
) {
9717 if (GMOCK_FLAG(verbose
) == kInfoVerbosity
) {
9718 // Always show the log if --gmock_verbose=info.
9720 } else if (GMOCK_FLAG(verbose
) == kErrorVerbosity
) {
9721 // Always hide it if --gmock_verbose=error.
9724 // If --gmock_verbose is neither "info" nor "error", we treat it
9725 // as "warning" (its default value).
9726 return severity
== kWarning
;
9730 // Prints the given message to stdout iff 'severity' >= the level
9731 // specified by the --gmock_verbose flag. If stack_frames_to_skip >=
9732 // 0, also prints the stack trace excluding the top
9733 // stack_frames_to_skip frames. In opt mode, any positive
9734 // stack_frames_to_skip is treated as 0, since we don't know which
9735 // function calls will be inlined by the compiler and need to be
9737 GTEST_API_
void Log(LogSeverity severity
, const string
& message
,
9738 int stack_frames_to_skip
) {
9739 if (!LogIsVisible(severity
)) return;
9741 // Ensures that logs from different threads don't interleave.
9742 MutexLock
l(&g_log_mutex
);
9744 // "using ::std::cout;" doesn't work with Symbian's STLport, where cout is a
9747 if (severity
== kWarning
) {
9748 // Prints a GMOCK WARNING marker to make the warnings easily searchable.
9749 std::cout
<< "\nGMOCK WARNING:";
9751 // Pre-pends a new-line to message if it doesn't start with one.
9752 if (message
.empty() || message
[0] != '\n') {
9755 std::cout
<< message
;
9756 if (stack_frames_to_skip
>= 0) {
9758 // In opt mode, we have to be conservative and skip no stack frame.
9759 const int actual_to_skip
= 0;
9761 // In dbg mode, we can do what the caller tell us to do (plus one
9762 // for skipping this function's stack frame).
9763 const int actual_to_skip
= stack_frames_to_skip
+ 1;
9766 // Appends a new-line to message if it doesn't end with one.
9767 if (!message
.empty() && *message
.rbegin() != '\n') {
9770 std::cout
<< "Stack trace:\n"
9771 << ::testing::internal::GetCurrentOsStackTraceExceptTop(
9772 ::testing::UnitTest::GetInstance(), actual_to_skip
);
9774 std::cout
<< ::std::flush
;
9777 } // namespace internal
9778 } // namespace testing
9779 // Copyright 2007, Google Inc.
9780 // All rights reserved.
9782 // Redistribution and use in source and binary forms, with or without
9783 // modification, are permitted provided that the following conditions are
9786 // * Redistributions of source code must retain the above copyright
9787 // notice, this list of conditions and the following disclaimer.
9788 // * Redistributions in binary form must reproduce the above
9789 // copyright notice, this list of conditions and the following disclaimer
9790 // in the documentation and/or other materials provided with the
9792 // * Neither the name of Google Inc. nor the names of its
9793 // contributors may be used to endorse or promote products derived from
9794 // this software without specific prior written permission.
9796 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
9797 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
9798 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
9799 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9800 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
9801 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9802 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
9803 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
9804 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
9805 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
9806 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
9808 // Author: wan@google.com (Zhanyong Wan)
9810 // Google Mock - a framework for writing C++ mock classes.
9812 // This file implements Matcher<const string&>, Matcher<string>, and
9813 // utilities for defining matchers.
9822 // Constructs a matcher that matches a const string& whose value is
9824 Matcher
<const internal::string
&>::Matcher(const internal::string
& s
) {
9828 // Constructs a matcher that matches a const string& whose value is
9830 Matcher
<const internal::string
&>::Matcher(const char* s
) {
9831 *this = Eq(internal::string(s
));
9834 // Constructs a matcher that matches a string whose value is equal to s.
9835 Matcher
<internal::string
>::Matcher(const internal::string
& s
) { *this = Eq(s
); }
9837 // Constructs a matcher that matches a string whose value is equal to s.
9838 Matcher
<internal::string
>::Matcher(const char* s
) {
9839 *this = Eq(internal::string(s
));
9842 #if GTEST_HAS_STRING_PIECE_
9843 // Constructs a matcher that matches a const StringPiece& whose value is
9845 Matcher
<const StringPiece
&>::Matcher(const internal::string
& s
) {
9849 // Constructs a matcher that matches a const StringPiece& whose value is
9851 Matcher
<const StringPiece
&>::Matcher(const char* s
) {
9852 *this = Eq(internal::string(s
));
9855 // Constructs a matcher that matches a const StringPiece& whose value is
9857 Matcher
<const StringPiece
&>::Matcher(StringPiece s
) {
9858 *this = Eq(s
.ToString());
9861 // Constructs a matcher that matches a StringPiece whose value is equal to s.
9862 Matcher
<StringPiece
>::Matcher(const internal::string
& s
) { *this = Eq(s
); }
9864 // Constructs a matcher that matches a StringPiece whose value is equal to s.
9865 Matcher
<StringPiece
>::Matcher(const char* s
) {
9866 *this = Eq(internal::string(s
));
9869 // Constructs a matcher that matches a StringPiece whose value is equal to s.
9870 Matcher
<StringPiece
>::Matcher(StringPiece s
) { *this = Eq(s
.ToString()); }
9871 #endif // GTEST_HAS_STRING_PIECE_
9873 namespace internal
{
9875 // Joins a vector of strings as if they are fields of a tuple; returns
9876 // the joined string.
9877 GTEST_API_ string
JoinAsTuple(const Strings
& fields
) {
9878 switch (fields
.size()) {
9884 string result
= "(" + fields
[0];
9885 for (size_t i
= 1; i
< fields
.size(); i
++) {
9887 result
+= fields
[i
];
9894 // Returns the description for a matcher defined using the MATCHER*()
9895 // macro where the user-supplied description string is "", if
9896 // 'negation' is false; otherwise returns the description of the
9897 // negation of the matcher. 'param_values' contains a list of strings
9898 // that are the print-out of the matcher's parameters.
9899 GTEST_API_ string
FormatMatcherDescription(bool negation
,
9900 const char* matcher_name
,
9901 const Strings
& param_values
) {
9902 string result
= ConvertIdentifierNameToWords(matcher_name
);
9903 if (param_values
.size() >= 1) result
+= " " + JoinAsTuple(param_values
);
9904 return negation
? "not (" + result
+ ")" : result
;
9907 // FindMaxBipartiteMatching and its helper class.
9909 // Uses the well-known Ford-Fulkerson max flow method to find a maximum
9910 // bipartite matching. Flow is considered to be from left to right.
9911 // There is an implicit source node that is connected to all of the left
9912 // nodes, and an implicit sink node that is connected to all of the
9913 // right nodes. All edges have unit capacity.
9915 // Neither the flow graph nor the residual flow graph are represented
9916 // explicitly. Instead, they are implied by the information in 'graph' and
9917 // a vector<int> called 'left_' whose elements are initialized to the
9918 // value kUnused. This represents the initial state of the algorithm,
9919 // where the flow graph is empty, and the residual flow graph has the
9921 // - An edge from source to each left_ node
9922 // - An edge from each right_ node to sink
9923 // - An edge from each left_ node to each right_ node, if the
9924 // corresponding edge exists in 'graph'.
9926 // When the TryAugment() method adds a flow, it sets left_[l] = r for some
9927 // nodes l and r. This induces the following changes:
9928 // - The edges (source, l), (l, r), and (r, sink) are added to the
9930 // - The same three edges are removed from the residual flow graph.
9931 // - The reverse edges (l, source), (r, l), and (sink, r) are added
9932 // to the residual flow graph, which is a directional graph
9933 // representing unused flow capacity.
9935 // When the method augments a flow (moving left_[l] from some r1 to some
9936 // other r2), this can be thought of as "undoing" the above steps with
9937 // respect to r1 and "redoing" them with respect to r2.
9939 // It bears repeating that the flow graph and residual flow graph are
9940 // never represented explicitly, but can be derived by looking at the
9941 // information in 'graph' and in left_.
9943 // As an optimization, there is a second vector<int> called right_ which
9944 // does not provide any new information. Instead, it enables more
9945 // efficient queries about edges entering or leaving the right-side nodes
9946 // of the flow or residual flow graphs. The following invariants are
9949 // left[l] == kUnused or right[left[l]] == l
9950 // right[r] == kUnused or left[right[r]] == r
9955 // . ||\--> left[0]=1 ---\ right[0]=-1 ----\ .
9957 // . |\---> left[1]=-1 \--> right[1]=0 ---\| .
9959 // . \----> left[2]=2 ------> right[2]=2 --\|| .
9961 // . elements matchers vvv .
9965 // [1] Cormen, et al (2001). "Section 26.2: The Ford–Fulkerson method".
9966 // "Introduction to Algorithms (Second ed.)", pp. 651–664.
9967 // [2] "Ford–Fulkerson algorithm", Wikipedia,
9968 // 'http://en.wikipedia.org/wiki/Ford%E2%80%93Fulkerson_algorithm'
9969 class MaxBipartiteMatchState
{
9971 explicit MaxBipartiteMatchState(const MatchMatrix
& graph
)
9973 left_(graph_
->LhsSize(), kUnused
),
9974 right_(graph_
->RhsSize(), kUnused
) {}
9976 // Returns the edges of a maximal match, each in the form {left, right}.
9977 ElementMatcherPairs
Compute() {
9978 // 'seen' is used for path finding { 0: unseen, 1: seen }.
9979 ::std::vector
<char> seen
;
9980 // Searches the residual flow graph for a path from each left node to
9981 // the sink in the residual flow graph, and if one is found, add flow
9982 // to the graph. It's okay to search through the left nodes once. The
9983 // edge from the implicit source node to each previously-visited left
9984 // node will have flow if that left node has any path to the sink
9985 // whatsoever. Subsequent augmentations can only add flow to the
9986 // network, and cannot take away that previous flow unit from the source.
9987 // Since the source-to-left edge can only carry one flow unit (or,
9988 // each element can be matched to only one matcher), there is no need
9989 // to visit the left nodes more than once looking for augmented paths.
9990 // The flow is known to be possible or impossible by looking at the
9992 for (size_t ilhs
= 0; ilhs
< graph_
->LhsSize(); ++ilhs
) {
9993 // Reset the path-marking vector and try to find a path from
9994 // source to sink starting at the left_[ilhs] node.
9995 GTEST_CHECK_(left_
[ilhs
] == kUnused
)
9996 << "ilhs: " << ilhs
<< ", left_[ilhs]: " << left_
[ilhs
];
9997 // 'seen' initialized to 'graph_->RhsSize()' copies of 0.
9998 seen
.assign(graph_
->RhsSize(), 0);
9999 TryAugment(ilhs
, &seen
);
10001 ElementMatcherPairs result
;
10002 for (size_t ilhs
= 0; ilhs
< left_
.size(); ++ilhs
) {
10003 size_t irhs
= left_
[ilhs
];
10004 if (irhs
== kUnused
) continue;
10005 result
.push_back(ElementMatcherPair(ilhs
, irhs
));
10011 static const size_t kUnused
= static_cast<size_t>(-1);
10013 // Perform a depth-first search from left node ilhs to the sink. If a
10014 // path is found, flow is added to the network by linking the left and
10015 // right vector elements corresponding each segment of the path.
10016 // Returns true if a path to sink was found, which means that a unit of
10017 // flow was added to the network. The 'seen' vector elements correspond
10018 // to right nodes and are marked to eliminate cycles from the search.
10020 // Left nodes will only be explored at most once because they
10021 // are accessible from at most one right node in the residual flow
10024 // Note that left_[ilhs] is the only element of left_ that TryAugment will
10025 // potentially transition from kUnused to another value. Any other
10026 // left_ element holding kUnused before TryAugment will be holding it
10027 // when TryAugment returns.
10029 bool TryAugment(size_t ilhs
, ::std::vector
<char>* seen
) {
10030 for (size_t irhs
= 0; irhs
< graph_
->RhsSize(); ++irhs
) {
10031 if ((*seen
)[irhs
]) continue;
10032 if (!graph_
->HasEdge(ilhs
, irhs
)) continue;
10033 // There's an available edge from ilhs to irhs.
10035 // Next a search is performed to determine whether
10036 // this edge is a dead end or leads to the sink.
10038 // right_[irhs] == kUnused means that there is residual flow from
10039 // right node irhs to the sink, so we can use that to finish this
10040 // flow path and return success.
10042 // Otherwise there is residual flow to some ilhs. We push flow
10043 // along that path and call ourselves recursively to see if this
10044 // ultimately leads to sink.
10045 if (right_
[irhs
] == kUnused
|| TryAugment(right_
[irhs
], seen
)) {
10046 // Add flow from left_[ilhs] to right_[irhs].
10047 left_
[ilhs
] = irhs
;
10048 right_
[irhs
] = ilhs
;
10055 const MatchMatrix
* graph_
; // not owned
10056 // Each element of the left_ vector represents a left hand side node
10057 // (i.e. an element) and each element of right_ is a right hand side
10058 // node (i.e. a matcher). The values in the left_ vector indicate
10059 // outflow from that node to a node on the the right_ side. The values
10060 // in the right_ indicate inflow, and specify which left_ node is
10061 // feeding that right_ node, if any. For example, left_[3] == 1 means
10062 // there's a flow from element #3 to matcher #1. Such a flow would also
10063 // be redundantly represented in the right_ vector as right_[1] == 3.
10064 // Elements of left_ and right_ are either kUnused or mutually
10065 // referent. Mutually referent means that left_[right_[i]] = i and
10066 // right_[left_[i]] = i.
10067 ::std::vector
<size_t> left_
;
10068 ::std::vector
<size_t> right_
;
10070 GTEST_DISALLOW_ASSIGN_(MaxBipartiteMatchState
);
10073 const size_t MaxBipartiteMatchState::kUnused
;
10075 GTEST_API_ ElementMatcherPairs
FindMaxBipartiteMatching(const MatchMatrix
& g
) {
10076 return MaxBipartiteMatchState(g
).Compute();
10079 static void LogElementMatcherPairVec(const ElementMatcherPairs
& pairs
,
10080 ::std::ostream
* stream
) {
10081 typedef ElementMatcherPairs::const_iterator Iter
;
10082 ::std::ostream
& os
= *stream
;
10084 const char* sep
= "";
10085 for (Iter it
= pairs
.begin(); it
!= pairs
.end(); ++it
) {
10086 os
<< sep
<< "\n ("
10087 << "element #" << it
->first
<< ", "
10088 << "matcher #" << it
->second
<< ")";
10094 // Tries to find a pairing, and explains the result.
10095 GTEST_API_
bool FindPairing(const MatchMatrix
& matrix
,
10096 MatchResultListener
* listener
) {
10097 ElementMatcherPairs matches
= FindMaxBipartiteMatching(matrix
);
10099 size_t max_flow
= matches
.size();
10100 bool result
= (max_flow
== matrix
.RhsSize());
10103 if (listener
->IsInterested()) {
10104 *listener
<< "where no permutation of the elements can "
10105 "satisfy all matchers, and the closest match is "
10106 << max_flow
<< " of " << matrix
.RhsSize()
10107 << " matchers with the pairings:\n";
10108 LogElementMatcherPairVec(matches
, listener
->stream());
10113 if (matches
.size() > 1) {
10114 if (listener
->IsInterested()) {
10115 const char* sep
= "where:\n";
10116 for (size_t mi
= 0; mi
< matches
.size(); ++mi
) {
10117 *listener
<< sep
<< " - element #" << matches
[mi
].first
10118 << " is matched by matcher #" << matches
[mi
].second
;
10126 bool MatchMatrix::NextGraph() {
10127 for (size_t ilhs
= 0; ilhs
< LhsSize(); ++ilhs
) {
10128 for (size_t irhs
= 0; irhs
< RhsSize(); ++irhs
) {
10129 char& b
= matched_
[SpaceIndex(ilhs
, irhs
)];
10140 void MatchMatrix::Randomize() {
10141 for (size_t ilhs
= 0; ilhs
< LhsSize(); ++ilhs
) {
10142 for (size_t irhs
= 0; irhs
< RhsSize(); ++irhs
) {
10143 char& b
= matched_
[SpaceIndex(ilhs
, irhs
)];
10144 b
= static_cast<char>(rand() & 1); // NOLINT
10149 string
MatchMatrix::DebugString() const {
10150 ::std::stringstream ss
;
10151 const char* sep
= "";
10152 for (size_t i
= 0; i
< LhsSize(); ++i
) {
10154 for (size_t j
= 0; j
< RhsSize(); ++j
) {
10155 ss
<< HasEdge(i
, j
);
10162 void UnorderedElementsAreMatcherImplBase::DescribeToImpl(
10163 ::std::ostream
* os
) const {
10164 if (matcher_describers_
.empty()) {
10168 if (matcher_describers_
.size() == 1) {
10169 *os
<< "has " << Elements(1) << " and that element ";
10170 matcher_describers_
[0]->DescribeTo(os
);
10173 *os
<< "has " << Elements(matcher_describers_
.size())
10174 << " and there exists some permutation of elements such that:\n";
10175 const char* sep
= "";
10176 for (size_t i
= 0; i
!= matcher_describers_
.size(); ++i
) {
10177 *os
<< sep
<< " - element #" << i
<< " ";
10178 matcher_describers_
[i
]->DescribeTo(os
);
10183 void UnorderedElementsAreMatcherImplBase::DescribeNegationToImpl(
10184 ::std::ostream
* os
) const {
10185 if (matcher_describers_
.empty()) {
10186 *os
<< "isn't empty";
10189 if (matcher_describers_
.size() == 1) {
10190 *os
<< "doesn't have " << Elements(1) << ", or has " << Elements(1)
10192 matcher_describers_
[0]->DescribeNegationTo(os
);
10195 *os
<< "doesn't have " << Elements(matcher_describers_
.size())
10196 << ", or there exists no permutation of elements such that:\n";
10197 const char* sep
= "";
10198 for (size_t i
= 0; i
!= matcher_describers_
.size(); ++i
) {
10199 *os
<< sep
<< " - element #" << i
<< " ";
10200 matcher_describers_
[i
]->DescribeTo(os
);
10205 // Checks that all matchers match at least one element, and that all
10206 // elements match at least one matcher. This enables faster matching
10207 // and better error reporting.
10208 // Returns false, writing an explanation to 'listener', if and only
10209 // if the success criteria are not met.
10210 bool UnorderedElementsAreMatcherImplBase::
10211 VerifyAllElementsAndMatchersAreMatched(
10212 const ::std::vector
<string
>& element_printouts
,
10213 const MatchMatrix
& matrix
, MatchResultListener
* listener
) const {
10214 bool result
= true;
10215 ::std::vector
<char> element_matched(matrix
.LhsSize(), 0);
10216 ::std::vector
<char> matcher_matched(matrix
.RhsSize(), 0);
10218 for (size_t ilhs
= 0; ilhs
< matrix
.LhsSize(); ilhs
++) {
10219 for (size_t irhs
= 0; irhs
< matrix
.RhsSize(); irhs
++) {
10220 char matched
= matrix
.HasEdge(ilhs
, irhs
);
10221 element_matched
[ilhs
] |= matched
;
10222 matcher_matched
[irhs
] |= matched
;
10228 "where the following matchers don't match any elements:\n";
10229 for (size_t mi
= 0; mi
< matcher_matched
.size(); ++mi
) {
10230 if (matcher_matched
[mi
]) continue;
10232 if (listener
->IsInterested()) {
10233 *listener
<< sep
<< "matcher #" << mi
<< ": ";
10234 matcher_describers_
[mi
]->DescribeTo(listener
->stream());
10242 "where the following elements don't match any matchers:\n";
10243 const char* outer_sep
= "";
10245 outer_sep
= "\nand ";
10247 for (size_t ei
= 0; ei
< element_matched
.size(); ++ei
) {
10248 if (element_matched
[ei
]) continue;
10250 if (listener
->IsInterested()) {
10251 *listener
<< outer_sep
<< sep
<< "element #" << ei
<< ": "
10252 << element_printouts
[ei
];
10261 } // namespace internal
10262 } // namespace testing
10263 // Copyright 2007, Google Inc.
10264 // All rights reserved.
10266 // Redistribution and use in source and binary forms, with or without
10267 // modification, are permitted provided that the following conditions are
10270 // * Redistributions of source code must retain the above copyright
10271 // notice, this list of conditions and the following disclaimer.
10272 // * Redistributions in binary form must reproduce the above
10273 // copyright notice, this list of conditions and the following disclaimer
10274 // in the documentation and/or other materials provided with the
10276 // * Neither the name of Google Inc. nor the names of its
10277 // contributors may be used to endorse or promote products derived from
10278 // this software without specific prior written permission.
10280 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
10281 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
10282 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
10283 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
10284 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
10285 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
10286 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
10287 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
10288 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
10289 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
10290 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
10292 // Author: wan@google.com (Zhanyong Wan)
10294 // Google Mock - a framework for writing C++ mock classes.
10296 // This file implements the spec builder syntax (ON_CALL and
10299 #include <stdlib.h>
10301 #include <iostream> // NOLINT
10306 #if GTEST_OS_CYGWIN || GTEST_OS_LINUX || GTEST_OS_MAC
10307 # include <unistd.h> // NOLINT
10310 namespace testing
{
10311 namespace internal
{
10313 // Protects the mock object registry (in class Mock), all function
10314 // mockers, and all expectations.
10315 GTEST_API_
GTEST_DEFINE_STATIC_MUTEX_(g_gmock_mutex
);
10317 // Logs a message including file and line number information.
10318 GTEST_API_
void LogWithLocation(testing::internal::LogSeverity severity
,
10319 const char* file
, int line
,
10320 const string
& message
) {
10321 ::std::ostringstream s
;
10322 s
<< file
<< ":" << line
<< ": " << message
<< ::std::endl
;
10323 Log(severity
, s
.str(), 0);
10326 // Constructs an ExpectationBase object.
10327 ExpectationBase::ExpectationBase(const char* a_file
, int a_line
,
10328 const string
& a_source_text
)
10331 source_text_(a_source_text
),
10332 cardinality_specified_(false),
10333 cardinality_(Exactly(1)),
10336 extra_matcher_specified_(false),
10337 repeated_action_specified_(false),
10338 retires_on_saturation_(false),
10339 last_clause_(kNone
),
10340 action_count_checked_(false) {}
10342 // Destructs an ExpectationBase object.
10343 ExpectationBase::~ExpectationBase() {}
10345 // Explicitly specifies the cardinality of this expectation. Used by
10346 // the subclasses to implement the .Times() clause.
10347 void ExpectationBase::SpecifyCardinality(const Cardinality
& a_cardinality
) {
10348 cardinality_specified_
= true;
10349 cardinality_
= a_cardinality
;
10352 // Retires all pre-requisites of this expectation.
10353 void ExpectationBase::RetireAllPreRequisites()
10354 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex
) {
10355 if (is_retired()) {
10356 // We can take this short-cut as we never retire an expectation
10357 // until we have retired all its pre-requisites.
10361 for (ExpectationSet::const_iterator it
= immediate_prerequisites_
.begin();
10362 it
!= immediate_prerequisites_
.end(); ++it
) {
10363 ExpectationBase
* const prerequisite
= it
->expectation_base().get();
10364 if (!prerequisite
->is_retired()) {
10365 prerequisite
->RetireAllPreRequisites();
10366 prerequisite
->Retire();
10371 // Returns true iff all pre-requisites of this expectation have been
10373 bool ExpectationBase::AllPrerequisitesAreSatisfied() const
10374 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex
) {
10375 g_gmock_mutex
.AssertHeld();
10376 for (ExpectationSet::const_iterator it
= immediate_prerequisites_
.begin();
10377 it
!= immediate_prerequisites_
.end(); ++it
) {
10378 if (!(it
->expectation_base()->IsSatisfied()) ||
10379 !(it
->expectation_base()->AllPrerequisitesAreSatisfied()))
10385 // Adds unsatisfied pre-requisites of this expectation to 'result'.
10386 void ExpectationBase::FindUnsatisfiedPrerequisites(ExpectationSet
* result
) const
10387 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex
) {
10388 g_gmock_mutex
.AssertHeld();
10389 for (ExpectationSet::const_iterator it
= immediate_prerequisites_
.begin();
10390 it
!= immediate_prerequisites_
.end(); ++it
) {
10391 if (it
->expectation_base()->IsSatisfied()) {
10392 // If *it is satisfied and has a call count of 0, some of its
10393 // pre-requisites may not be satisfied yet.
10394 if (it
->expectation_base()->call_count_
== 0) {
10395 it
->expectation_base()->FindUnsatisfiedPrerequisites(result
);
10398 // Now that we know *it is unsatisfied, we are not so interested
10399 // in whether its pre-requisites are satisfied. Therefore we
10400 // don't recursively call FindUnsatisfiedPrerequisites() here.
10406 // Describes how many times a function call matching this
10407 // expectation has occurred.
10408 void ExpectationBase::DescribeCallCountTo(::std::ostream
* os
) const
10409 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex
) {
10410 g_gmock_mutex
.AssertHeld();
10412 // Describes how many times the function is expected to be called.
10413 *os
<< " Expected: to be ";
10414 cardinality().DescribeTo(os
);
10415 *os
<< "\n Actual: ";
10416 Cardinality::DescribeActualCallCountTo(call_count(), os
);
10418 // Describes the state of the expectation (e.g. is it satisfied?
10421 << (IsOverSaturated()
10423 : IsSaturated() ? "saturated"
10424 : IsSatisfied() ? "satisfied" : "unsatisfied")
10425 << " and " << (is_retired() ? "retired" : "active");
10428 // Checks the action count (i.e. the number of WillOnce() and
10429 // WillRepeatedly() clauses) against the cardinality if this hasn't
10430 // been done before. Prints a warning if there are too many or too
10432 void ExpectationBase::CheckActionCountIfNotDone() const
10433 GTEST_LOCK_EXCLUDED_(mutex_
) {
10434 bool should_check
= false;
10436 MutexLock
l(&mutex_
);
10437 if (!action_count_checked_
) {
10438 action_count_checked_
= true;
10439 should_check
= true;
10443 if (should_check
) {
10444 if (!cardinality_specified_
) {
10445 // The cardinality was inferred - no need to check the action
10446 // count against it.
10450 // The cardinality was explicitly specified.
10451 const int action_count
= static_cast<int>(untyped_actions_
.size());
10452 const int upper_bound
= cardinality().ConservativeUpperBound();
10453 const int lower_bound
= cardinality().ConservativeLowerBound();
10454 bool too_many
; // True if there are too many actions, or false
10455 // if there are too few.
10456 if (action_count
> upper_bound
||
10457 (action_count
== upper_bound
&& repeated_action_specified_
)) {
10459 } else if (0 < action_count
&& action_count
< lower_bound
&&
10460 !repeated_action_specified_
) {
10466 ::std::stringstream ss
;
10467 DescribeLocationTo(&ss
);
10468 ss
<< "Too " << (too_many
? "many" : "few") << " actions specified in "
10469 << source_text() << "...\n"
10470 << "Expected to be ";
10471 cardinality().DescribeTo(&ss
);
10472 ss
<< ", but has " << (too_many
? "" : "only ") << action_count
10473 << " WillOnce()" << (action_count
== 1 ? "" : "s");
10474 if (repeated_action_specified_
) {
10475 ss
<< " and a WillRepeatedly()";
10478 Log(kWarning
, ss
.str(), -1); // -1 means "don't print stack trace".
10482 // Implements the .Times() clause.
10483 void ExpectationBase::UntypedTimes(const Cardinality
& a_cardinality
) {
10484 if (last_clause_
== kTimes
) {
10485 ExpectSpecProperty(false,
10486 ".Times() cannot appear "
10487 "more than once in an EXPECT_CALL().");
10489 ExpectSpecProperty(last_clause_
< kTimes
,
10490 ".Times() cannot appear after "
10491 ".InSequence(), .WillOnce(), .WillRepeatedly(), "
10492 "or .RetiresOnSaturation().");
10494 last_clause_
= kTimes
;
10496 SpecifyCardinality(a_cardinality
);
10499 // Points to the implicit sequence introduced by a living InSequence
10500 // object (if any) in the current thread or NULL.
10501 GTEST_API_ ThreadLocal
<Sequence
*> g_gmock_implicit_sequence
;
10503 // Reports an uninteresting call (whose description is in msg) in the
10504 // manner specified by 'reaction'.
10505 void ReportUninterestingCall(CallReaction reaction
, const string
& msg
) {
10506 switch (reaction
) {
10508 Log(kInfo
, msg
, 3);
10511 Log(kWarning
, msg
, 3);
10514 Expect(false, NULL
, -1, msg
);
10518 UntypedFunctionMockerBase::UntypedFunctionMockerBase()
10519 : mock_obj_(NULL
), name_("") {}
10521 UntypedFunctionMockerBase::~UntypedFunctionMockerBase() {}
10523 // Sets the mock object this mock method belongs to, and registers
10524 // this information in the global mock registry. Will be called
10525 // whenever an EXPECT_CALL() or ON_CALL() is executed on this mock
10527 void UntypedFunctionMockerBase::RegisterOwner(const void* mock_obj
)
10528 GTEST_LOCK_EXCLUDED_(g_gmock_mutex
) {
10530 MutexLock
l(&g_gmock_mutex
);
10531 mock_obj_
= mock_obj
;
10533 Mock::Register(mock_obj
, this);
10536 // Sets the mock object this mock method belongs to, and sets the name
10537 // of the mock function. Will be called upon each invocation of this
10539 void UntypedFunctionMockerBase::SetOwnerAndName(const void* mock_obj
,
10541 GTEST_LOCK_EXCLUDED_(g_gmock_mutex
) {
10542 // We protect name_ under g_gmock_mutex in case this mock function
10543 // is called from two threads concurrently.
10544 MutexLock
l(&g_gmock_mutex
);
10545 mock_obj_
= mock_obj
;
10549 // Returns the name of the function being mocked. Must be called
10550 // after RegisterOwner() or SetOwnerAndName() has been called.
10551 const void* UntypedFunctionMockerBase::MockObject() const
10552 GTEST_LOCK_EXCLUDED_(g_gmock_mutex
) {
10553 const void* mock_obj
;
10555 // We protect mock_obj_ under g_gmock_mutex in case this mock
10556 // function is called from two threads concurrently.
10557 MutexLock
l(&g_gmock_mutex
);
10558 Assert(mock_obj_
!= NULL
, __FILE__
, __LINE__
,
10559 "MockObject() must not be called before RegisterOwner() or "
10560 "SetOwnerAndName() has been called.");
10561 mock_obj
= mock_obj_
;
10566 // Returns the name of this mock method. Must be called after
10567 // SetOwnerAndName() has been called.
10568 const char* UntypedFunctionMockerBase::Name() const
10569 GTEST_LOCK_EXCLUDED_(g_gmock_mutex
) {
10572 // We protect name_ under g_gmock_mutex in case this mock
10573 // function is called from two threads concurrently.
10574 MutexLock
l(&g_gmock_mutex
);
10575 Assert(name_
!= NULL
, __FILE__
, __LINE__
,
10576 "Name() must not be called before SetOwnerAndName() has "
10583 // Calculates the result of invoking this mock function with the given
10584 // arguments, prints it, and returns it. The caller is responsible
10585 // for deleting the result.
10586 const UntypedActionResultHolderBase
*
10587 UntypedFunctionMockerBase::UntypedInvokeWith(const void* const untyped_args
)
10588 GTEST_LOCK_EXCLUDED_(g_gmock_mutex
) {
10589 if (untyped_expectations_
.size() == 0) {
10590 // No expectation is set on this mock method - we have an
10591 // uninteresting call.
10593 // We must get Google Mock's reaction on uninteresting calls
10594 // made on this mock object BEFORE performing the action,
10595 // because the action may DELETE the mock object and make the
10596 // following expression meaningless.
10597 const CallReaction reaction
=
10598 Mock::GetReactionOnUninterestingCalls(MockObject());
10600 // True iff we need to print this call's arguments and return
10601 // value. This definition must be kept in sync with
10602 // the behavior of ReportUninterestingCall().
10603 const bool need_to_report_uninteresting_call
=
10604 // If the user allows this uninteresting call, we print it
10605 // only when he wants informational messages.
10606 reaction
== kAllow
? LogIsVisible(kInfo
) :
10607 // If the user wants this to be a warning, we print
10608 // it only when he wants to see warnings.
10610 ? LogIsVisible(kWarning
)
10612 // Otherwise, the user wants this to be an error, and we
10613 // should always print detailed information in the error.
10616 if (!need_to_report_uninteresting_call
) {
10617 // Perform the action without printing the call information.
10618 return this->UntypedPerformDefaultAction(untyped_args
, "");
10621 // Warns about the uninteresting call.
10622 ::std::stringstream ss
;
10623 this->UntypedDescribeUninterestingCall(untyped_args
, &ss
);
10625 // Calculates the function result.
10626 const UntypedActionResultHolderBase
* const result
=
10627 this->UntypedPerformDefaultAction(untyped_args
, ss
.str());
10629 // Prints the function result.
10630 if (result
!= NULL
) result
->PrintAsActionResult(&ss
);
10632 ReportUninterestingCall(reaction
, ss
.str());
10636 bool is_excessive
= false;
10637 ::std::stringstream ss
;
10638 ::std::stringstream why
;
10639 ::std::stringstream loc
;
10640 const void* untyped_action
= NULL
;
10642 // The UntypedFindMatchingExpectation() function acquires and
10643 // releases g_gmock_mutex.
10644 const ExpectationBase
* const untyped_expectation
=
10645 this->UntypedFindMatchingExpectation(untyped_args
, &untyped_action
,
10646 &is_excessive
, &ss
, &why
);
10647 const bool found
= untyped_expectation
!= NULL
;
10649 // True iff we need to print the call's arguments and return value.
10650 // This definition must be kept in sync with the uses of Expect()
10651 // and Log() in this function.
10652 const bool need_to_report_call
=
10653 !found
|| is_excessive
|| LogIsVisible(kInfo
);
10654 if (!need_to_report_call
) {
10655 // Perform the action without printing the call information.
10656 return untyped_action
== NULL
10657 ? this->UntypedPerformDefaultAction(untyped_args
, "")
10658 : this->UntypedPerformAction(untyped_action
, untyped_args
);
10661 ss
<< " Function call: " << Name();
10662 this->UntypedPrintArgs(untyped_args
, &ss
);
10664 // In case the action deletes a piece of the expectation, we
10665 // generate the message beforehand.
10666 if (found
&& !is_excessive
) {
10667 untyped_expectation
->DescribeLocationTo(&loc
);
10670 const UntypedActionResultHolderBase
* const result
=
10671 untyped_action
== NULL
10672 ? this->UntypedPerformDefaultAction(untyped_args
, ss
.str())
10673 : this->UntypedPerformAction(untyped_action
, untyped_args
);
10674 if (result
!= NULL
) result
->PrintAsActionResult(&ss
);
10675 ss
<< "\n" << why
.str();
10678 // No expectation matches this call - reports a failure.
10679 Expect(false, NULL
, -1, ss
.str());
10680 } else if (is_excessive
) {
10681 // We had an upper-bound violation and the failure message is in ss.
10682 Expect(false, untyped_expectation
->file(), untyped_expectation
->line(),
10685 // We had an expected call and the matching expectation is
10686 // described in ss.
10687 Log(kInfo
, loc
.str() + ss
.str(), 2);
10693 // Returns an Expectation object that references and co-owns exp,
10694 // which must be an expectation on this mock function.
10695 Expectation
UntypedFunctionMockerBase::GetHandleOf(ExpectationBase
* exp
) {
10696 for (UntypedExpectations::const_iterator it
= untyped_expectations_
.begin();
10697 it
!= untyped_expectations_
.end(); ++it
) {
10698 if (it
->get() == exp
) {
10699 return Expectation(*it
);
10703 Assert(false, __FILE__
, __LINE__
, "Cannot find expectation.");
10704 return Expectation();
10705 // The above statement is just to make the code compile, and will
10706 // never be executed.
10709 // Verifies that all expectations on this mock function have been
10710 // satisfied. Reports one or more Google Test non-fatal failures
10711 // and returns false if not.
10712 bool UntypedFunctionMockerBase::VerifyAndClearExpectationsLocked()
10713 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex
) {
10714 g_gmock_mutex
.AssertHeld();
10715 bool expectations_met
= true;
10716 for (UntypedExpectations::const_iterator it
= untyped_expectations_
.begin();
10717 it
!= untyped_expectations_
.end(); ++it
) {
10718 ExpectationBase
* const untyped_expectation
= it
->get();
10719 if (untyped_expectation
->IsOverSaturated()) {
10720 // There was an upper-bound violation. Since the error was
10721 // already reported when it occurred, there is no need to do
10723 expectations_met
= false;
10724 } else if (!untyped_expectation
->IsSatisfied()) {
10725 expectations_met
= false;
10726 ::std::stringstream ss
;
10727 ss
<< "Actual function call count doesn't match "
10728 << untyped_expectation
->source_text() << "...\n";
10729 // No need to show the source file location of the expectation
10730 // in the description, as the Expect() call that follows already
10731 // takes care of it.
10732 untyped_expectation
->MaybeDescribeExtraMatcherTo(&ss
);
10733 untyped_expectation
->DescribeCallCountTo(&ss
);
10734 Expect(false, untyped_expectation
->file(), untyped_expectation
->line(),
10739 // Deleting our expectations may trigger other mock objects to be deleted, for
10740 // example if an action contains a reference counted smart pointer to that
10741 // mock object, and that is the last reference. So if we delete our
10742 // expectations within the context of the global mutex we may deadlock when
10743 // this method is called again. Instead, make a copy of the set of
10744 // expectations to delete, clear our set within the mutex, and then clear the
10745 // copied set outside of it.
10746 UntypedExpectations expectations_to_delete
;
10747 untyped_expectations_
.swap(expectations_to_delete
);
10749 g_gmock_mutex
.Unlock();
10750 expectations_to_delete
.clear();
10751 g_gmock_mutex
.Lock();
10753 return expectations_met
;
10756 } // namespace internal
10762 typedef std::set
<internal::UntypedFunctionMockerBase
*> FunctionMockers
;
10764 // The current state of a mock object. Such information is needed for
10765 // detecting leaked mock objects and explicitly verifying a mock's
10767 struct MockObjectState
{
10769 : first_used_file(NULL
), first_used_line(-1), leakable(false) {}
10771 // Where in the source file an ON_CALL or EXPECT_CALL is first
10772 // invoked on this mock object.
10773 const char* first_used_file
;
10774 int first_used_line
;
10775 ::std::string first_used_test_case
;
10776 ::std::string first_used_test
;
10777 bool leakable
; // true iff it's OK to leak the object.
10778 FunctionMockers function_mockers
; // All registered methods of the object.
10781 // A global registry holding the state of all mock objects that are
10782 // alive. A mock object is added to this registry the first time
10783 // Mock::AllowLeak(), ON_CALL(), or EXPECT_CALL() is called on it. It
10784 // is removed from the registry in the mock object's destructor.
10785 class MockObjectRegistry
{
10787 // Maps a mock object (identified by its address) to its state.
10788 typedef std::map
<const void*, MockObjectState
> StateMap
;
10790 // This destructor will be called when a program exits, after all
10791 // tests in it have been run. By then, there should be no mock
10792 // object alive. Therefore we report any living object as test
10793 // failure, unless the user explicitly asked us to ignore it.
10794 ~MockObjectRegistry() {
10795 // "using ::std::cout;" doesn't work with Symbian's STLport, where cout is
10798 if (!GMOCK_FLAG(catch_leaked_mocks
)) return;
10800 int leaked_count
= 0;
10801 for (StateMap::const_iterator it
= states_
.begin(); it
!= states_
.end();
10803 if (it
->second
.leakable
) // The user said it's fine to leak this object.
10806 // TODO(wan@google.com): Print the type of the leaked object.
10807 // This can help the user identify the leaked object.
10809 const MockObjectState
& state
= it
->second
;
10810 std::cout
<< internal::FormatFileLocation(state
.first_used_file
,
10811 state
.first_used_line
);
10812 std::cout
<< " ERROR: this mock object";
10813 if (state
.first_used_test
!= "") {
10814 std::cout
<< " (used in test " << state
.first_used_test_case
<< "."
10815 << state
.first_used_test
<< ")";
10817 std::cout
<< " should be deleted but never is. Its address is @"
10818 << it
->first
<< ".";
10821 if (leaked_count
> 0) {
10822 std::cout
<< "\nERROR: " << leaked_count
<< " leaked mock "
10823 << (leaked_count
== 1 ? "object" : "objects")
10824 << " found at program exit.\n";
10826 ::std::cerr
.flush();
10827 // RUN_ALL_TESTS() has already returned when this destructor is
10828 // called. Therefore we cannot use the normal Google Test
10829 // failure reporting mechanism.
10830 _exit(1); // We cannot call exit() as it is not reentrant and
10831 // may already have been called.
10835 StateMap
& states() { return states_
; }
10841 // Protected by g_gmock_mutex.
10842 MockObjectRegistry g_mock_object_registry
;
10844 // Maps a mock object to the reaction Google Mock should have when an
10845 // uninteresting method is called. Protected by g_gmock_mutex.
10846 std::map
<const void*, internal::CallReaction
> g_uninteresting_call_reaction
;
10848 // Sets the reaction Google Mock should have when an uninteresting
10849 // method of the given mock object is called.
10850 void SetReactionOnUninterestingCalls(const void* mock_obj
,
10851 internal::CallReaction reaction
)
10852 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex
) {
10853 internal::MutexLock
l(&internal::g_gmock_mutex
);
10854 g_uninteresting_call_reaction
[mock_obj
] = reaction
;
10859 // Tells Google Mock to allow uninteresting calls on the given mock
10861 void Mock::AllowUninterestingCalls(const void* mock_obj
)
10862 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex
) {
10863 SetReactionOnUninterestingCalls(mock_obj
, internal::kAllow
);
10866 // Tells Google Mock to warn the user about uninteresting calls on the
10867 // given mock object.
10868 void Mock::WarnUninterestingCalls(const void* mock_obj
)
10869 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex
) {
10870 SetReactionOnUninterestingCalls(mock_obj
, internal::kWarn
);
10873 // Tells Google Mock to fail uninteresting calls on the given mock
10875 void Mock::FailUninterestingCalls(const void* mock_obj
)
10876 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex
) {
10877 SetReactionOnUninterestingCalls(mock_obj
, internal::kFail
);
10880 // Tells Google Mock the given mock object is being destroyed and its
10881 // entry in the call-reaction table should be removed.
10882 void Mock::UnregisterCallReaction(const void* mock_obj
)
10883 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex
) {
10884 internal::MutexLock
l(&internal::g_gmock_mutex
);
10885 g_uninteresting_call_reaction
.erase(mock_obj
);
10888 // Returns the reaction Google Mock will have on uninteresting calls
10889 // made on the given mock object.
10890 internal::CallReaction
Mock::GetReactionOnUninterestingCalls(
10891 const void* mock_obj
) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex
) {
10892 internal::MutexLock
l(&internal::g_gmock_mutex
);
10893 return (g_uninteresting_call_reaction
.count(mock_obj
) == 0)
10894 ? internal::kDefault
10895 : g_uninteresting_call_reaction
[mock_obj
];
10898 // Tells Google Mock to ignore mock_obj when checking for leaked mock
10900 void Mock::AllowLeak(const void* mock_obj
)
10901 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex
) {
10902 internal::MutexLock
l(&internal::g_gmock_mutex
);
10903 g_mock_object_registry
.states()[mock_obj
].leakable
= true;
10906 // Verifies and clears all expectations on the given mock object. If
10907 // the expectations aren't satisfied, generates one or more Google
10908 // Test non-fatal failures and returns false.
10909 bool Mock::VerifyAndClearExpectations(void* mock_obj
)
10910 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex
) {
10911 internal::MutexLock
l(&internal::g_gmock_mutex
);
10912 return VerifyAndClearExpectationsLocked(mock_obj
);
10915 // Verifies all expectations on the given mock object and clears its
10916 // default actions and expectations. Returns true iff the
10917 // verification was successful.
10918 bool Mock::VerifyAndClear(void* mock_obj
)
10919 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex
) {
10920 internal::MutexLock
l(&internal::g_gmock_mutex
);
10921 ClearDefaultActionsLocked(mock_obj
);
10922 return VerifyAndClearExpectationsLocked(mock_obj
);
10925 // Verifies and clears all expectations on the given mock object. If
10926 // the expectations aren't satisfied, generates one or more Google
10927 // Test non-fatal failures and returns false.
10928 bool Mock::VerifyAndClearExpectationsLocked(void* mock_obj
)
10929 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex
) {
10930 internal::g_gmock_mutex
.AssertHeld();
10931 if (g_mock_object_registry
.states().count(mock_obj
) == 0) {
10932 // No EXPECT_CALL() was set on the given mock object.
10936 // Verifies and clears the expectations on each mock method in the
10937 // given mock object.
10938 bool expectations_met
= true;
10939 FunctionMockers
& mockers
=
10940 g_mock_object_registry
.states()[mock_obj
].function_mockers
;
10941 for (FunctionMockers::const_iterator it
= mockers
.begin();
10942 it
!= mockers
.end(); ++it
) {
10943 if (!(*it
)->VerifyAndClearExpectationsLocked()) {
10944 expectations_met
= false;
10948 // We don't clear the content of mockers, as they may still be
10949 // needed by ClearDefaultActionsLocked().
10950 return expectations_met
;
10953 // Registers a mock object and a mock method it owns.
10954 void Mock::Register(const void* mock_obj
,
10955 internal::UntypedFunctionMockerBase
* mocker
)
10956 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex
) {
10957 internal::MutexLock
l(&internal::g_gmock_mutex
);
10958 g_mock_object_registry
.states()[mock_obj
].function_mockers
.insert(mocker
);
10961 // Tells Google Mock where in the source code mock_obj is used in an
10962 // ON_CALL or EXPECT_CALL. In case mock_obj is leaked, this
10963 // information helps the user identify which object it is.
10964 void Mock::RegisterUseByOnCallOrExpectCall(const void* mock_obj
,
10965 const char* file
, int line
)
10966 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex
) {
10967 internal::MutexLock
l(&internal::g_gmock_mutex
);
10968 MockObjectState
& state
= g_mock_object_registry
.states()[mock_obj
];
10969 if (state
.first_used_file
== NULL
) {
10970 state
.first_used_file
= file
;
10971 state
.first_used_line
= line
;
10972 const TestInfo
* const test_info
=
10973 UnitTest::GetInstance()->current_test_info();
10974 if (test_info
!= NULL
) {
10975 // TODO(wan@google.com): record the test case name when the
10976 // ON_CALL or EXPECT_CALL is invoked from SetUpTestCase() or
10977 // TearDownTestCase().
10978 state
.first_used_test_case
= test_info
->test_case_name();
10979 state
.first_used_test
= test_info
->name();
10984 // Unregisters a mock method; removes the owning mock object from the
10985 // registry when the last mock method associated with it has been
10986 // unregistered. This is called only in the destructor of
10987 // FunctionMockerBase.
10988 void Mock::UnregisterLocked(internal::UntypedFunctionMockerBase
* mocker
)
10989 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex
) {
10990 internal::g_gmock_mutex
.AssertHeld();
10991 for (MockObjectRegistry::StateMap::iterator it
=
10992 g_mock_object_registry
.states().begin();
10993 it
!= g_mock_object_registry
.states().end(); ++it
) {
10994 FunctionMockers
& mockers
= it
->second
.function_mockers
;
10995 if (mockers
.erase(mocker
) > 0) {
10996 // mocker was in mockers and has been just removed.
10997 if (mockers
.empty()) {
10998 g_mock_object_registry
.states().erase(it
);
11005 // Clears all ON_CALL()s set on the given mock object.
11006 void Mock::ClearDefaultActionsLocked(void* mock_obj
)
11007 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex
) {
11008 internal::g_gmock_mutex
.AssertHeld();
11010 if (g_mock_object_registry
.states().count(mock_obj
) == 0) {
11011 // No ON_CALL() was set on the given mock object.
11015 // Clears the default actions for each mock method in the given mock
11017 FunctionMockers
& mockers
=
11018 g_mock_object_registry
.states()[mock_obj
].function_mockers
;
11019 for (FunctionMockers::const_iterator it
= mockers
.begin();
11020 it
!= mockers
.end(); ++it
) {
11021 (*it
)->ClearDefaultActionsLocked();
11024 // We don't clear the content of mockers, as they may still be
11025 // needed by VerifyAndClearExpectationsLocked().
11028 Expectation::Expectation() {}
11030 Expectation::Expectation(
11031 const internal::linked_ptr
<internal::ExpectationBase
>& an_expectation_base
)
11032 : expectation_base_(an_expectation_base
) {}
11034 Expectation::~Expectation() {}
11036 // Adds an expectation to a sequence.
11037 void Sequence::AddExpectation(const Expectation
& expectation
) const {
11038 if (*last_expectation_
!= expectation
) {
11039 if (last_expectation_
->expectation_base() != NULL
) {
11040 expectation
.expectation_base()->immediate_prerequisites_
+=
11041 *last_expectation_
;
11043 *last_expectation_
= expectation
;
11047 // Creates the implicit sequence if there isn't one.
11048 InSequence::InSequence() {
11049 if (internal::g_gmock_implicit_sequence
.get() == NULL
) {
11050 internal::g_gmock_implicit_sequence
.set(new Sequence
);
11051 sequence_created_
= true;
11053 sequence_created_
= false;
11057 // Deletes the implicit sequence if it was created by the constructor
11059 InSequence::~InSequence() {
11060 if (sequence_created_
) {
11061 delete internal::g_gmock_implicit_sequence
.get();
11062 internal::g_gmock_implicit_sequence
.set(NULL
);
11066 } // namespace testing
11067 // Copyright 2008, Google Inc.
11068 // All rights reserved.
11070 // Redistribution and use in source and binary forms, with or without
11071 // modification, are permitted provided that the following conditions are
11074 // * Redistributions of source code must retain the above copyright
11075 // notice, this list of conditions and the following disclaimer.
11076 // * Redistributions in binary form must reproduce the above
11077 // copyright notice, this list of conditions and the following disclaimer
11078 // in the documentation and/or other materials provided with the
11080 // * Neither the name of Google Inc. nor the names of its
11081 // contributors may be used to endorse or promote products derived from
11082 // this software without specific prior written permission.
11084 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
11085 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
11086 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
11087 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
11088 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
11089 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
11090 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
11091 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
11092 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
11093 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
11094 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
11096 // Author: wan@google.com (Zhanyong Wan)
11098 namespace testing
{
11100 // TODO(wan@google.com): support using environment variables to
11101 // control the flag values, like what Google Test does.
11103 GMOCK_DEFINE_bool_(catch_leaked_mocks
, true,
11104 "true iff Google Mock should report leaked mock objects "
11107 GMOCK_DEFINE_string_(verbose
, internal::kWarningVerbosity
,
11108 "Controls how verbose Google Mock's output is."
11110 " info - prints all messages.\n"
11111 " warning - prints warnings and errors.\n"
11112 " error - prints errors only.");
11114 namespace internal
{
11116 // Parses a string as a command line flag. The string should have the
11117 // format "--gmock_flag=value". When def_optional is true, the
11118 // "=value" part can be omitted.
11120 // Returns the value of the flag, or NULL if the parsing failed.
11121 static const char* ParseGoogleMockFlagValue(const char* str
, const char* flag
,
11122 bool def_optional
) {
11123 // str and flag must not be NULL.
11124 if (str
== NULL
|| flag
== NULL
) return NULL
;
11126 // The flag must start with "--gmock_".
11127 const std::string flag_str
= std::string("--gmock_") + flag
;
11128 const size_t flag_len
= flag_str
.length();
11129 if (strncmp(str
, flag_str
.c_str(), flag_len
) != 0) return NULL
;
11131 // Skips the flag name.
11132 const char* flag_end
= str
+ flag_len
;
11134 // When def_optional is true, it's OK to not have a "=value" part.
11135 if (def_optional
&& (flag_end
[0] == '\0')) {
11139 // If def_optional is true and there are more characters after the
11140 // flag name, or if def_optional is false, there must be a '=' after
11142 if (flag_end
[0] != '=') return NULL
;
11144 // Returns the string after "=".
11145 return flag_end
+ 1;
11148 // Parses a string for a Google Mock bool flag, in the form of
11149 // "--gmock_flag=value".
11151 // On success, stores the value of the flag in *value, and returns
11152 // true. On failure, returns false without changing *value.
11153 static bool ParseGoogleMockBoolFlag(const char* str
, const char* flag
,
11155 // Gets the value of the flag as a string.
11156 const char* const value_str
= ParseGoogleMockFlagValue(str
, flag
, true);
11158 // Aborts if the parsing failed.
11159 if (value_str
== NULL
) return false;
11161 // Converts the string value to a bool.
11162 *value
= !(*value_str
== '0' || *value_str
== 'f' || *value_str
== 'F');
11166 // Parses a string for a Google Mock string flag, in the form of
11167 // "--gmock_flag=value".
11169 // On success, stores the value of the flag in *value, and returns
11170 // true. On failure, returns false without changing *value.
11171 static bool ParseGoogleMockStringFlag(const char* str
, const char* flag
,
11172 std::string
* value
) {
11173 // Gets the value of the flag as a string.
11174 const char* const value_str
= ParseGoogleMockFlagValue(str
, flag
, false);
11176 // Aborts if the parsing failed.
11177 if (value_str
== NULL
) return false;
11179 // Sets *value to the value of the flag.
11180 *value
= value_str
;
11184 // The internal implementation of InitGoogleMock().
11186 // The type parameter CharType can be instantiated to either char or
11188 template <typename CharType
>
11189 void InitGoogleMockImpl(int* argc
, CharType
** argv
) {
11190 // Makes sure Google Test is initialized. InitGoogleTest() is
11191 // idempotent, so it's fine if the user has already called it.
11192 InitGoogleTest(argc
, argv
);
11193 if (*argc
<= 0) return;
11195 for (int i
= 1; i
!= *argc
; i
++) {
11196 const std::string arg_string
= StreamableToString(argv
[i
]);
11197 const char* const arg
= arg_string
.c_str();
11199 // Do we see a Google Mock flag?
11200 if (ParseGoogleMockBoolFlag(arg
, "catch_leaked_mocks",
11201 &GMOCK_FLAG(catch_leaked_mocks
)) ||
11202 ParseGoogleMockStringFlag(arg
, "verbose", &GMOCK_FLAG(verbose
))) {
11203 // Yes. Shift the remainder of the argv list left by one. Note
11204 // that argv has (*argc + 1) elements, the last one always being
11205 // NULL. The following loop moves the trailing NULL element as
11207 for (int j
= i
; j
!= *argc
; j
++) {
11208 argv
[j
] = argv
[j
+ 1];
11211 // Decrements the argument count.
11214 // We also need to decrement the iterator as we just removed
11221 } // namespace internal
11223 // Initializes Google Mock. This must be called before running the
11224 // tests. In particular, it parses a command line for the flags that
11225 // Google Mock recognizes. Whenever a Google Mock flag is seen, it is
11226 // removed from argv, and *argc is decremented.
11228 // No value is returned. Instead, the Google Mock flag variables are
11231 // Since Google Test is needed for Google Mock to work, this function
11232 // also initializes Google Test and parses its flags, if that hasn't
11234 GTEST_API_
void InitGoogleMock(int* argc
, char** argv
) {
11235 internal::InitGoogleMockImpl(argc
, argv
);
11238 // This overloaded version can be used in Windows programs compiled in
11240 GTEST_API_
void InitGoogleMock(int* argc
, wchar_t** argv
) {
11241 internal::InitGoogleMockImpl(argc
, argv
);
11244 } // namespace testing