1 // Copyright 2008, Google Inc.
2 // All rights reserved.
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
8 // * Redistributions of source code must retain the above copyright
9 // notice, this list of conditions and the following disclaimer.
10 // * Redistributions in binary form must reproduce the above
11 // copyright notice, this list of conditions and the following disclaimer
12 // in the documentation and/or other materials provided with the
14 // * Neither the name of Google Inc. nor the names of its
15 // contributors may be used to endorse or promote products derived from
16 // this software without specific prior written permission.
18 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 // Author: mheule@google.com (Markus Heule)
32 // Google C++ Testing Framework (Google Test)
34 // Sometimes it's desirable to build Google Test by compiling a single file.
35 // This file serves this purpose.
37 // This line ensures that gtest.h can be compiled on its own, even
39 #include "gtest/gtest.h"
41 // The following lines pull in the real gtest *.cc files.
42 // Copyright 2005, Google Inc.
43 // All rights reserved.
45 // Redistribution and use in source and binary forms, with or without
46 // modification, are permitted provided that the following conditions are
49 // * Redistributions of source code must retain the above copyright
50 // notice, this list of conditions and the following disclaimer.
51 // * Redistributions in binary form must reproduce the above
52 // copyright notice, this list of conditions and the following disclaimer
53 // in the documentation and/or other materials provided with the
55 // * Neither the name of Google Inc. nor the names of its
56 // contributors may be used to endorse or promote products derived from
57 // this software without specific prior written permission.
59 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
60 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
61 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
62 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
63 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
64 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
65 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
66 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
67 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
68 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
69 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
71 // Author: wan@google.com (Zhanyong Wan)
73 // The Google C++ Testing Framework (Google Test)
75 // Copyright 2007, Google Inc.
76 // All rights reserved.
78 // Redistribution and use in source and binary forms, with or without
79 // modification, are permitted provided that the following conditions are
82 // * Redistributions of source code must retain the above copyright
83 // notice, this list of conditions and the following disclaimer.
84 // * Redistributions in binary form must reproduce the above
85 // copyright notice, this list of conditions and the following disclaimer
86 // in the documentation and/or other materials provided with the
88 // * Neither the name of Google Inc. nor the names of its
89 // contributors may be used to endorse or promote products derived from
90 // this software without specific prior written permission.
92 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
93 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
94 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
95 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
96 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
97 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
98 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
99 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
100 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
101 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
102 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
104 // Author: wan@google.com (Zhanyong Wan)
106 // Utilities for testing Google Test itself and code that uses Google Test
107 // (e.g. frameworks built on top of Google Test).
109 #ifndef GTEST_INCLUDE_GTEST_GTEST_SPI_H_
110 #define GTEST_INCLUDE_GTEST_GTEST_SPI_H_
115 // This helper class can be used to mock out Google Test failure reporting
116 // so that we can test Google Test or code that builds on Google Test.
118 // An object of this class appends a TestPartResult object to the
119 // TestPartResultArray object given in the constructor whenever a Google Test
120 // failure is reported. It can either intercept only failures that are
121 // generated in the same thread that created this object or it can intercept
122 // all generated failures. The scope of this mock object can be controlled with
123 // the second argument to the two arguments constructor.
124 class GTEST_API_ ScopedFakeTestPartResultReporter
125 : public TestPartResultReporterInterface {
127 // The two possible mocking modes of this object.
129 INTERCEPT_ONLY_CURRENT_THREAD, // Intercepts only thread local failures.
130 INTERCEPT_ALL_THREADS // Intercepts all failures.
133 // The c'tor sets this object as the test part result reporter used
134 // by Google Test. The 'result' parameter specifies where to report the
135 // results. This reporter will only catch failures generated in the current
136 // thread. DEPRECATED
137 explicit ScopedFakeTestPartResultReporter(TestPartResultArray* result);
139 // Same as above, but you can choose the interception scope of this object.
140 ScopedFakeTestPartResultReporter(InterceptMode intercept_mode,
141 TestPartResultArray* result);
143 // The d'tor restores the previous test part result reporter.
144 virtual ~ScopedFakeTestPartResultReporter();
146 // Appends the TestPartResult object to the TestPartResultArray
147 // received in the constructor.
149 // This method is from the TestPartResultReporterInterface
151 virtual void ReportTestPartResult(const TestPartResult& result);
155 const InterceptMode intercept_mode_;
156 TestPartResultReporterInterface* old_reporter_;
157 TestPartResultArray* const result_;
159 GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedFakeTestPartResultReporter);
164 // A helper class for implementing EXPECT_FATAL_FAILURE() and
165 // EXPECT_NONFATAL_FAILURE(). Its destructor verifies that the given
166 // TestPartResultArray contains exactly one failure that has the given
167 // type and contains the given substring. If that's not the case, a
168 // non-fatal failure will be generated.
169 class GTEST_API_ SingleFailureChecker {
171 // The constructor remembers the arguments.
172 SingleFailureChecker(const TestPartResultArray* results,
173 TestPartResult::Type type,
174 const string& substr);
175 ~SingleFailureChecker();
177 const TestPartResultArray* const results_;
178 const TestPartResult::Type type_;
179 const string substr_;
181 GTEST_DISALLOW_COPY_AND_ASSIGN_(SingleFailureChecker);
184 } // namespace internal
186 } // namespace testing
188 // A set of macros for testing Google Test assertions or code that's expected
189 // to generate Google Test fatal failures. It verifies that the given
190 // statement will cause exactly one fatal Google Test failure with 'substr'
191 // being part of the failure message.
193 // There are two different versions of this macro. EXPECT_FATAL_FAILURE only
194 // affects and considers failures generated in the current thread and
195 // EXPECT_FATAL_FAILURE_ON_ALL_THREADS does the same but for all threads.
197 // The verification of the assertion is done correctly even when the statement
198 // throws an exception or aborts the current function.
200 // Known restrictions:
201 // - 'statement' cannot reference local non-static variables or
202 // non-static members of the current object.
203 // - 'statement' cannot return a value.
204 // - You cannot stream a failure message to this macro.
206 // Note that even though the implementations of the following two
207 // macros are much alike, we cannot refactor them to use a common
208 // helper macro, due to some peculiarity in how the preprocessor
209 // works. The AcceptsMacroThatExpandsToUnprotectedComma test in
210 // gtest_unittest.cc will fail to compile if we do that.
211 #define EXPECT_FATAL_FAILURE(statement, substr) \
213 class GTestExpectFatalFailureHelper {\
215 static void Execute() { statement; }\
217 ::testing::TestPartResultArray gtest_failures;\
218 ::testing::internal::SingleFailureChecker gtest_checker(\
219 >est_failures, ::testing::TestPartResult::kFatalFailure, (substr));\
221 ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
222 ::testing::ScopedFakeTestPartResultReporter:: \
223 INTERCEPT_ONLY_CURRENT_THREAD, >est_failures);\
224 GTestExpectFatalFailureHelper::Execute();\
226 } while (::testing::internal::AlwaysFalse())
228 #define EXPECT_FATAL_FAILURE_ON_ALL_THREADS(statement, substr) \
230 class GTestExpectFatalFailureHelper {\
232 static void Execute() { statement; }\
234 ::testing::TestPartResultArray gtest_failures;\
235 ::testing::internal::SingleFailureChecker gtest_checker(\
236 >est_failures, ::testing::TestPartResult::kFatalFailure, (substr));\
238 ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
239 ::testing::ScopedFakeTestPartResultReporter:: \
240 INTERCEPT_ALL_THREADS, >est_failures);\
241 GTestExpectFatalFailureHelper::Execute();\
243 } while (::testing::internal::AlwaysFalse())
245 // A macro for testing Google Test assertions or code that's expected to
246 // generate Google Test non-fatal failures. It asserts that the given
247 // statement will cause exactly one non-fatal Google Test failure with 'substr'
248 // being part of the failure message.
250 // There are two different versions of this macro. EXPECT_NONFATAL_FAILURE only
251 // affects and considers failures generated in the current thread and
252 // EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS does the same but for all threads.
254 // 'statement' is allowed to reference local variables and members of
255 // the current object.
257 // The verification of the assertion is done correctly even when the statement
258 // throws an exception or aborts the current function.
260 // Known restrictions:
261 // - You cannot stream a failure message to this macro.
263 // Note that even though the implementations of the following two
264 // macros are much alike, we cannot refactor them to use a common
265 // helper macro, due to some peculiarity in how the preprocessor
266 // works. If we do that, the code won't compile when the user gives
267 // EXPECT_NONFATAL_FAILURE() a statement that contains a macro that
268 // expands to code containing an unprotected comma. The
269 // AcceptsMacroThatExpandsToUnprotectedComma test in gtest_unittest.cc
272 // For the same reason, we have to write
273 // if (::testing::internal::AlwaysTrue()) { statement; }
275 // GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement)
276 // to avoid an MSVC warning on unreachable code.
277 #define EXPECT_NONFATAL_FAILURE(statement, substr) \
279 ::testing::TestPartResultArray gtest_failures;\
280 ::testing::internal::SingleFailureChecker gtest_checker(\
281 >est_failures, ::testing::TestPartResult::kNonFatalFailure, \
284 ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
285 ::testing::ScopedFakeTestPartResultReporter:: \
286 INTERCEPT_ONLY_CURRENT_THREAD, >est_failures);\
287 if (::testing::internal::AlwaysTrue()) { statement; }\
289 } while (::testing::internal::AlwaysFalse())
291 #define EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(statement, substr) \
293 ::testing::TestPartResultArray gtest_failures;\
294 ::testing::internal::SingleFailureChecker gtest_checker(\
295 >est_failures, ::testing::TestPartResult::kNonFatalFailure, \
298 ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
299 ::testing::ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, \
301 if (::testing::internal::AlwaysTrue()) { statement; }\
303 } while (::testing::internal::AlwaysFalse())
305 #endif // GTEST_INCLUDE_GTEST_GTEST_SPI_H_
321 #include <ostream> // NOLINT
327 // TODO(kenton@google.com): Use autoconf to detect availability of
329 # define GTEST_HAS_GETTIMEOFDAY_ 1
331 # include <fcntl.h> // NOLINT
332 # include <limits.h> // NOLINT
333 # include <sched.h> // NOLINT
334 // Declares vsnprintf(). This header is not available on Windows.
335 # include <strings.h> // NOLINT
336 # include <sys/mman.h> // NOLINT
337 # include <sys/time.h> // NOLINT
338 # include <unistd.h> // NOLINT
341 #elif GTEST_OS_SYMBIAN
342 # define GTEST_HAS_GETTIMEOFDAY_ 1
343 # include <sys/time.h> // NOLINT
346 # define GTEST_HAS_GETTIMEOFDAY_ 1
347 # include <sys/time.h> // NOLINT
349 // On z/OS we additionally need strings.h for strcasecmp.
350 # include <strings.h> // NOLINT
352 #elif GTEST_OS_WINDOWS_MOBILE // We are on Windows CE.
354 # include <windows.h> // NOLINT
357 #elif GTEST_OS_WINDOWS // We are on Windows proper.
359 # include <io.h> // NOLINT
360 # include <sys/timeb.h> // NOLINT
361 # include <sys/types.h> // NOLINT
362 # include <sys/stat.h> // NOLINT
364 # if GTEST_OS_WINDOWS_MINGW
365 // MinGW has gettimeofday() but not _ftime64().
366 // TODO(kenton@google.com): Use autoconf to detect availability of
368 // TODO(kenton@google.com): There are other ways to get the time on
369 // Windows, like GetTickCount() or GetSystemTimeAsFileTime(). MinGW
370 // supports these. consider using them instead.
371 # define GTEST_HAS_GETTIMEOFDAY_ 1
372 # include <sys/time.h> // NOLINT
373 # endif // GTEST_OS_WINDOWS_MINGW
375 // cpplint thinks that the header is already included, so we want to
377 # include <windows.h> // NOLINT
382 // Assume other platforms have gettimeofday().
383 // TODO(kenton@google.com): Use autoconf to detect availability of
385 # define GTEST_HAS_GETTIMEOFDAY_ 1
387 // cpplint thinks that the header is already included, so we want to
389 # include <sys/time.h> // NOLINT
390 # include <unistd.h> // NOLINT
392 #endif // GTEST_OS_LINUX
394 #if GTEST_HAS_EXCEPTIONS
395 # include <stdexcept>
398 #if GTEST_CAN_STREAM_RESULTS_
399 # include <arpa/inet.h> // NOLINT
400 # include <netdb.h> // NOLINT
401 # include <sys/socket.h> // NOLINT
402 # include <sys/types.h> // NOLINT
405 // Indicates that this translation unit is part of Google Test's
406 // implementation. It must come before gtest-internal-inl.h is
407 // included, or there will be a compiler error. This trick is to
408 // prevent a user from accidentally including gtest-internal-inl.h in
410 #define GTEST_IMPLEMENTATION_ 1
411 // Copyright 2005, Google Inc.
412 // All rights reserved.
414 // Redistribution and use in source and binary forms, with or without
415 // modification, are permitted provided that the following conditions are
418 // * Redistributions of source code must retain the above copyright
419 // notice, this list of conditions and the following disclaimer.
420 // * Redistributions in binary form must reproduce the above
421 // copyright notice, this list of conditions and the following disclaimer
422 // in the documentation and/or other materials provided with the
424 // * Neither the name of Google Inc. nor the names of its
425 // contributors may be used to endorse or promote products derived from
426 // this software without specific prior written permission.
428 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
429 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
430 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
431 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
432 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
433 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
434 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
435 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
436 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
437 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
438 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
440 // Utility functions and classes used by the Google C++ testing framework.
442 // Author: wan@google.com (Zhanyong Wan)
444 // This file contains purely Google Test's internal implementation. Please
445 // DO NOT #INCLUDE IT IN A USER PROGRAM.
447 #ifndef GTEST_SRC_GTEST_INTERNAL_INL_H_
448 #define GTEST_SRC_GTEST_INTERNAL_INL_H_
450 // GTEST_IMPLEMENTATION_ is defined to 1 iff the current translation unit is
451 // part of Google Test's implementation; otherwise it's undefined.
452 #if !GTEST_IMPLEMENTATION_
453 // If this file is included from the user's code, just say no.
454 # error "gtest-internal-inl.h is part of Google Test's internal implementation."
455 # error "It must not be included except by Google Test itself."
456 #endif // GTEST_IMPLEMENTATION_
460 #endif // !_WIN32_WCE
462 #include <stdlib.h> // For strtoll/_strtoul64/malloc/free.
463 #include <string.h> // For memmove.
470 #if GTEST_CAN_STREAM_RESULTS_
471 # include <arpa/inet.h> // NOLINT
472 # include <netdb.h> // NOLINT
476 # include <windows.h> // NOLINT
477 #endif // GTEST_OS_WINDOWS
482 // Declares the flags.
484 // We don't want the users to modify this flag in the code, but want
485 // Google Test's own unit tests to be able to access it. Therefore we
486 // declare it here as opposed to in gtest.h.
487 GTEST_DECLARE_bool_(death_test_use_fork);
491 // The value of GetTestTypeId() as seen from within the Google Test
492 // library. This is solely for testing GetTestTypeId().
493 GTEST_API_ extern const TypeId kTestTypeIdInGoogleTest;
495 // Names of the flags (needed for parsing Google Test flags).
496 const char kAlsoRunDisabledTestsFlag[] = "also_run_disabled_tests";
497 const char kBreakOnFailureFlag[] = "break_on_failure";
498 const char kCatchExceptionsFlag[] = "catch_exceptions";
499 const char kColorFlag[] = "color";
500 const char kFilterFlag[] = "filter";
501 const char kListTestsFlag[] = "list_tests";
502 const char kOutputFlag[] = "output";
503 const char kPrintTimeFlag[] = "print_time";
504 const char kRandomSeedFlag[] = "random_seed";
505 const char kRepeatFlag[] = "repeat";
506 const char kShuffleFlag[] = "shuffle";
507 const char kStackTraceDepthFlag[] = "stack_trace_depth";
508 const char kStreamResultToFlag[] = "stream_result_to";
509 const char kThrowOnFailureFlag[] = "throw_on_failure";
510 const char kFlagfileFlag[] = "flagfile";
512 // A valid random seed must be in [1, kMaxRandomSeed].
513 const int kMaxRandomSeed = 99999;
515 // g_help_flag is true iff the --help flag or an equivalent form is
516 // specified on the command line.
517 GTEST_API_ extern bool g_help_flag;
519 // Returns the current time in milliseconds.
520 GTEST_API_ TimeInMillis GetTimeInMillis();
522 // Returns true iff Google Test should use colors in the output.
523 GTEST_API_ bool ShouldUseColor(bool stdout_is_tty);
525 // Formats the given time in milliseconds as seconds.
526 GTEST_API_ std::string FormatTimeInMillisAsSeconds(TimeInMillis ms);
528 // Converts the given time in milliseconds to a date string in the ISO 8601
529 // format, without the timezone information. N.B.: due to the use the
530 // non-reentrant localtime() function, this function is not thread safe. Do
531 // not use it in any code that can be called from multiple threads.
532 GTEST_API_ std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms);
534 // Parses a string for an Int32 flag, in the form of "--flag=value".
536 // On success, stores the value of the flag in *value, and returns
537 // true. On failure, returns false without changing *value.
538 GTEST_API_ bool ParseInt32Flag(
539 const char* str, const char* flag, Int32* value);
541 // Returns a random seed in range [1, kMaxRandomSeed] based on the
542 // given --gtest_random_seed flag value.
543 inline int GetRandomSeedFromFlag(Int32 random_seed_flag) {
544 const unsigned int raw_seed = (random_seed_flag == 0) ?
545 static_cast<unsigned int>(GetTimeInMillis()) :
546 static_cast<unsigned int>(random_seed_flag);
548 // Normalizes the actual seed to range [1, kMaxRandomSeed] such that
549 // it's easy to type.
550 const int normalized_seed =
551 static_cast<int>((raw_seed - 1U) %
552 static_cast<unsigned int>(kMaxRandomSeed)) + 1;
553 return normalized_seed;
556 // Returns the first valid random seed after 'seed'. The behavior is
557 // undefined if 'seed' is invalid. The seed after kMaxRandomSeed is
558 // considered to be 1.
559 inline int GetNextRandomSeed(int seed) {
560 GTEST_CHECK_(1 <= seed && seed <= kMaxRandomSeed)
561 << "Invalid random seed " << seed << " - must be in [1, "
562 << kMaxRandomSeed << "].";
563 const int next_seed = seed + 1;
564 return (next_seed > kMaxRandomSeed) ? 1 : next_seed;
567 // This class saves the values of all Google Test flags in its c'tor, and
568 // restores them in its d'tor.
569 class GTestFlagSaver {
573 also_run_disabled_tests_ = GTEST_FLAG(also_run_disabled_tests);
574 break_on_failure_ = GTEST_FLAG(break_on_failure);
575 catch_exceptions_ = GTEST_FLAG(catch_exceptions);
576 color_ = GTEST_FLAG(color);
577 death_test_style_ = GTEST_FLAG(death_test_style);
578 death_test_use_fork_ = GTEST_FLAG(death_test_use_fork);
579 filter_ = GTEST_FLAG(filter);
580 internal_run_death_test_ = GTEST_FLAG(internal_run_death_test);
581 list_tests_ = GTEST_FLAG(list_tests);
582 output_ = GTEST_FLAG(output);
583 print_time_ = GTEST_FLAG(print_time);
584 random_seed_ = GTEST_FLAG(random_seed);
585 repeat_ = GTEST_FLAG(repeat);
586 shuffle_ = GTEST_FLAG(shuffle);
587 stack_trace_depth_ = GTEST_FLAG(stack_trace_depth);
588 stream_result_to_ = GTEST_FLAG(stream_result_to);
589 throw_on_failure_ = GTEST_FLAG(throw_on_failure);
592 // The d'tor is not virtual. DO NOT INHERIT FROM THIS CLASS.
594 GTEST_FLAG(also_run_disabled_tests) = also_run_disabled_tests_;
595 GTEST_FLAG(break_on_failure) = break_on_failure_;
596 GTEST_FLAG(catch_exceptions) = catch_exceptions_;
597 GTEST_FLAG(color) = color_;
598 GTEST_FLAG(death_test_style) = death_test_style_;
599 GTEST_FLAG(death_test_use_fork) = death_test_use_fork_;
600 GTEST_FLAG(filter) = filter_;
601 GTEST_FLAG(internal_run_death_test) = internal_run_death_test_;
602 GTEST_FLAG(list_tests) = list_tests_;
603 GTEST_FLAG(output) = output_;
604 GTEST_FLAG(print_time) = print_time_;
605 GTEST_FLAG(random_seed) = random_seed_;
606 GTEST_FLAG(repeat) = repeat_;
607 GTEST_FLAG(shuffle) = shuffle_;
608 GTEST_FLAG(stack_trace_depth) = stack_trace_depth_;
609 GTEST_FLAG(stream_result_to) = stream_result_to_;
610 GTEST_FLAG(throw_on_failure) = throw_on_failure_;
614 // Fields for saving the original values of flags.
615 bool also_run_disabled_tests_;
616 bool break_on_failure_;
617 bool catch_exceptions_;
619 std::string death_test_style_;
620 bool death_test_use_fork_;
622 std::string internal_run_death_test_;
626 internal::Int32 random_seed_;
627 internal::Int32 repeat_;
629 internal::Int32 stack_trace_depth_;
630 std::string stream_result_to_;
631 bool throw_on_failure_;
632 } GTEST_ATTRIBUTE_UNUSED_;
634 // Converts a Unicode code point to a narrow string in UTF-8 encoding.
635 // code_point parameter is of type UInt32 because wchar_t may not be
636 // wide enough to contain a code point.
637 // If the code_point is not a valid Unicode code point
638 // (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted
639 // to "(Invalid Unicode 0xXXXXXXXX)".
640 GTEST_API_ std::string CodePointToUtf8(UInt32 code_point);
642 // Converts a wide string to a narrow string in UTF-8 encoding.
643 // The wide string is assumed to have the following encoding:
644 // UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS)
645 // UTF-32 if sizeof(wchar_t) == 4 (on Linux)
646 // Parameter str points to a null-terminated wide string.
647 // Parameter num_chars may additionally limit the number
648 // of wchar_t characters processed. -1 is used when the entire string
649 // should be processed.
650 // If the string contains code points that are not valid Unicode code points
651 // (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
652 // as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
653 // and contains invalid UTF-16 surrogate pairs, values in those pairs
654 // will be encoded as individual Unicode characters from Basic Normal Plane.
655 GTEST_API_ std::string WideStringToUtf8(const wchar_t* str, int num_chars);
657 // Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
658 // if the variable is present. If a file already exists at this location, this
659 // function will write over it. If the variable is present, but the file cannot
660 // be created, prints an error and exits.
661 void WriteToShardStatusFileIfNeeded();
663 // Checks whether sharding is enabled by examining the relevant
664 // environment variable values. If the variables are present,
665 // but inconsistent (e.g., shard_index >= total_shards), prints
666 // an error and exits. If in_subprocess_for_death_test, sharding is
667 // disabled because it must only be applied to the original test
668 // process. Otherwise, we could filter out death tests we intended to execute.
669 GTEST_API_ bool ShouldShard(const char* total_shards_str,
670 const char* shard_index_str,
671 bool in_subprocess_for_death_test);
673 // Parses the environment variable var as an Int32. If it is unset,
674 // returns default_val. If it is not an Int32, prints an error and
676 GTEST_API_ Int32 Int32FromEnvOrDie(const char* env_var, Int32 default_val);
678 // Given the total number of shards, the shard index, and the test id,
679 // returns true iff the test should be run on this shard. The test id is
680 // some arbitrary but unique non-negative integer assigned to each test
681 // method. Assumes that 0 <= shard_index < total_shards.
682 GTEST_API_ bool ShouldRunTestOnShard(
683 int total_shards, int shard_index, int test_id);
685 // STL container utilities.
687 // Returns the number of elements in the given container that satisfy
688 // the given predicate.
689 template <class Container, typename Predicate>
690 inline int CountIf(const Container& c, Predicate predicate) {
691 // Implemented as an explicit loop since std::count_if() in libCstd on
692 // Solaris has a non-standard signature.
694 for (typename Container::const_iterator it = c.begin(); it != c.end(); ++it) {
701 // Applies a function/functor to each element in the container.
702 template <class Container, typename Functor>
703 void ForEach(const Container& c, Functor functor) {
704 std::for_each(c.begin(), c.end(), functor);
707 // Returns the i-th element of the vector, or default_value if i is not
708 // in range [0, v.size()).
709 template <typename E>
710 inline E GetElementOr(const std::vector<E>& v, int i, E default_value) {
711 return (i < 0 || i >= static_cast<int>(v.size())) ? default_value : v[i];
714 // Performs an in-place shuffle of a range of the vector's elements.
715 // 'begin' and 'end' are element indices as an STL-style range;
716 // i.e. [begin, end) are shuffled, where 'end' == size() means to
717 // shuffle to the end of the vector.
718 template <typename E>
719 void ShuffleRange(internal::Random* random, int begin, int end,
721 const int size = static_cast<int>(v->size());
722 GTEST_CHECK_(0 <= begin && begin <= size)
723 << "Invalid shuffle range start " << begin << ": must be in range [0, "
725 GTEST_CHECK_(begin <= end && end <= size)
726 << "Invalid shuffle range finish " << end << ": must be in range ["
727 << begin << ", " << size << "].";
729 // Fisher-Yates shuffle, from
730 // http://en.wikipedia.org/wiki/Fisher-Yates_shuffle
731 for (int range_width = end - begin; range_width >= 2; range_width--) {
732 const int last_in_range = begin + range_width - 1;
733 const int selected = begin + random->Generate(range_width);
734 std::swap((*v)[selected], (*v)[last_in_range]);
738 // Performs an in-place shuffle of the vector's elements.
739 template <typename E>
740 inline void Shuffle(internal::Random* random, std::vector<E>* v) {
741 ShuffleRange(random, 0, static_cast<int>(v->size()), v);
744 // A function for deleting an object. Handy for being used as a
746 template <typename T>
747 static void Delete(T* x) {
751 // A predicate that checks the key of a TestProperty against a known key.
753 // TestPropertyKeyIs is copyable.
754 class TestPropertyKeyIs {
758 // TestPropertyKeyIs has NO default constructor.
759 explicit TestPropertyKeyIs(const std::string& key) : key_(key) {}
761 // Returns true iff the test name of test property matches on key_.
762 bool operator()(const TestProperty& test_property) const {
763 return test_property.key() == key_;
770 // Class UnitTestOptions.
772 // This class contains functions for processing options the user
773 // specifies when running the tests. It has only static members.
775 // In most cases, the user can specify an option using either an
776 // environment variable or a command line flag. E.g. you can set the
777 // test filter using either GTEST_FILTER or --gtest_filter. If both
778 // the variable and the flag are present, the latter overrides the
780 class GTEST_API_ UnitTestOptions {
782 // Functions for processing the gtest_output flag.
784 // Returns the output format, or "" for normal printed output.
785 static std::string GetOutputFormat();
787 // Returns the absolute path of the requested output file, or the
788 // default (test_detail.xml in the original working directory) if
789 // none was explicitly specified.
790 static std::string GetAbsolutePathToOutputFile();
792 // Functions for processing the gtest_filter flag.
794 // Returns true iff the wildcard pattern matches the string. The
795 // first ':' or '\0' character in pattern marks the end of it.
797 // This recursive algorithm isn't very efficient, but is clear and
798 // works well enough for matching test names, which are short.
799 static bool PatternMatchesString(const char *pattern, const char *str);
801 // Returns true iff the user-specified filter matches the test case
802 // name and the test name.
803 static bool FilterMatchesTest(const std::string &test_case_name,
804 const std::string &test_name);
807 // Function for supporting the gtest_catch_exception flag.
809 // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
810 // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
811 // This function is useful as an __except condition.
812 static int GTestShouldProcessSEH(DWORD exception_code);
813 #endif // GTEST_OS_WINDOWS
815 // Returns true if "name" matches the ':' separated list of glob-style
816 // filters in "filter".
817 static bool MatchesFilter(const std::string& name, const char* filter);
820 // Returns the current application's name, removing directory path if that
821 // is present. Used by UnitTestOptions::GetOutputFile.
822 GTEST_API_ FilePath GetCurrentExecutableName();
824 // The role interface for getting the OS stack trace as a string.
825 class OsStackTraceGetterInterface {
827 OsStackTraceGetterInterface() {}
828 virtual ~OsStackTraceGetterInterface() {}
830 // Returns the current OS stack trace as an std::string. Parameters:
832 // max_depth - the maximum number of stack frames to be included
834 // skip_count - the number of top frames to be skipped; doesn't count
835 // against max_depth.
836 virtual string CurrentStackTrace(int max_depth, int skip_count) = 0;
838 // UponLeavingGTest() should be called immediately before Google Test calls
839 // user code. It saves some information about the current stack that
840 // CurrentStackTrace() will use to find and hide Google Test stack frames.
841 virtual void UponLeavingGTest() = 0;
843 // This string is inserted in place of stack frames that are part of
844 // Google Test's implementation.
845 static const char* const kElidedFramesMarker;
848 GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetterInterface);
851 // A working implementation of the OsStackTraceGetterInterface interface.
852 class OsStackTraceGetter : public OsStackTraceGetterInterface {
854 OsStackTraceGetter() {}
856 virtual string CurrentStackTrace(int max_depth, int skip_count);
857 virtual void UponLeavingGTest();
860 GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetter);
863 // Information about a Google Test trace point.
870 // This is the default global test part result reporter used in UnitTestImpl.
871 // This class should only be used by UnitTestImpl.
872 class DefaultGlobalTestPartResultReporter
873 : public TestPartResultReporterInterface {
875 explicit DefaultGlobalTestPartResultReporter(UnitTestImpl* unit_test);
876 // Implements the TestPartResultReporterInterface. Reports the test part
877 // result in the current test.
878 virtual void ReportTestPartResult(const TestPartResult& result);
881 UnitTestImpl* const unit_test_;
883 GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultGlobalTestPartResultReporter);
886 // This is the default per thread test part result reporter used in
887 // UnitTestImpl. This class should only be used by UnitTestImpl.
888 class DefaultPerThreadTestPartResultReporter
889 : public TestPartResultReporterInterface {
891 explicit DefaultPerThreadTestPartResultReporter(UnitTestImpl* unit_test);
892 // Implements the TestPartResultReporterInterface. The implementation just
893 // delegates to the current global test part result reporter of *unit_test_.
894 virtual void ReportTestPartResult(const TestPartResult& result);
897 UnitTestImpl* const unit_test_;
899 GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultPerThreadTestPartResultReporter);
902 // The private implementation of the UnitTest class. We don't protect
903 // the methods under a mutex, as this class is not accessible by a
904 // user and the UnitTest class that delegates work to this class does
906 class GTEST_API_ UnitTestImpl {
908 explicit UnitTestImpl(UnitTest* parent);
909 virtual ~UnitTestImpl();
911 // There are two different ways to register your own TestPartResultReporter.
912 // You can register your own repoter to listen either only for test results
913 // from the current thread or for results from all threads.
914 // By default, each per-thread test result repoter just passes a new
915 // TestPartResult to the global test result reporter, which registers the
916 // test part result for the currently running test.
918 // Returns the global test part result reporter.
919 TestPartResultReporterInterface* GetGlobalTestPartResultReporter();
921 // Sets the global test part result reporter.
922 void SetGlobalTestPartResultReporter(
923 TestPartResultReporterInterface* reporter);
925 // Returns the test part result reporter for the current thread.
926 TestPartResultReporterInterface* GetTestPartResultReporterForCurrentThread();
928 // Sets the test part result reporter for the current thread.
929 void SetTestPartResultReporterForCurrentThread(
930 TestPartResultReporterInterface* reporter);
932 // Gets the number of successful test cases.
933 int successful_test_case_count() const;
935 // Gets the number of failed test cases.
936 int failed_test_case_count() const;
938 // Gets the number of all test cases.
939 int total_test_case_count() const;
941 // Gets the number of all test cases that contain at least one test
943 int test_case_to_run_count() const;
945 // Gets the number of successful tests.
946 int successful_test_count() const;
948 // Gets the number of failed tests.
949 int failed_test_count() const;
951 // Gets the number of disabled tests that will be reported in the XML report.
952 int reportable_disabled_test_count() const;
954 // Gets the number of disabled tests.
955 int disabled_test_count() const;
957 // Gets the number of tests to be printed in the XML report.
958 int reportable_test_count() const;
960 // Gets the number of all tests.
961 int total_test_count() const;
963 // Gets the number of tests that should run.
964 int test_to_run_count() const;
966 // Gets the time of the test program start, in ms from the start of the
968 TimeInMillis start_timestamp() const { return start_timestamp_; }
970 // Gets the elapsed time, in milliseconds.
971 TimeInMillis elapsed_time() const { return elapsed_time_; }
973 // Returns true iff the unit test passed (i.e. all test cases passed).
974 bool Passed() const { return !Failed(); }
976 // Returns true iff the unit test failed (i.e. some test case failed
977 // or something outside of all tests failed).
978 bool Failed() const {
979 return failed_test_case_count() > 0 || ad_hoc_test_result()->Failed();
982 // Gets the i-th test case among all the test cases. i can range from 0 to
983 // total_test_case_count() - 1. If i is not in that range, returns NULL.
984 const TestCase* GetTestCase(int i) const {
985 const int index = GetElementOr(test_case_indices_, i, -1);
986 return index < 0 ? NULL : test_cases_[i];
989 // Gets the i-th test case among all the test cases. i can range from 0 to
990 // total_test_case_count() - 1. If i is not in that range, returns NULL.
991 TestCase* GetMutableTestCase(int i) {
992 const int index = GetElementOr(test_case_indices_, i, -1);
993 return index < 0 ? NULL : test_cases_[index];
996 // Provides access to the event listener list.
997 TestEventListeners* listeners() { return &listeners_; }
999 // Returns the TestResult for the test that's currently running, or
1000 // the TestResult for the ad hoc test if no test is running.
1001 TestResult* current_test_result();
1003 // Returns the TestResult for the ad hoc test.
1004 const TestResult* ad_hoc_test_result() const { return &ad_hoc_test_result_; }
1006 // Sets the OS stack trace getter.
1008 // Does nothing if the input and the current OS stack trace getter
1009 // are the same; otherwise, deletes the old getter and makes the
1010 // input the current getter.
1011 void set_os_stack_trace_getter(OsStackTraceGetterInterface* getter);
1013 // Returns the current OS stack trace getter if it is not NULL;
1014 // otherwise, creates an OsStackTraceGetter, makes it the current
1015 // getter, and returns it.
1016 OsStackTraceGetterInterface* os_stack_trace_getter();
1018 // Returns the current OS stack trace as an std::string.
1020 // The maximum number of stack frames to be included is specified by
1021 // the gtest_stack_trace_depth flag. The skip_count parameter
1022 // specifies the number of top frames to be skipped, which doesn't
1023 // count against the number of frames to be included.
1025 // For example, if Foo() calls Bar(), which in turn calls
1026 // CurrentOsStackTraceExceptTop(1), Foo() will be included in the
1027 // trace but Bar() and CurrentOsStackTraceExceptTop() won't.
1028 std::string CurrentOsStackTraceExceptTop(int skip_count) GTEST_NO_INLINE_;
1030 // Finds and returns a TestCase with the given name. If one doesn't
1031 // exist, creates one and returns it.
1035 // test_case_name: name of the test case
1036 // type_param: the name of the test's type parameter, or NULL if
1037 // this is not a typed or a type-parameterized test.
1038 // set_up_tc: pointer to the function that sets up the test case
1039 // tear_down_tc: pointer to the function that tears down the test case
1040 TestCase* GetTestCase(const char* test_case_name,
1041 const char* type_param,
1042 Test::SetUpTestCaseFunc set_up_tc,
1043 Test::TearDownTestCaseFunc tear_down_tc);
1045 // Adds a TestInfo to the unit test.
1049 // set_up_tc: pointer to the function that sets up the test case
1050 // tear_down_tc: pointer to the function that tears down the test case
1051 // test_info: the TestInfo object
1052 void AddTestInfo(Test::SetUpTestCaseFunc set_up_tc,
1053 Test::TearDownTestCaseFunc tear_down_tc,
1054 TestInfo* test_info) {
1055 // In order to support thread-safe death tests, we need to
1056 // remember the original working directory when the test program
1057 // was first invoked. We cannot do this in RUN_ALL_TESTS(), as
1058 // the user may have changed the current directory before calling
1059 // RUN_ALL_TESTS(). Therefore we capture the current directory in
1060 // AddTestInfo(), which is called to register a TEST or TEST_F
1061 // before main() is reached.
1062 if (original_working_dir_.IsEmpty()) {
1063 original_working_dir_.Set(FilePath::GetCurrentDir());
1064 GTEST_CHECK_(!original_working_dir_.IsEmpty())
1065 << "Failed to get the current working directory.";
1068 GetTestCase(test_info->test_case_name(),
1069 test_info->type_param(),
1071 tear_down_tc)->AddTestInfo(test_info);
1074 #if GTEST_HAS_PARAM_TEST
1075 // Returns ParameterizedTestCaseRegistry object used to keep track of
1076 // value-parameterized tests and instantiate and register them.
1077 internal::ParameterizedTestCaseRegistry& parameterized_test_registry() {
1078 return parameterized_test_registry_;
1080 #endif // GTEST_HAS_PARAM_TEST
1082 // Sets the TestCase object for the test that's currently running.
1083 void set_current_test_case(TestCase* a_current_test_case) {
1084 current_test_case_ = a_current_test_case;
1087 // Sets the TestInfo object for the test that's currently running. If
1088 // current_test_info is NULL, the assertion results will be stored in
1089 // ad_hoc_test_result_.
1090 void set_current_test_info(TestInfo* a_current_test_info) {
1091 current_test_info_ = a_current_test_info;
1094 // Registers all parameterized tests defined using TEST_P and
1095 // INSTANTIATE_TEST_CASE_P, creating regular tests for each test/parameter
1096 // combination. This method can be called more then once; it has guards
1097 // protecting from registering the tests more then once. If
1098 // value-parameterized tests are disabled, RegisterParameterizedTests is
1099 // present but does nothing.
1100 void RegisterParameterizedTests();
1102 // Runs all tests in this UnitTest object, prints the result, and
1103 // returns true if all tests are successful. If any exception is
1104 // thrown during a test, this test is considered to be failed, but
1105 // the rest of the tests will still be run.
1108 // Clears the results of all tests, except the ad hoc tests.
1109 void ClearNonAdHocTestResult() {
1110 ForEach(test_cases_, TestCase::ClearTestCaseResult);
1113 // Clears the results of ad-hoc test assertions.
1114 void ClearAdHocTestResult() {
1115 ad_hoc_test_result_.Clear();
1118 // Adds a TestProperty to the current TestResult object when invoked in a
1119 // context of a test or a test case, or to the global property set. If the
1120 // result already contains a property with the same key, the value will be
1122 void RecordProperty(const TestProperty& test_property);
1124 enum ReactionToSharding {
1125 HONOR_SHARDING_PROTOCOL,
1126 IGNORE_SHARDING_PROTOCOL
1129 // Matches the full name of each test against the user-specified
1130 // filter to decide whether the test should run, then records the
1131 // result in each TestCase and TestInfo object.
1132 // If shard_tests == HONOR_SHARDING_PROTOCOL, further filters tests
1133 // based on sharding variables in the environment.
1134 // Returns the number of tests that should run.
1135 int FilterTests(ReactionToSharding shard_tests);
1137 // Prints the names of the tests matching the user-specified filter flag.
1138 void ListTestsMatchingFilter();
1140 const TestCase* current_test_case() const { return current_test_case_; }
1141 TestInfo* current_test_info() { return current_test_info_; }
1142 const TestInfo* current_test_info() const { return current_test_info_; }
1144 // Returns the vector of environments that need to be set-up/torn-down
1145 // before/after the tests are run.
1146 std::vector<Environment*>& environments() { return environments_; }
1148 // Getters for the per-thread Google Test trace stack.
1149 std::vector<TraceInfo>& gtest_trace_stack() {
1150 return *(gtest_trace_stack_.pointer());
1152 const std::vector<TraceInfo>& gtest_trace_stack() const {
1153 return gtest_trace_stack_.get();
1156 #if GTEST_HAS_DEATH_TEST
1157 void InitDeathTestSubprocessControlInfo() {
1158 internal_run_death_test_flag_.reset(ParseInternalRunDeathTestFlag());
1160 // Returns a pointer to the parsed --gtest_internal_run_death_test
1161 // flag, or NULL if that flag was not specified.
1162 // This information is useful only in a death test child process.
1163 // Must not be called before a call to InitGoogleTest.
1164 const InternalRunDeathTestFlag* internal_run_death_test_flag() const {
1165 return internal_run_death_test_flag_.get();
1168 // Returns a pointer to the current death test factory.
1169 internal::DeathTestFactory* death_test_factory() {
1170 return death_test_factory_.get();
1173 void SuppressTestEventsIfInSubprocess();
1175 friend class ReplaceDeathTestFactory;
1176 #endif // GTEST_HAS_DEATH_TEST
1178 // Initializes the event listener performing XML output as specified by
1179 // UnitTestOptions. Must not be called before InitGoogleTest.
1180 void ConfigureXmlOutput();
1182 #if GTEST_CAN_STREAM_RESULTS_
1183 // Initializes the event listener for streaming test results to a socket.
1184 // Must not be called before InitGoogleTest.
1185 void ConfigureStreamingOutput();
1188 // Performs initialization dependent upon flag values obtained in
1189 // ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to
1190 // ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest
1191 // this function is also called from RunAllTests. Since this function can be
1192 // called more than once, it has to be idempotent.
1193 void PostFlagParsingInit();
1195 // Gets the random seed used at the start of the current test iteration.
1196 int random_seed() const { return random_seed_; }
1198 // Gets the random number generator.
1199 internal::Random* random() { return &random_; }
1201 // Shuffles all test cases, and the tests within each test case,
1202 // making sure that death tests are still run first.
1203 void ShuffleTests();
1205 // Restores the test cases and tests to their order before the first shuffle.
1206 void UnshuffleTests();
1208 // Returns the value of GTEST_FLAG(catch_exceptions) at the moment
1209 // UnitTest::Run() starts.
1210 bool catch_exceptions() const { return catch_exceptions_; }
1213 friend class ::testing::UnitTest;
1215 // Used by UnitTest::Run() to capture the state of
1216 // GTEST_FLAG(catch_exceptions) at the moment it starts.
1217 void set_catch_exceptions(bool value) { catch_exceptions_ = value; }
1219 // The UnitTest object that owns this implementation object.
1220 UnitTest* const parent_;
1222 // The working directory when the first TEST() or TEST_F() was
1224 internal::FilePath original_working_dir_;
1226 // The default test part result reporters.
1227 DefaultGlobalTestPartResultReporter default_global_test_part_result_reporter_;
1228 DefaultPerThreadTestPartResultReporter
1229 default_per_thread_test_part_result_reporter_;
1231 // Points to (but doesn't own) the global test part result reporter.
1232 TestPartResultReporterInterface* global_test_part_result_repoter_;
1234 // Protects read and write access to global_test_part_result_reporter_.
1235 internal::Mutex global_test_part_result_reporter_mutex_;
1237 // Points to (but doesn't own) the per-thread test part result reporter.
1238 internal::ThreadLocal<TestPartResultReporterInterface*>
1239 per_thread_test_part_result_reporter_;
1241 // The vector of environments that need to be set-up/torn-down
1242 // before/after the tests are run.
1243 std::vector<Environment*> environments_;
1245 // The vector of TestCases in their original order. It owns the
1246 // elements in the vector.
1247 std::vector<TestCase*> test_cases_;
1249 // Provides a level of indirection for the test case list to allow
1250 // easy shuffling and restoring the test case order. The i-th
1251 // element of this vector is the index of the i-th test case in the
1253 std::vector<int> test_case_indices_;
1255 #if GTEST_HAS_PARAM_TEST
1256 // ParameterizedTestRegistry object used to register value-parameterized
1258 internal::ParameterizedTestCaseRegistry parameterized_test_registry_;
1260 // Indicates whether RegisterParameterizedTests() has been called already.
1261 bool parameterized_tests_registered_;
1262 #endif // GTEST_HAS_PARAM_TEST
1264 // Index of the last death test case registered. Initially -1.
1265 int last_death_test_case_;
1267 // This points to the TestCase for the currently running test. It
1268 // changes as Google Test goes through one test case after another.
1269 // When no test is running, this is set to NULL and Google Test
1270 // stores assertion results in ad_hoc_test_result_. Initially NULL.
1271 TestCase* current_test_case_;
1273 // This points to the TestInfo for the currently running test. It
1274 // changes as Google Test goes through one test after another. When
1275 // no test is running, this is set to NULL and Google Test stores
1276 // assertion results in ad_hoc_test_result_. Initially NULL.
1277 TestInfo* current_test_info_;
1279 // Normally, a user only writes assertions inside a TEST or TEST_F,
1280 // or inside a function called by a TEST or TEST_F. Since Google
1281 // Test keeps track of which test is current running, it can
1282 // associate such an assertion with the test it belongs to.
1284 // If an assertion is encountered when no TEST or TEST_F is running,
1285 // Google Test attributes the assertion result to an imaginary "ad hoc"
1286 // test, and records the result in ad_hoc_test_result_.
1287 TestResult ad_hoc_test_result_;
1289 // The list of event listeners that can be used to track events inside
1291 TestEventListeners listeners_;
1293 // The OS stack trace getter. Will be deleted when the UnitTest
1294 // object is destructed. By default, an OsStackTraceGetter is used,
1295 // but the user can set this field to use a custom getter if that is
1297 OsStackTraceGetterInterface* os_stack_trace_getter_;
1299 // True iff PostFlagParsingInit() has been called.
1300 bool post_flag_parse_init_performed_;
1302 // The random number seed used at the beginning of the test run.
1305 // Our random number generator.
1306 internal::Random random_;
1308 // The time of the test program start, in ms from the start of the
1310 TimeInMillis start_timestamp_;
1312 // How long the test took to run, in milliseconds.
1313 TimeInMillis elapsed_time_;
1315 #if GTEST_HAS_DEATH_TEST
1316 // The decomposed components of the gtest_internal_run_death_test flag,
1317 // parsed when RUN_ALL_TESTS is called.
1318 internal::scoped_ptr<InternalRunDeathTestFlag> internal_run_death_test_flag_;
1319 internal::scoped_ptr<internal::DeathTestFactory> death_test_factory_;
1320 #endif // GTEST_HAS_DEATH_TEST
1322 // A per-thread stack of traces created by the SCOPED_TRACE() macro.
1323 internal::ThreadLocal<std::vector<TraceInfo> > gtest_trace_stack_;
1325 // The value of GTEST_FLAG(catch_exceptions) at the moment RunAllTests()
1327 bool catch_exceptions_;
1329 GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTestImpl);
1330 }; // class UnitTestImpl
1332 // Convenience function for accessing the global UnitTest
1333 // implementation object.
1334 inline UnitTestImpl* GetUnitTestImpl() {
1335 return UnitTest::GetInstance()->impl();
1338 #if GTEST_USES_SIMPLE_RE
1340 // Internal helper functions for implementing the simple regular
1341 // expression matcher.
1342 GTEST_API_ bool IsInSet(char ch, const char* str);
1343 GTEST_API_ bool IsAsciiDigit(char ch);
1344 GTEST_API_ bool IsAsciiPunct(char ch);
1345 GTEST_API_ bool IsRepeat(char ch);
1346 GTEST_API_ bool IsAsciiWhiteSpace(char ch);
1347 GTEST_API_ bool IsAsciiWordChar(char ch);
1348 GTEST_API_ bool IsValidEscape(char ch);
1349 GTEST_API_ bool AtomMatchesChar(bool escaped, char pattern, char ch);
1350 GTEST_API_ bool ValidateRegex(const char* regex);
1351 GTEST_API_ bool MatchRegexAtHead(const char* regex, const char* str);
1352 GTEST_API_ bool MatchRepetitionAndRegexAtHead(
1353 bool escaped, char ch, char repeat, const char* regex, const char* str);
1354 GTEST_API_ bool MatchRegexAnywhere(const char* regex, const char* str);
1356 #endif // GTEST_USES_SIMPLE_RE
1358 // Parses the command line for Google Test flags, without initializing
1359 // other parts of Google Test.
1360 GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, char** argv);
1361 GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv);
1363 #if GTEST_HAS_DEATH_TEST
1365 // Returns the message describing the last system error, regardless of the
1367 GTEST_API_ std::string GetLastErrnoDescription();
1369 // Attempts to parse a string into a positive integer pointed to by the
1370 // number parameter. Returns true if that is possible.
1371 // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we can use
1373 template <typename Integer>
1374 bool ParseNaturalNumber(const ::std::string& str, Integer* number) {
1375 // Fail fast if the given string does not begin with a digit;
1376 // this bypasses strtoXXX's "optional leading whitespace and plus
1377 // or minus sign" semantics, which are undesirable here.
1378 if (str.empty() || !IsDigit(str[0])) {
1384 // BiggestConvertible is the largest integer type that system-provided
1385 // string-to-number conversion routines can return.
1387 # if GTEST_OS_WINDOWS && !defined(__GNUC__)
1389 // MSVC and C++ Builder define __int64 instead of the standard long long.
1390 typedef unsigned __int64 BiggestConvertible;
1391 const BiggestConvertible parsed = _strtoui64(str.c_str(), &end, 10);
1395 typedef unsigned long long BiggestConvertible; // NOLINT
1396 const BiggestConvertible parsed = strtoull(str.c_str(), &end, 10);
1398 # endif // GTEST_OS_WINDOWS && !defined(__GNUC__)
1400 const bool parse_success = *end == '\0' && errno == 0;
1402 // TODO(vladl@google.com): Convert this to compile time assertion when it is
1404 GTEST_CHECK_(sizeof(Integer) <= sizeof(parsed));
1406 const Integer result = static_cast<Integer>(parsed);
1407 if (parse_success && static_cast<BiggestConvertible>(result) == parsed) {
1413 #endif // GTEST_HAS_DEATH_TEST
1415 // TestResult contains some private methods that should be hidden from
1416 // Google Test user but are required for testing. This class allow our tests
1419 // This class is supplied only for the purpose of testing Google Test's own
1420 // constructs. Do not use it in user tests, either directly or indirectly.
1421 class TestResultAccessor {
1423 static void RecordProperty(TestResult* test_result,
1424 const std::string& xml_element,
1425 const TestProperty& property) {
1426 test_result->RecordProperty(xml_element, property);
1429 static void ClearTestPartResults(TestResult* test_result) {
1430 test_result->ClearTestPartResults();
1433 static const std::vector<testing::TestPartResult>& test_part_results(
1434 const TestResult& test_result) {
1435 return test_result.test_part_results();
1439 #if GTEST_CAN_STREAM_RESULTS_
1441 // Streams test results to the given port on the given host machine.
1442 class GTEST_API_ StreamingListener : public EmptyTestEventListener {
1444 // Abstract base class for writing strings to a socket.
1445 class AbstractSocketWriter {
1447 virtual ~AbstractSocketWriter() {}
1449 // Sends a string to the socket.
1450 virtual void Send(const string& message) = 0;
1452 // Closes the socket.
1453 virtual void CloseConnection() {}
1455 // Sends a string and a newline to the socket.
1456 void SendLn(const string& message) {
1457 Send(message + "\n");
1461 // Concrete class for actually writing strings to a socket.
1462 class SocketWriter : public AbstractSocketWriter {
1464 SocketWriter(const string& host, const string& port)
1465 : sockfd_(-1), host_name_(host), port_num_(port) {
1469 virtual ~SocketWriter() {
1474 // Sends a string to the socket.
1475 virtual void Send(const string& message) {
1476 GTEST_CHECK_(sockfd_ != -1)
1477 << "Send() can be called only when there is a connection.";
1479 const int len = static_cast<int>(message.length());
1480 if (write(sockfd_, message.c_str(), len) != len) {
1482 << "stream_result_to: failed to stream to "
1483 << host_name_ << ":" << port_num_;
1488 // Creates a client socket and connects to the server.
1489 void MakeConnection();
1491 // Closes the socket.
1492 void CloseConnection() {
1493 GTEST_CHECK_(sockfd_ != -1)
1494 << "CloseConnection() can be called only when there is a connection.";
1500 int sockfd_; // socket file descriptor
1501 const string host_name_;
1502 const string port_num_;
1504 GTEST_DISALLOW_COPY_AND_ASSIGN_(SocketWriter);
1505 }; // class SocketWriter
1507 // Escapes '=', '&', '%', and '\n' characters in str as "%xx".
1508 static string UrlEncode(const char* str);
1510 StreamingListener(const string& host, const string& port)
1511 : socket_writer_(new SocketWriter(host, port)) { Start(); }
1513 explicit StreamingListener(AbstractSocketWriter* socket_writer)
1514 : socket_writer_(socket_writer) { Start(); }
1516 void OnTestProgramStart(const UnitTest& /* unit_test */) {
1517 SendLn("event=TestProgramStart");
1520 void OnTestProgramEnd(const UnitTest& unit_test) {
1521 // Note that Google Test current only report elapsed time for each
1522 // test iteration, not for the entire test program.
1523 SendLn("event=TestProgramEnd&passed=" + FormatBool(unit_test.Passed()));
1525 // Notify the streaming server to stop.
1526 socket_writer_->CloseConnection();
1529 void OnTestIterationStart(const UnitTest& /* unit_test */, int iteration) {
1530 SendLn("event=TestIterationStart&iteration=" +
1531 StreamableToString(iteration));
1534 void OnTestIterationEnd(const UnitTest& unit_test, int /* iteration */) {
1535 SendLn("event=TestIterationEnd&passed=" +
1536 FormatBool(unit_test.Passed()) + "&elapsed_time=" +
1537 StreamableToString(unit_test.elapsed_time()) + "ms");
1540 void OnTestCaseStart(const TestCase& test_case) {
1541 SendLn(std::string("event=TestCaseStart&name=") + test_case.name());
1544 void OnTestCaseEnd(const TestCase& test_case) {
1545 SendLn("event=TestCaseEnd&passed=" + FormatBool(test_case.Passed())
1546 + "&elapsed_time=" + StreamableToString(test_case.elapsed_time())
1550 void OnTestStart(const TestInfo& test_info) {
1551 SendLn(std::string("event=TestStart&name=") + test_info.name());
1554 void OnTestEnd(const TestInfo& test_info) {
1555 SendLn("event=TestEnd&passed=" +
1556 FormatBool((test_info.result())->Passed()) +
1558 StreamableToString((test_info.result())->elapsed_time()) + "ms");
1561 void OnTestPartResult(const TestPartResult& test_part_result) {
1562 const char* file_name = test_part_result.file_name();
1563 if (file_name == NULL)
1565 SendLn("event=TestPartResult&file=" + UrlEncode(file_name) +
1566 "&line=" + StreamableToString(test_part_result.line_number()) +
1567 "&message=" + UrlEncode(test_part_result.message()));
1571 // Sends the given message and a newline to the socket.
1572 void SendLn(const string& message) { socket_writer_->SendLn(message); }
1574 // Called at the start of streaming to notify the receiver what
1575 // protocol we are using.
1576 void Start() { SendLn("gtest_streaming_protocol_version=1.0"); }
1578 string FormatBool(bool value) { return value ? "1" : "0"; }
1580 const scoped_ptr<AbstractSocketWriter> socket_writer_;
1582 GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamingListener);
1583 }; // class StreamingListener
1585 #endif // GTEST_CAN_STREAM_RESULTS_
1587 } // namespace internal
1588 } // namespace testing
1590 #endif // GTEST_SRC_GTEST_INTERNAL_INL_H_
1591 #undef GTEST_IMPLEMENTATION_
1593 #if GTEST_OS_WINDOWS
1594 # define vsnprintf _vsnprintf
1595 #endif // GTEST_OS_WINDOWS
1599 using internal::CountIf;
1600 using internal::ForEach;
1601 using internal::GetElementOr;
1602 using internal::Shuffle;
1606 // A test whose test case name or test name matches this filter is
1607 // disabled and not run.
1608 static const char kDisableTestFilter[] = "DISABLED_*:*/DISABLED_*";
1610 // A test case whose name matches this filter is considered a death
1611 // test case and will be run before test cases whose name doesn't
1612 // match this filter.
1613 static const char kDeathTestCaseFilter[] = "*DeathTest:*DeathTest/*";
1615 // A test filter that matches everything.
1616 static const char kUniversalFilter[] = "*";
1618 // The default output file for XML output.
1619 static const char kDefaultOutputFile[] = "test_detail.xml";
1621 // The environment variable name for the test shard index.
1622 static const char kTestShardIndex[] = "GTEST_SHARD_INDEX";
1623 // The environment variable name for the total number of test shards.
1624 static const char kTestTotalShards[] = "GTEST_TOTAL_SHARDS";
1625 // The environment variable name for the test shard status file.
1626 static const char kTestShardStatusFile[] = "GTEST_SHARD_STATUS_FILE";
1628 namespace internal {
1630 // The text used in failure messages to indicate the start of the
1632 const char kStackTraceMarker[] = "\nStack trace:\n";
1634 // g_help_flag is true iff the --help flag or an equivalent form is
1635 // specified on the command line.
1636 bool g_help_flag = false;
1638 } // namespace internal
1640 static const char* GetDefaultFilter() {
1641 #ifdef GTEST_TEST_FILTER_ENV_VAR_
1642 const char* const testbridge_test_only = getenv(GTEST_TEST_FILTER_ENV_VAR_);
1643 if (testbridge_test_only != NULL) {
1644 return testbridge_test_only;
1646 #endif // GTEST_TEST_FILTER_ENV_VAR_
1647 return kUniversalFilter;
1651 also_run_disabled_tests,
1652 internal::BoolFromGTestEnv("also_run_disabled_tests", false),
1653 "Run disabled tests too, in addition to the tests normally being run.");
1657 internal::BoolFromGTestEnv("break_on_failure", false),
1658 "True iff a failed assertion should be a debugger break-point.");
1662 internal::BoolFromGTestEnv("catch_exceptions", true),
1663 "True iff " GTEST_NAME_
1664 " should catch exceptions and treat them as test failures.");
1666 GTEST_DEFINE_string_(
1668 internal::StringFromGTestEnv("color", "auto"),
1669 "Whether to use colors in the output. Valid values: yes, no, "
1670 "and auto. 'auto' means to use colors if the output is "
1671 "being sent to a terminal and the TERM environment variable "
1672 "is set to a terminal type that supports colors.");
1674 GTEST_DEFINE_string_(
1676 internal::StringFromGTestEnv("filter", GetDefaultFilter()),
1677 "A colon-separated list of glob (not regex) patterns "
1678 "for filtering the tests to run, optionally followed by a "
1679 "'-' and a : separated list of negative patterns (tests to "
1680 "exclude). A test is run if it matches one of the positive "
1681 "patterns and does not match any of the negative patterns.");
1683 GTEST_DEFINE_bool_(list_tests, false,
1684 "List all tests without running them.");
1686 GTEST_DEFINE_string_(
1688 internal::StringFromGTestEnv("output", ""),
1689 "A format (currently must be \"xml\"), optionally followed "
1690 "by a colon and an output file name or directory. A directory "
1691 "is indicated by a trailing pathname separator. "
1692 "Examples: \"xml:filename.xml\", \"xml::directoryname/\". "
1693 "If a directory is specified, output files will be created "
1694 "within that directory, with file-names based on the test "
1695 "executable's name and, if necessary, made unique by adding "
1700 internal::BoolFromGTestEnv("print_time", true),
1701 "True iff " GTEST_NAME_
1702 " should display elapsed time in text output.");
1704 GTEST_DEFINE_int32_(
1706 internal::Int32FromGTestEnv("random_seed", 0),
1707 "Random number seed to use when shuffling test orders. Must be in range "
1708 "[1, 99999], or 0 to use a seed based on the current time.");
1710 GTEST_DEFINE_int32_(
1712 internal::Int32FromGTestEnv("repeat", 1),
1713 "How many times to repeat each test. Specify a negative number "
1714 "for repeating forever. Useful for shaking out flaky tests.");
1717 show_internal_stack_frames, false,
1718 "True iff " GTEST_NAME_ " should include internal stack frames when "
1719 "printing test failure stack traces.");
1723 internal::BoolFromGTestEnv("shuffle", false),
1724 "True iff " GTEST_NAME_
1725 " should randomize tests' order on every run.");
1727 GTEST_DEFINE_int32_(
1729 internal::Int32FromGTestEnv("stack_trace_depth", kMaxStackTraceDepth),
1730 "The maximum number of stack frames to print when an "
1731 "assertion fails. The valid range is 0 through 100, inclusive.");
1733 GTEST_DEFINE_string_(
1735 internal::StringFromGTestEnv("stream_result_to", ""),
1736 "This flag specifies the host name and the port number on which to stream "
1737 "test results. Example: \"localhost:555\". The flag is effective only on "
1742 internal::BoolFromGTestEnv("throw_on_failure", false),
1743 "When this flag is specified, a failed assertion will throw an exception "
1744 "if exceptions are enabled or exit the program with a non-zero code "
1747 #if GTEST_USE_OWN_FLAGFILE_FLAG_
1748 GTEST_DEFINE_string_(
1750 internal::StringFromGTestEnv("flagfile", ""),
1751 "This flag specifies the flagfile to read command-line flags from.");
1752 #endif // GTEST_USE_OWN_FLAGFILE_FLAG_
1754 namespace internal {
1756 // Generates a random number from [0, range), using a Linear
1757 // Congruential Generator (LCG). Crashes if 'range' is 0 or greater
1759 UInt32 Random::Generate(UInt32 range) {
1760 // These constants are the same as are used in glibc's rand(3).
1761 state_ = (1103515245U*state_ + 12345U) % kMaxRange;
1763 GTEST_CHECK_(range > 0)
1764 << "Cannot generate a number in the range [0, 0).";
1765 GTEST_CHECK_(range <= kMaxRange)
1766 << "Generation of a number in [0, " << range << ") was requested, "
1767 << "but this can only generate numbers in [0, " << kMaxRange << ").";
1769 // Converting via modulus introduces a bit of downward bias, but
1770 // it's simple, and a linear congruential generator isn't too good
1772 return state_ % range;
1775 // GTestIsInitialized() returns true iff the user has initialized
1776 // Google Test. Useful for catching the user mistake of not initializing
1777 // Google Test before calling RUN_ALL_TESTS().
1778 static bool GTestIsInitialized() { return GetArgvs().size() > 0; }
1780 // Iterates over a vector of TestCases, keeping a running sum of the
1781 // results of calling a given int-returning method on each.
1783 static int SumOverTestCaseList(const std::vector<TestCase*>& case_list,
1784 int (TestCase::*method)() const) {
1786 for (size_t i = 0; i < case_list.size(); i++) {
1787 sum += (case_list[i]->*method)();
1792 // Returns true iff the test case passed.
1793 static bool TestCasePassed(const TestCase* test_case) {
1794 return test_case->should_run() && test_case->Passed();
1797 // Returns true iff the test case failed.
1798 static bool TestCaseFailed(const TestCase* test_case) {
1799 return test_case->should_run() && test_case->Failed();
1802 // Returns true iff test_case contains at least one test that should
1804 static bool ShouldRunTestCase(const TestCase* test_case) {
1805 return test_case->should_run();
1808 // AssertHelper constructor.
1809 AssertHelper::AssertHelper(TestPartResult::Type type,
1812 const char* message)
1813 : data_(new AssertHelperData(type, file, line, message)) {
1816 AssertHelper::~AssertHelper() {
1820 // Message assignment, for assertion streaming support.
1821 void AssertHelper::operator=(const Message& message) const {
1822 UnitTest::GetInstance()->
1823 AddTestPartResult(data_->type, data_->file, data_->line,
1824 AppendUserMessage(data_->message, message),
1825 UnitTest::GetInstance()->impl()
1826 ->CurrentOsStackTraceExceptTop(1)
1827 // Skips the stack frame for this function itself.
1831 // Mutex for linked pointers.
1832 GTEST_API_ GTEST_DEFINE_STATIC_MUTEX_(g_linked_ptr_mutex);
1834 // A copy of all command line arguments. Set by InitGoogleTest().
1835 ::std::vector<testing::internal::string> g_argvs;
1837 const ::std::vector<testing::internal::string>& GetArgvs() {
1838 #if defined(GTEST_CUSTOM_GET_ARGVS_)
1839 return GTEST_CUSTOM_GET_ARGVS_();
1840 #else // defined(GTEST_CUSTOM_GET_ARGVS_)
1842 #endif // defined(GTEST_CUSTOM_GET_ARGVS_)
1845 // Returns the current application's name, removing directory path if that
1847 FilePath GetCurrentExecutableName() {
1850 #if GTEST_OS_WINDOWS
1851 result.Set(FilePath(GetArgvs()[0]).RemoveExtension("exe"));
1853 result.Set(FilePath(GetArgvs()[0]));
1854 #endif // GTEST_OS_WINDOWS
1856 return result.RemoveDirectoryName();
1859 // Functions for processing the gtest_output flag.
1861 // Returns the output format, or "" for normal printed output.
1862 std::string UnitTestOptions::GetOutputFormat() {
1863 const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
1864 if (gtest_output_flag == NULL) return std::string("");
1866 const char* const colon = strchr(gtest_output_flag, ':');
1867 return (colon == NULL) ?
1868 std::string(gtest_output_flag) :
1869 std::string(gtest_output_flag, colon - gtest_output_flag);
1872 // Returns the name of the requested output file, or the default if none
1873 // was explicitly specified.
1874 std::string UnitTestOptions::GetAbsolutePathToOutputFile() {
1875 const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
1876 if (gtest_output_flag == NULL)
1879 const char* const colon = strchr(gtest_output_flag, ':');
1881 return internal::FilePath::ConcatPaths(
1883 UnitTest::GetInstance()->original_working_dir()),
1884 internal::FilePath(kDefaultOutputFile)).string();
1886 internal::FilePath output_name(colon + 1);
1887 if (!output_name.IsAbsolutePath())
1888 // TODO(wan@google.com): on Windows \some\path is not an absolute
1889 // path (as its meaning depends on the current drive), yet the
1890 // following logic for turning it into an absolute path is wrong.
1892 output_name = internal::FilePath::ConcatPaths(
1893 internal::FilePath(UnitTest::GetInstance()->original_working_dir()),
1894 internal::FilePath(colon + 1));
1896 if (!output_name.IsDirectory())
1897 return output_name.string();
1899 internal::FilePath result(internal::FilePath::GenerateUniqueFileName(
1900 output_name, internal::GetCurrentExecutableName(),
1901 GetOutputFormat().c_str()));
1902 return result.string();
1905 // Returns true iff the wildcard pattern matches the string. The
1906 // first ':' or '\0' character in pattern marks the end of it.
1908 // This recursive algorithm isn't very efficient, but is clear and
1909 // works well enough for matching test names, which are short.
1910 bool UnitTestOptions::PatternMatchesString(const char *pattern,
1914 case ':': // Either ':' or '\0' marks the end of the pattern.
1915 return *str == '\0';
1916 case '?': // Matches any single character.
1917 return *str != '\0' && PatternMatchesString(pattern + 1, str + 1);
1918 case '*': // Matches any string (possibly empty) of characters.
1919 return (*str != '\0' && PatternMatchesString(pattern, str + 1)) ||
1920 PatternMatchesString(pattern + 1, str);
1921 default: // Non-special character. Matches itself.
1922 return *pattern == *str &&
1923 PatternMatchesString(pattern + 1, str + 1);
1927 bool UnitTestOptions::MatchesFilter(
1928 const std::string& name, const char* filter) {
1929 const char *cur_pattern = filter;
1931 if (PatternMatchesString(cur_pattern, name.c_str())) {
1935 // Finds the next pattern in the filter.
1936 cur_pattern = strchr(cur_pattern, ':');
1938 // Returns if no more pattern can be found.
1939 if (cur_pattern == NULL) {
1943 // Skips the pattern separater (the ':' character).
1948 // Returns true iff the user-specified filter matches the test case
1949 // name and the test name.
1950 bool UnitTestOptions::FilterMatchesTest(const std::string &test_case_name,
1951 const std::string &test_name) {
1952 const std::string& full_name = test_case_name + "." + test_name.c_str();
1954 // Split --gtest_filter at '-', if there is one, to separate into
1955 // positive filter and negative filter portions
1956 const char* const p = GTEST_FLAG(filter).c_str();
1957 const char* const dash = strchr(p, '-');
1958 std::string positive;
1959 std::string negative;
1961 positive = GTEST_FLAG(filter).c_str(); // Whole string is a positive filter
1964 positive = std::string(p, dash); // Everything up to the dash
1965 negative = std::string(dash + 1); // Everything after the dash
1966 if (positive.empty()) {
1967 // Treat '-test1' as the same as '*-test1'
1968 positive = kUniversalFilter;
1972 // A filter is a colon-separated list of patterns. It matches a
1973 // test if any pattern in it matches the test.
1974 return (MatchesFilter(full_name, positive.c_str()) &&
1975 !MatchesFilter(full_name, negative.c_str()));
1979 // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
1980 // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
1981 // This function is useful as an __except condition.
1982 int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) {
1983 // Google Test should handle a SEH exception if:
1984 // 1. the user wants it to, AND
1985 // 2. this is not a breakpoint exception, AND
1986 // 3. this is not a C++ exception (VC++ implements them via SEH,
1989 // SEH exception code for C++ exceptions.
1990 // (see http://support.microsoft.com/kb/185294 for more information).
1991 const DWORD kCxxExceptionCode = 0xe06d7363;
1993 bool should_handle = true;
1995 if (!GTEST_FLAG(catch_exceptions))
1996 should_handle = false;
1997 else if (exception_code == EXCEPTION_BREAKPOINT)
1998 should_handle = false;
1999 else if (exception_code == kCxxExceptionCode)
2000 should_handle = false;
2002 return should_handle ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH;
2004 #endif // GTEST_HAS_SEH
2006 } // namespace internal
2008 // The c'tor sets this object as the test part result reporter used by
2009 // Google Test. The 'result' parameter specifies where to report the
2010 // results. Intercepts only failures from the current thread.
2011 ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
2012 TestPartResultArray* result)
2013 : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD),
2018 // The c'tor sets this object as the test part result reporter used by
2019 // Google Test. The 'result' parameter specifies where to report the
2021 ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
2022 InterceptMode intercept_mode, TestPartResultArray* result)
2023 : intercept_mode_(intercept_mode),
2028 void ScopedFakeTestPartResultReporter::Init() {
2029 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
2030 if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
2031 old_reporter_ = impl->GetGlobalTestPartResultReporter();
2032 impl->SetGlobalTestPartResultReporter(this);
2034 old_reporter_ = impl->GetTestPartResultReporterForCurrentThread();
2035 impl->SetTestPartResultReporterForCurrentThread(this);
2039 // The d'tor restores the test part result reporter used by Google Test
2041 ScopedFakeTestPartResultReporter::~ScopedFakeTestPartResultReporter() {
2042 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
2043 if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
2044 impl->SetGlobalTestPartResultReporter(old_reporter_);
2046 impl->SetTestPartResultReporterForCurrentThread(old_reporter_);
2050 // Increments the test part result count and remembers the result.
2051 // This method is from the TestPartResultReporterInterface interface.
2052 void ScopedFakeTestPartResultReporter::ReportTestPartResult(
2053 const TestPartResult& result) {
2054 result_->Append(result);
2057 namespace internal {
2059 // Returns the type ID of ::testing::Test. We should always call this
2060 // instead of GetTypeId< ::testing::Test>() to get the type ID of
2061 // testing::Test. This is to work around a suspected linker bug when
2062 // using Google Test as a framework on Mac OS X. The bug causes
2063 // GetTypeId< ::testing::Test>() to return different values depending
2064 // on whether the call is from the Google Test framework itself or
2065 // from user test code. GetTestTypeId() is guaranteed to always
2066 // return the same value, as it always calls GetTypeId<>() from the
2067 // gtest.cc, which is within the Google Test framework.
2068 TypeId GetTestTypeId() {
2069 return GetTypeId<Test>();
2072 // The value of GetTestTypeId() as seen from within the Google Test
2073 // library. This is solely for testing GetTestTypeId().
2074 extern const TypeId kTestTypeIdInGoogleTest = GetTestTypeId();
2076 // This predicate-formatter checks that 'results' contains a test part
2077 // failure of the given type and that the failure message contains the
2079 AssertionResult HasOneFailure(const char* /* results_expr */,
2080 const char* /* type_expr */,
2081 const char* /* substr_expr */,
2082 const TestPartResultArray& results,
2083 TestPartResult::Type type,
2084 const string& substr) {
2085 const std::string expected(type == TestPartResult::kFatalFailure ?
2087 "1 non-fatal failure");
2089 if (results.size() != 1) {
2090 msg << "Expected: " << expected << "\n"
2091 << " Actual: " << results.size() << " failures";
2092 for (int i = 0; i < results.size(); i++) {
2093 msg << "\n" << results.GetTestPartResult(i);
2095 return AssertionFailure() << msg;
2098 const TestPartResult& r = results.GetTestPartResult(0);
2099 if (r.type() != type) {
2100 return AssertionFailure() << "Expected: " << expected << "\n"
2105 if (strstr(r.message(), substr.c_str()) == NULL) {
2106 return AssertionFailure() << "Expected: " << expected << " containing \""
2112 return AssertionSuccess();
2115 // The constructor of SingleFailureChecker remembers where to look up
2116 // test part results, what type of failure we expect, and what
2117 // substring the failure message should contain.
2118 SingleFailureChecker:: SingleFailureChecker(
2119 const TestPartResultArray* results,
2120 TestPartResult::Type type,
2121 const string& substr)
2122 : results_(results),
2126 // The destructor of SingleFailureChecker verifies that the given
2127 // TestPartResultArray contains exactly one failure that has the given
2128 // type and contains the given substring. If that's not the case, a
2129 // non-fatal failure will be generated.
2130 SingleFailureChecker::~SingleFailureChecker() {
2131 EXPECT_PRED_FORMAT3(HasOneFailure, *results_, type_, substr_);
2134 DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter(
2135 UnitTestImpl* unit_test) : unit_test_(unit_test) {}
2137 void DefaultGlobalTestPartResultReporter::ReportTestPartResult(
2138 const TestPartResult& result) {
2139 unit_test_->current_test_result()->AddTestPartResult(result);
2140 unit_test_->listeners()->repeater()->OnTestPartResult(result);
2143 DefaultPerThreadTestPartResultReporter::DefaultPerThreadTestPartResultReporter(
2144 UnitTestImpl* unit_test) : unit_test_(unit_test) {}
2146 void DefaultPerThreadTestPartResultReporter::ReportTestPartResult(
2147 const TestPartResult& result) {
2148 unit_test_->GetGlobalTestPartResultReporter()->ReportTestPartResult(result);
2151 // Returns the global test part result reporter.
2152 TestPartResultReporterInterface*
2153 UnitTestImpl::GetGlobalTestPartResultReporter() {
2154 internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
2155 return global_test_part_result_repoter_;
2158 // Sets the global test part result reporter.
2159 void UnitTestImpl::SetGlobalTestPartResultReporter(
2160 TestPartResultReporterInterface* reporter) {
2161 internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
2162 global_test_part_result_repoter_ = reporter;
2165 // Returns the test part result reporter for the current thread.
2166 TestPartResultReporterInterface*
2167 UnitTestImpl::GetTestPartResultReporterForCurrentThread() {
2168 return per_thread_test_part_result_reporter_.get();
2171 // Sets the test part result reporter for the current thread.
2172 void UnitTestImpl::SetTestPartResultReporterForCurrentThread(
2173 TestPartResultReporterInterface* reporter) {
2174 per_thread_test_part_result_reporter_.set(reporter);
2177 // Gets the number of successful test cases.
2178 int UnitTestImpl::successful_test_case_count() const {
2179 return CountIf(test_cases_, TestCasePassed);
2182 // Gets the number of failed test cases.
2183 int UnitTestImpl::failed_test_case_count() const {
2184 return CountIf(test_cases_, TestCaseFailed);
2187 // Gets the number of all test cases.
2188 int UnitTestImpl::total_test_case_count() const {
2189 return static_cast<int>(test_cases_.size());
2192 // Gets the number of all test cases that contain at least one test
2194 int UnitTestImpl::test_case_to_run_count() const {
2195 return CountIf(test_cases_, ShouldRunTestCase);
2198 // Gets the number of successful tests.
2199 int UnitTestImpl::successful_test_count() const {
2200 return SumOverTestCaseList(test_cases_, &TestCase::successful_test_count);
2203 // Gets the number of failed tests.
2204 int UnitTestImpl::failed_test_count() const {
2205 return SumOverTestCaseList(test_cases_, &TestCase::failed_test_count);
2208 // Gets the number of disabled tests that will be reported in the XML report.
2209 int UnitTestImpl::reportable_disabled_test_count() const {
2210 return SumOverTestCaseList(test_cases_,
2211 &TestCase::reportable_disabled_test_count);
2214 // Gets the number of disabled tests.
2215 int UnitTestImpl::disabled_test_count() const {
2216 return SumOverTestCaseList(test_cases_, &TestCase::disabled_test_count);
2219 // Gets the number of tests to be printed in the XML report.
2220 int UnitTestImpl::reportable_test_count() const {
2221 return SumOverTestCaseList(test_cases_, &TestCase::reportable_test_count);
2224 // Gets the number of all tests.
2225 int UnitTestImpl::total_test_count() const {
2226 return SumOverTestCaseList(test_cases_, &TestCase::total_test_count);
2229 // Gets the number of tests that should run.
2230 int UnitTestImpl::test_to_run_count() const {
2231 return SumOverTestCaseList(test_cases_, &TestCase::test_to_run_count);
2234 // Returns the current OS stack trace as an std::string.
2236 // The maximum number of stack frames to be included is specified by
2237 // the gtest_stack_trace_depth flag. The skip_count parameter
2238 // specifies the number of top frames to be skipped, which doesn't
2239 // count against the number of frames to be included.
2241 // For example, if Foo() calls Bar(), which in turn calls
2242 // CurrentOsStackTraceExceptTop(1), Foo() will be included in the
2243 // trace but Bar() and CurrentOsStackTraceExceptTop() won't.
2244 std::string UnitTestImpl::CurrentOsStackTraceExceptTop(int skip_count) {
2245 return os_stack_trace_getter()->CurrentStackTrace(
2246 static_cast<int>(GTEST_FLAG(stack_trace_depth)),
2248 // Skips the user-specified number of frames plus this function
2253 // Returns the current time in milliseconds.
2254 TimeInMillis GetTimeInMillis() {
2255 #if GTEST_OS_WINDOWS_MOBILE || defined(__BORLANDC__)
2256 // Difference between 1970-01-01 and 1601-01-01 in milliseconds.
2257 // http://analogous.blogspot.com/2005/04/epoch.html
2258 const TimeInMillis kJavaEpochToWinFileTimeDelta =
2259 static_cast<TimeInMillis>(116444736UL) * 100000UL;
2260 const DWORD kTenthMicrosInMilliSecond = 10000;
2262 SYSTEMTIME now_systime;
2263 FILETIME now_filetime;
2264 ULARGE_INTEGER now_int64;
2265 // TODO(kenton@google.com): Shouldn't this just use
2266 // GetSystemTimeAsFileTime()?
2267 GetSystemTime(&now_systime);
2268 if (SystemTimeToFileTime(&now_systime, &now_filetime)) {
2269 now_int64.LowPart = now_filetime.dwLowDateTime;
2270 now_int64.HighPart = now_filetime.dwHighDateTime;
2271 now_int64.QuadPart = (now_int64.QuadPart / kTenthMicrosInMilliSecond) -
2272 kJavaEpochToWinFileTimeDelta;
2273 return now_int64.QuadPart;
2276 #elif GTEST_OS_WINDOWS && !GTEST_HAS_GETTIMEOFDAY_
2279 // MSVC 8 deprecates _ftime64(), so we want to suppress warning 4996
2280 // (deprecated function) there.
2281 // TODO(kenton@google.com): Use GetTickCount()? Or use
2282 // SystemTimeToFileTime()
2283 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4996)
2285 GTEST_DISABLE_MSC_WARNINGS_POP_()
2287 return static_cast<TimeInMillis>(now.time) * 1000 + now.millitm;
2288 #elif GTEST_HAS_GETTIMEOFDAY_
2290 gettimeofday(&now, NULL);
2291 return static_cast<TimeInMillis>(now.tv_sec) * 1000 + now.tv_usec / 1000;
2293 # error "Don't know how to get the current time on your system."
2301 #if GTEST_OS_WINDOWS_MOBILE
2302 // Creates a UTF-16 wide string from the given ANSI string, allocating
2303 // memory using new. The caller is responsible for deleting the return
2304 // value using delete[]. Returns the wide string, or NULL if the
2306 LPCWSTR String::AnsiToUtf16(const char* ansi) {
2307 if (!ansi) return NULL;
2308 const int length = strlen(ansi);
2309 const int unicode_length =
2310 MultiByteToWideChar(CP_ACP, 0, ansi, length,
2312 WCHAR* unicode = new WCHAR[unicode_length + 1];
2313 MultiByteToWideChar(CP_ACP, 0, ansi, length,
2314 unicode, unicode_length);
2315 unicode[unicode_length] = 0;
2319 // Creates an ANSI string from the given wide string, allocating
2320 // memory using new. The caller is responsible for deleting the return
2321 // value using delete[]. Returns the ANSI string, or NULL if the
2323 const char* String::Utf16ToAnsi(LPCWSTR utf16_str) {
2324 if (!utf16_str) return NULL;
2325 const int ansi_length =
2326 WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
2327 NULL, 0, NULL, NULL);
2328 char* ansi = new char[ansi_length + 1];
2329 WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
2330 ansi, ansi_length, NULL, NULL);
2331 ansi[ansi_length] = 0;
2335 #endif // GTEST_OS_WINDOWS_MOBILE
2337 // Compares two C strings. Returns true iff they have the same content.
2339 // Unlike strcmp(), this function can handle NULL argument(s). A NULL
2340 // C string is considered different to any non-NULL C string,
2341 // including the empty string.
2342 bool String::CStringEquals(const char * lhs, const char * rhs) {
2343 if ( lhs == NULL ) return rhs == NULL;
2345 if ( rhs == NULL ) return false;
2347 return strcmp(lhs, rhs) == 0;
2350 #if GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
2352 // Converts an array of wide chars to a narrow string using the UTF-8
2353 // encoding, and streams the result to the given Message object.
2354 static void StreamWideCharsToMessage(const wchar_t* wstr, size_t length,
2356 for (size_t i = 0; i != length; ) { // NOLINT
2357 if (wstr[i] != L'\0') {
2358 *msg << WideStringToUtf8(wstr + i, static_cast<int>(length - i));
2359 while (i != length && wstr[i] != L'\0')
2368 #endif // GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
2370 void SplitString(const ::std::string& str, char delimiter,
2371 ::std::vector< ::std::string>* dest) {
2372 ::std::vector< ::std::string> parsed;
2373 ::std::string::size_type pos = 0;
2374 while (::testing::internal::AlwaysTrue()) {
2375 const ::std::string::size_type colon = str.find(delimiter, pos);
2376 if (colon == ::std::string::npos) {
2377 parsed.push_back(str.substr(pos));
2380 parsed.push_back(str.substr(pos, colon - pos));
2387 } // namespace internal
2389 // Constructs an empty Message.
2390 // We allocate the stringstream separately because otherwise each use of
2391 // ASSERT/EXPECT in a procedure adds over 200 bytes to the procedure's
2392 // stack frame leading to huge stack frames in some cases; gcc does not reuse
2394 Message::Message() : ss_(new ::std::stringstream) {
2395 // By default, we want there to be enough precision when printing
2396 // a double to a Message.
2397 *ss_ << std::setprecision(std::numeric_limits<double>::digits10 + 2);
2400 // These two overloads allow streaming a wide C string to a Message
2401 // using the UTF-8 encoding.
2402 Message& Message::operator <<(const wchar_t* wide_c_str) {
2403 return *this << internal::String::ShowWideCString(wide_c_str);
2405 Message& Message::operator <<(wchar_t* wide_c_str) {
2406 return *this << internal::String::ShowWideCString(wide_c_str);
2409 #if GTEST_HAS_STD_WSTRING
2410 // Converts the given wide string to a narrow string using the UTF-8
2411 // encoding, and streams the result to this Message object.
2412 Message& Message::operator <<(const ::std::wstring& wstr) {
2413 internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
2416 #endif // GTEST_HAS_STD_WSTRING
2418 #if GTEST_HAS_GLOBAL_WSTRING
2419 // Converts the given wide string to a narrow string using the UTF-8
2420 // encoding, and streams the result to this Message object.
2421 Message& Message::operator <<(const ::wstring& wstr) {
2422 internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
2425 #endif // GTEST_HAS_GLOBAL_WSTRING
2427 // Gets the text streamed to this object so far as an std::string.
2428 // Each '\0' character in the buffer is replaced with "\\0".
2429 std::string Message::GetString() const {
2430 return internal::StringStreamToString(ss_.get());
2433 // AssertionResult constructors.
2434 // Used in EXPECT_TRUE/FALSE(assertion_result).
2435 AssertionResult::AssertionResult(const AssertionResult& other)
2436 : success_(other.success_),
2437 message_(other.message_.get() != NULL ?
2438 new ::std::string(*other.message_) :
2439 static_cast< ::std::string*>(NULL)) {
2442 // Swaps two AssertionResults.
2443 void AssertionResult::swap(AssertionResult& other) {
2445 swap(success_, other.success_);
2446 swap(message_, other.message_);
2449 // Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE.
2450 AssertionResult AssertionResult::operator!() const {
2451 AssertionResult negation(!success_);
2452 if (message_.get() != NULL)
2453 negation << *message_;
2457 // Makes a successful assertion result.
2458 AssertionResult AssertionSuccess() {
2459 return AssertionResult(true);
2462 // Makes a failed assertion result.
2463 AssertionResult AssertionFailure() {
2464 return AssertionResult(false);
2467 // Makes a failed assertion result with the given failure message.
2468 // Deprecated; use AssertionFailure() << message.
2469 AssertionResult AssertionFailure(const Message& message) {
2470 return AssertionFailure() << message;
2473 namespace internal {
2475 namespace edit_distance {
2476 std::vector<EditType> CalculateOptimalEdits(const std::vector<size_t>& left,
2477 const std::vector<size_t>& right) {
2478 std::vector<std::vector<double> > costs(
2479 left.size() + 1, std::vector<double>(right.size() + 1));
2480 std::vector<std::vector<EditType> > best_move(
2481 left.size() + 1, std::vector<EditType>(right.size() + 1));
2483 // Populate for empty right.
2484 for (size_t l_i = 0; l_i < costs.size(); ++l_i) {
2485 costs[l_i][0] = static_cast<double>(l_i);
2486 best_move[l_i][0] = kRemove;
2488 // Populate for empty left.
2489 for (size_t r_i = 1; r_i < costs[0].size(); ++r_i) {
2490 costs[0][r_i] = static_cast<double>(r_i);
2491 best_move[0][r_i] = kAdd;
2494 for (size_t l_i = 0; l_i < left.size(); ++l_i) {
2495 for (size_t r_i = 0; r_i < right.size(); ++r_i) {
2496 if (left[l_i] == right[r_i]) {
2497 // Found a match. Consume it.
2498 costs[l_i + 1][r_i + 1] = costs[l_i][r_i];
2499 best_move[l_i + 1][r_i + 1] = kMatch;
2503 const double add = costs[l_i + 1][r_i];
2504 const double remove = costs[l_i][r_i + 1];
2505 const double replace = costs[l_i][r_i];
2506 if (add < remove && add < replace) {
2507 costs[l_i + 1][r_i + 1] = add + 1;
2508 best_move[l_i + 1][r_i + 1] = kAdd;
2509 } else if (remove < add && remove < replace) {
2510 costs[l_i + 1][r_i + 1] = remove + 1;
2511 best_move[l_i + 1][r_i + 1] = kRemove;
2513 // We make replace a little more expensive than add/remove to lower
2515 costs[l_i + 1][r_i + 1] = replace + 1.00001;
2516 best_move[l_i + 1][r_i + 1] = kReplace;
2521 // Reconstruct the best path. We do it in reverse order.
2522 std::vector<EditType> best_path;
2523 for (size_t l_i = left.size(), r_i = right.size(); l_i > 0 || r_i > 0;) {
2524 EditType move = best_move[l_i][r_i];
2525 best_path.push_back(move);
2526 l_i -= move != kAdd;
2527 r_i -= move != kRemove;
2529 std::reverse(best_path.begin(), best_path.end());
2535 // Helper class to convert string into ids with deduplication.
2536 class InternalStrings {
2538 size_t GetId(const std::string& str) {
2539 IdMap::iterator it = ids_.find(str);
2540 if (it != ids_.end()) return it->second;
2541 size_t id = ids_.size();
2542 return ids_[str] = id;
2546 typedef std::map<std::string, size_t> IdMap;
2552 std::vector<EditType> CalculateOptimalEdits(
2553 const std::vector<std::string>& left,
2554 const std::vector<std::string>& right) {
2555 std::vector<size_t> left_ids, right_ids;
2557 InternalStrings intern_table;
2558 for (size_t i = 0; i < left.size(); ++i) {
2559 left_ids.push_back(intern_table.GetId(left[i]));
2561 for (size_t i = 0; i < right.size(); ++i) {
2562 right_ids.push_back(intern_table.GetId(right[i]));
2565 return CalculateOptimalEdits(left_ids, right_ids);
2570 // Helper class that holds the state for one hunk and prints it out to the
2572 // It reorders adds/removes when possible to group all removes before all
2573 // adds. It also adds the hunk header before printint into the stream.
2576 Hunk(size_t left_start, size_t right_start)
2577 : left_start_(left_start),
2578 right_start_(right_start),
2583 void PushLine(char edit, const char* line) {
2588 hunk_.push_back(std::make_pair(' ', line));
2592 hunk_removes_.push_back(std::make_pair('-', line));
2596 hunk_adds_.push_back(std::make_pair('+', line));
2601 void PrintTo(std::ostream* os) {
2604 for (std::list<std::pair<char, const char*> >::const_iterator it =
2606 it != hunk_.end(); ++it) {
2607 *os << it->first << it->second << "\n";
2611 bool has_edits() const { return adds_ || removes_; }
2615 hunk_.splice(hunk_.end(), hunk_removes_);
2616 hunk_.splice(hunk_.end(), hunk_adds_);
2619 // Print a unified diff header for one hunk.
2621 // "@@ -<left_start>,<left_length> +<right_start>,<right_length> @@"
2622 // where the left/right parts are ommitted if unnecessary.
2623 void PrintHeader(std::ostream* ss) const {
2626 *ss << "-" << left_start_ << "," << (removes_ + common_);
2628 if (removes_ && adds_) {
2632 *ss << "+" << right_start_ << "," << (adds_ + common_);
2637 size_t left_start_, right_start_;
2638 size_t adds_, removes_, common_;
2639 std::list<std::pair<char, const char*> > hunk_, hunk_adds_, hunk_removes_;
2644 // Create a list of diff hunks in Unified diff format.
2645 // Each hunk has a header generated by PrintHeader above plus a body with
2646 // lines prefixed with ' ' for no change, '-' for deletion and '+' for
2648 // 'context' represents the desired unchanged prefix/suffix around the diff.
2649 // If two hunks are close enough that their contexts overlap, then they are
2650 // joined into one hunk.
2651 std::string CreateUnifiedDiff(const std::vector<std::string>& left,
2652 const std::vector<std::string>& right,
2654 const std::vector<EditType> edits = CalculateOptimalEdits(left, right);
2656 size_t l_i = 0, r_i = 0, edit_i = 0;
2657 std::stringstream ss;
2658 while (edit_i < edits.size()) {
2660 while (edit_i < edits.size() && edits[edit_i] == kMatch) {
2666 // Find the first line to include in the hunk.
2667 const size_t prefix_context = std::min(l_i, context);
2668 Hunk hunk(l_i - prefix_context + 1, r_i - prefix_context + 1);
2669 for (size_t i = prefix_context; i > 0; --i) {
2670 hunk.PushLine(' ', left[l_i - i].c_str());
2673 // Iterate the edits until we found enough suffix for the hunk or the input
2675 size_t n_suffix = 0;
2676 for (; edit_i < edits.size(); ++edit_i) {
2677 if (n_suffix >= context) {
2678 // Continue only if the next hunk is very close.
2679 std::vector<EditType>::const_iterator it = edits.begin() + edit_i;
2680 while (it != edits.end() && *it == kMatch) ++it;
2681 if (it == edits.end() || (it - edits.begin()) - edit_i >= context) {
2682 // There is no next edit or it is too far away.
2687 EditType edit = edits[edit_i];
2688 // Reset count when a non match is found.
2689 n_suffix = edit == kMatch ? n_suffix + 1 : 0;
2691 if (edit == kMatch || edit == kRemove || edit == kReplace) {
2692 hunk.PushLine(edit == kMatch ? ' ' : '-', left[l_i].c_str());
2694 if (edit == kAdd || edit == kReplace) {
2695 hunk.PushLine('+', right[r_i].c_str());
2698 // Advance indices, depending on edit type.
2699 l_i += edit != kAdd;
2700 r_i += edit != kRemove;
2703 if (!hunk.has_edits()) {
2704 // We are done. We don't want this hunk.
2713 } // namespace edit_distance
2717 // The string representation of the values received in EqFailure() are already
2718 // escaped. Split them on escaped '\n' boundaries. Leave all other escaped
2719 // characters the same.
2720 std::vector<std::string> SplitEscapedString(const std::string& str) {
2721 std::vector<std::string> lines;
2722 size_t start = 0, end = str.size();
2723 if (end > 2 && str[0] == '"' && str[end - 1] == '"') {
2727 bool escaped = false;
2728 for (size_t i = start; i + 1 < end; ++i) {
2731 if (str[i] == 'n') {
2732 lines.push_back(str.substr(start, i - start - 1));
2736 escaped = str[i] == '\\';
2739 lines.push_back(str.substr(start, end - start));
2745 // Constructs and returns the message for an equality assertion
2746 // (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure.
2748 // The first four parameters are the expressions used in the assertion
2749 // and their values, as strings. For example, for ASSERT_EQ(foo, bar)
2750 // where foo is 5 and bar is 6, we have:
2752 // lhs_expression: "foo"
2753 // rhs_expression: "bar"
2757 // The ignoring_case parameter is true iff the assertion is a
2758 // *_STRCASEEQ*. When it's true, the string "Ignoring case" will
2759 // be inserted into the message.
2760 AssertionResult EqFailure(const char* lhs_expression,
2761 const char* rhs_expression,
2762 const std::string& lhs_value,
2763 const std::string& rhs_value,
2764 bool ignoring_case) {
2766 msg << " Expected: " << lhs_expression;
2767 if (lhs_value != lhs_expression) {
2768 msg << "\n Which is: " << lhs_value;
2770 msg << "\nTo be equal to: " << rhs_expression;
2771 if (rhs_value != rhs_expression) {
2772 msg << "\n Which is: " << rhs_value;
2775 if (ignoring_case) {
2776 msg << "\nIgnoring case";
2779 if (!lhs_value.empty() && !rhs_value.empty()) {
2780 const std::vector<std::string> lhs_lines =
2781 SplitEscapedString(lhs_value);
2782 const std::vector<std::string> rhs_lines =
2783 SplitEscapedString(rhs_value);
2784 if (lhs_lines.size() > 1 || rhs_lines.size() > 1) {
2785 msg << "\nWith diff:\n"
2786 << edit_distance::CreateUnifiedDiff(lhs_lines, rhs_lines);
2790 return AssertionFailure() << msg;
2793 // Constructs a failure message for Boolean assertions such as EXPECT_TRUE.
2794 std::string GetBoolAssertionFailureMessage(
2795 const AssertionResult& assertion_result,
2796 const char* expression_text,
2797 const char* actual_predicate_value,
2798 const char* expected_predicate_value) {
2799 const char* actual_message = assertion_result.message();
2801 msg << "Value of: " << expression_text
2802 << "\n Actual: " << actual_predicate_value;
2803 if (actual_message[0] != '\0')
2804 msg << " (" << actual_message << ")";
2805 msg << "\nExpected: " << expected_predicate_value;
2806 return msg.GetString();
2809 // Helper function for implementing ASSERT_NEAR.
2810 AssertionResult DoubleNearPredFormat(const char* expr1,
2812 const char* abs_error_expr,
2816 const double diff = fabs(val1 - val2);
2817 if (diff <= abs_error) return AssertionSuccess();
2819 // TODO(wan): do not print the value of an expression if it's
2820 // already a literal.
2821 return AssertionFailure()
2822 << "The difference between " << expr1 << " and " << expr2
2823 << " is " << diff << ", which exceeds " << abs_error_expr << ", where\n"
2824 << expr1 << " evaluates to " << val1 << ",\n"
2825 << expr2 << " evaluates to " << val2 << ", and\n"
2826 << abs_error_expr << " evaluates to " << abs_error << ".";
2830 // Helper template for implementing FloatLE() and DoubleLE().
2831 template <typename RawType>
2832 AssertionResult FloatingPointLE(const char* expr1,
2836 // Returns success if val1 is less than val2,
2838 return AssertionSuccess();
2841 // or if val1 is almost equal to val2.
2842 const FloatingPoint<RawType> lhs(val1), rhs(val2);
2843 if (lhs.AlmostEquals(rhs)) {
2844 return AssertionSuccess();
2847 // Note that the above two checks will both fail if either val1 or
2848 // val2 is NaN, as the IEEE floating-point standard requires that
2849 // any predicate involving a NaN must return false.
2851 ::std::stringstream val1_ss;
2852 val1_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
2855 ::std::stringstream val2_ss;
2856 val2_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
2859 return AssertionFailure()
2860 << "Expected: (" << expr1 << ") <= (" << expr2 << ")\n"
2861 << " Actual: " << StringStreamToString(&val1_ss) << " vs "
2862 << StringStreamToString(&val2_ss);
2865 } // namespace internal
2867 // Asserts that val1 is less than, or almost equal to, val2. Fails
2868 // otherwise. In particular, it fails if either val1 or val2 is NaN.
2869 AssertionResult FloatLE(const char* expr1, const char* expr2,
2870 float val1, float val2) {
2871 return internal::FloatingPointLE<float>(expr1, expr2, val1, val2);
2874 // Asserts that val1 is less than, or almost equal to, val2. Fails
2875 // otherwise. In particular, it fails if either val1 or val2 is NaN.
2876 AssertionResult DoubleLE(const char* expr1, const char* expr2,
2877 double val1, double val2) {
2878 return internal::FloatingPointLE<double>(expr1, expr2, val1, val2);
2881 namespace internal {
2883 // The helper function for {ASSERT|EXPECT}_EQ with int or enum
2885 AssertionResult CmpHelperEQ(const char* lhs_expression,
2886 const char* rhs_expression,
2890 return AssertionSuccess();
2893 return EqFailure(lhs_expression,
2895 FormatForComparisonFailureMessage(lhs, rhs),
2896 FormatForComparisonFailureMessage(rhs, lhs),
2900 // A macro for implementing the helper functions needed to implement
2901 // ASSERT_?? and EXPECT_?? with integer or enum arguments. It is here
2902 // just to avoid copy-and-paste of similar code.
2903 #define GTEST_IMPL_CMP_HELPER_(op_name, op)\
2904 AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \
2905 BiggestInt val1, BiggestInt val2) {\
2906 if (val1 op val2) {\
2907 return AssertionSuccess();\
2909 return AssertionFailure() \
2910 << "Expected: (" << expr1 << ") " #op " (" << expr2\
2911 << "), actual: " << FormatForComparisonFailureMessage(val1, val2)\
2912 << " vs " << FormatForComparisonFailureMessage(val2, val1);\
2916 // Implements the helper function for {ASSERT|EXPECT}_NE with int or
2918 GTEST_IMPL_CMP_HELPER_(NE, !=)
2919 // Implements the helper function for {ASSERT|EXPECT}_LE with int or
2921 GTEST_IMPL_CMP_HELPER_(LE, <=)
2922 // Implements the helper function for {ASSERT|EXPECT}_LT with int or
2924 GTEST_IMPL_CMP_HELPER_(LT, < )
2925 // Implements the helper function for {ASSERT|EXPECT}_GE with int or
2927 GTEST_IMPL_CMP_HELPER_(GE, >=)
2928 // Implements the helper function for {ASSERT|EXPECT}_GT with int or
2930 GTEST_IMPL_CMP_HELPER_(GT, > )
2932 #undef GTEST_IMPL_CMP_HELPER_
2934 // The helper function for {ASSERT|EXPECT}_STREQ.
2935 AssertionResult CmpHelperSTREQ(const char* lhs_expression,
2936 const char* rhs_expression,
2939 if (String::CStringEquals(lhs, rhs)) {
2940 return AssertionSuccess();
2943 return EqFailure(lhs_expression,
2950 // The helper function for {ASSERT|EXPECT}_STRCASEEQ.
2951 AssertionResult CmpHelperSTRCASEEQ(const char* lhs_expression,
2952 const char* rhs_expression,
2955 if (String::CaseInsensitiveCStringEquals(lhs, rhs)) {
2956 return AssertionSuccess();
2959 return EqFailure(lhs_expression,
2966 // The helper function for {ASSERT|EXPECT}_STRNE.
2967 AssertionResult CmpHelperSTRNE(const char* s1_expression,
2968 const char* s2_expression,
2971 if (!String::CStringEquals(s1, s2)) {
2972 return AssertionSuccess();
2974 return AssertionFailure() << "Expected: (" << s1_expression << ") != ("
2975 << s2_expression << "), actual: \""
2976 << s1 << "\" vs \"" << s2 << "\"";
2980 // The helper function for {ASSERT|EXPECT}_STRCASENE.
2981 AssertionResult CmpHelperSTRCASENE(const char* s1_expression,
2982 const char* s2_expression,
2985 if (!String::CaseInsensitiveCStringEquals(s1, s2)) {
2986 return AssertionSuccess();
2988 return AssertionFailure()
2989 << "Expected: (" << s1_expression << ") != ("
2990 << s2_expression << ") (ignoring case), actual: \""
2991 << s1 << "\" vs \"" << s2 << "\"";
2995 } // namespace internal
2999 // Helper functions for implementing IsSubString() and IsNotSubstring().
3001 // This group of overloaded functions return true iff needle is a
3002 // substring of haystack. NULL is considered a substring of itself
3005 bool IsSubstringPred(const char* needle, const char* haystack) {
3006 if (needle == NULL || haystack == NULL)
3007 return needle == haystack;
3009 return strstr(haystack, needle) != NULL;
3012 bool IsSubstringPred(const wchar_t* needle, const wchar_t* haystack) {
3013 if (needle == NULL || haystack == NULL)
3014 return needle == haystack;
3016 return wcsstr(haystack, needle) != NULL;
3019 // StringType here can be either ::std::string or ::std::wstring.
3020 template <typename StringType>
3021 bool IsSubstringPred(const StringType& needle,
3022 const StringType& haystack) {
3023 return haystack.find(needle) != StringType::npos;
3026 // This function implements either IsSubstring() or IsNotSubstring(),
3027 // depending on the value of the expected_to_be_substring parameter.
3028 // StringType here can be const char*, const wchar_t*, ::std::string,
3029 // or ::std::wstring.
3030 template <typename StringType>
3031 AssertionResult IsSubstringImpl(
3032 bool expected_to_be_substring,
3033 const char* needle_expr, const char* haystack_expr,
3034 const StringType& needle, const StringType& haystack) {
3035 if (IsSubstringPred(needle, haystack) == expected_to_be_substring)
3036 return AssertionSuccess();
3038 const bool is_wide_string = sizeof(needle[0]) > 1;
3039 const char* const begin_string_quote = is_wide_string ? "L\"" : "\"";
3040 return AssertionFailure()
3041 << "Value of: " << needle_expr << "\n"
3042 << " Actual: " << begin_string_quote << needle << "\"\n"
3043 << "Expected: " << (expected_to_be_substring ? "" : "not ")
3044 << "a substring of " << haystack_expr << "\n"
3045 << "Which is: " << begin_string_quote << haystack << "\"";
3050 // IsSubstring() and IsNotSubstring() check whether needle is a
3051 // substring of haystack (NULL is considered a substring of itself
3052 // only), and return an appropriate error message when they fail.
3054 AssertionResult IsSubstring(
3055 const char* needle_expr, const char* haystack_expr,
3056 const char* needle, const char* haystack) {
3057 return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
3060 AssertionResult IsSubstring(
3061 const char* needle_expr, const char* haystack_expr,
3062 const wchar_t* needle, const wchar_t* haystack) {
3063 return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
3066 AssertionResult IsNotSubstring(
3067 const char* needle_expr, const char* haystack_expr,
3068 const char* needle, const char* haystack) {
3069 return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
3072 AssertionResult IsNotSubstring(
3073 const char* needle_expr, const char* haystack_expr,
3074 const wchar_t* needle, const wchar_t* haystack) {
3075 return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
3078 AssertionResult IsSubstring(
3079 const char* needle_expr, const char* haystack_expr,
3080 const ::std::string& needle, const ::std::string& haystack) {
3081 return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
3084 AssertionResult IsNotSubstring(
3085 const char* needle_expr, const char* haystack_expr,
3086 const ::std::string& needle, const ::std::string& haystack) {
3087 return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
3090 #if GTEST_HAS_STD_WSTRING
3091 AssertionResult IsSubstring(
3092 const char* needle_expr, const char* haystack_expr,
3093 const ::std::wstring& needle, const ::std::wstring& haystack) {
3094 return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
3097 AssertionResult IsNotSubstring(
3098 const char* needle_expr, const char* haystack_expr,
3099 const ::std::wstring& needle, const ::std::wstring& haystack) {
3100 return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
3102 #endif // GTEST_HAS_STD_WSTRING
3104 namespace internal {
3106 #if GTEST_OS_WINDOWS
3110 // Helper function for IsHRESULT{SuccessFailure} predicates
3111 AssertionResult HRESULTFailureHelper(const char* expr,
3112 const char* expected,
3113 long hr) { // NOLINT
3114 # if GTEST_OS_WINDOWS_MOBILE
3116 // Windows CE doesn't support FormatMessage.
3117 const char error_text[] = "";
3121 // Looks up the human-readable system message for the HRESULT code
3122 // and since we're not passing any params to FormatMessage, we don't
3123 // want inserts expanded.
3124 const DWORD kFlags = FORMAT_MESSAGE_FROM_SYSTEM |
3125 FORMAT_MESSAGE_IGNORE_INSERTS;
3126 const DWORD kBufSize = 4096;
3127 // Gets the system's human readable message string for this HRESULT.
3128 char error_text[kBufSize] = { '\0' };
3129 DWORD message_length = ::FormatMessageA(kFlags,
3130 0, // no source, we're asking system
3132 0, // no line width restrictions
3133 error_text, // output buffer
3134 kBufSize, // buf size
3135 NULL); // no arguments for inserts
3136 // Trims tailing white space (FormatMessage leaves a trailing CR-LF)
3137 for (; message_length && IsSpace(error_text[message_length - 1]);
3139 error_text[message_length - 1] = '\0';
3142 # endif // GTEST_OS_WINDOWS_MOBILE
3144 const std::string error_hex("0x" + String::FormatHexInt(hr));
3145 return ::testing::AssertionFailure()
3146 << "Expected: " << expr << " " << expected << ".\n"
3147 << " Actual: " << error_hex << " " << error_text << "\n";
3152 AssertionResult IsHRESULTSuccess(const char* expr, long hr) { // NOLINT
3153 if (SUCCEEDED(hr)) {
3154 return AssertionSuccess();
3156 return HRESULTFailureHelper(expr, "succeeds", hr);
3159 AssertionResult IsHRESULTFailure(const char* expr, long hr) { // NOLINT
3161 return AssertionSuccess();
3163 return HRESULTFailureHelper(expr, "fails", hr);
3166 #endif // GTEST_OS_WINDOWS
3168 // Utility functions for encoding Unicode text (wide strings) in
3171 // A Unicode code-point can have upto 21 bits, and is encoded in UTF-8
3174 // Code-point length Encoding
3175 // 0 - 7 bits 0xxxxxxx
3176 // 8 - 11 bits 110xxxxx 10xxxxxx
3177 // 12 - 16 bits 1110xxxx 10xxxxxx 10xxxxxx
3178 // 17 - 21 bits 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
3180 // The maximum code-point a one-byte UTF-8 sequence can represent.
3181 const UInt32 kMaxCodePoint1 = (static_cast<UInt32>(1) << 7) - 1;
3183 // The maximum code-point a two-byte UTF-8 sequence can represent.
3184 const UInt32 kMaxCodePoint2 = (static_cast<UInt32>(1) << (5 + 6)) - 1;
3186 // The maximum code-point a three-byte UTF-8 sequence can represent.
3187 const UInt32 kMaxCodePoint3 = (static_cast<UInt32>(1) << (4 + 2*6)) - 1;
3189 // The maximum code-point a four-byte UTF-8 sequence can represent.
3190 const UInt32 kMaxCodePoint4 = (static_cast<UInt32>(1) << (3 + 3*6)) - 1;
3192 // Chops off the n lowest bits from a bit pattern. Returns the n
3193 // lowest bits. As a side effect, the original bit pattern will be
3194 // shifted to the right by n bits.
3195 inline UInt32 ChopLowBits(UInt32* bits, int n) {
3196 const UInt32 low_bits = *bits & ((static_cast<UInt32>(1) << n) - 1);
3201 // Converts a Unicode code point to a narrow string in UTF-8 encoding.
3202 // code_point parameter is of type UInt32 because wchar_t may not be
3203 // wide enough to contain a code point.
3204 // If the code_point is not a valid Unicode code point
3205 // (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted
3206 // to "(Invalid Unicode 0xXXXXXXXX)".
3207 std::string CodePointToUtf8(UInt32 code_point) {
3208 if (code_point > kMaxCodePoint4) {
3209 return "(Invalid Unicode 0x" + String::FormatHexInt(code_point) + ")";
3212 char str[5]; // Big enough for the largest valid code point.
3213 if (code_point <= kMaxCodePoint1) {
3215 str[0] = static_cast<char>(code_point); // 0xxxxxxx
3216 } else if (code_point <= kMaxCodePoint2) {
3218 str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
3219 str[0] = static_cast<char>(0xC0 | code_point); // 110xxxxx
3220 } else if (code_point <= kMaxCodePoint3) {
3222 str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
3223 str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
3224 str[0] = static_cast<char>(0xE0 | code_point); // 1110xxxx
3225 } else { // code_point <= kMaxCodePoint4
3227 str[3] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
3228 str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
3229 str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
3230 str[0] = static_cast<char>(0xF0 | code_point); // 11110xxx
3235 // The following two functions only make sense if the the system
3236 // uses UTF-16 for wide string encoding. All supported systems
3237 // with 16 bit wchar_t (Windows, Cygwin, Symbian OS) do use UTF-16.
3239 // Determines if the arguments constitute UTF-16 surrogate pair
3240 // and thus should be combined into a single Unicode code point
3241 // using CreateCodePointFromUtf16SurrogatePair.
3242 inline bool IsUtf16SurrogatePair(wchar_t first, wchar_t second) {
3243 return sizeof(wchar_t) == 2 &&
3244 (first & 0xFC00) == 0xD800 && (second & 0xFC00) == 0xDC00;
3247 // Creates a Unicode code point from UTF16 surrogate pair.
3248 inline UInt32 CreateCodePointFromUtf16SurrogatePair(wchar_t first,
3250 const UInt32 mask = (1 << 10) - 1;
3251 return (sizeof(wchar_t) == 2) ?
3252 (((first & mask) << 10) | (second & mask)) + 0x10000 :
3253 // This function should not be called when the condition is
3254 // false, but we provide a sensible default in case it is.
3255 static_cast<UInt32>(first);
3258 // Converts a wide string to a narrow string in UTF-8 encoding.
3259 // The wide string is assumed to have the following encoding:
3260 // UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS)
3261 // UTF-32 if sizeof(wchar_t) == 4 (on Linux)
3262 // Parameter str points to a null-terminated wide string.
3263 // Parameter num_chars may additionally limit the number
3264 // of wchar_t characters processed. -1 is used when the entire string
3265 // should be processed.
3266 // If the string contains code points that are not valid Unicode code points
3267 // (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
3268 // as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
3269 // and contains invalid UTF-16 surrogate pairs, values in those pairs
3270 // will be encoded as individual Unicode characters from Basic Normal Plane.
3271 std::string WideStringToUtf8(const wchar_t* str, int num_chars) {
3272 if (num_chars == -1)
3273 num_chars = static_cast<int>(wcslen(str));
3275 ::std::stringstream stream;
3276 for (int i = 0; i < num_chars; ++i) {
3277 UInt32 unicode_code_point;
3279 if (str[i] == L'\0') {
3281 } else if (i + 1 < num_chars && IsUtf16SurrogatePair(str[i], str[i + 1])) {
3282 unicode_code_point = CreateCodePointFromUtf16SurrogatePair(str[i],
3286 unicode_code_point = static_cast<UInt32>(str[i]);
3289 stream << CodePointToUtf8(unicode_code_point);
3291 return StringStreamToString(&stream);
3294 // Converts a wide C string to an std::string using the UTF-8 encoding.
3295 // NULL will be converted to "(null)".
3296 std::string String::ShowWideCString(const wchar_t * wide_c_str) {
3297 if (wide_c_str == NULL) return "(null)";
3299 return internal::WideStringToUtf8(wide_c_str, -1);
3302 // Compares two wide C strings. Returns true iff they have the same
3305 // Unlike wcscmp(), this function can handle NULL argument(s). A NULL
3306 // C string is considered different to any non-NULL C string,
3307 // including the empty string.
3308 bool String::WideCStringEquals(const wchar_t * lhs, const wchar_t * rhs) {
3309 if (lhs == NULL) return rhs == NULL;
3311 if (rhs == NULL) return false;
3313 return wcscmp(lhs, rhs) == 0;
3316 // Helper function for *_STREQ on wide strings.
3317 AssertionResult CmpHelperSTREQ(const char* lhs_expression,
3318 const char* rhs_expression,
3320 const wchar_t* rhs) {
3321 if (String::WideCStringEquals(lhs, rhs)) {
3322 return AssertionSuccess();
3325 return EqFailure(lhs_expression,
3332 // Helper function for *_STRNE on wide strings.
3333 AssertionResult CmpHelperSTRNE(const char* s1_expression,
3334 const char* s2_expression,
3336 const wchar_t* s2) {
3337 if (!String::WideCStringEquals(s1, s2)) {
3338 return AssertionSuccess();
3341 return AssertionFailure() << "Expected: (" << s1_expression << ") != ("
3342 << s2_expression << "), actual: "
3343 << PrintToString(s1)
3344 << " vs " << PrintToString(s2);
3347 // Compares two C strings, ignoring case. Returns true iff they have
3348 // the same content.
3350 // Unlike strcasecmp(), this function can handle NULL argument(s). A
3351 // NULL C string is considered different to any non-NULL C string,
3352 // including the empty string.
3353 bool String::CaseInsensitiveCStringEquals(const char * lhs, const char * rhs) {
3358 return posix::StrCaseCmp(lhs, rhs) == 0;
3361 // Compares two wide C strings, ignoring case. Returns true iff they
3362 // have the same content.
3364 // Unlike wcscasecmp(), this function can handle NULL argument(s).
3365 // A NULL C string is considered different to any non-NULL wide C string,
3366 // including the empty string.
3367 // NB: The implementations on different platforms slightly differ.
3368 // On windows, this method uses _wcsicmp which compares according to LC_CTYPE
3369 // environment variable. On GNU platform this method uses wcscasecmp
3370 // which compares according to LC_CTYPE category of the current locale.
3371 // On MacOS X, it uses towlower, which also uses LC_CTYPE category of the
3373 bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs,
3374 const wchar_t* rhs) {
3375 if (lhs == NULL) return rhs == NULL;
3377 if (rhs == NULL) return false;
3379 #if GTEST_OS_WINDOWS
3380 return _wcsicmp(lhs, rhs) == 0;
3381 #elif GTEST_OS_LINUX && !GTEST_OS_LINUX_ANDROID
3382 return wcscasecmp(lhs, rhs) == 0;
3384 // Android, Mac OS X and Cygwin don't define wcscasecmp.
3385 // Other unknown OSes may not define it either.
3388 left = towlower(*lhs++);
3389 right = towlower(*rhs++);
3390 } while (left && left == right);
3391 return left == right;
3392 #endif // OS selector
3395 // Returns true iff str ends with the given suffix, ignoring case.
3396 // Any string is considered to end with an empty suffix.
3397 bool String::EndsWithCaseInsensitive(
3398 const std::string& str, const std::string& suffix) {
3399 const size_t str_len = str.length();
3400 const size_t suffix_len = suffix.length();
3401 return (str_len >= suffix_len) &&
3402 CaseInsensitiveCStringEquals(str.c_str() + str_len - suffix_len,
3406 // Formats an int value as "%02d".
3407 std::string String::FormatIntWidth2(int value) {
3408 std::stringstream ss;
3409 ss << std::setfill('0') << std::setw(2) << value;
3413 // Formats an int value as "%X".
3414 std::string String::FormatHexInt(int value) {
3415 std::stringstream ss;
3416 ss << std::hex << std::uppercase << value;
3420 // Formats a byte as "%02X".
3421 std::string String::FormatByte(unsigned char value) {
3422 std::stringstream ss;
3423 ss << std::setfill('0') << std::setw(2) << std::hex << std::uppercase
3424 << static_cast<unsigned int>(value);
3428 // Converts the buffer in a stringstream to an std::string, converting NUL
3429 // bytes to "\\0" along the way.
3430 std::string StringStreamToString(::std::stringstream* ss) {
3431 const ::std::string& str = ss->str();
3432 const char* const start = str.c_str();
3433 const char* const end = start + str.length();
3436 result.reserve(2 * (end - start));
3437 for (const char* ch = start; ch != end; ++ch) {
3439 result += "\\0"; // Replaces NUL with "\\0";
3448 // Appends the user-supplied message to the Google-Test-generated message.
3449 std::string AppendUserMessage(const std::string& gtest_msg,
3450 const Message& user_msg) {
3451 // Appends the user message if it's non-empty.
3452 const std::string user_msg_string = user_msg.GetString();
3453 if (user_msg_string.empty()) {
3457 return gtest_msg + "\n" + user_msg_string;
3460 } // namespace internal
3464 // Creates an empty TestResult.
3465 TestResult::TestResult()
3466 : death_test_count_(0),
3471 TestResult::~TestResult() {
3474 // Returns the i-th test part result among all the results. i can
3475 // range from 0 to total_part_count() - 1. If i is not in that range,
3476 // aborts the program.
3477 const TestPartResult& TestResult::GetTestPartResult(int i) const {
3478 if (i < 0 || i >= total_part_count())
3479 internal::posix::Abort();
3480 return test_part_results_.at(i);
3483 // Returns the i-th test property. i can range from 0 to
3484 // test_property_count() - 1. If i is not in that range, aborts the
3486 const TestProperty& TestResult::GetTestProperty(int i) const {
3487 if (i < 0 || i >= test_property_count())
3488 internal::posix::Abort();
3489 return test_properties_.at(i);
3492 // Clears the test part results.
3493 void TestResult::ClearTestPartResults() {
3494 test_part_results_.clear();
3497 // Adds a test part result to the list.
3498 void TestResult::AddTestPartResult(const TestPartResult& test_part_result) {
3499 test_part_results_.push_back(test_part_result);
3502 // Adds a test property to the list. If a property with the same key as the
3503 // supplied property is already represented, the value of this test_property
3504 // replaces the old value for that key.
3505 void TestResult::RecordProperty(const std::string& xml_element,
3506 const TestProperty& test_property) {
3507 if (!ValidateTestProperty(xml_element, test_property)) {
3510 internal::MutexLock lock(&test_properites_mutex_);
3511 const std::vector<TestProperty>::iterator property_with_matching_key =
3512 std::find_if(test_properties_.begin(), test_properties_.end(),
3513 internal::TestPropertyKeyIs(test_property.key()));
3514 if (property_with_matching_key == test_properties_.end()) {
3515 test_properties_.push_back(test_property);
3518 property_with_matching_key->SetValue(test_property.value());
3521 // The list of reserved attributes used in the <testsuites> element of XML
3523 static const char* const kReservedTestSuitesAttributes[] = {
3534 // The list of reserved attributes used in the <testsuite> element of XML
3536 static const char* const kReservedTestSuiteAttributes[] = {
3545 // The list of reserved attributes used in the <testcase> element of XML output.
3546 static const char* const kReservedTestCaseAttributes[] = {
3555 template <int kSize>
3556 std::vector<std::string> ArrayAsVector(const char* const (&array)[kSize]) {
3557 return std::vector<std::string>(array, array + kSize);
3560 static std::vector<std::string> GetReservedAttributesForElement(
3561 const std::string& xml_element) {
3562 if (xml_element == "testsuites") {
3563 return ArrayAsVector(kReservedTestSuitesAttributes);
3564 } else if (xml_element == "testsuite") {
3565 return ArrayAsVector(kReservedTestSuiteAttributes);
3566 } else if (xml_element == "testcase") {
3567 return ArrayAsVector(kReservedTestCaseAttributes);
3569 GTEST_CHECK_(false) << "Unrecognized xml_element provided: " << xml_element;
3571 // This code is unreachable but some compilers may not realizes that.
3572 return std::vector<std::string>();
3575 static std::string FormatWordList(const std::vector<std::string>& words) {
3577 for (size_t i = 0; i < words.size(); ++i) {
3578 if (i > 0 && words.size() > 2) {
3581 if (i == words.size() - 1) {
3582 word_list << "and ";
3584 word_list << "'" << words[i] << "'";
3586 return word_list.GetString();
3589 bool ValidateTestPropertyName(const std::string& property_name,
3590 const std::vector<std::string>& reserved_names) {
3591 if (std::find(reserved_names.begin(), reserved_names.end(), property_name) !=
3592 reserved_names.end()) {
3593 ADD_FAILURE() << "Reserved key used in RecordProperty(): " << property_name
3594 << " (" << FormatWordList(reserved_names)
3595 << " are reserved by " << GTEST_NAME_ << ")";
3601 // Adds a failure if the key is a reserved attribute of the element named
3602 // xml_element. Returns true if the property is valid.
3603 bool TestResult::ValidateTestProperty(const std::string& xml_element,
3604 const TestProperty& test_property) {
3605 return ValidateTestPropertyName(test_property.key(),
3606 GetReservedAttributesForElement(xml_element));
3609 // Clears the object.
3610 void TestResult::Clear() {
3611 test_part_results_.clear();
3612 test_properties_.clear();
3613 death_test_count_ = 0;
3617 // Returns true iff the test failed.
3618 bool TestResult::Failed() const {
3619 for (int i = 0; i < total_part_count(); ++i) {
3620 if (GetTestPartResult(i).failed())
3626 // Returns true iff the test part fatally failed.
3627 static bool TestPartFatallyFailed(const TestPartResult& result) {
3628 return result.fatally_failed();
3631 // Returns true iff the test fatally failed.
3632 bool TestResult::HasFatalFailure() const {
3633 return CountIf(test_part_results_, TestPartFatallyFailed) > 0;
3636 // Returns true iff the test part non-fatally failed.
3637 static bool TestPartNonfatallyFailed(const TestPartResult& result) {
3638 return result.nonfatally_failed();
3641 // Returns true iff the test has a non-fatal failure.
3642 bool TestResult::HasNonfatalFailure() const {
3643 return CountIf(test_part_results_, TestPartNonfatallyFailed) > 0;
3646 // Gets the number of all test parts. This is the sum of the number
3647 // of successful test parts and the number of failed test parts.
3648 int TestResult::total_part_count() const {
3649 return static_cast<int>(test_part_results_.size());
3652 // Returns the number of the test properties.
3653 int TestResult::test_property_count() const {
3654 return static_cast<int>(test_properties_.size());
3659 // Creates a Test object.
3661 // The c'tor saves the states of all flags.
3663 : gtest_flag_saver_(new GTEST_FLAG_SAVER_) {
3666 // The d'tor restores the states of all flags. The actual work is
3667 // done by the d'tor of the gtest_flag_saver_ field, and thus not
3672 // Sets up the test fixture.
3674 // A sub-class may override this.
3675 void Test::SetUp() {
3678 // Tears down the test fixture.
3680 // A sub-class may override this.
3681 void Test::TearDown() {
3684 // Allows user supplied key value pairs to be recorded for later output.
3685 void Test::RecordProperty(const std::string& key, const std::string& value) {
3686 UnitTest::GetInstance()->RecordProperty(key, value);
3689 // Allows user supplied key value pairs to be recorded for later output.
3690 void Test::RecordProperty(const std::string& key, int value) {
3691 Message value_message;
3692 value_message << value;
3693 RecordProperty(key, value_message.GetString().c_str());
3696 namespace internal {
3698 void ReportFailureInUnknownLocation(TestPartResult::Type result_type,
3699 const std::string& message) {
3700 // This function is a friend of UnitTest and as such has access to
3701 // AddTestPartResult.
3702 UnitTest::GetInstance()->AddTestPartResult(
3704 NULL, // No info about the source file where the exception occurred.
3705 -1, // We have no info on which line caused the exception.
3707 ""); // No stack trace, either.
3710 } // namespace internal
3712 // Google Test requires all tests in the same test case to use the same test
3713 // fixture class. This function checks if the current test has the
3714 // same fixture class as the first test in the current test case. If
3715 // yes, it returns true; otherwise it generates a Google Test failure and
3717 bool Test::HasSameFixtureClass() {
3718 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
3719 const TestCase* const test_case = impl->current_test_case();
3721 // Info about the first test in the current test case.
3722 const TestInfo* const first_test_info = test_case->test_info_list()[0];
3723 const internal::TypeId first_fixture_id = first_test_info->fixture_class_id_;
3724 const char* const first_test_name = first_test_info->name();
3726 // Info about the current test.
3727 const TestInfo* const this_test_info = impl->current_test_info();
3728 const internal::TypeId this_fixture_id = this_test_info->fixture_class_id_;
3729 const char* const this_test_name = this_test_info->name();
3731 if (this_fixture_id != first_fixture_id) {
3732 // Is the first test defined using TEST?
3733 const bool first_is_TEST = first_fixture_id == internal::GetTestTypeId();
3734 // Is this test defined using TEST?
3735 const bool this_is_TEST = this_fixture_id == internal::GetTestTypeId();
3737 if (first_is_TEST || this_is_TEST) {
3738 // Both TEST and TEST_F appear in same test case, which is incorrect.
3739 // Tell the user how to fix this.
3741 // Gets the name of the TEST and the name of the TEST_F. Note
3742 // that first_is_TEST and this_is_TEST cannot both be true, as
3743 // the fixture IDs are different for the two tests.
3744 const char* const TEST_name =
3745 first_is_TEST ? first_test_name : this_test_name;
3746 const char* const TEST_F_name =
3747 first_is_TEST ? this_test_name : first_test_name;
3750 << "All tests in the same test case must use the same test fixture\n"
3751 << "class, so mixing TEST_F and TEST in the same test case is\n"
3752 << "illegal. In test case " << this_test_info->test_case_name()
3754 << "test " << TEST_F_name << " is defined using TEST_F but\n"
3755 << "test " << TEST_name << " is defined using TEST. You probably\n"
3756 << "want to change the TEST to TEST_F or move it to another test\n"
3759 // Two fixture classes with the same name appear in two different
3760 // namespaces, which is not allowed. Tell the user how to fix this.
3762 << "All tests in the same test case must use the same test fixture\n"
3763 << "class. However, in test case "
3764 << this_test_info->test_case_name() << ",\n"
3765 << "you defined test " << first_test_name
3766 << " and test " << this_test_name << "\n"
3767 << "using two different test fixture classes. This can happen if\n"
3768 << "the two classes are from different namespaces or translation\n"
3769 << "units and have the same name. You should probably rename one\n"
3770 << "of the classes to put the tests into different test cases.";
3780 // Adds an "exception thrown" fatal failure to the current test. This
3781 // function returns its result via an output parameter pointer because VC++
3782 // prohibits creation of objects with destructors on stack in functions
3783 // using __try (see error C2712).
3784 static std::string* FormatSehExceptionMessage(DWORD exception_code,
3785 const char* location) {
3787 message << "SEH exception with code 0x" << std::setbase(16) <<
3788 exception_code << std::setbase(10) << " thrown in " << location << ".";
3790 return new std::string(message.GetString());
3793 #endif // GTEST_HAS_SEH
3795 namespace internal {
3797 #if GTEST_HAS_EXCEPTIONS
3799 // Adds an "exception thrown" fatal failure to the current test.
3800 static std::string FormatCxxExceptionMessage(const char* description,
3801 const char* location) {
3803 if (description != NULL) {
3804 message << "C++ exception with description \"" << description << "\"";
3806 message << "Unknown C++ exception";
3808 message << " thrown in " << location << ".";
3810 return message.GetString();
3813 static std::string PrintTestPartResultToString(
3814 const TestPartResult& test_part_result);
3816 GoogleTestFailureException::GoogleTestFailureException(
3817 const TestPartResult& failure)
3818 : ::std::runtime_error(PrintTestPartResultToString(failure).c_str()) {}
3820 #endif // GTEST_HAS_EXCEPTIONS
3822 // We put these helper functions in the internal namespace as IBM's xlC
3823 // compiler rejects the code if they were declared static.
3825 // Runs the given method and handles SEH exceptions it throws, when
3826 // SEH is supported; returns the 0-value for type Result in case of an
3827 // SEH exception. (Microsoft compilers cannot handle SEH and C++
3828 // exceptions in the same function. Therefore, we provide a separate
3829 // wrapper function for handling SEH exceptions.)
3830 template <class T, typename Result>
3831 Result HandleSehExceptionsInMethodIfSupported(
3832 T* object, Result (T::*method)(), const char* location) {
3835 return (object->*method)();
3836 } __except (internal::UnitTestOptions::GTestShouldProcessSEH( // NOLINT
3837 GetExceptionCode())) {
3838 // We create the exception message on the heap because VC++ prohibits
3839 // creation of objects with destructors on stack in functions using __try
3840 // (see error C2712).
3841 std::string* exception_message = FormatSehExceptionMessage(
3842 GetExceptionCode(), location);
3843 internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure,
3844 *exception_message);
3845 delete exception_message;
3846 return static_cast<Result>(0);
3850 return (object->*method)();
3851 #endif // GTEST_HAS_SEH
3854 // Runs the given method and catches and reports C++ and/or SEH-style
3855 // exceptions, if they are supported; returns the 0-value for type
3856 // Result in case of an SEH exception.
3857 template <class T, typename Result>
3858 Result HandleExceptionsInMethodIfSupported(
3859 T* object, Result (T::*method)(), const char* location) {
3860 // NOTE: The user code can affect the way in which Google Test handles
3861 // exceptions by setting GTEST_FLAG(catch_exceptions), but only before
3862 // RUN_ALL_TESTS() starts. It is technically possible to check the flag
3863 // after the exception is caught and either report or re-throw the
3864 // exception based on the flag's value:
3867 // // Perform the test method.
3869 // if (GTEST_FLAG(catch_exceptions))
3870 // // Report the exception as failure.
3872 // throw; // Re-throws the original exception.
3875 // However, the purpose of this flag is to allow the program to drop into
3876 // the debugger when the exception is thrown. On most platforms, once the
3877 // control enters the catch block, the exception origin information is
3878 // lost and the debugger will stop the program at the point of the
3879 // re-throw in this function -- instead of at the point of the original
3880 // throw statement in the code under test. For this reason, we perform
3881 // the check early, sacrificing the ability to affect Google Test's
3882 // exception handling in the method where the exception is thrown.
3883 if (internal::GetUnitTestImpl()->catch_exceptions()) {
3884 #if GTEST_HAS_EXCEPTIONS
3886 return HandleSehExceptionsInMethodIfSupported(object, method, location);
3887 } catch (const internal::GoogleTestFailureException&) { // NOLINT
3888 // This exception type can only be thrown by a failed Google
3889 // Test assertion with the intention of letting another testing
3890 // framework catch it. Therefore we just re-throw it.
3892 } catch (const std::exception& e) { // NOLINT
3893 internal::ReportFailureInUnknownLocation(
3894 TestPartResult::kFatalFailure,
3895 FormatCxxExceptionMessage(e.what(), location));
3896 } catch (...) { // NOLINT
3897 internal::ReportFailureInUnknownLocation(
3898 TestPartResult::kFatalFailure,
3899 FormatCxxExceptionMessage(NULL, location));
3901 return static_cast<Result>(0);
3903 return HandleSehExceptionsInMethodIfSupported(object, method, location);
3904 #endif // GTEST_HAS_EXCEPTIONS
3906 return (object->*method)();
3910 } // namespace internal
3912 // Runs the test and updates the test result.
3914 if (!HasSameFixtureClass()) return;
3916 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
3917 impl->os_stack_trace_getter()->UponLeavingGTest();
3918 internal::HandleExceptionsInMethodIfSupported(this, &Test::SetUp, "SetUp()");
3919 // We will run the test only if SetUp() was successful.
3920 if (!HasFatalFailure()) {
3921 impl->os_stack_trace_getter()->UponLeavingGTest();
3922 internal::HandleExceptionsInMethodIfSupported(
3923 this, &Test::TestBody, "the test body");
3926 // However, we want to clean up as much as possible. Hence we will
3927 // always call TearDown(), even if SetUp() or the test body has
3929 impl->os_stack_trace_getter()->UponLeavingGTest();
3930 internal::HandleExceptionsInMethodIfSupported(
3931 this, &Test::TearDown, "TearDown()");
3934 // Returns true iff the current test has a fatal failure.
3935 bool Test::HasFatalFailure() {
3936 return internal::GetUnitTestImpl()->current_test_result()->HasFatalFailure();
3939 // Returns true iff the current test has a non-fatal failure.
3940 bool Test::HasNonfatalFailure() {
3941 return internal::GetUnitTestImpl()->current_test_result()->
3942 HasNonfatalFailure();
3947 // Constructs a TestInfo object. It assumes ownership of the test factory
3949 TestInfo::TestInfo(const std::string& a_test_case_name,
3950 const std::string& a_name,
3951 const char* a_type_param,
3952 const char* a_value_param,
3953 internal::CodeLocation a_code_location,
3954 internal::TypeId fixture_class_id,
3955 internal::TestFactoryBase* factory)
3956 : test_case_name_(a_test_case_name),
3958 type_param_(a_type_param ? new std::string(a_type_param) : NULL),
3959 value_param_(a_value_param ? new std::string(a_value_param) : NULL),
3960 location_(a_code_location),
3961 fixture_class_id_(fixture_class_id),
3963 is_disabled_(false),
3964 matches_filter_(false),
3968 // Destructs a TestInfo object.
3969 TestInfo::~TestInfo() { delete factory_; }
3971 namespace internal {
3973 // Creates a new TestInfo object and registers it with Google Test;
3974 // returns the created object.
3978 // test_case_name: name of the test case
3979 // name: name of the test
3980 // type_param: the name of the test's type parameter, or NULL if
3981 // this is not a typed or a type-parameterized test.
3982 // value_param: text representation of the test's value parameter,
3983 // or NULL if this is not a value-parameterized test.
3984 // code_location: code location where the test is defined
3985 // fixture_class_id: ID of the test fixture class
3986 // set_up_tc: pointer to the function that sets up the test case
3987 // tear_down_tc: pointer to the function that tears down the test case
3988 // factory: pointer to the factory that creates a test object.
3989 // The newly created TestInfo instance will assume
3990 // ownership of the factory object.
3991 TestInfo* MakeAndRegisterTestInfo(
3992 const char* test_case_name,
3994 const char* type_param,
3995 const char* value_param,
3996 CodeLocation code_location,
3997 TypeId fixture_class_id,
3998 SetUpTestCaseFunc set_up_tc,
3999 TearDownTestCaseFunc tear_down_tc,
4000 TestFactoryBase* factory) {
4001 TestInfo* const test_info =
4002 new TestInfo(test_case_name, name, type_param, value_param,
4003 code_location, fixture_class_id, factory);
4004 GetUnitTestImpl()->AddTestInfo(set_up_tc, tear_down_tc, test_info);
4008 #if GTEST_HAS_PARAM_TEST
4009 void ReportInvalidTestCaseType(const char* test_case_name,
4010 CodeLocation code_location) {
4013 << "Attempted redefinition of test case " << test_case_name << ".\n"
4014 << "All tests in the same test case must use the same test fixture\n"
4015 << "class. However, in test case " << test_case_name << ", you tried\n"
4016 << "to define a test using a fixture class different from the one\n"
4017 << "used earlier. This can happen if the two fixture classes are\n"
4018 << "from different namespaces and have the same name. You should\n"
4019 << "probably rename one of the classes to put the tests into different\n"
4022 fprintf(stderr, "%s %s",
4023 FormatFileLocation(code_location.file.c_str(),
4024 code_location.line).c_str(),
4025 errors.GetString().c_str());
4027 #endif // GTEST_HAS_PARAM_TEST
4029 } // namespace internal
4033 // A predicate that checks the test name of a TestInfo against a known
4036 // This is used for implementation of the TestCase class only. We put
4037 // it in the anonymous namespace to prevent polluting the outer
4040 // TestNameIs is copyable.
4045 // TestNameIs has NO default constructor.
4046 explicit TestNameIs(const char* name)
4049 // Returns true iff the test name of test_info matches name_.
4050 bool operator()(const TestInfo * test_info) const {
4051 return test_info && test_info->name() == name_;
4060 namespace internal {
4062 // This method expands all parameterized tests registered with macros TEST_P
4063 // and INSTANTIATE_TEST_CASE_P into regular tests and registers those.
4064 // This will be done just once during the program runtime.
4065 void UnitTestImpl::RegisterParameterizedTests() {
4066 #if GTEST_HAS_PARAM_TEST
4067 if (!parameterized_tests_registered_) {
4068 parameterized_test_registry_.RegisterTests();
4069 parameterized_tests_registered_ = true;
4074 } // namespace internal
4076 // Creates the test object, runs it, records its result, and then
4078 void TestInfo::Run() {
4079 if (!should_run_) return;
4081 // Tells UnitTest where to store test result.
4082 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
4083 impl->set_current_test_info(this);
4085 TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
4087 // Notifies the unit test event listeners that a test is about to start.
4088 repeater->OnTestStart(*this);
4090 const TimeInMillis start = internal::GetTimeInMillis();
4092 impl->os_stack_trace_getter()->UponLeavingGTest();
4094 // Creates the test object.
4095 Test* const test = internal::HandleExceptionsInMethodIfSupported(
4096 factory_, &internal::TestFactoryBase::CreateTest,
4097 "the test fixture's constructor");
4099 // Runs the test only if the test object was created and its
4100 // constructor didn't generate a fatal failure.
4101 if ((test != NULL) && !Test::HasFatalFailure()) {
4102 // This doesn't throw as all user code that can throw are wrapped into
4103 // exception handling code.
4107 // Deletes the test object.
4108 impl->os_stack_trace_getter()->UponLeavingGTest();
4109 internal::HandleExceptionsInMethodIfSupported(
4110 test, &Test::DeleteSelf_, "the test fixture's destructor");
4112 result_.set_elapsed_time(internal::GetTimeInMillis() - start);
4114 // Notifies the unit test event listener that a test has just finished.
4115 repeater->OnTestEnd(*this);
4117 // Tells UnitTest to stop associating assertion results to this
4119 impl->set_current_test_info(NULL);
4124 // Gets the number of successful tests in this test case.
4125 int TestCase::successful_test_count() const {
4126 return CountIf(test_info_list_, TestPassed);
4129 // Gets the number of failed tests in this test case.
4130 int TestCase::failed_test_count() const {
4131 return CountIf(test_info_list_, TestFailed);
4134 // Gets the number of disabled tests that will be reported in the XML report.
4135 int TestCase::reportable_disabled_test_count() const {
4136 return CountIf(test_info_list_, TestReportableDisabled);
4139 // Gets the number of disabled tests in this test case.
4140 int TestCase::disabled_test_count() const {
4141 return CountIf(test_info_list_, TestDisabled);
4144 // Gets the number of tests to be printed in the XML report.
4145 int TestCase::reportable_test_count() const {
4146 return CountIf(test_info_list_, TestReportable);
4149 // Get the number of tests in this test case that should run.
4150 int TestCase::test_to_run_count() const {
4151 return CountIf(test_info_list_, ShouldRunTest);
4154 // Gets the number of all tests.
4155 int TestCase::total_test_count() const {
4156 return static_cast<int>(test_info_list_.size());
4159 // Creates a TestCase with the given name.
4163 // name: name of the test case
4164 // a_type_param: the name of the test case's type parameter, or NULL if
4165 // this is not a typed or a type-parameterized test case.
4166 // set_up_tc: pointer to the function that sets up the test case
4167 // tear_down_tc: pointer to the function that tears down the test case
4168 TestCase::TestCase(const char* a_name, const char* a_type_param,
4169 Test::SetUpTestCaseFunc set_up_tc,
4170 Test::TearDownTestCaseFunc tear_down_tc)
4172 type_param_(a_type_param ? new std::string(a_type_param) : NULL),
4173 set_up_tc_(set_up_tc),
4174 tear_down_tc_(tear_down_tc),
4179 // Destructor of TestCase.
4180 TestCase::~TestCase() {
4181 // Deletes every Test in the collection.
4182 ForEach(test_info_list_, internal::Delete<TestInfo>);
4185 // Returns the i-th test among all the tests. i can range from 0 to
4186 // total_test_count() - 1. If i is not in that range, returns NULL.
4187 const TestInfo* TestCase::GetTestInfo(int i) const {
4188 const int index = GetElementOr(test_indices_, i, -1);
4189 return index < 0 ? NULL : test_info_list_[index];
4192 // Returns the i-th test among all the tests. i can range from 0 to
4193 // total_test_count() - 1. If i is not in that range, returns NULL.
4194 TestInfo* TestCase::GetMutableTestInfo(int i) {
4195 const int index = GetElementOr(test_indices_, i, -1);
4196 return index < 0 ? NULL : test_info_list_[index];
4199 // Adds a test to this test case. Will delete the test upon
4200 // destruction of the TestCase object.
4201 void TestCase::AddTestInfo(TestInfo * test_info) {
4202 test_info_list_.push_back(test_info);
4203 test_indices_.push_back(static_cast<int>(test_indices_.size()));
4206 // Runs every test in this TestCase.
4207 void TestCase::Run() {
4208 if (!should_run_) return;
4210 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
4211 impl->set_current_test_case(this);
4213 TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
4215 repeater->OnTestCaseStart(*this);
4216 impl->os_stack_trace_getter()->UponLeavingGTest();
4217 internal::HandleExceptionsInMethodIfSupported(
4218 this, &TestCase::RunSetUpTestCase, "SetUpTestCase()");
4220 const internal::TimeInMillis start = internal::GetTimeInMillis();
4221 for (int i = 0; i < total_test_count(); i++) {
4222 GetMutableTestInfo(i)->Run();
4224 elapsed_time_ = internal::GetTimeInMillis() - start;
4226 impl->os_stack_trace_getter()->UponLeavingGTest();
4227 internal::HandleExceptionsInMethodIfSupported(
4228 this, &TestCase::RunTearDownTestCase, "TearDownTestCase()");
4230 repeater->OnTestCaseEnd(*this);
4231 impl->set_current_test_case(NULL);
4234 // Clears the results of all tests in this test case.
4235 void TestCase::ClearResult() {
4236 ad_hoc_test_result_.Clear();
4237 ForEach(test_info_list_, TestInfo::ClearTestResult);
4240 // Shuffles the tests in this test case.
4241 void TestCase::ShuffleTests(internal::Random* random) {
4242 Shuffle(random, &test_indices_);
4245 // Restores the test order to before the first shuffle.
4246 void TestCase::UnshuffleTests() {
4247 for (size_t i = 0; i < test_indices_.size(); i++) {
4248 test_indices_[i] = static_cast<int>(i);
4252 // Formats a countable noun. Depending on its quantity, either the
4253 // singular form or the plural form is used. e.g.
4255 // FormatCountableNoun(1, "formula", "formuli") returns "1 formula".
4256 // FormatCountableNoun(5, "book", "books") returns "5 books".
4257 static std::string FormatCountableNoun(int count,
4258 const char * singular_form,
4259 const char * plural_form) {
4260 return internal::StreamableToString(count) + " " +
4261 (count == 1 ? singular_form : plural_form);
4264 // Formats the count of tests.
4265 static std::string FormatTestCount(int test_count) {
4266 return FormatCountableNoun(test_count, "test", "tests");
4269 // Formats the count of test cases.
4270 static std::string FormatTestCaseCount(int test_case_count) {
4271 return FormatCountableNoun(test_case_count, "test case", "test cases");
4274 // Converts a TestPartResult::Type enum to human-friendly string
4275 // representation. Both kNonFatalFailure and kFatalFailure are translated
4276 // to "Failure", as the user usually doesn't care about the difference
4277 // between the two when viewing the test result.
4278 static const char * TestPartResultTypeToString(TestPartResult::Type type) {
4280 case TestPartResult::kSuccess:
4283 case TestPartResult::kNonFatalFailure:
4284 case TestPartResult::kFatalFailure:
4291 return "Unknown result type";
4295 namespace internal {
4297 // Prints a TestPartResult to an std::string.
4298 static std::string PrintTestPartResultToString(
4299 const TestPartResult& test_part_result) {
4301 << internal::FormatFileLocation(test_part_result.file_name(),
4302 test_part_result.line_number())
4303 << " " << TestPartResultTypeToString(test_part_result.type())
4304 << test_part_result.message()).GetString();
4307 // Prints a TestPartResult.
4308 static void PrintTestPartResult(const TestPartResult& test_part_result) {
4309 const std::string& result =
4310 PrintTestPartResultToString(test_part_result);
4311 printf("%s\n", result.c_str());
4313 // If the test program runs in Visual Studio or a debugger, the
4314 // following statements add the test part result message to the Output
4315 // window such that the user can double-click on it to jump to the
4316 // corresponding source code location; otherwise they do nothing.
4317 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
4318 // We don't call OutputDebugString*() on Windows Mobile, as printing
4319 // to stdout is done by OutputDebugString() there already - we don't
4320 // want the same message printed twice.
4321 ::OutputDebugStringA(result.c_str());
4322 ::OutputDebugStringA("\n");
4326 // class PrettyUnitTestResultPrinter
4335 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && \
4336 !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
4338 // Returns the character attribute for the given color.
4339 WORD GetColorAttribute(GTestColor color) {
4341 case COLOR_RED: return FOREGROUND_RED;
4342 case COLOR_GREEN: return FOREGROUND_GREEN;
4343 case COLOR_YELLOW: return FOREGROUND_RED | FOREGROUND_GREEN;
4350 // Returns the ANSI color code for the given color. COLOR_DEFAULT is
4351 // an invalid input.
4352 const char* GetAnsiColorCode(GTestColor color) {
4354 case COLOR_RED: return "1";
4355 case COLOR_GREEN: return "2";
4356 case COLOR_YELLOW: return "3";
4357 default: return NULL;
4361 #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
4363 // Returns true iff Google Test should use colors in the output.
4364 bool ShouldUseColor(bool stdout_is_tty) {
4365 const char* const gtest_color = GTEST_FLAG(color).c_str();
4367 if (String::CaseInsensitiveCStringEquals(gtest_color, "auto")) {
4368 #if GTEST_OS_WINDOWS
4369 // On Windows the TERM variable is usually not set, but the
4370 // console there does support colors.
4371 return stdout_is_tty;
4373 // On non-Windows platforms, we rely on the TERM variable.
4374 const char* const term = posix::GetEnv("TERM");
4375 const bool term_supports_color =
4376 String::CStringEquals(term, "xterm") ||
4377 String::CStringEquals(term, "xterm-color") ||
4378 String::CStringEquals(term, "xterm-256color") ||
4379 String::CStringEquals(term, "screen") ||
4380 String::CStringEquals(term, "screen-256color") ||
4381 String::CStringEquals(term, "tmux") ||
4382 String::CStringEquals(term, "tmux-256color") ||
4383 String::CStringEquals(term, "rxvt-unicode") ||
4384 String::CStringEquals(term, "rxvt-unicode-256color") ||
4385 String::CStringEquals(term, "linux") ||
4386 String::CStringEquals(term, "cygwin");
4387 return stdout_is_tty && term_supports_color;
4388 #endif // GTEST_OS_WINDOWS
4391 return String::CaseInsensitiveCStringEquals(gtest_color, "yes") ||
4392 String::CaseInsensitiveCStringEquals(gtest_color, "true") ||
4393 String::CaseInsensitiveCStringEquals(gtest_color, "t") ||
4394 String::CStringEquals(gtest_color, "1");
4395 // We take "yes", "true", "t", and "1" as meaning "yes". If the
4396 // value is neither one of these nor "auto", we treat it as "no" to
4400 // Helpers for printing colored strings to stdout. Note that on Windows, we
4401 // cannot simply emit special characters and have the terminal change colors.
4402 // This routine must actually emit the characters rather than return a string
4403 // that would be colored when printed, as can be done on Linux.
4404 void ColoredPrintf(GTestColor color, const char* fmt, ...) {
4406 va_start(args, fmt);
4408 #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS || \
4409 GTEST_OS_IOS || GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT
4410 const bool use_color = AlwaysFalse();
4412 static const bool in_color_mode =
4413 ShouldUseColor(posix::IsATTY(posix::FileNo(stdout)) != 0);
4414 const bool use_color = in_color_mode && (color != COLOR_DEFAULT);
4415 #endif // GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS
4416 // The '!= 0' comparison is necessary to satisfy MSVC 7.1.
4424 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && \
4425 !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
4426 const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
4428 // Gets the current text color.
4429 CONSOLE_SCREEN_BUFFER_INFO buffer_info;
4430 GetConsoleScreenBufferInfo(stdout_handle, &buffer_info);
4431 const WORD old_color_attrs = buffer_info.wAttributes;
4433 // We need to flush the stream buffers into the console before each
4434 // SetConsoleTextAttribute call lest it affect the text that is already
4435 // printed but has not yet reached the console.
4437 SetConsoleTextAttribute(stdout_handle,
4438 GetColorAttribute(color) | FOREGROUND_INTENSITY);
4442 // Restores the text color.
4443 SetConsoleTextAttribute(stdout_handle, old_color_attrs);
4445 printf("\033[0;3%sm", GetAnsiColorCode(color));
4447 printf("\033[m"); // Resets the terminal to default.
4448 #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
4452 // Text printed in Google Test's text output and --gunit_list_tests
4453 // output to label the type parameter and value parameter for a test.
4454 static const char kTypeParamLabel[] = "TypeParam";
4455 static const char kValueParamLabel[] = "GetParam()";
4457 void PrintFullTestCommentIfPresent(const TestInfo& test_info) {
4458 const char* const type_param = test_info.type_param();
4459 const char* const value_param = test_info.value_param();
4461 if (type_param != NULL || value_param != NULL) {
4463 if (type_param != NULL) {
4464 printf("%s = %s", kTypeParamLabel, type_param);
4465 if (value_param != NULL)
4468 if (value_param != NULL) {
4469 printf("%s = %s", kValueParamLabel, value_param);
4474 // This class implements the TestEventListener interface.
4476 // Class PrettyUnitTestResultPrinter is copyable.
4477 class PrettyUnitTestResultPrinter : public TestEventListener {
4479 PrettyUnitTestResultPrinter() {}
4480 static void PrintTestName(const char * test_case, const char * test) {
4481 printf("%s.%s", test_case, test);
4484 // The following methods override what's in the TestEventListener class.
4485 virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {}
4486 virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration);
4487 virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test);
4488 virtual void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) {}
4489 virtual void OnTestCaseStart(const TestCase& test_case);
4490 virtual void OnTestStart(const TestInfo& test_info);
4491 virtual void OnTestPartResult(const TestPartResult& result);
4492 virtual void OnTestEnd(const TestInfo& test_info);
4493 virtual void OnTestCaseEnd(const TestCase& test_case);
4494 virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test);
4495 virtual void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) {}
4496 virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
4497 virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) {}
4500 static void PrintFailedTests(const UnitTest& unit_test);
4503 // Fired before each iteration of tests starts.
4504 void PrettyUnitTestResultPrinter::OnTestIterationStart(
4505 const UnitTest& unit_test, int iteration) {
4506 if (GTEST_FLAG(repeat) != 1)
4507 printf("\nRepeating all tests (iteration %d) . . .\n\n", iteration + 1);
4509 const char* const filter = GTEST_FLAG(filter).c_str();
4511 // Prints the filter if it's not *. This reminds the user that some
4512 // tests may be skipped.
4513 if (!String::CStringEquals(filter, kUniversalFilter)) {
4514 ColoredPrintf(COLOR_YELLOW,
4515 "Note: %s filter = %s\n", GTEST_NAME_, filter);
4518 if (internal::ShouldShard(kTestTotalShards, kTestShardIndex, false)) {
4519 const Int32 shard_index = Int32FromEnvOrDie(kTestShardIndex, -1);
4520 ColoredPrintf(COLOR_YELLOW,
4521 "Note: This is test shard %d of %s.\n",
4522 static_cast<int>(shard_index) + 1,
4523 internal::posix::GetEnv(kTestTotalShards));
4526 if (GTEST_FLAG(shuffle)) {
4527 ColoredPrintf(COLOR_YELLOW,
4528 "Note: Randomizing tests' orders with a seed of %d .\n",
4529 unit_test.random_seed());
4532 ColoredPrintf(COLOR_GREEN, "[==========] ");
4533 printf("Running %s from %s.\n",
4534 FormatTestCount(unit_test.test_to_run_count()).c_str(),
4535 FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str());
4539 void PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart(
4540 const UnitTest& /*unit_test*/) {
4541 ColoredPrintf(COLOR_GREEN, "[----------] ");
4542 printf("Global test environment set-up.\n");
4546 void PrettyUnitTestResultPrinter::OnTestCaseStart(const TestCase& test_case) {
4547 const std::string counts =
4548 FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
4549 ColoredPrintf(COLOR_GREEN, "[----------] ");
4550 printf("%s from %s", counts.c_str(), test_case.name());
4551 if (test_case.type_param() == NULL) {
4554 printf(", where %s = %s\n", kTypeParamLabel, test_case.type_param());
4559 void PrettyUnitTestResultPrinter::OnTestStart(const TestInfo& test_info) {
4560 ColoredPrintf(COLOR_GREEN, "[ RUN ] ");
4561 PrintTestName(test_info.test_case_name(), test_info.name());
4566 // Called after an assertion failure.
4567 void PrettyUnitTestResultPrinter::OnTestPartResult(
4568 const TestPartResult& result) {
4569 // If the test part succeeded, we don't need to do anything.
4570 if (result.type() == TestPartResult::kSuccess)
4573 // Print failure message from the assertion (e.g. expected this and got that).
4574 PrintTestPartResult(result);
4578 void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) {
4579 if (test_info.result()->Passed()) {
4580 ColoredPrintf(COLOR_GREEN, "[ OK ] ");
4582 ColoredPrintf(COLOR_RED, "[ FAILED ] ");
4584 PrintTestName(test_info.test_case_name(), test_info.name());
4585 if (test_info.result()->Failed())
4586 PrintFullTestCommentIfPresent(test_info);
4588 if (GTEST_FLAG(print_time)) {
4589 printf(" (%s ms)\n", internal::StreamableToString(
4590 test_info.result()->elapsed_time()).c_str());
4597 void PrettyUnitTestResultPrinter::OnTestCaseEnd(const TestCase& test_case) {
4598 if (!GTEST_FLAG(print_time)) return;
4600 const std::string counts =
4601 FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
4602 ColoredPrintf(COLOR_GREEN, "[----------] ");
4603 printf("%s from %s (%s ms total)\n\n",
4604 counts.c_str(), test_case.name(),
4605 internal::StreamableToString(test_case.elapsed_time()).c_str());
4609 void PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart(
4610 const UnitTest& /*unit_test*/) {
4611 ColoredPrintf(COLOR_GREEN, "[----------] ");
4612 printf("Global test environment tear-down\n");
4616 // Internal helper for printing the list of failed tests.
4617 void PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest& unit_test) {
4618 const int failed_test_count = unit_test.failed_test_count();
4619 if (failed_test_count == 0) {
4623 for (int i = 0; i < unit_test.total_test_case_count(); ++i) {
4624 const TestCase& test_case = *unit_test.GetTestCase(i);
4625 if (!test_case.should_run() || (test_case.failed_test_count() == 0)) {
4628 for (int j = 0; j < test_case.total_test_count(); ++j) {
4629 const TestInfo& test_info = *test_case.GetTestInfo(j);
4630 if (!test_info.should_run() || test_info.result()->Passed()) {
4633 ColoredPrintf(COLOR_RED, "[ FAILED ] ");
4634 printf("%s.%s", test_case.name(), test_info.name());
4635 PrintFullTestCommentIfPresent(test_info);
4641 void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
4642 int /*iteration*/) {
4643 ColoredPrintf(COLOR_GREEN, "[==========] ");
4644 printf("%s from %s ran.",
4645 FormatTestCount(unit_test.test_to_run_count()).c_str(),
4646 FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str());
4647 if (GTEST_FLAG(print_time)) {
4648 printf(" (%s ms total)",
4649 internal::StreamableToString(unit_test.elapsed_time()).c_str());
4652 ColoredPrintf(COLOR_GREEN, "[ PASSED ] ");
4653 printf("%s.\n", FormatTestCount(unit_test.successful_test_count()).c_str());
4655 int num_failures = unit_test.failed_test_count();
4656 if (!unit_test.Passed()) {
4657 const int failed_test_count = unit_test.failed_test_count();
4658 ColoredPrintf(COLOR_RED, "[ FAILED ] ");
4659 printf("%s, listed below:\n", FormatTestCount(failed_test_count).c_str());
4660 PrintFailedTests(unit_test);
4661 printf("\n%2d FAILED %s\n", num_failures,
4662 num_failures == 1 ? "TEST" : "TESTS");
4665 int num_disabled = unit_test.reportable_disabled_test_count();
4666 if (num_disabled && !GTEST_FLAG(also_run_disabled_tests)) {
4667 if (!num_failures) {
4668 printf("\n"); // Add a spacer if no FAILURE banner is displayed.
4670 ColoredPrintf(COLOR_YELLOW,
4671 " YOU HAVE %d DISABLED %s\n\n",
4673 num_disabled == 1 ? "TEST" : "TESTS");
4675 // Ensure that Google Test output is printed before, e.g., heapchecker output.
4679 // End PrettyUnitTestResultPrinter
4681 // class TestEventRepeater
4683 // This class forwards events to other event listeners.
4684 class TestEventRepeater : public TestEventListener {
4686 TestEventRepeater() : forwarding_enabled_(true) {}
4687 virtual ~TestEventRepeater();
4688 void Append(TestEventListener *listener);
4689 TestEventListener* Release(TestEventListener* listener);
4691 // Controls whether events will be forwarded to listeners_. Set to false
4692 // in death test child processes.
4693 bool forwarding_enabled() const { return forwarding_enabled_; }
4694 void set_forwarding_enabled(bool enable) { forwarding_enabled_ = enable; }
4696 virtual void OnTestProgramStart(const UnitTest& unit_test);
4697 virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration);
4698 virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test);
4699 virtual void OnEnvironmentsSetUpEnd(const UnitTest& unit_test);
4700 virtual void OnTestCaseStart(const TestCase& test_case);
4701 virtual void OnTestStart(const TestInfo& test_info);
4702 virtual void OnTestPartResult(const TestPartResult& result);
4703 virtual void OnTestEnd(const TestInfo& test_info);
4704 virtual void OnTestCaseEnd(const TestCase& test_case);
4705 virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test);
4706 virtual void OnEnvironmentsTearDownEnd(const UnitTest& unit_test);
4707 virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
4708 virtual void OnTestProgramEnd(const UnitTest& unit_test);
4711 // Controls whether events will be forwarded to listeners_. Set to false
4712 // in death test child processes.
4713 bool forwarding_enabled_;
4714 // The list of listeners that receive events.
4715 std::vector<TestEventListener*> listeners_;
4717 GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventRepeater);
4720 TestEventRepeater::~TestEventRepeater() {
4721 ForEach(listeners_, Delete<TestEventListener>);
4724 void TestEventRepeater::Append(TestEventListener *listener) {
4725 listeners_.push_back(listener);
4728 // TODO(vladl@google.com): Factor the search functionality into Vector::Find.
4729 TestEventListener* TestEventRepeater::Release(TestEventListener *listener) {
4730 for (size_t i = 0; i < listeners_.size(); ++i) {
4731 if (listeners_[i] == listener) {
4732 listeners_.erase(listeners_.begin() + i);
4740 // Since most methods are very similar, use macros to reduce boilerplate.
4741 // This defines a member that forwards the call to all listeners.
4742 #define GTEST_REPEATER_METHOD_(Name, Type) \
4743 void TestEventRepeater::Name(const Type& parameter) { \
4744 if (forwarding_enabled_) { \
4745 for (size_t i = 0; i < listeners_.size(); i++) { \
4746 listeners_[i]->Name(parameter); \
4750 // This defines a member that forwards the call to all listeners in reverse
4752 #define GTEST_REVERSE_REPEATER_METHOD_(Name, Type) \
4753 void TestEventRepeater::Name(const Type& parameter) { \
4754 if (forwarding_enabled_) { \
4755 for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) { \
4756 listeners_[i]->Name(parameter); \
4761 GTEST_REPEATER_METHOD_(OnTestProgramStart, UnitTest)
4762 GTEST_REPEATER_METHOD_(OnEnvironmentsSetUpStart, UnitTest)
4763 GTEST_REPEATER_METHOD_(OnTestCaseStart, TestCase)
4764 GTEST_REPEATER_METHOD_(OnTestStart, TestInfo)
4765 GTEST_REPEATER_METHOD_(OnTestPartResult, TestPartResult)
4766 GTEST_REPEATER_METHOD_(OnEnvironmentsTearDownStart, UnitTest)
4767 GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsSetUpEnd, UnitTest)
4768 GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsTearDownEnd, UnitTest)
4769 GTEST_REVERSE_REPEATER_METHOD_(OnTestEnd, TestInfo)
4770 GTEST_REVERSE_REPEATER_METHOD_(OnTestCaseEnd, TestCase)
4771 GTEST_REVERSE_REPEATER_METHOD_(OnTestProgramEnd, UnitTest)
4773 #undef GTEST_REPEATER_METHOD_
4774 #undef GTEST_REVERSE_REPEATER_METHOD_
4776 void TestEventRepeater::OnTestIterationStart(const UnitTest& unit_test,
4778 if (forwarding_enabled_) {
4779 for (size_t i = 0; i < listeners_.size(); i++) {
4780 listeners_[i]->OnTestIterationStart(unit_test, iteration);
4785 void TestEventRepeater::OnTestIterationEnd(const UnitTest& unit_test,
4787 if (forwarding_enabled_) {
4788 for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) {
4789 listeners_[i]->OnTestIterationEnd(unit_test, iteration);
4794 // End TestEventRepeater
4796 // This class generates an XML output file.
4797 class XmlUnitTestResultPrinter : public EmptyTestEventListener {
4799 explicit XmlUnitTestResultPrinter(const char* output_file);
4801 virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
4804 // Is c a whitespace character that is normalized to a space character
4805 // when it appears in an XML attribute value?
4806 static bool IsNormalizableWhitespace(char c) {
4807 return c == 0x9 || c == 0xA || c == 0xD;
4810 // May c appear in a well-formed XML document?
4811 static bool IsValidXmlCharacter(char c) {
4812 return IsNormalizableWhitespace(c) || c >= 0x20;
4815 // Returns an XML-escaped copy of the input string str. If
4816 // is_attribute is true, the text is meant to appear as an attribute
4817 // value, and normalizable whitespace is preserved by replacing it
4818 // with character references.
4819 static std::string EscapeXml(const std::string& str, bool is_attribute);
4821 // Returns the given string with all characters invalid in XML removed.
4822 static std::string RemoveInvalidXmlCharacters(const std::string& str);
4824 // Convenience wrapper around EscapeXml when str is an attribute value.
4825 static std::string EscapeXmlAttribute(const std::string& str) {
4826 return EscapeXml(str, true);
4829 // Convenience wrapper around EscapeXml when str is not an attribute value.
4830 static std::string EscapeXmlText(const char* str) {
4831 return EscapeXml(str, false);
4834 // Verifies that the given attribute belongs to the given element and
4835 // streams the attribute as XML.
4836 static void OutputXmlAttribute(std::ostream* stream,
4837 const std::string& element_name,
4838 const std::string& name,
4839 const std::string& value);
4841 // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
4842 static void OutputXmlCDataSection(::std::ostream* stream, const char* data);
4844 // Streams an XML representation of a TestInfo object.
4845 static void OutputXmlTestInfo(::std::ostream* stream,
4846 const char* test_case_name,
4847 const TestInfo& test_info);
4849 // Prints an XML representation of a TestCase object
4850 static void PrintXmlTestCase(::std::ostream* stream,
4851 const TestCase& test_case);
4853 // Prints an XML summary of unit_test to output stream out.
4854 static void PrintXmlUnitTest(::std::ostream* stream,
4855 const UnitTest& unit_test);
4857 // Produces a string representing the test properties in a result as space
4858 // delimited XML attributes based on the property key="value" pairs.
4859 // When the std::string is not empty, it includes a space at the beginning,
4860 // to delimit this attribute from prior attributes.
4861 static std::string TestPropertiesAsXmlAttributes(const TestResult& result);
4864 const std::string output_file_;
4866 GTEST_DISALLOW_COPY_AND_ASSIGN_(XmlUnitTestResultPrinter);
4869 // Creates a new XmlUnitTestResultPrinter.
4870 XmlUnitTestResultPrinter::XmlUnitTestResultPrinter(const char* output_file)
4871 : output_file_(output_file) {
4872 if (output_file_.c_str() == NULL || output_file_.empty()) {
4873 fprintf(stderr, "XML output file may not be null\n");
4879 // Called after the unit test ends.
4880 void XmlUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
4881 int /*iteration*/) {
4882 FILE* xmlout = NULL;
4883 FilePath output_file(output_file_);
4884 FilePath output_dir(output_file.RemoveFileName());
4886 if (output_dir.CreateDirectoriesRecursively()) {
4887 xmlout = posix::FOpen(output_file_.c_str(), "w");
4889 if (xmlout == NULL) {
4890 // TODO(wan): report the reason of the failure.
4892 // We don't do it for now as:
4894 // 1. There is no urgent need for it.
4895 // 2. It's a bit involved to make the errno variable thread-safe on
4896 // all three operating systems (Linux, Windows, and Mac OS).
4897 // 3. To interpret the meaning of errno in a thread-safe way,
4898 // we need the strerror_r() function, which is not available on
4901 "Unable to open file \"%s\"\n",
4902 output_file_.c_str());
4906 std::stringstream stream;
4907 PrintXmlUnitTest(&stream, unit_test);
4908 fprintf(xmlout, "%s", StringStreamToString(&stream).c_str());
4912 // Returns an XML-escaped copy of the input string str. If is_attribute
4913 // is true, the text is meant to appear as an attribute value, and
4914 // normalizable whitespace is preserved by replacing it with character
4917 // Invalid XML characters in str, if any, are stripped from the output.
4918 // It is expected that most, if not all, of the text processed by this
4919 // module will consist of ordinary English text.
4920 // If this module is ever modified to produce version 1.1 XML output,
4921 // most invalid characters can be retained using character references.
4922 // TODO(wan): It might be nice to have a minimally invasive, human-readable
4923 // escaping scheme for invalid characters, rather than dropping them.
4924 std::string XmlUnitTestResultPrinter::EscapeXml(
4925 const std::string& str, bool is_attribute) {
4928 for (size_t i = 0; i < str.size(); ++i) {
4929 const char ch = str[i];
4953 if (IsValidXmlCharacter(ch)) {
4954 if (is_attribute && IsNormalizableWhitespace(ch))
4955 m << "&#x" << String::FormatByte(static_cast<unsigned char>(ch))
4964 return m.GetString();
4967 // Returns the given string with all characters invalid in XML removed.
4968 // Currently invalid characters are dropped from the string. An
4969 // alternative is to replace them with certain characters such as . or ?.
4970 std::string XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters(
4971 const std::string& str) {
4973 output.reserve(str.size());
4974 for (std::string::const_iterator it = str.begin(); it != str.end(); ++it)
4975 if (IsValidXmlCharacter(*it))
4976 output.push_back(*it);
4981 // The following routines generate an XML representation of a UnitTest
4984 // This is how Google Test concepts map to the DTD:
4986 // <testsuites name="AllTests"> <-- corresponds to a UnitTest object
4987 // <testsuite name="testcase-name"> <-- corresponds to a TestCase object
4988 // <testcase name="test-name"> <-- corresponds to a TestInfo object
4989 // <failure message="...">...</failure>
4990 // <failure message="...">...</failure>
4991 // <failure message="...">...</failure>
4992 // <-- individual assertion failures
4997 // Formats the given time in milliseconds as seconds.
4998 std::string FormatTimeInMillisAsSeconds(TimeInMillis ms) {
4999 ::std::stringstream ss;
5000 ss << (static_cast<double>(ms) * 1e-3);
5004 static bool PortableLocaltime(time_t seconds, struct tm* out) {
5005 #if defined(_MSC_VER)
5006 return localtime_s(out, &seconds) == 0;
5007 #elif defined(__MINGW32__) || defined(__MINGW64__)
5008 // MINGW <time.h> provides neither localtime_r nor localtime_s, but uses
5009 // Windows' localtime(), which has a thread-local tm buffer.
5010 struct tm* tm_ptr = localtime(&seconds); // NOLINT
5016 return localtime_r(&seconds, out) != NULL;
5020 // Converts the given epoch time in milliseconds to a date string in the ISO
5021 // 8601 format, without the timezone information.
5022 std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms) {
5023 struct tm time_struct;
5024 if (!PortableLocaltime(static_cast<time_t>(ms / 1000), &time_struct))
5026 // YYYY-MM-DDThh:mm:ss
5027 return StreamableToString(time_struct.tm_year + 1900) + "-" +
5028 String::FormatIntWidth2(time_struct.tm_mon + 1) + "-" +
5029 String::FormatIntWidth2(time_struct.tm_mday) + "T" +
5030 String::FormatIntWidth2(time_struct.tm_hour) + ":" +
5031 String::FormatIntWidth2(time_struct.tm_min) + ":" +
5032 String::FormatIntWidth2(time_struct.tm_sec);
5035 // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
5036 void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream,
5038 const char* segment = data;
5039 *stream << "<![CDATA[";
5041 const char* const next_segment = strstr(segment, "]]>");
5042 if (next_segment != NULL) {
5044 segment, static_cast<std::streamsize>(next_segment - segment));
5045 *stream << "]]>]]><![CDATA[";
5046 segment = next_segment + strlen("]]>");
5055 void XmlUnitTestResultPrinter::OutputXmlAttribute(
5056 std::ostream* stream,
5057 const std::string& element_name,
5058 const std::string& name,
5059 const std::string& value) {
5060 const std::vector<std::string>& allowed_names =
5061 GetReservedAttributesForElement(element_name);
5063 GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
5064 allowed_names.end())
5065 << "Attribute " << name << " is not allowed for element <" << element_name
5068 *stream << " " << name << "=\"" << EscapeXmlAttribute(value) << "\"";
5071 // Prints an XML representation of a TestInfo object.
5072 // TODO(wan): There is also value in printing properties with the plain printer.
5073 void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream,
5074 const char* test_case_name,
5075 const TestInfo& test_info) {
5076 const TestResult& result = *test_info.result();
5077 const std::string kTestcase = "testcase";
5079 *stream << " <testcase";
5080 OutputXmlAttribute(stream, kTestcase, "name", test_info.name());
5082 if (test_info.value_param() != NULL) {
5083 OutputXmlAttribute(stream, kTestcase, "value_param",
5084 test_info.value_param());
5086 if (test_info.type_param() != NULL) {
5087 OutputXmlAttribute(stream, kTestcase, "type_param", test_info.type_param());
5090 OutputXmlAttribute(stream, kTestcase, "status",
5091 test_info.should_run() ? "run" : "notrun");
5092 OutputXmlAttribute(stream, kTestcase, "time",
5093 FormatTimeInMillisAsSeconds(result.elapsed_time()));
5094 OutputXmlAttribute(stream, kTestcase, "classname", test_case_name);
5095 *stream << TestPropertiesAsXmlAttributes(result);
5098 for (int i = 0; i < result.total_part_count(); ++i) {
5099 const TestPartResult& part = result.GetTestPartResult(i);
5100 if (part.failed()) {
5101 if (++failures == 1) {
5104 const string location = internal::FormatCompilerIndependentFileLocation(
5105 part.file_name(), part.line_number());
5106 const string summary = location + "\n" + part.summary();
5107 *stream << " <failure message=\""
5108 << EscapeXmlAttribute(summary.c_str())
5110 const string detail = location + "\n" + part.message();
5111 OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str());
5112 *stream << "</failure>\n";
5119 *stream << " </testcase>\n";
5122 // Prints an XML representation of a TestCase object
5123 void XmlUnitTestResultPrinter::PrintXmlTestCase(std::ostream* stream,
5124 const TestCase& test_case) {
5125 const std::string kTestsuite = "testsuite";
5126 *stream << " <" << kTestsuite;
5127 OutputXmlAttribute(stream, kTestsuite, "name", test_case.name());
5128 OutputXmlAttribute(stream, kTestsuite, "tests",
5129 StreamableToString(test_case.reportable_test_count()));
5130 OutputXmlAttribute(stream, kTestsuite, "failures",
5131 StreamableToString(test_case.failed_test_count()));
5133 stream, kTestsuite, "disabled",
5134 StreamableToString(test_case.reportable_disabled_test_count()));
5135 OutputXmlAttribute(stream, kTestsuite, "errors", "0");
5136 OutputXmlAttribute(stream, kTestsuite, "time",
5137 FormatTimeInMillisAsSeconds(test_case.elapsed_time()));
5138 *stream << TestPropertiesAsXmlAttributes(test_case.ad_hoc_test_result())
5141 for (int i = 0; i < test_case.total_test_count(); ++i) {
5142 if (test_case.GetTestInfo(i)->is_reportable())
5143 OutputXmlTestInfo(stream, test_case.name(), *test_case.GetTestInfo(i));
5145 *stream << " </" << kTestsuite << ">\n";
5148 // Prints an XML summary of unit_test to output stream out.
5149 void XmlUnitTestResultPrinter::PrintXmlUnitTest(std::ostream* stream,
5150 const UnitTest& unit_test) {
5151 const std::string kTestsuites = "testsuites";
5153 *stream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
5154 *stream << "<" << kTestsuites;
5156 OutputXmlAttribute(stream, kTestsuites, "tests",
5157 StreamableToString(unit_test.reportable_test_count()));
5158 OutputXmlAttribute(stream, kTestsuites, "failures",
5159 StreamableToString(unit_test.failed_test_count()));
5161 stream, kTestsuites, "disabled",
5162 StreamableToString(unit_test.reportable_disabled_test_count()));
5163 OutputXmlAttribute(stream, kTestsuites, "errors", "0");
5165 stream, kTestsuites, "timestamp",
5166 FormatEpochTimeInMillisAsIso8601(unit_test.start_timestamp()));
5167 OutputXmlAttribute(stream, kTestsuites, "time",
5168 FormatTimeInMillisAsSeconds(unit_test.elapsed_time()));
5170 if (GTEST_FLAG(shuffle)) {
5171 OutputXmlAttribute(stream, kTestsuites, "random_seed",
5172 StreamableToString(unit_test.random_seed()));
5175 *stream << TestPropertiesAsXmlAttributes(unit_test.ad_hoc_test_result());
5177 OutputXmlAttribute(stream, kTestsuites, "name", "AllTests");
5180 for (int i = 0; i < unit_test.total_test_case_count(); ++i) {
5181 if (unit_test.GetTestCase(i)->reportable_test_count() > 0)
5182 PrintXmlTestCase(stream, *unit_test.GetTestCase(i));
5184 *stream << "</" << kTestsuites << ">\n";
5187 // Produces a string representing the test properties in a result as space
5188 // delimited XML attributes based on the property key="value" pairs.
5189 std::string XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes(
5190 const TestResult& result) {
5192 for (int i = 0; i < result.test_property_count(); ++i) {
5193 const TestProperty& property = result.GetTestProperty(i);
5194 attributes << " " << property.key() << "="
5195 << "\"" << EscapeXmlAttribute(property.value()) << "\"";
5197 return attributes.GetString();
5200 // End XmlUnitTestResultPrinter
5202 #if GTEST_CAN_STREAM_RESULTS_
5204 // Checks if str contains '=', '&', '%' or '\n' characters. If yes,
5205 // replaces them by "%xx" where xx is their hexadecimal value. For
5206 // example, replaces "=" with "%3D". This algorithm is O(strlen(str))
5207 // in both time and space -- important as the input str may contain an
5208 // arbitrarily long test failure message and stack trace.
5209 string StreamingListener::UrlEncode(const char* str) {
5211 result.reserve(strlen(str) + 1);
5212 for (char ch = *str; ch != '\0'; ch = *++str) {
5218 result.append("%" + String::FormatByte(static_cast<unsigned char>(ch)));
5221 result.push_back(ch);
5228 void StreamingListener::SocketWriter::MakeConnection() {
5229 GTEST_CHECK_(sockfd_ == -1)
5230 << "MakeConnection() can't be called when there is already a connection.";
5233 memset(&hints, 0, sizeof(hints));
5234 hints.ai_family = AF_UNSPEC; // To allow both IPv4 and IPv6 addresses.
5235 hints.ai_socktype = SOCK_STREAM;
5236 addrinfo* servinfo = NULL;
5238 // Use the getaddrinfo() to get a linked list of IP addresses for
5239 // the given host name.
5240 const int error_num = getaddrinfo(
5241 host_name_.c_str(), port_num_.c_str(), &hints, &servinfo);
5242 if (error_num != 0) {
5243 GTEST_LOG_(WARNING) << "stream_result_to: getaddrinfo() failed: "
5244 << gai_strerror(error_num);
5247 // Loop through all the results and connect to the first we can.
5248 for (addrinfo* cur_addr = servinfo; sockfd_ == -1 && cur_addr != NULL;
5249 cur_addr = cur_addr->ai_next) {
5251 cur_addr->ai_family, cur_addr->ai_socktype, cur_addr->ai_protocol);
5252 if (sockfd_ != -1) {
5253 // Connect the client socket to the server socket.
5254 if (connect(sockfd_, cur_addr->ai_addr, cur_addr->ai_addrlen) == -1) {
5261 freeaddrinfo(servinfo); // all done with this structure
5263 if (sockfd_ == -1) {
5264 GTEST_LOG_(WARNING) << "stream_result_to: failed to connect to "
5265 << host_name_ << ":" << port_num_;
5269 // End of class Streaming Listener
5270 #endif // GTEST_CAN_STREAM_RESULTS__
5272 // Class ScopedTrace
5274 // Pushes the given source file location and message onto a per-thread
5275 // trace stack maintained by Google Test.
5276 ScopedTrace::ScopedTrace(const char* file, int line, const Message& message)
5277 GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) {
5281 trace.message = message.GetString();
5283 UnitTest::GetInstance()->PushGTestTrace(trace);
5286 // Pops the info pushed by the c'tor.
5287 ScopedTrace::~ScopedTrace()
5288 GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) {
5289 UnitTest::GetInstance()->PopGTestTrace();
5293 // class OsStackTraceGetter
5295 const char* const OsStackTraceGetterInterface::kElidedFramesMarker =
5296 "... " GTEST_NAME_ " internal frames ...";
5298 string OsStackTraceGetter::CurrentStackTrace(int /*max_depth*/,
5299 int /*skip_count*/) {
5303 void OsStackTraceGetter::UponLeavingGTest() {}
5305 // A helper class that creates the premature-exit file in its
5306 // constructor and deletes the file in its destructor.
5307 class ScopedPrematureExitFile {
5309 explicit ScopedPrematureExitFile(const char* premature_exit_filepath)
5310 : premature_exit_filepath_(premature_exit_filepath) {
5311 // If a path to the premature-exit file is specified...
5312 if (premature_exit_filepath != NULL && *premature_exit_filepath != '\0') {
5313 // create the file with a single "0" character in it. I/O
5314 // errors are ignored as there's nothing better we can do and we
5315 // don't want to fail the test because of this.
5316 FILE* pfile = posix::FOpen(premature_exit_filepath, "w");
5317 fwrite("0", 1, 1, pfile);
5322 ~ScopedPrematureExitFile() {
5323 if (premature_exit_filepath_ != NULL && *premature_exit_filepath_ != '\0') {
5324 remove(premature_exit_filepath_);
5329 const char* const premature_exit_filepath_;
5331 GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedPrematureExitFile);
5334 } // namespace internal
5336 // class TestEventListeners
5338 TestEventListeners::TestEventListeners()
5339 : repeater_(new internal::TestEventRepeater()),
5340 default_result_printer_(NULL),
5341 default_xml_generator_(NULL) {
5344 TestEventListeners::~TestEventListeners() { delete repeater_; }
5346 // Returns the standard listener responsible for the default console
5347 // output. Can be removed from the listeners list to shut down default
5348 // console output. Note that removing this object from the listener list
5349 // with Release transfers its ownership to the user.
5350 void TestEventListeners::Append(TestEventListener* listener) {
5351 repeater_->Append(listener);
5354 // Removes the given event listener from the list and returns it. It then
5355 // becomes the caller's responsibility to delete the listener. Returns
5356 // NULL if the listener is not found in the list.
5357 TestEventListener* TestEventListeners::Release(TestEventListener* listener) {
5358 if (listener == default_result_printer_)
5359 default_result_printer_ = NULL;
5360 else if (listener == default_xml_generator_)
5361 default_xml_generator_ = NULL;
5362 return repeater_->Release(listener);
5365 // Returns repeater that broadcasts the TestEventListener events to all
5367 TestEventListener* TestEventListeners::repeater() { return repeater_; }
5369 // Sets the default_result_printer attribute to the provided listener.
5370 // The listener is also added to the listener list and previous
5371 // default_result_printer is removed from it and deleted. The listener can
5372 // also be NULL in which case it will not be added to the list. Does
5373 // nothing if the previous and the current listener objects are the same.
5374 void TestEventListeners::SetDefaultResultPrinter(TestEventListener* listener) {
5375 if (default_result_printer_ != listener) {
5376 // It is an error to pass this method a listener that is already in the
5378 delete Release(default_result_printer_);
5379 default_result_printer_ = listener;
5380 if (listener != NULL)
5385 // Sets the default_xml_generator attribute to the provided listener. The
5386 // listener is also added to the listener list and previous
5387 // default_xml_generator is removed from it and deleted. The listener can
5388 // also be NULL in which case it will not be added to the list. Does
5389 // nothing if the previous and the current listener objects are the same.
5390 void TestEventListeners::SetDefaultXmlGenerator(TestEventListener* listener) {
5391 if (default_xml_generator_ != listener) {
5392 // It is an error to pass this method a listener that is already in the
5394 delete Release(default_xml_generator_);
5395 default_xml_generator_ = listener;
5396 if (listener != NULL)
5401 // Controls whether events will be forwarded by the repeater to the
5402 // listeners in the list.
5403 bool TestEventListeners::EventForwardingEnabled() const {
5404 return repeater_->forwarding_enabled();
5407 void TestEventListeners::SuppressEventForwarding() {
5408 repeater_->set_forwarding_enabled(false);
5413 // Gets the singleton UnitTest object. The first time this method is
5414 // called, a UnitTest object is constructed and returned. Consecutive
5415 // calls will return the same object.
5417 // We don't protect this under mutex_ as a user is not supposed to
5418 // call this before main() starts, from which point on the return
5419 // value will never change.
5420 UnitTest* UnitTest::GetInstance() {
5421 // When compiled with MSVC 7.1 in optimized mode, destroying the
5422 // UnitTest object upon exiting the program messes up the exit code,
5423 // causing successful tests to appear failed. We have to use a
5424 // different implementation in this case to bypass the compiler bug.
5425 // This implementation makes the compiler happy, at the cost of
5426 // leaking the UnitTest object.
5428 // CodeGear C++Builder insists on a public destructor for the
5429 // default implementation. Use this implementation to keep good OO
5430 // design with private destructor.
5432 #if (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)
5433 static UnitTest* const instance = new UnitTest;
5436 static UnitTest instance;
5438 #endif // (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)
5441 // Gets the number of successful test cases.
5442 int UnitTest::successful_test_case_count() const {
5443 return impl()->successful_test_case_count();
5446 // Gets the number of failed test cases.
5447 int UnitTest::failed_test_case_count() const {
5448 return impl()->failed_test_case_count();
5451 // Gets the number of all test cases.
5452 int UnitTest::total_test_case_count() const {
5453 return impl()->total_test_case_count();
5456 // Gets the number of all test cases that contain at least one test
5458 int UnitTest::test_case_to_run_count() const {
5459 return impl()->test_case_to_run_count();
5462 // Gets the number of successful tests.
5463 int UnitTest::successful_test_count() const {
5464 return impl()->successful_test_count();
5467 // Gets the number of failed tests.
5468 int UnitTest::failed_test_count() const { return impl()->failed_test_count(); }
5470 // Gets the number of disabled tests that will be reported in the XML report.
5471 int UnitTest::reportable_disabled_test_count() const {
5472 return impl()->reportable_disabled_test_count();
5475 // Gets the number of disabled tests.
5476 int UnitTest::disabled_test_count() const {
5477 return impl()->disabled_test_count();
5480 // Gets the number of tests to be printed in the XML report.
5481 int UnitTest::reportable_test_count() const {
5482 return impl()->reportable_test_count();
5485 // Gets the number of all tests.
5486 int UnitTest::total_test_count() const { return impl()->total_test_count(); }
5488 // Gets the number of tests that should run.
5489 int UnitTest::test_to_run_count() const { return impl()->test_to_run_count(); }
5491 // Gets the time of the test program start, in ms from the start of the
5493 internal::TimeInMillis UnitTest::start_timestamp() const {
5494 return impl()->start_timestamp();
5497 // Gets the elapsed time, in milliseconds.
5498 internal::TimeInMillis UnitTest::elapsed_time() const {
5499 return impl()->elapsed_time();
5502 // Returns true iff the unit test passed (i.e. all test cases passed).
5503 bool UnitTest::Passed() const { return impl()->Passed(); }
5505 // Returns true iff the unit test failed (i.e. some test case failed
5506 // or something outside of all tests failed).
5507 bool UnitTest::Failed() const { return impl()->Failed(); }
5509 // Gets the i-th test case among all the test cases. i can range from 0 to
5510 // total_test_case_count() - 1. If i is not in that range, returns NULL.
5511 const TestCase* UnitTest::GetTestCase(int i) const {
5512 return impl()->GetTestCase(i);
5515 // Returns the TestResult containing information on test failures and
5516 // properties logged outside of individual test cases.
5517 const TestResult& UnitTest::ad_hoc_test_result() const {
5518 return *impl()->ad_hoc_test_result();
5521 // Gets the i-th test case among all the test cases. i can range from 0 to
5522 // total_test_case_count() - 1. If i is not in that range, returns NULL.
5523 TestCase* UnitTest::GetMutableTestCase(int i) {
5524 return impl()->GetMutableTestCase(i);
5527 // Returns the list of event listeners that can be used to track events
5528 // inside Google Test.
5529 TestEventListeners& UnitTest::listeners() {
5530 return *impl()->listeners();
5533 // Registers and returns a global test environment. When a test
5534 // program is run, all global test environments will be set-up in the
5535 // order they were registered. After all tests in the program have
5536 // finished, all global test environments will be torn-down in the
5537 // *reverse* order they were registered.
5539 // The UnitTest object takes ownership of the given environment.
5541 // We don't protect this under mutex_, as we only support calling it
5542 // from the main thread.
5543 Environment* UnitTest::AddEnvironment(Environment* env) {
5548 impl_->environments().push_back(env);
5552 // Adds a TestPartResult to the current TestResult object. All Google Test
5553 // assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) eventually call
5554 // this to report their results. The user code should use the
5555 // assertion macros instead of calling this directly.
5556 void UnitTest::AddTestPartResult(
5557 TestPartResult::Type result_type,
5558 const char* file_name,
5560 const std::string& message,
5561 const std::string& os_stack_trace) GTEST_LOCK_EXCLUDED_(mutex_) {
5565 internal::MutexLock lock(&mutex_);
5566 if (impl_->gtest_trace_stack().size() > 0) {
5567 msg << "\n" << GTEST_NAME_ << " trace:";
5569 for (int i = static_cast<int>(impl_->gtest_trace_stack().size());
5571 const internal::TraceInfo& trace = impl_->gtest_trace_stack()[i - 1];
5572 msg << "\n" << internal::FormatFileLocation(trace.file, trace.line)
5573 << " " << trace.message;
5577 if (os_stack_trace.c_str() != NULL && !os_stack_trace.empty()) {
5578 msg << internal::kStackTraceMarker << os_stack_trace;
5581 const TestPartResult result =
5582 TestPartResult(result_type, file_name, line_number,
5583 msg.GetString().c_str());
5584 impl_->GetTestPartResultReporterForCurrentThread()->
5585 ReportTestPartResult(result);
5587 if (result_type != TestPartResult::kSuccess) {
5588 // gtest_break_on_failure takes precedence over
5589 // gtest_throw_on_failure. This allows a user to set the latter
5590 // in the code (perhaps in order to use Google Test assertions
5591 // with another testing framework) and specify the former on the
5592 // command line for debugging.
5593 if (GTEST_FLAG(break_on_failure)) {
5594 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
5595 // Using DebugBreak on Windows allows gtest to still break into a debugger
5596 // when a failure happens and both the --gtest_break_on_failure and
5597 // the --gtest_catch_exceptions flags are specified.
5600 // Dereference NULL through a volatile pointer to prevent the compiler
5601 // from removing. We use this rather than abort() or __builtin_trap() for
5602 // portability: Symbian doesn't implement abort() well, and some debuggers
5603 // don't correctly trap abort().
5604 *static_cast<volatile int*>(NULL) = 1;
5605 #endif // GTEST_OS_WINDOWS
5606 } else if (GTEST_FLAG(throw_on_failure)) {
5607 #if GTEST_HAS_EXCEPTIONS
5608 throw internal::GoogleTestFailureException(result);
5610 // We cannot call abort() as it generates a pop-up in debug mode
5611 // that cannot be suppressed in VC 7.1 or below.
5618 // Adds a TestProperty to the current TestResult object when invoked from
5619 // inside a test, to current TestCase's ad_hoc_test_result_ when invoked
5620 // from SetUpTestCase or TearDownTestCase, or to the global property set
5621 // when invoked elsewhere. If the result already contains a property with
5622 // the same key, the value will be updated.
5623 void UnitTest::RecordProperty(const std::string& key,
5624 const std::string& value) {
5625 impl_->RecordProperty(TestProperty(key, value));
5628 // Runs all tests in this UnitTest object and prints the result.
5629 // Returns 0 if successful, or 1 otherwise.
5631 // We don't protect this under mutex_, as we only support calling it
5632 // from the main thread.
5633 int UnitTest::Run() {
5634 const bool in_death_test_child_process =
5635 internal::GTEST_FLAG(internal_run_death_test).length() > 0;
5637 // Google Test implements this protocol for catching that a test
5638 // program exits before returning control to Google Test:
5640 // 1. Upon start, Google Test creates a file whose absolute path
5641 // is specified by the environment variable
5642 // TEST_PREMATURE_EXIT_FILE.
5643 // 2. When Google Test has finished its work, it deletes the file.
5645 // This allows a test runner to set TEST_PREMATURE_EXIT_FILE before
5646 // running a Google-Test-based test program and check the existence
5647 // of the file at the end of the test execution to see if it has
5648 // exited prematurely.
5650 // If we are in the child process of a death test, don't
5651 // create/delete the premature exit file, as doing so is unnecessary
5652 // and will confuse the parent process. Otherwise, create/delete
5653 // the file upon entering/leaving this function. If the program
5654 // somehow exits before this function has a chance to return, the
5655 // premature-exit file will be left undeleted, causing a test runner
5656 // that understands the premature-exit-file protocol to report the
5657 // test as having failed.
5658 const internal::ScopedPrematureExitFile premature_exit_file(
5659 in_death_test_child_process ?
5660 NULL : internal::posix::GetEnv("TEST_PREMATURE_EXIT_FILE"));
5662 // Captures the value of GTEST_FLAG(catch_exceptions). This value will be
5663 // used for the duration of the program.
5664 impl()->set_catch_exceptions(GTEST_FLAG(catch_exceptions));
5667 // Either the user wants Google Test to catch exceptions thrown by the
5668 // tests or this is executing in the context of death test child
5669 // process. In either case the user does not want to see pop-up dialogs
5670 // about crashes - they are expected.
5671 if (impl()->catch_exceptions() || in_death_test_child_process) {
5672 # if !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT
5673 // SetErrorMode doesn't exist on CE.
5674 SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT |
5675 SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);
5676 # endif // !GTEST_OS_WINDOWS_MOBILE
5678 # if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE
5679 // Death test children can be terminated with _abort(). On Windows,
5680 // _abort() can show a dialog with a warning message. This forces the
5681 // abort message to go to stderr instead.
5682 _set_error_mode(_OUT_TO_STDERR);
5685 # if _MSC_VER >= 1400 && !GTEST_OS_WINDOWS_MOBILE
5686 // In the debug version, Visual Studio pops up a separate dialog
5687 // offering a choice to debug the aborted program. We need to suppress
5688 // this dialog or it will pop up for every EXPECT/ASSERT_DEATH statement
5689 // executed. Google Test will notify the user of any unexpected
5690 // failure via stderr.
5692 // VC++ doesn't define _set_abort_behavior() prior to the version 8.0.
5693 // Users of prior VC versions shall suffer the agony and pain of
5694 // clicking through the countless debug dialogs.
5695 // TODO(vladl@google.com): find a way to suppress the abort dialog() in the
5696 // debug mode when compiled with VC 7.1 or lower.
5697 if (!GTEST_FLAG(break_on_failure))
5698 _set_abort_behavior(
5699 0x0, // Clear the following flags:
5700 _WRITE_ABORT_MSG | _CALL_REPORTFAULT); // pop-up window, core dump.
5703 #endif // GTEST_HAS_SEH
5705 return internal::HandleExceptionsInMethodIfSupported(
5707 &internal::UnitTestImpl::RunAllTests,
5708 "auxiliary test code (environments or event listeners)") ? 0 : 1;
5711 // Returns the working directory when the first TEST() or TEST_F() was
5713 const char* UnitTest::original_working_dir() const {
5714 return impl_->original_working_dir_.c_str();
5717 // Returns the TestCase object for the test that's currently running,
5718 // or NULL if no test is running.
5719 const TestCase* UnitTest::current_test_case() const
5720 GTEST_LOCK_EXCLUDED_(mutex_) {
5721 internal::MutexLock lock(&mutex_);
5722 return impl_->current_test_case();
5725 // Returns the TestInfo object for the test that's currently running,
5726 // or NULL if no test is running.
5727 const TestInfo* UnitTest::current_test_info() const
5728 GTEST_LOCK_EXCLUDED_(mutex_) {
5729 internal::MutexLock lock(&mutex_);
5730 return impl_->current_test_info();
5733 // Returns the random seed used at the start of the current test run.
5734 int UnitTest::random_seed() const { return impl_->random_seed(); }
5736 #if GTEST_HAS_PARAM_TEST
5737 // Returns ParameterizedTestCaseRegistry object used to keep track of
5738 // value-parameterized tests and instantiate and register them.
5739 internal::ParameterizedTestCaseRegistry&
5740 UnitTest::parameterized_test_registry()
5741 GTEST_LOCK_EXCLUDED_(mutex_) {
5742 return impl_->parameterized_test_registry();
5744 #endif // GTEST_HAS_PARAM_TEST
5746 // Creates an empty UnitTest.
5747 UnitTest::UnitTest() {
5748 impl_ = new internal::UnitTestImpl(this);
5751 // Destructor of UnitTest.
5752 UnitTest::~UnitTest() {
5756 // Pushes a trace defined by SCOPED_TRACE() on to the per-thread
5757 // Google Test trace stack.
5758 void UnitTest::PushGTestTrace(const internal::TraceInfo& trace)
5759 GTEST_LOCK_EXCLUDED_(mutex_) {
5760 internal::MutexLock lock(&mutex_);
5761 impl_->gtest_trace_stack().push_back(trace);
5764 // Pops a trace from the per-thread Google Test trace stack.
5765 void UnitTest::PopGTestTrace()
5766 GTEST_LOCK_EXCLUDED_(mutex_) {
5767 internal::MutexLock lock(&mutex_);
5768 impl_->gtest_trace_stack().pop_back();
5771 namespace internal {
5773 UnitTestImpl::UnitTestImpl(UnitTest* parent)
5775 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4355 /* using this in initializer */)
5776 default_global_test_part_result_reporter_(this),
5777 default_per_thread_test_part_result_reporter_(this),
5778 GTEST_DISABLE_MSC_WARNINGS_POP_()
5779 global_test_part_result_repoter_(
5780 &default_global_test_part_result_reporter_),
5781 per_thread_test_part_result_reporter_(
5782 &default_per_thread_test_part_result_reporter_),
5783 #if GTEST_HAS_PARAM_TEST
5784 parameterized_test_registry_(),
5785 parameterized_tests_registered_(false),
5786 #endif // GTEST_HAS_PARAM_TEST
5787 last_death_test_case_(-1),
5788 current_test_case_(NULL),
5789 current_test_info_(NULL),
5790 ad_hoc_test_result_(),
5791 os_stack_trace_getter_(NULL),
5792 post_flag_parse_init_performed_(false),
5793 random_seed_(0), // Will be overridden by the flag before first use.
5794 random_(0), // Will be reseeded before first use.
5795 start_timestamp_(0),
5797 #if GTEST_HAS_DEATH_TEST
5798 death_test_factory_(new DefaultDeathTestFactory),
5800 // Will be overridden by the flag before first use.
5801 catch_exceptions_(false) {
5802 listeners()->SetDefaultResultPrinter(new PrettyUnitTestResultPrinter);
5805 UnitTestImpl::~UnitTestImpl() {
5806 // Deletes every TestCase.
5807 ForEach(test_cases_, internal::Delete<TestCase>);
5809 // Deletes every Environment.
5810 ForEach(environments_, internal::Delete<Environment>);
5812 delete os_stack_trace_getter_;
5815 // Adds a TestProperty to the current TestResult object when invoked in a
5816 // context of a test, to current test case's ad_hoc_test_result when invoke
5817 // from SetUpTestCase/TearDownTestCase, or to the global property set
5818 // otherwise. If the result already contains a property with the same key,
5819 // the value will be updated.
5820 void UnitTestImpl::RecordProperty(const TestProperty& test_property) {
5821 std::string xml_element;
5822 TestResult* test_result; // TestResult appropriate for property recording.
5824 if (current_test_info_ != NULL) {
5825 xml_element = "testcase";
5826 test_result = &(current_test_info_->result_);
5827 } else if (current_test_case_ != NULL) {
5828 xml_element = "testsuite";
5829 test_result = &(current_test_case_->ad_hoc_test_result_);
5831 xml_element = "testsuites";
5832 test_result = &ad_hoc_test_result_;
5834 test_result->RecordProperty(xml_element, test_property);
5837 #if GTEST_HAS_DEATH_TEST
5838 // Disables event forwarding if the control is currently in a death test
5839 // subprocess. Must not be called before InitGoogleTest.
5840 void UnitTestImpl::SuppressTestEventsIfInSubprocess() {
5841 if (internal_run_death_test_flag_.get() != NULL)
5842 listeners()->SuppressEventForwarding();
5844 #endif // GTEST_HAS_DEATH_TEST
5846 // Initializes event listeners performing XML output as specified by
5847 // UnitTestOptions. Must not be called before InitGoogleTest.
5848 void UnitTestImpl::ConfigureXmlOutput() {
5849 const std::string& output_format = UnitTestOptions::GetOutputFormat();
5850 if (output_format == "xml") {
5851 listeners()->SetDefaultXmlGenerator(new XmlUnitTestResultPrinter(
5852 UnitTestOptions::GetAbsolutePathToOutputFile().c_str()));
5853 } else if (output_format != "") {
5854 printf("WARNING: unrecognized output format \"%s\" ignored.\n",
5855 output_format.c_str());
5860 #if GTEST_CAN_STREAM_RESULTS_
5861 // Initializes event listeners for streaming test results in string form.
5862 // Must not be called before InitGoogleTest.
5863 void UnitTestImpl::ConfigureStreamingOutput() {
5864 const std::string& target = GTEST_FLAG(stream_result_to);
5865 if (!target.empty()) {
5866 const size_t pos = target.find(':');
5867 if (pos != std::string::npos) {
5868 listeners()->Append(new StreamingListener(target.substr(0, pos),
5869 target.substr(pos+1)));
5871 printf("WARNING: unrecognized streaming target \"%s\" ignored.\n",
5877 #endif // GTEST_CAN_STREAM_RESULTS_
5879 // Performs initialization dependent upon flag values obtained in
5880 // ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to
5881 // ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest
5882 // this function is also called from RunAllTests. Since this function can be
5883 // called more than once, it has to be idempotent.
5884 void UnitTestImpl::PostFlagParsingInit() {
5885 // Ensures that this function does not execute more than once.
5886 if (!post_flag_parse_init_performed_) {
5887 post_flag_parse_init_performed_ = true;
5889 #if defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_)
5890 // Register to send notifications about key process state changes.
5891 listeners()->Append(new GTEST_CUSTOM_TEST_EVENT_LISTENER_());
5892 #endif // defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_)
5894 #if GTEST_HAS_DEATH_TEST
5895 InitDeathTestSubprocessControlInfo();
5896 SuppressTestEventsIfInSubprocess();
5897 #endif // GTEST_HAS_DEATH_TEST
5899 // Registers parameterized tests. This makes parameterized tests
5900 // available to the UnitTest reflection API without running
5902 RegisterParameterizedTests();
5904 // Configures listeners for XML output. This makes it possible for users
5905 // to shut down the default XML output before invoking RUN_ALL_TESTS.
5906 ConfigureXmlOutput();
5908 #if GTEST_CAN_STREAM_RESULTS_
5909 // Configures listeners for streaming test results to the specified server.
5910 ConfigureStreamingOutput();
5911 #endif // GTEST_CAN_STREAM_RESULTS_
5915 // A predicate that checks the name of a TestCase against a known
5918 // This is used for implementation of the UnitTest class only. We put
5919 // it in the anonymous namespace to prevent polluting the outer
5922 // TestCaseNameIs is copyable.
5923 class TestCaseNameIs {
5926 explicit TestCaseNameIs(const std::string& name)
5929 // Returns true iff the name of test_case matches name_.
5930 bool operator()(const TestCase* test_case) const {
5931 return test_case != NULL && strcmp(test_case->name(), name_.c_str()) == 0;
5938 // Finds and returns a TestCase with the given name. If one doesn't
5939 // exist, creates one and returns it. It's the CALLER'S
5940 // RESPONSIBILITY to ensure that this function is only called WHEN THE
5941 // TESTS ARE NOT SHUFFLED.
5945 // test_case_name: name of the test case
5946 // type_param: the name of the test case's type parameter, or NULL if
5947 // this is not a typed or a type-parameterized test case.
5948 // set_up_tc: pointer to the function that sets up the test case
5949 // tear_down_tc: pointer to the function that tears down the test case
5950 TestCase* UnitTestImpl::GetTestCase(const char* test_case_name,
5951 const char* type_param,
5952 Test::SetUpTestCaseFunc set_up_tc,
5953 Test::TearDownTestCaseFunc tear_down_tc) {
5954 // Can we find a TestCase with the given name?
5955 const std::vector<TestCase*>::const_iterator test_case =
5956 std::find_if(test_cases_.begin(), test_cases_.end(),
5957 TestCaseNameIs(test_case_name));
5959 if (test_case != test_cases_.end())
5962 // No. Let's create one.
5963 TestCase* const new_test_case =
5964 new TestCase(test_case_name, type_param, set_up_tc, tear_down_tc);
5966 // Is this a death test case?
5967 if (internal::UnitTestOptions::MatchesFilter(test_case_name,
5968 kDeathTestCaseFilter)) {
5969 // Yes. Inserts the test case after the last death test case
5970 // defined so far. This only works when the test cases haven't
5971 // been shuffled. Otherwise we may end up running a death test
5972 // after a non-death test.
5973 ++last_death_test_case_;
5974 test_cases_.insert(test_cases_.begin() + last_death_test_case_,
5977 // No. Appends to the end of the list.
5978 test_cases_.push_back(new_test_case);
5981 test_case_indices_.push_back(static_cast<int>(test_case_indices_.size()));
5982 return new_test_case;
5985 // Helpers for setting up / tearing down the given environment. They
5986 // are for use in the ForEach() function.
5987 static void SetUpEnvironment(Environment* env) { env->SetUp(); }
5988 static void TearDownEnvironment(Environment* env) { env->TearDown(); }
5990 // Runs all tests in this UnitTest object, prints the result, and
5991 // returns true if all tests are successful. If any exception is
5992 // thrown during a test, the test is considered to be failed, but the
5993 // rest of the tests will still be run.
5995 // When parameterized tests are enabled, it expands and registers
5996 // parameterized tests first in RegisterParameterizedTests().
5997 // All other functions called from RunAllTests() may safely assume that
5998 // parameterized tests are ready to be counted and run.
5999 bool UnitTestImpl::RunAllTests() {
6000 // Makes sure InitGoogleTest() was called.
6001 if (!GTestIsInitialized()) {
6003 "\nThis test program did NOT call ::testing::InitGoogleTest "
6004 "before calling RUN_ALL_TESTS(). Please fix it.\n");
6008 // Do not run any test if the --help flag was specified.
6012 // Repeats the call to the post-flag parsing initialization in case the
6013 // user didn't call InitGoogleTest.
6014 PostFlagParsingInit();
6016 // Even if sharding is not on, test runners may want to use the
6017 // GTEST_SHARD_STATUS_FILE to query whether the test supports the sharding
6019 internal::WriteToShardStatusFileIfNeeded();
6021 // True iff we are in a subprocess for running a thread-safe-style
6023 bool in_subprocess_for_death_test = false;
6025 #if GTEST_HAS_DEATH_TEST
6026 in_subprocess_for_death_test = (internal_run_death_test_flag_.get() != NULL);
6027 # if defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_)
6028 if (in_subprocess_for_death_test) {
6029 GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_();
6031 # endif // defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_)
6032 #endif // GTEST_HAS_DEATH_TEST
6034 const bool should_shard = ShouldShard(kTestTotalShards, kTestShardIndex,
6035 in_subprocess_for_death_test);
6037 // Compares the full test names with the filter to decide which
6039 const bool has_tests_to_run = FilterTests(should_shard
6040 ? HONOR_SHARDING_PROTOCOL
6041 : IGNORE_SHARDING_PROTOCOL) > 0;
6043 // Lists the tests and exits if the --gtest_list_tests flag was specified.
6044 if (GTEST_FLAG(list_tests)) {
6045 // This must be called *after* FilterTests() has been called.
6046 ListTestsMatchingFilter();
6050 random_seed_ = GTEST_FLAG(shuffle) ?
6051 GetRandomSeedFromFlag(GTEST_FLAG(random_seed)) : 0;
6053 // True iff at least one test has failed.
6054 bool failed = false;
6056 TestEventListener* repeater = listeners()->repeater();
6058 start_timestamp_ = GetTimeInMillis();
6059 repeater->OnTestProgramStart(*parent_);
6061 // How many times to repeat the tests? We don't want to repeat them
6062 // when we are inside the subprocess of a death test.
6063 const int repeat = in_subprocess_for_death_test ? 1 : GTEST_FLAG(repeat);
6064 // Repeats forever if the repeat count is negative.
6065 const bool forever = repeat < 0;
6066 for (int i = 0; forever || i != repeat; i++) {
6067 // We want to preserve failures generated by ad-hoc test
6068 // assertions executed before RUN_ALL_TESTS().
6069 ClearNonAdHocTestResult();
6071 const TimeInMillis start = GetTimeInMillis();
6073 // Shuffles test cases and tests if requested.
6074 if (has_tests_to_run && GTEST_FLAG(shuffle)) {
6075 random()->Reseed(random_seed_);
6076 // This should be done before calling OnTestIterationStart(),
6077 // such that a test event listener can see the actual test order
6082 // Tells the unit test event listeners that the tests are about to start.
6083 repeater->OnTestIterationStart(*parent_, i);
6085 // Runs each test case if there is at least one test to run.
6086 if (has_tests_to_run) {
6087 // Sets up all environments beforehand.
6088 repeater->OnEnvironmentsSetUpStart(*parent_);
6089 ForEach(environments_, SetUpEnvironment);
6090 repeater->OnEnvironmentsSetUpEnd(*parent_);
6092 // Runs the tests only if there was no fatal failure during global
6094 if (!Test::HasFatalFailure()) {
6095 for (int test_index = 0; test_index < total_test_case_count();
6097 GetMutableTestCase(test_index)->Run();
6101 // Tears down all environments in reverse order afterwards.
6102 repeater->OnEnvironmentsTearDownStart(*parent_);
6103 std::for_each(environments_.rbegin(), environments_.rend(),
6104 TearDownEnvironment);
6105 repeater->OnEnvironmentsTearDownEnd(*parent_);
6108 elapsed_time_ = GetTimeInMillis() - start;
6110 // Tells the unit test event listener that the tests have just finished.
6111 repeater->OnTestIterationEnd(*parent_, i);
6113 // Gets the result and clears it.
6118 // Restores the original test order after the iteration. This
6119 // allows the user to quickly repro a failure that happens in the
6120 // N-th iteration without repeating the first (N - 1) iterations.
6121 // This is not enclosed in "if (GTEST_FLAG(shuffle)) { ... }", in
6122 // case the user somehow changes the value of the flag somewhere
6123 // (it's always safe to unshuffle the tests).
6126 if (GTEST_FLAG(shuffle)) {
6127 // Picks a new random seed for each iteration.
6128 random_seed_ = GetNextRandomSeed(random_seed_);
6132 repeater->OnTestProgramEnd(*parent_);
6137 // Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
6138 // if the variable is present. If a file already exists at this location, this
6139 // function will write over it. If the variable is present, but the file cannot
6140 // be created, prints an error and exits.
6141 void WriteToShardStatusFileIfNeeded() {
6142 const char* const test_shard_file = posix::GetEnv(kTestShardStatusFile);
6143 if (test_shard_file != NULL) {
6144 FILE* const file = posix::FOpen(test_shard_file, "w");
6146 ColoredPrintf(COLOR_RED,
6147 "Could not write to the test shard status file \"%s\" "
6148 "specified by the %s environment variable.\n",
6149 test_shard_file, kTestShardStatusFile);
6157 // Checks whether sharding is enabled by examining the relevant
6158 // environment variable values. If the variables are present,
6159 // but inconsistent (i.e., shard_index >= total_shards), prints
6160 // an error and exits. If in_subprocess_for_death_test, sharding is
6161 // disabled because it must only be applied to the original test
6162 // process. Otherwise, we could filter out death tests we intended to execute.
6163 bool ShouldShard(const char* total_shards_env,
6164 const char* shard_index_env,
6165 bool in_subprocess_for_death_test) {
6166 if (in_subprocess_for_death_test) {
6170 const Int32 total_shards = Int32FromEnvOrDie(total_shards_env, -1);
6171 const Int32 shard_index = Int32FromEnvOrDie(shard_index_env, -1);
6173 if (total_shards == -1 && shard_index == -1) {
6175 } else if (total_shards == -1 && shard_index != -1) {
6176 const Message msg = Message()
6177 << "Invalid environment variables: you have "
6178 << kTestShardIndex << " = " << shard_index
6179 << ", but have left " << kTestTotalShards << " unset.\n";
6180 ColoredPrintf(COLOR_RED, msg.GetString().c_str());
6183 } else if (total_shards != -1 && shard_index == -1) {
6184 const Message msg = Message()
6185 << "Invalid environment variables: you have "
6186 << kTestTotalShards << " = " << total_shards
6187 << ", but have left " << kTestShardIndex << " unset.\n";
6188 ColoredPrintf(COLOR_RED, msg.GetString().c_str());
6191 } else if (shard_index < 0 || shard_index >= total_shards) {
6192 const Message msg = Message()
6193 << "Invalid environment variables: we require 0 <= "
6194 << kTestShardIndex << " < " << kTestTotalShards
6195 << ", but you have " << kTestShardIndex << "=" << shard_index
6196 << ", " << kTestTotalShards << "=" << total_shards << ".\n";
6197 ColoredPrintf(COLOR_RED, msg.GetString().c_str());
6202 return total_shards > 1;
6205 // Parses the environment variable var as an Int32. If it is unset,
6206 // returns default_val. If it is not an Int32, prints an error
6208 Int32 Int32FromEnvOrDie(const char* var, Int32 default_val) {
6209 const char* str_val = posix::GetEnv(var);
6210 if (str_val == NULL) {
6215 if (!ParseInt32(Message() << "The value of environment variable " << var,
6216 str_val, &result)) {
6222 // Given the total number of shards, the shard index, and the test id,
6223 // returns true iff the test should be run on this shard. The test id is
6224 // some arbitrary but unique non-negative integer assigned to each test
6225 // method. Assumes that 0 <= shard_index < total_shards.
6226 bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) {
6227 return (test_id % total_shards) == shard_index;
6230 // Compares the name of each test with the user-specified filter to
6231 // decide whether the test should be run, then records the result in
6232 // each TestCase and TestInfo object.
6233 // If shard_tests == true, further filters tests based on sharding
6234 // variables in the environment - see
6235 // http://code.google.com/p/googletest/wiki/GoogleTestAdvancedGuide.
6236 // Returns the number of tests that should run.
6237 int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) {
6238 const Int32 total_shards = shard_tests == HONOR_SHARDING_PROTOCOL ?
6239 Int32FromEnvOrDie(kTestTotalShards, -1) : -1;
6240 const Int32 shard_index = shard_tests == HONOR_SHARDING_PROTOCOL ?
6241 Int32FromEnvOrDie(kTestShardIndex, -1) : -1;
6243 // num_runnable_tests are the number of tests that will
6244 // run across all shards (i.e., match filter and are not disabled).
6245 // num_selected_tests are the number of tests to be run on
6247 int num_runnable_tests = 0;
6248 int num_selected_tests = 0;
6249 for (size_t i = 0; i < test_cases_.size(); i++) {
6250 TestCase* const test_case = test_cases_[i];
6251 const std::string &test_case_name = test_case->name();
6252 test_case->set_should_run(false);
6254 for (size_t j = 0; j < test_case->test_info_list().size(); j++) {
6255 TestInfo* const test_info = test_case->test_info_list()[j];
6256 const std::string test_name(test_info->name());
6257 // A test is disabled if test case name or test name matches
6258 // kDisableTestFilter.
6259 const bool is_disabled =
6260 internal::UnitTestOptions::MatchesFilter(test_case_name,
6261 kDisableTestFilter) ||
6262 internal::UnitTestOptions::MatchesFilter(test_name,
6263 kDisableTestFilter);
6264 test_info->is_disabled_ = is_disabled;
6266 const bool matches_filter =
6267 internal::UnitTestOptions::FilterMatchesTest(test_case_name,
6269 test_info->matches_filter_ = matches_filter;
6271 const bool is_runnable =
6272 (GTEST_FLAG(also_run_disabled_tests) || !is_disabled) &&
6275 const bool is_selected = is_runnable &&
6276 (shard_tests == IGNORE_SHARDING_PROTOCOL ||
6277 ShouldRunTestOnShard(total_shards, shard_index,
6278 num_runnable_tests));
6280 num_runnable_tests += is_runnable;
6281 num_selected_tests += is_selected;
6283 test_info->should_run_ = is_selected;
6284 test_case->set_should_run(test_case->should_run() || is_selected);
6287 return num_selected_tests;
6290 // Prints the given C-string on a single line by replacing all '\n'
6291 // characters with string "\\n". If the output takes more than
6292 // max_length characters, only prints the first max_length characters
6294 static void PrintOnOneLine(const char* str, int max_length) {
6296 for (int i = 0; *str != '\0'; ++str) {
6297 if (i >= max_length) {
6312 // Prints the names of the tests matching the user-specified filter flag.
6313 void UnitTestImpl::ListTestsMatchingFilter() {
6314 // Print at most this many characters for each type/value parameter.
6315 const int kMaxParamLength = 250;
6317 for (size_t i = 0; i < test_cases_.size(); i++) {
6318 const TestCase* const test_case = test_cases_[i];
6319 bool printed_test_case_name = false;
6321 for (size_t j = 0; j < test_case->test_info_list().size(); j++) {
6322 const TestInfo* const test_info =
6323 test_case->test_info_list()[j];
6324 if (test_info->matches_filter_) {
6325 if (!printed_test_case_name) {
6326 printed_test_case_name = true;
6327 printf("%s.", test_case->name());
6328 if (test_case->type_param() != NULL) {
6329 printf(" # %s = ", kTypeParamLabel);
6330 // We print the type parameter on a single line to make
6331 // the output easy to parse by a program.
6332 PrintOnOneLine(test_case->type_param(), kMaxParamLength);
6336 printf(" %s", test_info->name());
6337 if (test_info->value_param() != NULL) {
6338 printf(" # %s = ", kValueParamLabel);
6339 // We print the value parameter on a single line to make the
6340 // output easy to parse by a program.
6341 PrintOnOneLine(test_info->value_param(), kMaxParamLength);
6350 // Sets the OS stack trace getter.
6352 // Does nothing if the input and the current OS stack trace getter are
6353 // the same; otherwise, deletes the old getter and makes the input the
6355 void UnitTestImpl::set_os_stack_trace_getter(
6356 OsStackTraceGetterInterface* getter) {
6357 if (os_stack_trace_getter_ != getter) {
6358 delete os_stack_trace_getter_;
6359 os_stack_trace_getter_ = getter;
6363 // Returns the current OS stack trace getter if it is not NULL;
6364 // otherwise, creates an OsStackTraceGetter, makes it the current
6365 // getter, and returns it.
6366 OsStackTraceGetterInterface* UnitTestImpl::os_stack_trace_getter() {
6367 if (os_stack_trace_getter_ == NULL) {
6368 #ifdef GTEST_OS_STACK_TRACE_GETTER_
6369 os_stack_trace_getter_ = new GTEST_OS_STACK_TRACE_GETTER_;
6371 os_stack_trace_getter_ = new OsStackTraceGetter;
6372 #endif // GTEST_OS_STACK_TRACE_GETTER_
6375 return os_stack_trace_getter_;
6378 // Returns the TestResult for the test that's currently running, or
6379 // the TestResult for the ad hoc test if no test is running.
6380 TestResult* UnitTestImpl::current_test_result() {
6381 return current_test_info_ ?
6382 &(current_test_info_->result_) : &ad_hoc_test_result_;
6385 // Shuffles all test cases, and the tests within each test case,
6386 // making sure that death tests are still run first.
6387 void UnitTestImpl::ShuffleTests() {
6388 // Shuffles the death test cases.
6389 ShuffleRange(random(), 0, last_death_test_case_ + 1, &test_case_indices_);
6391 // Shuffles the non-death test cases.
6392 ShuffleRange(random(), last_death_test_case_ + 1,
6393 static_cast<int>(test_cases_.size()), &test_case_indices_);
6395 // Shuffles the tests inside each test case.
6396 for (size_t i = 0; i < test_cases_.size(); i++) {
6397 test_cases_[i]->ShuffleTests(random());
6401 // Restores the test cases and tests to their order before the first shuffle.
6402 void UnitTestImpl::UnshuffleTests() {
6403 for (size_t i = 0; i < test_cases_.size(); i++) {
6404 // Unshuffles the tests in each test case.
6405 test_cases_[i]->UnshuffleTests();
6406 // Resets the index of each test case.
6407 test_case_indices_[i] = static_cast<int>(i);
6411 // Returns the current OS stack trace as an std::string.
6413 // The maximum number of stack frames to be included is specified by
6414 // the gtest_stack_trace_depth flag. The skip_count parameter
6415 // specifies the number of top frames to be skipped, which doesn't
6416 // count against the number of frames to be included.
6418 // For example, if Foo() calls Bar(), which in turn calls
6419 // GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in
6420 // the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.
6421 std::string GetCurrentOsStackTraceExceptTop(UnitTest* /*unit_test*/,
6423 // We pass skip_count + 1 to skip this wrapper function in addition
6424 // to what the user really wants to skip.
6425 return GetUnitTestImpl()->CurrentOsStackTraceExceptTop(skip_count + 1);
6428 // Used by the GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_ macro to
6429 // suppress unreachable code warnings.
6431 class ClassUniqueToAlwaysTrue {};
6434 bool IsTrue(bool condition) { return condition; }
6437 #if GTEST_HAS_EXCEPTIONS
6438 // This condition is always false so AlwaysTrue() never actually throws,
6439 // but it makes the compiler think that it may throw.
6441 throw ClassUniqueToAlwaysTrue();
6442 #endif // GTEST_HAS_EXCEPTIONS
6446 // If *pstr starts with the given prefix, modifies *pstr to be right
6447 // past the prefix and returns true; otherwise leaves *pstr unchanged
6448 // and returns false. None of pstr, *pstr, and prefix can be NULL.
6449 bool SkipPrefix(const char* prefix, const char** pstr) {
6450 const size_t prefix_len = strlen(prefix);
6451 if (strncmp(*pstr, prefix, prefix_len) == 0) {
6452 *pstr += prefix_len;
6458 // Parses a string as a command line flag. The string should have
6459 // the format "--flag=value". When def_optional is true, the "=value"
6460 // part can be omitted.
6462 // Returns the value of the flag, or NULL if the parsing failed.
6463 const char* ParseFlagValue(const char* str,
6465 bool def_optional) {
6466 // str and flag must not be NULL.
6467 if (str == NULL || flag == NULL) return NULL;
6469 // The flag must start with "--" followed by GTEST_FLAG_PREFIX_.
6470 const std::string flag_str = std::string("--") + GTEST_FLAG_PREFIX_ + flag;
6471 const size_t flag_len = flag_str.length();
6472 if (strncmp(str, flag_str.c_str(), flag_len) != 0) return NULL;
6474 // Skips the flag name.
6475 const char* flag_end = str + flag_len;
6477 // When def_optional is true, it's OK to not have a "=value" part.
6478 if (def_optional && (flag_end[0] == '\0')) {
6482 // If def_optional is true and there are more characters after the
6483 // flag name, or if def_optional is false, there must be a '=' after
6485 if (flag_end[0] != '=') return NULL;
6487 // Returns the string after "=".
6488 return flag_end + 1;
6491 // Parses a string for a bool flag, in the form of either
6492 // "--flag=value" or "--flag".
6494 // In the former case, the value is taken as true as long as it does
6495 // not start with '0', 'f', or 'F'.
6497 // In the latter case, the value is taken as true.
6499 // On success, stores the value of the flag in *value, and returns
6500 // true. On failure, returns false without changing *value.
6501 bool ParseBoolFlag(const char* str, const char* flag, bool* value) {
6502 // Gets the value of the flag as a string.
6503 const char* const value_str = ParseFlagValue(str, flag, true);
6505 // Aborts if the parsing failed.
6506 if (value_str == NULL) return false;
6508 // Converts the string value to a bool.
6509 *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F');
6513 // Parses a string for an Int32 flag, in the form of
6516 // On success, stores the value of the flag in *value, and returns
6517 // true. On failure, returns false without changing *value.
6518 bool ParseInt32Flag(const char* str, const char* flag, Int32* value) {
6519 // Gets the value of the flag as a string.
6520 const char* const value_str = ParseFlagValue(str, flag, false);
6522 // Aborts if the parsing failed.
6523 if (value_str == NULL) return false;
6525 // Sets *value to the value of the flag.
6526 return ParseInt32(Message() << "The value of flag --" << flag,
6530 // Parses a string for a string flag, in the form of
6533 // On success, stores the value of the flag in *value, and returns
6534 // true. On failure, returns false without changing *value.
6535 bool ParseStringFlag(const char* str, const char* flag, std::string* value) {
6536 // Gets the value of the flag as a string.
6537 const char* const value_str = ParseFlagValue(str, flag, false);
6539 // Aborts if the parsing failed.
6540 if (value_str == NULL) return false;
6542 // Sets *value to the value of the flag.
6547 // Determines whether a string has a prefix that Google Test uses for its
6548 // flags, i.e., starts with GTEST_FLAG_PREFIX_ or GTEST_FLAG_PREFIX_DASH_.
6549 // If Google Test detects that a command line flag has its prefix but is not
6550 // recognized, it will print its help message. Flags starting with
6551 // GTEST_INTERNAL_PREFIX_ followed by "internal_" are considered Google Test
6552 // internal flags and do not trigger the help message.
6553 static bool HasGoogleTestFlagPrefix(const char* str) {
6554 return (SkipPrefix("--", &str) ||
6555 SkipPrefix("-", &str) ||
6556 SkipPrefix("/", &str)) &&
6557 !SkipPrefix(GTEST_FLAG_PREFIX_ "internal_", &str) &&
6558 (SkipPrefix(GTEST_FLAG_PREFIX_, &str) ||
6559 SkipPrefix(GTEST_FLAG_PREFIX_DASH_, &str));
6562 // Prints a string containing code-encoded text. The following escape
6563 // sequences can be used in the string to control the text color:
6565 // @@ prints a single '@' character.
6566 // @R changes the color to red.
6567 // @G changes the color to green.
6568 // @Y changes the color to yellow.
6569 // @D changes to the default terminal text color.
6571 // TODO(wan@google.com): Write tests for this once we add stdout
6572 // capturing to Google Test.
6573 static void PrintColorEncoded(const char* str) {
6574 GTestColor color = COLOR_DEFAULT; // The current color.
6576 // Conceptually, we split the string into segments divided by escape
6577 // sequences. Then we print one segment at a time. At the end of
6578 // each iteration, the str pointer advances to the beginning of the
6581 const char* p = strchr(str, '@');
6583 ColoredPrintf(color, "%s", str);
6587 ColoredPrintf(color, "%s", std::string(str, p).c_str());
6589 const char ch = p[1];
6592 ColoredPrintf(color, "@");
6593 } else if (ch == 'D') {
6594 color = COLOR_DEFAULT;
6595 } else if (ch == 'R') {
6597 } else if (ch == 'G') {
6598 color = COLOR_GREEN;
6599 } else if (ch == 'Y') {
6600 color = COLOR_YELLOW;
6607 static const char kColorEncodedHelpMessage[] =
6608 "This program contains tests written using " GTEST_NAME_ ". You can use the\n"
6609 "following command line flags to control its behavior:\n"
6612 " @G--" GTEST_FLAG_PREFIX_ "list_tests@D\n"
6613 " List the names of all tests instead of running them. The name of\n"
6614 " TEST(Foo, Bar) is \"Foo.Bar\".\n"
6615 " @G--" GTEST_FLAG_PREFIX_ "filter=@YPOSTIVE_PATTERNS"
6616 "[@G-@YNEGATIVE_PATTERNS]@D\n"
6617 " Run only the tests whose name matches one of the positive patterns but\n"
6618 " none of the negative patterns. '?' matches any single character; '*'\n"
6619 " matches any substring; ':' separates two patterns.\n"
6620 " @G--" GTEST_FLAG_PREFIX_ "also_run_disabled_tests@D\n"
6621 " Run all disabled tests too.\n"
6624 " @G--" GTEST_FLAG_PREFIX_ "repeat=@Y[COUNT]@D\n"
6625 " Run the tests repeatedly; use a negative count to repeat forever.\n"
6626 " @G--" GTEST_FLAG_PREFIX_ "shuffle@D\n"
6627 " Randomize tests' orders on every iteration.\n"
6628 " @G--" GTEST_FLAG_PREFIX_ "random_seed=@Y[NUMBER]@D\n"
6629 " Random number seed to use for shuffling test orders (between 1 and\n"
6630 " 99999, or 0 to use a seed based on the current time).\n"
6633 " @G--" GTEST_FLAG_PREFIX_ "color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\n"
6634 " Enable/disable colored output. The default is @Gauto@D.\n"
6635 " -@G-" GTEST_FLAG_PREFIX_ "print_time=0@D\n"
6636 " Don't print the elapsed time of each test.\n"
6637 " @G--" GTEST_FLAG_PREFIX_ "output=xml@Y[@G:@YDIRECTORY_PATH@G"
6638 GTEST_PATH_SEP_ "@Y|@G:@YFILE_PATH]@D\n"
6639 " Generate an XML report in the given directory or with the given file\n"
6640 " name. @YFILE_PATH@D defaults to @Gtest_details.xml@D.\n"
6641 #if GTEST_CAN_STREAM_RESULTS_
6642 " @G--" GTEST_FLAG_PREFIX_ "stream_result_to=@YHOST@G:@YPORT@D\n"
6643 " Stream test results to the given server.\n"
6644 #endif // GTEST_CAN_STREAM_RESULTS_
6646 "Assertion Behavior:\n"
6647 #if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
6648 " @G--" GTEST_FLAG_PREFIX_ "death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n"
6649 " Set the default death test style.\n"
6650 #endif // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
6651 " @G--" GTEST_FLAG_PREFIX_ "break_on_failure@D\n"
6652 " Turn assertion failures into debugger break-points.\n"
6653 " @G--" GTEST_FLAG_PREFIX_ "throw_on_failure@D\n"
6654 " Turn assertion failures into C++ exceptions.\n"
6655 " @G--" GTEST_FLAG_PREFIX_ "catch_exceptions=0@D\n"
6656 " Do not report exceptions as test failures. Instead, allow them\n"
6657 " to crash the program or throw a pop-up (on Windows).\n"
6659 "Except for @G--" GTEST_FLAG_PREFIX_ "list_tests@D, you can alternatively set "
6660 "the corresponding\n"
6661 "environment variable of a flag (all letters in upper-case). For example, to\n"
6662 "disable colored text output, you can either specify @G--" GTEST_FLAG_PREFIX_
6663 "color=no@D or set\n"
6664 "the @G" GTEST_FLAG_PREFIX_UPPER_ "COLOR@D environment variable to @Gno@D.\n"
6666 "For more information, please read the " GTEST_NAME_ " documentation at\n"
6667 "@G" GTEST_PROJECT_URL_ "@D. If you find a bug in " GTEST_NAME_ "\n"
6668 "(not one in your own code or tests), please report it to\n"
6669 "@G<" GTEST_DEV_EMAIL_ ">@D.\n";
6671 bool ParseGoogleTestFlag(const char* const arg) {
6672 return ParseBoolFlag(arg, kAlsoRunDisabledTestsFlag,
6673 >EST_FLAG(also_run_disabled_tests)) ||
6674 ParseBoolFlag(arg, kBreakOnFailureFlag,
6675 >EST_FLAG(break_on_failure)) ||
6676 ParseBoolFlag(arg, kCatchExceptionsFlag,
6677 >EST_FLAG(catch_exceptions)) ||
6678 ParseStringFlag(arg, kColorFlag, >EST_FLAG(color)) ||
6679 ParseStringFlag(arg, kDeathTestStyleFlag,
6680 >EST_FLAG(death_test_style)) ||
6681 ParseBoolFlag(arg, kDeathTestUseFork,
6682 >EST_FLAG(death_test_use_fork)) ||
6683 ParseStringFlag(arg, kFilterFlag, >EST_FLAG(filter)) ||
6684 ParseStringFlag(arg, kInternalRunDeathTestFlag,
6685 >EST_FLAG(internal_run_death_test)) ||
6686 ParseBoolFlag(arg, kListTestsFlag, >EST_FLAG(list_tests)) ||
6687 ParseStringFlag(arg, kOutputFlag, >EST_FLAG(output)) ||
6688 ParseBoolFlag(arg, kPrintTimeFlag, >EST_FLAG(print_time)) ||
6689 ParseInt32Flag(arg, kRandomSeedFlag, >EST_FLAG(random_seed)) ||
6690 ParseInt32Flag(arg, kRepeatFlag, >EST_FLAG(repeat)) ||
6691 ParseBoolFlag(arg, kShuffleFlag, >EST_FLAG(shuffle)) ||
6692 ParseInt32Flag(arg, kStackTraceDepthFlag,
6693 >EST_FLAG(stack_trace_depth)) ||
6694 ParseStringFlag(arg, kStreamResultToFlag,
6695 >EST_FLAG(stream_result_to)) ||
6696 ParseBoolFlag(arg, kThrowOnFailureFlag,
6697 >EST_FLAG(throw_on_failure));
6700 #if GTEST_USE_OWN_FLAGFILE_FLAG_
6701 void LoadFlagsFromFile(const std::string& path) {
6702 FILE* flagfile = posix::FOpen(path.c_str(), "r");
6705 "Unable to open file \"%s\"\n",
6706 GTEST_FLAG(flagfile).c_str());
6710 std::string contents(ReadEntireFile(flagfile));
6711 posix::FClose(flagfile);
6712 std::vector<std::string> lines;
6713 SplitString(contents, '\n', &lines);
6714 for (size_t i = 0; i < lines.size(); ++i) {
6715 if (lines[i].empty())
6717 if (!ParseGoogleTestFlag(lines[i].c_str()))
6721 #endif // GTEST_USE_OWN_FLAGFILE_FLAG_
6723 // Parses the command line for Google Test flags, without initializing
6724 // other parts of Google Test. The type parameter CharType can be
6725 // instantiated to either char or wchar_t.
6726 template <typename CharType>
6727 void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) {
6728 for (int i = 1; i < *argc; i++) {
6729 const std::string arg_string = StreamableToString(argv[i]);
6730 const char* const arg = arg_string.c_str();
6732 using internal::ParseBoolFlag;
6733 using internal::ParseInt32Flag;
6734 using internal::ParseStringFlag;
6736 bool remove_flag = false;
6737 if (ParseGoogleTestFlag(arg)) {
6739 #if GTEST_USE_OWN_FLAGFILE_FLAG_
6740 } else if (ParseStringFlag(arg, kFlagfileFlag, >EST_FLAG(flagfile))) {
6741 LoadFlagsFromFile(GTEST_FLAG(flagfile));
6743 #endif // GTEST_USE_OWN_FLAGFILE_FLAG_
6744 } else if (arg_string == "--help" || arg_string == "-h" ||
6745 arg_string == "-?" || arg_string == "/?" ||
6746 HasGoogleTestFlagPrefix(arg)) {
6747 // Both help flag and unrecognized Google Test flags (excluding
6748 // internal ones) trigger help display.
6753 // Shift the remainder of the argv list left by one. Note
6754 // that argv has (*argc + 1) elements, the last one always being
6755 // NULL. The following loop moves the trailing NULL element as
6757 for (int j = i; j != *argc; j++) {
6758 argv[j] = argv[j + 1];
6761 // Decrements the argument count.
6764 // We also need to decrement the iterator as we just removed
6771 // We print the help here instead of in RUN_ALL_TESTS(), as the
6772 // latter may not be called at all if the user is using Google
6773 // Test with another testing framework.
6774 PrintColorEncoded(kColorEncodedHelpMessage);
6778 // Parses the command line for Google Test flags, without initializing
6779 // other parts of Google Test.
6780 void ParseGoogleTestFlagsOnly(int* argc, char** argv) {
6781 ParseGoogleTestFlagsOnlyImpl(argc, argv);
6783 void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv) {
6784 ParseGoogleTestFlagsOnlyImpl(argc, argv);
6787 // The internal implementation of InitGoogleTest().
6789 // The type parameter CharType can be instantiated to either char or
6791 template <typename CharType>
6792 void InitGoogleTestImpl(int* argc, CharType** argv) {
6793 // We don't want to run the initialization code twice.
6794 if (GTestIsInitialized()) return;
6796 if (*argc <= 0) return;
6799 for (int i = 0; i != *argc; i++) {
6800 g_argvs.push_back(StreamableToString(argv[i]));
6803 ParseGoogleTestFlagsOnly(argc, argv);
6804 GetUnitTestImpl()->PostFlagParsingInit();
6807 } // namespace internal
6809 // Initializes Google Test. This must be called before calling
6810 // RUN_ALL_TESTS(). In particular, it parses a command line for the
6811 // flags that Google Test recognizes. Whenever a Google Test flag is
6812 // seen, it is removed from argv, and *argc is decremented.
6814 // No value is returned. Instead, the Google Test flag variables are
6817 // Calling the function for the second time has no user-visible effect.
6818 void InitGoogleTest(int* argc, char** argv) {
6819 #if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
6820 GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv);
6821 #else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
6822 internal::InitGoogleTestImpl(argc, argv);
6823 #endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
6826 // This overloaded version can be used in Windows programs compiled in
6828 void InitGoogleTest(int* argc, wchar_t** argv) {
6829 #if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
6830 GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv);
6831 #else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
6832 internal::InitGoogleTestImpl(argc, argv);
6833 #endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)
6836 } // namespace testing
6837 // Copyright 2005, Google Inc.
6838 // All rights reserved.
6840 // Redistribution and use in source and binary forms, with or without
6841 // modification, are permitted provided that the following conditions are
6844 // * Redistributions of source code must retain the above copyright
6845 // notice, this list of conditions and the following disclaimer.
6846 // * Redistributions in binary form must reproduce the above
6847 // copyright notice, this list of conditions and the following disclaimer
6848 // in the documentation and/or other materials provided with the
6850 // * Neither the name of Google Inc. nor the names of its
6851 // contributors may be used to endorse or promote products derived from
6852 // this software without specific prior written permission.
6854 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
6855 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
6856 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
6857 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
6858 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
6859 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
6860 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
6861 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
6862 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
6863 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
6864 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
6866 // Author: wan@google.com (Zhanyong Wan), vladl@google.com (Vlad Losev)
6868 // This file implements death tests.
6871 #if GTEST_HAS_DEATH_TEST
6874 # include <crt_externs.h>
6875 # endif // GTEST_OS_MAC
6879 # include <limits.h>
6882 # include <signal.h>
6883 # endif // GTEST_OS_LINUX
6885 # include <stdarg.h>
6887 # if GTEST_OS_WINDOWS
6888 # include <windows.h>
6890 # include <sys/mman.h>
6891 # include <sys/wait.h>
6892 # endif // GTEST_OS_WINDOWS
6896 # endif // GTEST_OS_QNX
6898 #endif // GTEST_HAS_DEATH_TEST
6901 // Indicates that this translation unit is part of Google Test's
6902 // implementation. It must come before gtest-internal-inl.h is
6903 // included, or there will be a compiler error. This trick exists to
6904 // prevent the accidental inclusion of gtest-internal-inl.h in the
6906 #define GTEST_IMPLEMENTATION_ 1
6907 #undef GTEST_IMPLEMENTATION_
6913 // The default death test style.
6914 static const char kDefaultDeathTestStyle[] = "fast";
6916 GTEST_DEFINE_string_(
6918 internal::StringFromGTestEnv("death_test_style", kDefaultDeathTestStyle),
6919 "Indicates how to run a death test in a forked child process: "
6920 "\"threadsafe\" (child process re-executes the test binary "
6921 "from the beginning, running only the specific death test) or "
6922 "\"fast\" (child process runs the death test immediately "
6926 death_test_use_fork,
6927 internal::BoolFromGTestEnv("death_test_use_fork", false),
6928 "Instructs to use fork()/_exit() instead of clone() in death tests. "
6929 "Ignored and always uses fork() on POSIX systems where clone() is not "
6930 "implemented. Useful when running under valgrind or similar tools if "
6931 "those do not support clone(). Valgrind 3.3.1 will just fail if "
6932 "it sees an unsupported combination of clone() flags. "
6933 "It is not recommended to use this flag w/o valgrind though it will "
6934 "work in 99% of the cases. Once valgrind is fixed, this flag will "
6935 "most likely be removed.");
6937 namespace internal {
6938 GTEST_DEFINE_string_(
6939 internal_run_death_test, "",
6940 "Indicates the file, line number, temporal index of "
6941 "the single death test to run, and a file descriptor to "
6942 "which a success code may be sent, all separated by "
6943 "the '|' characters. This flag is specified if and only if the current "
6944 "process is a sub-process launched for running a thread-safe "
6945 "death test. FOR INTERNAL USE ONLY.");
6946 } // namespace internal
6948 #if GTEST_HAS_DEATH_TEST
6950 namespace internal {
6952 // Valid only for fast death tests. Indicates the code is running in the
6953 // child process of a fast style death test.
6954 # if !GTEST_OS_WINDOWS
6955 static bool g_in_fast_death_test_child = false;
6958 // Returns a Boolean value indicating whether the caller is currently
6959 // executing in the context of the death test child process. Tools such as
6960 // Valgrind heap checkers may need this to modify their behavior in death
6961 // tests. IMPORTANT: This is an internal utility. Using it may break the
6962 // implementation of death tests. User code MUST NOT use it.
6963 bool InDeathTestChild() {
6964 # if GTEST_OS_WINDOWS
6966 // On Windows, death tests are thread-safe regardless of the value of the
6967 // death_test_style flag.
6968 return !GTEST_FLAG(internal_run_death_test).empty();
6972 if (GTEST_FLAG(death_test_style) == "threadsafe")
6973 return !GTEST_FLAG(internal_run_death_test).empty();
6975 return g_in_fast_death_test_child;
6979 } // namespace internal
6981 // ExitedWithCode constructor.
6982 ExitedWithCode::ExitedWithCode(int exit_code) : exit_code_(exit_code) {
6985 // ExitedWithCode function-call operator.
6986 bool ExitedWithCode::operator()(int exit_status) const {
6987 # if GTEST_OS_WINDOWS
6989 return exit_status == exit_code_;
6993 return WIFEXITED(exit_status) && WEXITSTATUS(exit_status) == exit_code_;
6995 # endif // GTEST_OS_WINDOWS
6998 # if !GTEST_OS_WINDOWS
6999 // KilledBySignal constructor.
7000 KilledBySignal::KilledBySignal(int signum) : signum_(signum) {
7003 // KilledBySignal function-call operator.
7004 bool KilledBySignal::operator()(int exit_status) const {
7005 # if defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_)
7008 if (GTEST_KILLED_BY_SIGNAL_OVERRIDE_(signum_, exit_status, &result)) {
7012 # endif // defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_)
7013 return WIFSIGNALED(exit_status) && WTERMSIG(exit_status) == signum_;
7015 # endif // !GTEST_OS_WINDOWS
7017 namespace internal {
7019 // Utilities needed for death tests.
7021 // Generates a textual description of a given exit code, in the format
7022 // specified by wait(2).
7023 static std::string ExitSummary(int exit_code) {
7026 # if GTEST_OS_WINDOWS
7028 m << "Exited with exit status " << exit_code;
7032 if (WIFEXITED(exit_code)) {
7033 m << "Exited with exit status " << WEXITSTATUS(exit_code);
7034 } else if (WIFSIGNALED(exit_code)) {
7035 m << "Terminated by signal " << WTERMSIG(exit_code);
7038 if (WCOREDUMP(exit_code)) {
7039 m << " (core dumped)";
7042 # endif // GTEST_OS_WINDOWS
7044 return m.GetString();
7047 // Returns true if exit_status describes a process that was terminated
7048 // by a signal, or exited normally with a nonzero exit code.
7049 bool ExitedUnsuccessfully(int exit_status) {
7050 return !ExitedWithCode(0)(exit_status);
7053 # if !GTEST_OS_WINDOWS
7054 // Generates a textual failure message when a death test finds more than
7055 // one thread running, or cannot determine the number of threads, prior
7056 // to executing the given statement. It is the responsibility of the
7057 // caller not to pass a thread_count of 1.
7058 static std::string DeathTestThreadWarning(size_t thread_count) {
7060 msg << "Death tests use fork(), which is unsafe particularly"
7061 << " in a threaded context. For this test, " << GTEST_NAME_ << " ";
7062 if (thread_count == 0)
7063 msg << "couldn't detect the number of threads.";
7065 msg << "detected " << thread_count << " threads.";
7066 return msg.GetString();
7068 # endif // !GTEST_OS_WINDOWS
7070 // Flag characters for reporting a death test that did not die.
7071 static const char kDeathTestLived = 'L';
7072 static const char kDeathTestReturned = 'R';
7073 static const char kDeathTestThrew = 'T';
7074 static const char kDeathTestInternalError = 'I';
7076 // An enumeration describing all of the possible ways that a death test can
7077 // conclude. DIED means that the process died while executing the test
7078 // code; LIVED means that process lived beyond the end of the test code;
7079 // RETURNED means that the test statement attempted to execute a return
7080 // statement, which is not allowed; THREW means that the test statement
7081 // returned control by throwing an exception. IN_PROGRESS means the test
7082 // has not yet concluded.
7083 // TODO(vladl@google.com): Unify names and possibly values for
7084 // AbortReason, DeathTestOutcome, and flag characters above.
7085 enum DeathTestOutcome { IN_PROGRESS, DIED, LIVED, RETURNED, THREW };
7087 // Routine for aborting the program which is safe to call from an
7088 // exec-style death test child process, in which case the error
7089 // message is propagated back to the parent process. Otherwise, the
7090 // message is simply printed to stderr. In either case, the program
7091 // then exits with status 1.
7092 void DeathTestAbort(const std::string& message) {
7093 // On a POSIX system, this function may be called from a threadsafe-style
7094 // death test child process, which operates on a very small stack. Use
7095 // the heap for any additional non-minuscule memory requirements.
7096 const InternalRunDeathTestFlag* const flag =
7097 GetUnitTestImpl()->internal_run_death_test_flag();
7099 FILE* parent = posix::FDOpen(flag->write_fd(), "w");
7100 fputc(kDeathTestInternalError, parent);
7101 fprintf(parent, "%s", message.c_str());
7105 fprintf(stderr, "%s", message.c_str());
7111 // A replacement for CHECK that calls DeathTestAbort if the assertion
7113 # define GTEST_DEATH_TEST_CHECK_(expression) \
7115 if (!::testing::internal::IsTrue(expression)) { \
7117 ::std::string("CHECK failed: File ") + __FILE__ + ", line " \
7118 + ::testing::internal::StreamableToString(__LINE__) + ": " \
7121 } while (::testing::internal::AlwaysFalse())
7123 // This macro is similar to GTEST_DEATH_TEST_CHECK_, but it is meant for
7124 // evaluating any system call that fulfills two conditions: it must return
7125 // -1 on failure, and set errno to EINTR when it is interrupted and
7126 // should be tried again. The macro expands to a loop that repeatedly
7127 // evaluates the expression as long as it evaluates to -1 and sets
7128 // errno to EINTR. If the expression evaluates to -1 but errno is
7129 // something other than EINTR, DeathTestAbort is called.
7130 # define GTEST_DEATH_TEST_CHECK_SYSCALL_(expression) \
7134 gtest_retval = (expression); \
7135 } while (gtest_retval == -1 && errno == EINTR); \
7136 if (gtest_retval == -1) { \
7138 ::std::string("CHECK failed: File ") + __FILE__ + ", line " \
7139 + ::testing::internal::StreamableToString(__LINE__) + ": " \
7140 + #expression + " != -1"); \
7142 } while (::testing::internal::AlwaysFalse())
7144 // Returns the message describing the last system error in errno.
7145 std::string GetLastErrnoDescription() {
7146 return errno == 0 ? "" : posix::StrError(errno);
7149 // This is called from a death test parent process to read a failure
7150 // message from the death test child process and log it with the FATAL
7151 // severity. On Windows, the message is read from a pipe handle. On other
7152 // platforms, it is read from a file descriptor.
7153 static void FailFromInternalError(int fd) {
7159 while ((num_read = posix::Read(fd, buffer, 255)) > 0) {
7160 buffer[num_read] = '\0';
7163 } while (num_read == -1 && errno == EINTR);
7165 if (num_read == 0) {
7166 GTEST_LOG_(FATAL) << error.GetString();
7168 const int last_error = errno;
7169 GTEST_LOG_(FATAL) << "Error while reading death test internal: "
7170 << GetLastErrnoDescription() << " [" << last_error << "]";
7174 // Death test constructor. Increments the running death test count
7175 // for the current test.
7176 DeathTest::DeathTest() {
7177 TestInfo* const info = GetUnitTestImpl()->current_test_info();
7179 DeathTestAbort("Cannot run a death test outside of a TEST or "
7180 "TEST_F construct");
7184 // Creates and returns a death test by dispatching to the current
7185 // death test factory.
7186 bool DeathTest::Create(const char* statement, const RE* regex,
7187 const char* file, int line, DeathTest** test) {
7188 return GetUnitTestImpl()->death_test_factory()->Create(
7189 statement, regex, file, line, test);
7192 const char* DeathTest::LastMessage() {
7193 return last_death_test_message_.c_str();
7196 void DeathTest::set_last_death_test_message(const std::string& message) {
7197 last_death_test_message_ = message;
7200 std::string DeathTest::last_death_test_message_;
7202 // Provides cross platform implementation for some death functionality.
7203 class DeathTestImpl : public DeathTest {
7205 DeathTestImpl(const char* a_statement, const RE* a_regex)
7206 : statement_(a_statement),
7210 outcome_(IN_PROGRESS),
7214 // read_fd_ is expected to be closed and cleared by a derived class.
7215 ~DeathTestImpl() { GTEST_DEATH_TEST_CHECK_(read_fd_ == -1); }
7217 void Abort(AbortReason reason);
7218 virtual bool Passed(bool status_ok);
7220 const char* statement() const { return statement_; }
7221 const RE* regex() const { return regex_; }
7222 bool spawned() const { return spawned_; }
7223 void set_spawned(bool is_spawned) { spawned_ = is_spawned; }
7224 int status() const { return status_; }
7225 void set_status(int a_status) { status_ = a_status; }
7226 DeathTestOutcome outcome() const { return outcome_; }
7227 void set_outcome(DeathTestOutcome an_outcome) { outcome_ = an_outcome; }
7228 int read_fd() const { return read_fd_; }
7229 void set_read_fd(int fd) { read_fd_ = fd; }
7230 int write_fd() const { return write_fd_; }
7231 void set_write_fd(int fd) { write_fd_ = fd; }
7233 // Called in the parent process only. Reads the result code of the death
7234 // test child process via a pipe, interprets it to set the outcome_
7235 // member, and closes read_fd_. Outputs diagnostics and terminates in
7236 // case of unexpected codes.
7237 void ReadAndInterpretStatusByte();
7240 // The textual content of the code this object is testing. This class
7241 // doesn't own this string and should not attempt to delete it.
7242 const char* const statement_;
7243 // The regular expression which test output must match. DeathTestImpl
7244 // doesn't own this object and should not attempt to delete it.
7245 const RE* const regex_;
7246 // True if the death test child process has been successfully spawned.
7248 // The exit status of the child process.
7250 // How the death test concluded.
7251 DeathTestOutcome outcome_;
7252 // Descriptor to the read end of the pipe to the child process. It is
7253 // always -1 in the child process. The child keeps its write end of the
7254 // pipe in write_fd_.
7256 // Descriptor to the child's write end of the pipe to the parent process.
7257 // It is always -1 in the parent process. The parent keeps its end of the
7258 // pipe in read_fd_.
7262 // Called in the parent process only. Reads the result code of the death
7263 // test child process via a pipe, interprets it to set the outcome_
7264 // member, and closes read_fd_. Outputs diagnostics and terminates in
7265 // case of unexpected codes.
7266 void DeathTestImpl::ReadAndInterpretStatusByte() {
7270 // The read() here blocks until data is available (signifying the
7271 // failure of the death test) or until the pipe is closed (signifying
7272 // its success), so it's okay to call this in the parent before
7273 // the child process has exited.
7275 bytes_read = posix::Read(read_fd(), &flag, 1);
7276 } while (bytes_read == -1 && errno == EINTR);
7278 if (bytes_read == 0) {
7280 } else if (bytes_read == 1) {
7282 case kDeathTestReturned:
7283 set_outcome(RETURNED);
7285 case kDeathTestThrew:
7288 case kDeathTestLived:
7291 case kDeathTestInternalError:
7292 FailFromInternalError(read_fd()); // Does not return.
7295 GTEST_LOG_(FATAL) << "Death test child process reported "
7296 << "unexpected status byte ("
7297 << static_cast<unsigned int>(flag) << ")";
7300 GTEST_LOG_(FATAL) << "Read from death test child process failed: "
7301 << GetLastErrnoDescription();
7303 GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Close(read_fd()));
7307 // Signals that the death test code which should have exited, didn't.
7308 // Should be called only in a death test child process.
7309 // Writes a status byte to the child's status file descriptor, then
7311 void DeathTestImpl::Abort(AbortReason reason) {
7312 // The parent process considers the death test to be a failure if
7313 // it finds any data in our pipe. So, here we write a single flag byte
7314 // to the pipe, then exit.
7315 const char status_ch =
7316 reason == TEST_DID_NOT_DIE ? kDeathTestLived :
7317 reason == TEST_THREW_EXCEPTION ? kDeathTestThrew : kDeathTestReturned;
7319 GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Write(write_fd(), &status_ch, 1));
7320 // We are leaking the descriptor here because on some platforms (i.e.,
7321 // when built as Windows DLL), destructors of global objects will still
7322 // run after calling _exit(). On such systems, write_fd_ will be
7323 // indirectly closed from the destructor of UnitTestImpl, causing double
7324 // close if it is also closed here. On debug configurations, double close
7325 // may assert. As there are no in-process buffers to flush here, we are
7326 // relying on the OS to close the descriptor after the process terminates
7327 // when the destructors are not run.
7328 _exit(1); // Exits w/o any normal exit hooks (we were supposed to crash)
7331 // Returns an indented copy of stderr output for a death test.
7332 // This makes distinguishing death test output lines from regular log lines
7334 static ::std::string FormatDeathTestOutput(const ::std::string& output) {
7336 for (size_t at = 0; ; ) {
7337 const size_t line_end = output.find('\n', at);
7338 ret += "[ DEATH ] ";
7339 if (line_end == ::std::string::npos) {
7340 ret += output.substr(at);
7343 ret += output.substr(at, line_end + 1 - at);
7349 // Assesses the success or failure of a death test, using both private
7350 // members which have previously been set, and one argument:
7352 // Private data members:
7353 // outcome: An enumeration describing how the death test
7354 // concluded: DIED, LIVED, THREW, or RETURNED. The death test
7355 // fails in the latter three cases.
7356 // status: The exit status of the child process. On *nix, it is in the
7357 // in the format specified by wait(2). On Windows, this is the
7358 // value supplied to the ExitProcess() API or a numeric code
7359 // of the exception that terminated the program.
7360 // regex: A regular expression object to be applied to
7361 // the test's captured standard error output; the death test
7362 // fails if it does not match.
7365 // status_ok: true if exit_status is acceptable in the context of
7366 // this particular death test, which fails if it is false
7368 // Returns true iff all of the above conditions are met. Otherwise, the
7369 // first failing condition, in the order given above, is the one that is
7370 // reported. Also sets the last death test message string.
7371 bool DeathTestImpl::Passed(bool status_ok) {
7375 const std::string error_message = GetCapturedStderr();
7377 bool success = false;
7380 buffer << "Death test: " << statement() << "\n";
7381 switch (outcome()) {
7383 buffer << " Result: failed to die.\n"
7384 << " Error msg:\n" << FormatDeathTestOutput(error_message);
7387 buffer << " Result: threw an exception.\n"
7388 << " Error msg:\n" << FormatDeathTestOutput(error_message);
7391 buffer << " Result: illegal return in test statement.\n"
7392 << " Error msg:\n" << FormatDeathTestOutput(error_message);
7396 const bool matched = RE::PartialMatch(error_message.c_str(), *regex());
7400 buffer << " Result: died but not with expected error.\n"
7401 << " Expected: " << regex()->pattern() << "\n"
7402 << "Actual msg:\n" << FormatDeathTestOutput(error_message);
7405 buffer << " Result: died but not with expected exit code:\n"
7406 << " " << ExitSummary(status()) << "\n"
7407 << "Actual msg:\n" << FormatDeathTestOutput(error_message);
7413 << "DeathTest::Passed somehow called before conclusion of test";
7416 DeathTest::set_last_death_test_message(buffer.GetString());
7420 # if GTEST_OS_WINDOWS
7421 // WindowsDeathTest implements death tests on Windows. Due to the
7422 // specifics of starting new processes on Windows, death tests there are
7423 // always threadsafe, and Google Test considers the
7424 // --gtest_death_test_style=fast setting to be equivalent to
7425 // --gtest_death_test_style=threadsafe there.
7427 // A few implementation notes: Like the Linux version, the Windows
7428 // implementation uses pipes for child-to-parent communication. But due to
7429 // the specifics of pipes on Windows, some extra steps are required:
7431 // 1. The parent creates a communication pipe and stores handles to both
7433 // 2. The parent starts the child and provides it with the information
7434 // necessary to acquire the handle to the write end of the pipe.
7435 // 3. The child acquires the write end of the pipe and signals the parent
7436 // using a Windows event.
7437 // 4. Now the parent can release the write end of the pipe on its side. If
7438 // this is done before step 3, the object's reference count goes down to
7439 // 0 and it is destroyed, preventing the child from acquiring it. The
7440 // parent now has to release it, or read operations on the read end of
7441 // the pipe will not return when the child terminates.
7442 // 5. The parent reads child's output through the pipe (outcome code and
7443 // any possible error messages) from the pipe, and its stderr and then
7444 // determines whether to fail the test.
7446 // Note: to distinguish Win32 API calls from the local method and function
7447 // calls, the former are explicitly resolved in the global namespace.
7449 class WindowsDeathTest : public DeathTestImpl {
7451 WindowsDeathTest(const char* a_statement,
7455 : DeathTestImpl(a_statement, a_regex), file_(file), line_(line) {}
7457 // All of these virtual functions are inherited from DeathTest.
7459 virtual TestRole AssumeRole();
7462 // The name of the file in which the death test is located.
7463 const char* const file_;
7464 // The line number on which the death test is located.
7466 // Handle to the write end of the pipe to the child process.
7467 AutoHandle write_handle_;
7468 // Child process handle.
7469 AutoHandle child_handle_;
7470 // Event the child process uses to signal the parent that it has
7471 // acquired the handle to the write end of the pipe. After seeing this
7472 // event the parent can release its own handles to make sure its
7473 // ReadFile() calls return when the child terminates.
7474 AutoHandle event_handle_;
7477 // Waits for the child in a death test to exit, returning its exit
7478 // status, or 0 if no child process exists. As a side effect, sets the
7479 // outcome data member.
7480 int WindowsDeathTest::Wait() {
7484 // Wait until the child either signals that it has acquired the write end
7485 // of the pipe or it dies.
7486 const HANDLE wait_handles[2] = { child_handle_.Get(), event_handle_.Get() };
7487 switch (::WaitForMultipleObjects(2,
7489 FALSE, // Waits for any of the handles.
7492 case WAIT_OBJECT_0 + 1:
7495 GTEST_DEATH_TEST_CHECK_(false); // Should not get here.
7498 // The child has acquired the write end of the pipe or exited.
7499 // We release the handle on our side and continue.
7500 write_handle_.Reset();
7501 event_handle_.Reset();
7503 ReadAndInterpretStatusByte();
7505 // Waits for the child process to exit if it haven't already. This
7506 // returns immediately if the child has already exited, regardless of
7507 // whether previous calls to WaitForMultipleObjects synchronized on this
7509 GTEST_DEATH_TEST_CHECK_(
7510 WAIT_OBJECT_0 == ::WaitForSingleObject(child_handle_.Get(),
7513 GTEST_DEATH_TEST_CHECK_(
7514 ::GetExitCodeProcess(child_handle_.Get(), &status_code) != FALSE);
7515 child_handle_.Reset();
7516 set_status(static_cast<int>(status_code));
7520 // The AssumeRole process for a Windows death test. It creates a child
7521 // process with the same executable as the current process to run the
7522 // death test. The child process is given the --gtest_filter and
7523 // --gtest_internal_run_death_test flags such that it knows to run the
7524 // current death test only.
7525 DeathTest::TestRole WindowsDeathTest::AssumeRole() {
7526 const UnitTestImpl* const impl = GetUnitTestImpl();
7527 const InternalRunDeathTestFlag* const flag =
7528 impl->internal_run_death_test_flag();
7529 const TestInfo* const info = impl->current_test_info();
7530 const int death_test_index = info->result()->death_test_count();
7533 // ParseInternalRunDeathTestFlag() has performed all the necessary
7535 set_write_fd(flag->write_fd());
7536 return EXECUTE_TEST;
7539 // WindowsDeathTest uses an anonymous pipe to communicate results of
7541 SECURITY_ATTRIBUTES handles_are_inheritable = {
7542 sizeof(SECURITY_ATTRIBUTES), NULL, TRUE };
7543 HANDLE read_handle, write_handle;
7544 GTEST_DEATH_TEST_CHECK_(
7545 ::CreatePipe(&read_handle, &write_handle, &handles_are_inheritable,
7546 0) // Default buffer size.
7548 set_read_fd(::_open_osfhandle(reinterpret_cast<intptr_t>(read_handle),
7550 write_handle_.Reset(write_handle);
7551 event_handle_.Reset(::CreateEvent(
7552 &handles_are_inheritable,
7553 TRUE, // The event will automatically reset to non-signaled state.
7554 FALSE, // The initial state is non-signalled.
7555 NULL)); // The even is unnamed.
7556 GTEST_DEATH_TEST_CHECK_(event_handle_.Get() != NULL);
7557 const std::string filter_flag =
7558 std::string("--") + GTEST_FLAG_PREFIX_ + kFilterFlag + "=" +
7559 info->test_case_name() + "." + info->name();
7560 const std::string internal_flag =
7561 std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag +
7562 "=" + file_ + "|" + StreamableToString(line_) + "|" +
7563 StreamableToString(death_test_index) + "|" +
7564 StreamableToString(static_cast<unsigned int>(::GetCurrentProcessId())) +
7565 // size_t has the same width as pointers on both 32-bit and 64-bit
7566 // Windows platforms.
7567 // See http://msdn.microsoft.com/en-us/library/tcxf1dw6.aspx.
7568 "|" + StreamableToString(reinterpret_cast<size_t>(write_handle)) +
7569 "|" + StreamableToString(reinterpret_cast<size_t>(event_handle_.Get()));
7571 char executable_path[_MAX_PATH + 1]; // NOLINT
7572 GTEST_DEATH_TEST_CHECK_(
7573 _MAX_PATH + 1 != ::GetModuleFileNameA(NULL,
7577 std::string command_line =
7578 std::string(::GetCommandLineA()) + " " + filter_flag + " \"" +
7579 internal_flag + "\"";
7581 DeathTest::set_last_death_test_message("");
7584 // Flush the log buffers since the log streams are shared with the child.
7587 // The child process will share the standard handles with the parent.
7588 STARTUPINFOA startup_info;
7589 memset(&startup_info, 0, sizeof(STARTUPINFO));
7590 startup_info.dwFlags = STARTF_USESTDHANDLES;
7591 startup_info.hStdInput = ::GetStdHandle(STD_INPUT_HANDLE);
7592 startup_info.hStdOutput = ::GetStdHandle(STD_OUTPUT_HANDLE);
7593 startup_info.hStdError = ::GetStdHandle(STD_ERROR_HANDLE);
7595 PROCESS_INFORMATION process_info;
7596 GTEST_DEATH_TEST_CHECK_(::CreateProcessA(
7598 const_cast<char*>(command_line.c_str()),
7599 NULL, // Retuned process handle is not inheritable.
7600 NULL, // Retuned thread handle is not inheritable.
7601 TRUE, // Child inherits all inheritable handles (for write_handle_).
7602 0x0, // Default creation flags.
7603 NULL, // Inherit the parent's environment.
7604 UnitTest::GetInstance()->original_working_dir(),
7606 &process_info) != FALSE);
7607 child_handle_.Reset(process_info.hProcess);
7608 ::CloseHandle(process_info.hThread);
7610 return OVERSEE_TEST;
7612 # else // We are not on Windows.
7614 // ForkingDeathTest provides implementations for most of the abstract
7615 // methods of the DeathTest interface. Only the AssumeRole method is
7617 class ForkingDeathTest : public DeathTestImpl {
7619 ForkingDeathTest(const char* statement, const RE* regex);
7621 // All of these virtual functions are inherited from DeathTest.
7625 void set_child_pid(pid_t child_pid) { child_pid_ = child_pid; }
7628 // PID of child process during death test; 0 in the child process itself.
7632 // Constructs a ForkingDeathTest.
7633 ForkingDeathTest::ForkingDeathTest(const char* a_statement, const RE* a_regex)
7634 : DeathTestImpl(a_statement, a_regex),
7637 // Waits for the child in a death test to exit, returning its exit
7638 // status, or 0 if no child process exists. As a side effect, sets the
7639 // outcome data member.
7640 int ForkingDeathTest::Wait() {
7644 ReadAndInterpretStatusByte();
7647 GTEST_DEATH_TEST_CHECK_SYSCALL_(waitpid(child_pid_, &status_value, 0));
7648 set_status(status_value);
7649 return status_value;
7652 // A concrete death test class that forks, then immediately runs the test
7653 // in the child process.
7654 class NoExecDeathTest : public ForkingDeathTest {
7656 NoExecDeathTest(const char* a_statement, const RE* a_regex) :
7657 ForkingDeathTest(a_statement, a_regex) { }
7658 virtual TestRole AssumeRole();
7661 // The AssumeRole process for a fork-and-run death test. It implements a
7662 // straightforward fork, with a simple pipe to transmit the status byte.
7663 DeathTest::TestRole NoExecDeathTest::AssumeRole() {
7664 const size_t thread_count = GetThreadCount();
7665 if (thread_count != 1) {
7666 GTEST_LOG_(WARNING) << DeathTestThreadWarning(thread_count);
7670 GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
7672 DeathTest::set_last_death_test_message("");
7674 // When we fork the process below, the log file buffers are copied, but the
7675 // file descriptors are shared. We flush all log files here so that closing
7676 // the file descriptors in the child process doesn't throw off the
7677 // synchronization between descriptors and buffers in the parent process.
7678 // This is as close to the fork as possible to avoid a race condition in case
7679 // there are multiple threads running before the death test, and another
7680 // thread writes to the log file.
7683 const pid_t child_pid = fork();
7684 GTEST_DEATH_TEST_CHECK_(child_pid != -1);
7685 set_child_pid(child_pid);
7686 if (child_pid == 0) {
7687 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[0]));
7688 set_write_fd(pipe_fd[1]);
7689 // Redirects all logging to stderr in the child process to prevent
7690 // concurrent writes to the log files. We capture stderr in the parent
7691 // process and append the child process' output to a log.
7693 // Event forwarding to the listeners of event listener API mush be shut
7694 // down in death test subprocesses.
7695 GetUnitTestImpl()->listeners()->SuppressEventForwarding();
7696 g_in_fast_death_test_child = true;
7697 return EXECUTE_TEST;
7699 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
7700 set_read_fd(pipe_fd[0]);
7702 return OVERSEE_TEST;
7706 // A concrete death test class that forks and re-executes the main
7707 // program from the beginning, with command-line flags set that cause
7708 // only this specific death test to be run.
7709 class ExecDeathTest : public ForkingDeathTest {
7711 ExecDeathTest(const char* a_statement, const RE* a_regex,
7712 const char* file, int line) :
7713 ForkingDeathTest(a_statement, a_regex), file_(file), line_(line) { }
7714 virtual TestRole AssumeRole();
7716 static ::std::vector<testing::internal::string>
7717 GetArgvsForDeathTestChildProcess() {
7718 ::std::vector<testing::internal::string> args = GetInjectableArgvs();
7719 # if defined(GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_)
7720 ::std::vector<testing::internal::string> extra_args =
7721 GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_();
7722 args.insert(args.end(), extra_args.begin(), extra_args.end());
7723 # endif // defined(GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_)
7726 // The name of the file in which the death test is located.
7727 const char* const file_;
7728 // The line number on which the death test is located.
7732 // Utility class for accumulating command-line arguments.
7736 args_.push_back(NULL);
7740 for (std::vector<char*>::iterator i = args_.begin(); i != args_.end();
7745 void AddArgument(const char* argument) {
7746 args_.insert(args_.end() - 1, posix::StrDup(argument));
7749 template <typename Str>
7750 void AddArguments(const ::std::vector<Str>& arguments) {
7751 for (typename ::std::vector<Str>::const_iterator i = arguments.begin();
7752 i != arguments.end();
7754 args_.insert(args_.end() - 1, posix::StrDup(i->c_str()));
7757 char* const* Argv() {
7762 std::vector<char*> args_;
7765 // A struct that encompasses the arguments to the child process of a
7766 // threadsafe-style death test process.
7767 struct ExecDeathTestArgs {
7768 char* const* argv; // Command-line arguments for the child's call to exec
7769 int close_fd; // File descriptor to close; the read end of a pipe
7773 inline char** GetEnviron() {
7774 // When Google Test is built as a framework on MacOS X, the environ variable
7775 // is unavailable. Apple's documentation (man environ) recommends using
7776 // _NSGetEnviron() instead.
7777 return *_NSGetEnviron();
7780 // Some POSIX platforms expect you to declare environ. extern "C" makes
7781 // it reside in the global namespace.
7782 extern "C" char** environ;
7783 inline char** GetEnviron() { return environ; }
7784 # endif // GTEST_OS_MAC
7787 // The main function for a threadsafe-style death test child process.
7788 // This function is called in a clone()-ed process and thus must avoid
7789 // any potentially unsafe operations like malloc or libc functions.
7790 static int ExecDeathTestChildMain(void* child_arg) {
7791 ExecDeathTestArgs* const args = static_cast<ExecDeathTestArgs*>(child_arg);
7792 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(args->close_fd));
7794 // We need to execute the test program in the same environment where
7795 // it was originally invoked. Therefore we change to the original
7796 // working directory first.
7797 const char* const original_dir =
7798 UnitTest::GetInstance()->original_working_dir();
7799 // We can safely call chdir() as it's a direct system call.
7800 if (chdir(original_dir) != 0) {
7801 DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " +
7802 GetLastErrnoDescription());
7803 return EXIT_FAILURE;
7806 // We can safely call execve() as it's a direct system call. We
7807 // cannot use execvp() as it's a libc function and thus potentially
7808 // unsafe. Since execve() doesn't search the PATH, the user must
7809 // invoke the test program via a valid path that contains at least
7810 // one path separator.
7811 execve(args->argv[0], args->argv, GetEnviron());
7812 DeathTestAbort(std::string("execve(") + args->argv[0] + ", ...) in " +
7813 original_dir + " failed: " +
7814 GetLastErrnoDescription());
7815 return EXIT_FAILURE;
7817 # endif // !GTEST_OS_QNX
7819 // Two utility routines that together determine the direction the stack
7821 // This could be accomplished more elegantly by a single recursive
7822 // function, but we want to guard against the unlikely possibility of
7823 // a smart compiler optimizing the recursion away.
7825 // GTEST_NO_INLINE_ is required to prevent GCC 4.6 from inlining
7826 // StackLowerThanAddress into StackGrowsDown, which then doesn't give
7828 void StackLowerThanAddress(const void* ptr, bool* result) GTEST_NO_INLINE_;
7829 void StackLowerThanAddress(const void* ptr, bool* result) {
7831 *result = (&dummy < ptr);
7834 // Make sure AddressSanitizer does not tamper with the stack here.
7835 GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
7836 bool StackGrowsDown() {
7839 StackLowerThanAddress(&dummy, &result);
7843 // Spawns a child process with the same executable as the current process in
7844 // a thread-safe manner and instructs it to run the death test. The
7845 // implementation uses fork(2) + exec. On systems where clone(2) is
7846 // available, it is used instead, being slightly more thread-safe. On QNX,
7847 // fork supports only single-threaded environments, so this function uses
7848 // spawn(2) there instead. The function dies with an error message if
7849 // anything goes wrong.
7850 static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) {
7851 ExecDeathTestArgs args = { argv, close_fd };
7852 pid_t child_pid = -1;
7855 // Obtains the current directory and sets it to be closed in the child
7857 const int cwd_fd = open(".", O_RDONLY);
7858 GTEST_DEATH_TEST_CHECK_(cwd_fd != -1);
7859 GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(cwd_fd, F_SETFD, FD_CLOEXEC));
7860 // We need to execute the test program in the same environment where
7861 // it was originally invoked. Therefore we change to the original
7862 // working directory first.
7863 const char* const original_dir =
7864 UnitTest::GetInstance()->original_working_dir();
7865 // We can safely call chdir() as it's a direct system call.
7866 if (chdir(original_dir) != 0) {
7867 DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " +
7868 GetLastErrnoDescription());
7869 return EXIT_FAILURE;
7873 // Set close_fd to be closed after spawn.
7874 GTEST_DEATH_TEST_CHECK_SYSCALL_(fd_flags = fcntl(close_fd, F_GETFD));
7875 GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(close_fd, F_SETFD,
7876 fd_flags | FD_CLOEXEC));
7877 struct inheritance inherit = {0};
7878 // spawn is a system call.
7879 child_pid = spawn(args.argv[0], 0, NULL, &inherit, args.argv, GetEnviron());
7880 // Restores the current working directory.
7881 GTEST_DEATH_TEST_CHECK_(fchdir(cwd_fd) != -1);
7882 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(cwd_fd));
7884 # else // GTEST_OS_QNX
7886 // When a SIGPROF signal is received while fork() or clone() are executing,
7887 // the process may hang. To avoid this, we ignore SIGPROF here and re-enable
7888 // it after the call to fork()/clone() is complete.
7889 struct sigaction saved_sigprof_action;
7890 struct sigaction ignore_sigprof_action;
7891 memset(&ignore_sigprof_action, 0, sizeof(ignore_sigprof_action));
7892 sigemptyset(&ignore_sigprof_action.sa_mask);
7893 ignore_sigprof_action.sa_handler = SIG_IGN;
7894 GTEST_DEATH_TEST_CHECK_SYSCALL_(sigaction(
7895 SIGPROF, &ignore_sigprof_action, &saved_sigprof_action));
7896 # endif // GTEST_OS_LINUX
7898 # if GTEST_HAS_CLONE
7899 const bool use_fork = GTEST_FLAG(death_test_use_fork);
7902 static const bool stack_grows_down = StackGrowsDown();
7903 const size_t stack_size = getpagesize();
7904 // MMAP_ANONYMOUS is not defined on Mac, so we use MAP_ANON instead.
7905 void* const stack = mmap(NULL, stack_size, PROT_READ | PROT_WRITE,
7906 MAP_ANON | MAP_PRIVATE, -1, 0);
7907 GTEST_DEATH_TEST_CHECK_(stack != MAP_FAILED);
7909 // Maximum stack alignment in bytes: For a downward-growing stack, this
7910 // amount is subtracted from size of the stack space to get an address
7911 // that is within the stack space and is aligned on all systems we care
7912 // about. As far as I know there is no ABI with stack alignment greater
7913 // than 64. We assume stack and stack_size already have alignment of
7914 // kMaxStackAlignment.
7915 const size_t kMaxStackAlignment = 64;
7916 void* const stack_top =
7917 static_cast<char*>(stack) +
7918 (stack_grows_down ? stack_size - kMaxStackAlignment : 0);
7919 GTEST_DEATH_TEST_CHECK_(stack_size > kMaxStackAlignment &&
7920 reinterpret_cast<intptr_t>(stack_top) % kMaxStackAlignment == 0);
7922 child_pid = clone(&ExecDeathTestChildMain, stack_top, SIGCHLD, &args);
7924 GTEST_DEATH_TEST_CHECK_(munmap(stack, stack_size) != -1);
7927 const bool use_fork = true;
7928 # endif // GTEST_HAS_CLONE
7930 if (use_fork && (child_pid = fork()) == 0) {
7931 ExecDeathTestChildMain(&args);
7934 # endif // GTEST_OS_QNX
7936 GTEST_DEATH_TEST_CHECK_SYSCALL_(
7937 sigaction(SIGPROF, &saved_sigprof_action, NULL));
7938 # endif // GTEST_OS_LINUX
7940 GTEST_DEATH_TEST_CHECK_(child_pid != -1);
7944 // The AssumeRole process for a fork-and-exec death test. It re-executes the
7945 // main program from the beginning, setting the --gtest_filter
7946 // and --gtest_internal_run_death_test flags to cause only the current
7947 // death test to be re-run.
7948 DeathTest::TestRole ExecDeathTest::AssumeRole() {
7949 const UnitTestImpl* const impl = GetUnitTestImpl();
7950 const InternalRunDeathTestFlag* const flag =
7951 impl->internal_run_death_test_flag();
7952 const TestInfo* const info = impl->current_test_info();
7953 const int death_test_index = info->result()->death_test_count();
7956 set_write_fd(flag->write_fd());
7957 return EXECUTE_TEST;
7961 GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
7962 // Clear the close-on-exec flag on the write end of the pipe, lest
7963 // it be closed when the child process does an exec:
7964 GTEST_DEATH_TEST_CHECK_(fcntl(pipe_fd[1], F_SETFD, 0) != -1);
7966 const std::string filter_flag =
7967 std::string("--") + GTEST_FLAG_PREFIX_ + kFilterFlag + "="
7968 + info->test_case_name() + "." + info->name();
7969 const std::string internal_flag =
7970 std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag + "="
7971 + file_ + "|" + StreamableToString(line_) + "|"
7972 + StreamableToString(death_test_index) + "|"
7973 + StreamableToString(pipe_fd[1]);
7975 args.AddArguments(GetArgvsForDeathTestChildProcess());
7976 args.AddArgument(filter_flag.c_str());
7977 args.AddArgument(internal_flag.c_str());
7979 DeathTest::set_last_death_test_message("");
7982 // See the comment in NoExecDeathTest::AssumeRole for why the next line
7986 const pid_t child_pid = ExecDeathTestSpawnChild(args.Argv(), pipe_fd[0]);
7987 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
7988 set_child_pid(child_pid);
7989 set_read_fd(pipe_fd[0]);
7991 return OVERSEE_TEST;
7994 # endif // !GTEST_OS_WINDOWS
7996 // Creates a concrete DeathTest-derived class that depends on the
7997 // --gtest_death_test_style flag, and sets the pointer pointed to
7998 // by the "test" argument to its address. If the test should be
7999 // skipped, sets that pointer to NULL. Returns true, unless the
8000 // flag is set to an invalid value.
8001 bool DefaultDeathTestFactory::Create(const char* statement, const RE* regex,
8002 const char* file, int line,
8004 UnitTestImpl* const impl = GetUnitTestImpl();
8005 const InternalRunDeathTestFlag* const flag =
8006 impl->internal_run_death_test_flag();
8007 const int death_test_index = impl->current_test_info()
8008 ->increment_death_test_count();
8011 if (death_test_index > flag->index()) {
8012 DeathTest::set_last_death_test_message(
8013 "Death test count (" + StreamableToString(death_test_index)
8014 + ") somehow exceeded expected maximum ("
8015 + StreamableToString(flag->index()) + ")");
8019 if (!(flag->file() == file && flag->line() == line &&
8020 flag->index() == death_test_index)) {
8026 # if GTEST_OS_WINDOWS
8028 if (GTEST_FLAG(death_test_style) == "threadsafe" ||
8029 GTEST_FLAG(death_test_style) == "fast") {
8030 *test = new WindowsDeathTest(statement, regex, file, line);
8035 if (GTEST_FLAG(death_test_style) == "threadsafe") {
8036 *test = new ExecDeathTest(statement, regex, file, line);
8037 } else if (GTEST_FLAG(death_test_style) == "fast") {
8038 *test = new NoExecDeathTest(statement, regex);
8041 # endif // GTEST_OS_WINDOWS
8043 else { // NOLINT - this is more readable than unbalanced brackets inside #if.
8044 DeathTest::set_last_death_test_message(
8045 "Unknown death test style \"" + GTEST_FLAG(death_test_style)
8046 + "\" encountered");
8053 # if GTEST_OS_WINDOWS
8054 // Recreates the pipe and event handles from the provided parameters,
8055 // signals the event, and returns a file descriptor wrapped around the pipe
8056 // handle. This function is called in the child process only.
8057 int GetStatusFileDescriptor(unsigned int parent_process_id,
8058 size_t write_handle_as_size_t,
8059 size_t event_handle_as_size_t) {
8060 AutoHandle parent_process_handle(::OpenProcess(PROCESS_DUP_HANDLE,
8061 FALSE, // Non-inheritable.
8062 parent_process_id));
8063 if (parent_process_handle.Get() == INVALID_HANDLE_VALUE) {
8064 DeathTestAbort("Unable to open parent process " +
8065 StreamableToString(parent_process_id));
8068 // TODO(vladl@google.com): Replace the following check with a
8069 // compile-time assertion when available.
8070 GTEST_CHECK_(sizeof(HANDLE) <= sizeof(size_t));
8072 const HANDLE write_handle =
8073 reinterpret_cast<HANDLE>(write_handle_as_size_t);
8074 HANDLE dup_write_handle;
8076 // The newly initialized handle is accessible only in in the parent
8077 // process. To obtain one accessible within the child, we need to use
8079 if (!::DuplicateHandle(parent_process_handle.Get(), write_handle,
8080 ::GetCurrentProcess(), &dup_write_handle,
8081 0x0, // Requested privileges ignored since
8082 // DUPLICATE_SAME_ACCESS is used.
8083 FALSE, // Request non-inheritable handler.
8084 DUPLICATE_SAME_ACCESS)) {
8085 DeathTestAbort("Unable to duplicate the pipe handle " +
8086 StreamableToString(write_handle_as_size_t) +
8087 " from the parent process " +
8088 StreamableToString(parent_process_id));
8091 const HANDLE event_handle = reinterpret_cast<HANDLE>(event_handle_as_size_t);
8092 HANDLE dup_event_handle;
8094 if (!::DuplicateHandle(parent_process_handle.Get(), event_handle,
8095 ::GetCurrentProcess(), &dup_event_handle,
8098 DUPLICATE_SAME_ACCESS)) {
8099 DeathTestAbort("Unable to duplicate the event handle " +
8100 StreamableToString(event_handle_as_size_t) +
8101 " from the parent process " +
8102 StreamableToString(parent_process_id));
8105 const int write_fd =
8106 ::_open_osfhandle(reinterpret_cast<intptr_t>(dup_write_handle), O_APPEND);
8107 if (write_fd == -1) {
8108 DeathTestAbort("Unable to convert pipe handle " +
8109 StreamableToString(write_handle_as_size_t) +
8110 " to a file descriptor");
8113 // Signals the parent that the write end of the pipe has been acquired
8114 // so the parent can release its own write end.
8115 ::SetEvent(dup_event_handle);
8119 # endif // GTEST_OS_WINDOWS
8121 // Returns a newly created InternalRunDeathTestFlag object with fields
8122 // initialized from the GTEST_FLAG(internal_run_death_test) flag if
8123 // the flag is specified; otherwise returns NULL.
8124 InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() {
8125 if (GTEST_FLAG(internal_run_death_test) == "") return NULL;
8127 // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we
8131 ::std::vector< ::std::string> fields;
8132 SplitString(GTEST_FLAG(internal_run_death_test).c_str(), '|', &fields);
8135 # if GTEST_OS_WINDOWS
8137 unsigned int parent_process_id = 0;
8138 size_t write_handle_as_size_t = 0;
8139 size_t event_handle_as_size_t = 0;
8141 if (fields.size() != 6
8142 || !ParseNaturalNumber(fields[1], &line)
8143 || !ParseNaturalNumber(fields[2], &index)
8144 || !ParseNaturalNumber(fields[3], &parent_process_id)
8145 || !ParseNaturalNumber(fields[4], &write_handle_as_size_t)
8146 || !ParseNaturalNumber(fields[5], &event_handle_as_size_t)) {
8147 DeathTestAbort("Bad --gtest_internal_run_death_test flag: " +
8148 GTEST_FLAG(internal_run_death_test));
8150 write_fd = GetStatusFileDescriptor(parent_process_id,
8151 write_handle_as_size_t,
8152 event_handle_as_size_t);
8155 if (fields.size() != 4
8156 || !ParseNaturalNumber(fields[1], &line)
8157 || !ParseNaturalNumber(fields[2], &index)
8158 || !ParseNaturalNumber(fields[3], &write_fd)) {
8159 DeathTestAbort("Bad --gtest_internal_run_death_test flag: "
8160 + GTEST_FLAG(internal_run_death_test));
8163 # endif // GTEST_OS_WINDOWS
8165 return new InternalRunDeathTestFlag(fields[0], line, index, write_fd);
8168 } // namespace internal
8170 #endif // GTEST_HAS_DEATH_TEST
8172 } // namespace testing
8173 // Copyright 2008, Google Inc.
8174 // All rights reserved.
8176 // Redistribution and use in source and binary forms, with or without
8177 // modification, are permitted provided that the following conditions are
8180 // * Redistributions of source code must retain the above copyright
8181 // notice, this list of conditions and the following disclaimer.
8182 // * Redistributions in binary form must reproduce the above
8183 // copyright notice, this list of conditions and the following disclaimer
8184 // in the documentation and/or other materials provided with the
8186 // * Neither the name of Google Inc. nor the names of its
8187 // contributors may be used to endorse or promote products derived from
8188 // this software without specific prior written permission.
8190 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
8191 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
8192 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
8193 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
8194 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
8195 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
8196 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
8197 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
8198 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
8199 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
8200 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
8202 // Authors: keith.ray@gmail.com (Keith Ray)
8207 #if GTEST_OS_WINDOWS_MOBILE
8208 # include <windows.h>
8209 #elif GTEST_OS_WINDOWS
8210 # include <direct.h>
8212 #elif GTEST_OS_SYMBIAN
8213 // Symbian OpenC has PATH_MAX in sys/syslimits.h
8214 # include <sys/syslimits.h>
8216 # include <limits.h>
8217 # include <climits> // Some Linux distributions define PATH_MAX here.
8218 #endif // GTEST_OS_WINDOWS_MOBILE
8220 #if GTEST_OS_WINDOWS
8221 # define GTEST_PATH_MAX_ _MAX_PATH
8222 #elif defined(PATH_MAX)
8223 # define GTEST_PATH_MAX_ PATH_MAX
8224 #elif defined(_XOPEN_PATH_MAX)
8225 # define GTEST_PATH_MAX_ _XOPEN_PATH_MAX
8227 # define GTEST_PATH_MAX_ _POSIX_PATH_MAX
8228 #endif // GTEST_OS_WINDOWS
8232 namespace internal {
8234 #if GTEST_OS_WINDOWS
8235 // On Windows, '\\' is the standard path separator, but many tools and the
8236 // Windows API also accept '/' as an alternate path separator. Unless otherwise
8237 // noted, a file path can contain either kind of path separators, or a mixture
8239 const char kPathSeparator = '\\';
8240 const char kAlternatePathSeparator = '/';
8241 const char kAlternatePathSeparatorString[] = "/";
8242 # if GTEST_OS_WINDOWS_MOBILE
8243 // Windows CE doesn't have a current directory. You should not use
8244 // the current directory in tests on Windows CE, but this at least
8245 // provides a reasonable fallback.
8246 const char kCurrentDirectoryString[] = "\\";
8247 // Windows CE doesn't define INVALID_FILE_ATTRIBUTES
8248 const DWORD kInvalidFileAttributes = 0xffffffff;
8250 const char kCurrentDirectoryString[] = ".\\";
8251 # endif // GTEST_OS_WINDOWS_MOBILE
8253 const char kPathSeparator = '/';
8254 const char kCurrentDirectoryString[] = "./";
8255 #endif // GTEST_OS_WINDOWS
8257 // Returns whether the given character is a valid path separator.
8258 static bool IsPathSeparator(char c) {
8259 #if GTEST_HAS_ALT_PATH_SEP_
8260 return (c == kPathSeparator) || (c == kAlternatePathSeparator);
8262 return c == kPathSeparator;
8266 // Returns the current working directory, or "" if unsuccessful.
8267 FilePath FilePath::GetCurrentDir() {
8268 #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT
8269 // Windows CE doesn't have a current directory, so we just return
8270 // something reasonable.
8271 return FilePath(kCurrentDirectoryString);
8272 #elif GTEST_OS_WINDOWS
8273 char cwd[GTEST_PATH_MAX_ + 1] = { '\0' };
8274 return FilePath(_getcwd(cwd, sizeof(cwd)) == NULL ? "" : cwd);
8276 char cwd[GTEST_PATH_MAX_ + 1] = { '\0' };
8277 char* result = getcwd(cwd, sizeof(cwd));
8279 // getcwd will likely fail in NaCl due to the sandbox, so return something
8280 // reasonable. The user may have provided a shim implementation for getcwd,
8281 // however, so fallback only when failure is detected.
8282 return FilePath(result == NULL ? kCurrentDirectoryString : cwd);
8283 # endif // GTEST_OS_NACL
8284 return FilePath(result == NULL ? "" : cwd);
8285 #endif // GTEST_OS_WINDOWS_MOBILE
8288 // Returns a copy of the FilePath with the case-insensitive extension removed.
8289 // Example: FilePath("dir/file.exe").RemoveExtension("EXE") returns
8290 // FilePath("dir/file"). If a case-insensitive extension is not
8291 // found, returns a copy of the original FilePath.
8292 FilePath FilePath::RemoveExtension(const char* extension) const {
8293 const std::string dot_extension = std::string(".") + extension;
8294 if (String::EndsWithCaseInsensitive(pathname_, dot_extension)) {
8295 return FilePath(pathname_.substr(
8296 0, pathname_.length() - dot_extension.length()));
8301 // Returns a pointer to the last occurence of a valid path separator in
8302 // the FilePath. On Windows, for example, both '/' and '\' are valid path
8303 // separators. Returns NULL if no path separator was found.
8304 const char* FilePath::FindLastPathSeparator() const {
8305 const char* const last_sep = strrchr(c_str(), kPathSeparator);
8306 #if GTEST_HAS_ALT_PATH_SEP_
8307 const char* const last_alt_sep = strrchr(c_str(), kAlternatePathSeparator);
8308 // Comparing two pointers of which only one is NULL is undefined.
8309 if (last_alt_sep != NULL &&
8310 (last_sep == NULL || last_alt_sep > last_sep)) {
8311 return last_alt_sep;
8317 // Returns a copy of the FilePath with the directory part removed.
8318 // Example: FilePath("path/to/file").RemoveDirectoryName() returns
8319 // FilePath("file"). If there is no directory part ("just_a_file"), it returns
8320 // the FilePath unmodified. If there is no file part ("just_a_dir/") it
8321 // returns an empty FilePath ("").
8322 // On Windows platform, '\' is the path separator, otherwise it is '/'.
8323 FilePath FilePath::RemoveDirectoryName() const {
8324 const char* const last_sep = FindLastPathSeparator();
8325 return last_sep ? FilePath(last_sep + 1) : *this;
8328 // RemoveFileName returns the directory path with the filename removed.
8329 // Example: FilePath("path/to/file").RemoveFileName() returns "path/to/".
8330 // If the FilePath is "a_file" or "/a_file", RemoveFileName returns
8331 // FilePath("./") or, on Windows, FilePath(".\\"). If the filepath does
8332 // not have a file, like "just/a/dir/", it returns the FilePath unmodified.
8333 // On Windows platform, '\' is the path separator, otherwise it is '/'.
8334 FilePath FilePath::RemoveFileName() const {
8335 const char* const last_sep = FindLastPathSeparator();
8338 dir = std::string(c_str(), last_sep + 1 - c_str());
8340 dir = kCurrentDirectoryString;
8342 return FilePath(dir);
8345 // Helper functions for naming files in a directory for xml output.
8347 // Given directory = "dir", base_name = "test", number = 0,
8348 // extension = "xml", returns "dir/test.xml". If number is greater
8349 // than zero (e.g., 12), returns "dir/test_12.xml".
8350 // On Windows platform, uses \ as the separator rather than /.
8351 FilePath FilePath::MakeFileName(const FilePath& directory,
8352 const FilePath& base_name,
8354 const char* extension) {
8357 file = base_name.string() + "." + extension;
8359 file = base_name.string() + "_" + StreamableToString(number)
8362 return ConcatPaths(directory, FilePath(file));
8365 // Given directory = "dir", relative_path = "test.xml", returns "dir/test.xml".
8366 // On Windows, uses \ as the separator rather than /.
8367 FilePath FilePath::ConcatPaths(const FilePath& directory,
8368 const FilePath& relative_path) {
8369 if (directory.IsEmpty())
8370 return relative_path;
8371 const FilePath dir(directory.RemoveTrailingPathSeparator());
8372 return FilePath(dir.string() + kPathSeparator + relative_path.string());
8375 // Returns true if pathname describes something findable in the file-system,
8376 // either a file, directory, or whatever.
8377 bool FilePath::FileOrDirectoryExists() const {
8378 #if GTEST_OS_WINDOWS_MOBILE
8379 LPCWSTR unicode = String::AnsiToUtf16(pathname_.c_str());
8380 const DWORD attributes = GetFileAttributes(unicode);
8382 return attributes != kInvalidFileAttributes;
8384 posix::StatStruct file_stat;
8385 return posix::Stat(pathname_.c_str(), &file_stat) == 0;
8386 #endif // GTEST_OS_WINDOWS_MOBILE
8389 // Returns true if pathname describes a directory in the file-system
8391 bool FilePath::DirectoryExists() const {
8392 bool result = false;
8393 #if GTEST_OS_WINDOWS
8394 // Don't strip off trailing separator if path is a root directory on
8395 // Windows (like "C:\\").
8396 const FilePath& path(IsRootDirectory() ? *this :
8397 RemoveTrailingPathSeparator());
8399 const FilePath& path(*this);
8402 #if GTEST_OS_WINDOWS_MOBILE
8403 LPCWSTR unicode = String::AnsiToUtf16(path.c_str());
8404 const DWORD attributes = GetFileAttributes(unicode);
8406 if ((attributes != kInvalidFileAttributes) &&
8407 (attributes & FILE_ATTRIBUTE_DIRECTORY)) {
8411 posix::StatStruct file_stat;
8412 result = posix::Stat(path.c_str(), &file_stat) == 0 &&
8413 posix::IsDir(file_stat);
8414 #endif // GTEST_OS_WINDOWS_MOBILE
8419 // Returns true if pathname describes a root directory. (Windows has one
8420 // root directory per disk drive.)
8421 bool FilePath::IsRootDirectory() const {
8422 #if GTEST_OS_WINDOWS
8423 // TODO(wan@google.com): on Windows a network share like
8424 // \\server\share can be a root directory, although it cannot be the
8425 // current directory. Handle this properly.
8426 return pathname_.length() == 3 && IsAbsolutePath();
8428 return pathname_.length() == 1 && IsPathSeparator(pathname_.c_str()[0]);
8432 // Returns true if pathname describes an absolute path.
8433 bool FilePath::IsAbsolutePath() const {
8434 const char* const name = pathname_.c_str();
8435 #if GTEST_OS_WINDOWS
8436 return pathname_.length() >= 3 &&
8437 ((name[0] >= 'a' && name[0] <= 'z') ||
8438 (name[0] >= 'A' && name[0] <= 'Z')) &&
8440 IsPathSeparator(name[2]);
8442 return IsPathSeparator(name[0]);
8446 // Returns a pathname for a file that does not currently exist. The pathname
8447 // will be directory/base_name.extension or
8448 // directory/base_name_<number>.extension if directory/base_name.extension
8449 // already exists. The number will be incremented until a pathname is found
8450 // that does not already exist.
8451 // Examples: 'dir/foo_test.xml' or 'dir/foo_test_1.xml'.
8452 // There could be a race condition if two or more processes are calling this
8453 // function at the same time -- they could both pick the same filename.
8454 FilePath FilePath::GenerateUniqueFileName(const FilePath& directory,
8455 const FilePath& base_name,
8456 const char* extension) {
8457 FilePath full_pathname;
8460 full_pathname.Set(MakeFileName(directory, base_name, number++, extension));
8461 } while (full_pathname.FileOrDirectoryExists());
8462 return full_pathname;
8465 // Returns true if FilePath ends with a path separator, which indicates that
8466 // it is intended to represent a directory. Returns false otherwise.
8467 // This does NOT check that a directory (or file) actually exists.
8468 bool FilePath::IsDirectory() const {
8469 return !pathname_.empty() &&
8470 IsPathSeparator(pathname_.c_str()[pathname_.length() - 1]);
8473 // Create directories so that path exists. Returns true if successful or if
8474 // the directories already exist; returns false if unable to create directories
8476 bool FilePath::CreateDirectoriesRecursively() const {
8477 if (!this->IsDirectory()) {
8481 if (pathname_.length() == 0 || this->DirectoryExists()) {
8485 const FilePath parent(this->RemoveTrailingPathSeparator().RemoveFileName());
8486 return parent.CreateDirectoriesRecursively() && this->CreateFolder();
8489 // Create the directory so that path exists. Returns true if successful or
8490 // if the directory already exists; returns false if unable to create the
8491 // directory for any reason, including if the parent directory does not
8492 // exist. Not named "CreateDirectory" because that's a macro on Windows.
8493 bool FilePath::CreateFolder() const {
8494 #if GTEST_OS_WINDOWS_MOBILE
8495 FilePath removed_sep(this->RemoveTrailingPathSeparator());
8496 LPCWSTR unicode = String::AnsiToUtf16(removed_sep.c_str());
8497 int result = CreateDirectory(unicode, NULL) ? 0 : -1;
8499 #elif GTEST_OS_WINDOWS
8500 int result = _mkdir(pathname_.c_str());
8502 int result = mkdir(pathname_.c_str(), 0777);
8503 #endif // GTEST_OS_WINDOWS_MOBILE
8506 return this->DirectoryExists(); // An error is OK if the directory exists.
8508 return true; // No error.
8511 // If input name has a trailing separator character, remove it and return the
8512 // name, otherwise return the name string unmodified.
8513 // On Windows platform, uses \ as the separator, other platforms use /.
8514 FilePath FilePath::RemoveTrailingPathSeparator() const {
8515 return IsDirectory()
8516 ? FilePath(pathname_.substr(0, pathname_.length() - 1))
8520 // Removes any redundant separators that might be in the pathname.
8521 // For example, "bar///foo" becomes "bar/foo". Does not eliminate other
8522 // redundancies that might be in a pathname involving "." or "..".
8523 // TODO(wan@google.com): handle Windows network shares (e.g. \\server\share).
8524 void FilePath::Normalize() {
8525 if (pathname_.c_str() == NULL) {
8529 const char* src = pathname_.c_str();
8530 char* const dest = new char[pathname_.length() + 1];
8531 char* dest_ptr = dest;
8532 memset(dest_ptr, 0, pathname_.length() + 1);
8534 while (*src != '\0') {
8536 if (!IsPathSeparator(*src)) {
8539 #if GTEST_HAS_ALT_PATH_SEP_
8540 if (*dest_ptr == kAlternatePathSeparator) {
8541 *dest_ptr = kPathSeparator;
8544 while (IsPathSeparator(*src))
8554 } // namespace internal
8555 } // namespace testing
8556 // Copyright 2008, Google Inc.
8557 // All rights reserved.
8559 // Redistribution and use in source and binary forms, with or without
8560 // modification, are permitted provided that the following conditions are
8563 // * Redistributions of source code must retain the above copyright
8564 // notice, this list of conditions and the following disclaimer.
8565 // * Redistributions in binary form must reproduce the above
8566 // copyright notice, this list of conditions and the following disclaimer
8567 // in the documentation and/or other materials provided with the
8569 // * Neither the name of Google Inc. nor the names of its
8570 // contributors may be used to endorse or promote products derived from
8571 // this software without specific prior written permission.
8573 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
8574 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
8575 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
8576 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
8577 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
8578 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
8579 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
8580 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
8581 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
8582 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
8583 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
8585 // Author: wan@google.com (Zhanyong Wan)
8594 #if GTEST_OS_WINDOWS
8595 # include <windows.h>
8597 # include <sys/stat.h>
8598 # include <map> // Used in ThreadLocal.
8600 # include <unistd.h>
8601 #endif // GTEST_OS_WINDOWS
8604 # include <mach/mach_init.h>
8605 # include <mach/task.h>
8606 # include <mach/vm_map.h>
8607 #endif // GTEST_OS_MAC
8610 # include <devctl.h>
8612 # include <sys/procfs.h>
8613 #endif // GTEST_OS_QNX
8616 # include <procinfo.h>
8617 # include <sys/types.h>
8618 #endif // GTEST_OS_AIX
8621 // Indicates that this translation unit is part of Google Test's
8622 // implementation. It must come before gtest-internal-inl.h is
8623 // included, or there will be a compiler error. This trick exists to
8624 // prevent the accidental inclusion of gtest-internal-inl.h in the
8626 #define GTEST_IMPLEMENTATION_ 1
8627 #undef GTEST_IMPLEMENTATION_
8630 namespace internal {
8632 #if defined(_MSC_VER) || defined(__BORLANDC__)
8633 // MSVC and C++Builder do not provide a definition of STDERR_FILENO.
8634 const int kStdOutFileno = 1;
8635 const int kStdErrFileno = 2;
8637 const int kStdOutFileno = STDOUT_FILENO;
8638 const int kStdErrFileno = STDERR_FILENO;
8644 template <typename T>
8645 T ReadProcFileField(const string& filename, int field) {
8647 std::ifstream file(filename.c_str());
8648 while (field-- > 0) {
8657 // Returns the number of active threads, or 0 when there is an error.
8658 size_t GetThreadCount() {
8659 const string filename =
8660 (Message() << "/proc/" << getpid() << "/stat").GetString();
8661 return ReadProcFileField<int>(filename, 19);
8666 size_t GetThreadCount() {
8667 const task_t task = mach_task_self();
8668 mach_msg_type_number_t thread_count;
8669 thread_act_array_t thread_list;
8670 const kern_return_t status = task_threads(task, &thread_list, &thread_count);
8671 if (status == KERN_SUCCESS) {
8672 // task_threads allocates resources in thread_list and we need to free them
8675 reinterpret_cast<vm_address_t>(thread_list),
8676 sizeof(thread_t) * thread_count);
8677 return static_cast<size_t>(thread_count);
8685 // Returns the number of threads running in the process, or 0 to indicate that
8686 // we cannot detect it.
8687 size_t GetThreadCount() {
8688 const int fd = open("/proc/self/as", O_RDONLY);
8692 procfs_info process_info;
8694 devctl(fd, DCMD_PROC_INFO, &process_info, sizeof(process_info), NULL);
8696 if (status == EOK) {
8697 return static_cast<size_t>(process_info.num_threads);
8705 size_t GetThreadCount() {
8706 struct procentry64 entry;
8707 pid_t pid = getpid();
8708 int status = getprocs64(&entry, sizeof(entry), NULL, 0, &pid, 1);
8710 return entry.pi_thcount;
8718 size_t GetThreadCount() {
8719 // There's no portable way to detect the number of threads, so we just
8720 // return 0 to indicate that we cannot detect it.
8724 #endif // GTEST_OS_LINUX
8726 #if GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS
8728 void SleepMilliseconds(int n) {
8732 AutoHandle::AutoHandle()
8733 : handle_(INVALID_HANDLE_VALUE) {}
8735 AutoHandle::AutoHandle(Handle handle)
8736 : handle_(handle) {}
8738 AutoHandle::~AutoHandle() {
8742 AutoHandle::Handle AutoHandle::Get() const {
8746 void AutoHandle::Reset() {
8747 Reset(INVALID_HANDLE_VALUE);
8750 void AutoHandle::Reset(HANDLE handle) {
8751 // Resetting with the same handle we already own is invalid.
8752 if (handle_ != handle) {
8753 if (IsCloseable()) {
8754 ::CloseHandle(handle_);
8758 GTEST_CHECK_(!IsCloseable())
8759 << "Resetting a valid handle to itself is likely a programmer error "
8760 "and thus not allowed.";
8764 bool AutoHandle::IsCloseable() const {
8765 // Different Windows APIs may use either of these values to represent an
8767 return handle_ != NULL && handle_ != INVALID_HANDLE_VALUE;
8770 Notification::Notification()
8771 : event_(::CreateEvent(NULL, // Default security attributes.
8772 TRUE, // Do not reset automatically.
8773 FALSE, // Initially unset.
8774 NULL)) { // Anonymous event.
8775 GTEST_CHECK_(event_.Get() != NULL);
8778 void Notification::Notify() {
8779 GTEST_CHECK_(::SetEvent(event_.Get()) != FALSE);
8782 void Notification::WaitForNotification() {
8784 ::WaitForSingleObject(event_.Get(), INFINITE) == WAIT_OBJECT_0);
8788 : owner_thread_id_(0),
8790 critical_section_init_phase_(0),
8791 critical_section_(new CRITICAL_SECTION) {
8792 ::InitializeCriticalSection(critical_section_);
8796 // Static mutexes are leaked intentionally. It is not thread-safe to try
8797 // to clean them up.
8798 // TODO(yukawa): Switch to Slim Reader/Writer (SRW) Locks, which requires
8799 // nothing to clean it up but is available only on Vista and later.
8800 // http://msdn.microsoft.com/en-us/library/windows/desktop/aa904937.aspx
8801 if (type_ == kDynamic) {
8802 ::DeleteCriticalSection(critical_section_);
8803 delete critical_section_;
8804 critical_section_ = NULL;
8808 void Mutex::Lock() {
8809 ThreadSafeLazyInit();
8810 ::EnterCriticalSection(critical_section_);
8811 owner_thread_id_ = ::GetCurrentThreadId();
8814 void Mutex::Unlock() {
8815 ThreadSafeLazyInit();
8816 // We don't protect writing to owner_thread_id_ here, as it's the
8817 // caller's responsibility to ensure that the current thread holds the
8818 // mutex when this is called.
8819 owner_thread_id_ = 0;
8820 ::LeaveCriticalSection(critical_section_);
8823 // Does nothing if the current thread holds the mutex. Otherwise, crashes
8824 // with high probability.
8825 void Mutex::AssertHeld() {
8826 ThreadSafeLazyInit();
8827 GTEST_CHECK_(owner_thread_id_ == ::GetCurrentThreadId())
8828 << "The current thread is not holding the mutex @" << this;
8831 // Initializes owner_thread_id_ and critical_section_ in static mutexes.
8832 void Mutex::ThreadSafeLazyInit() {
8833 // Dynamic mutexes are initialized in the constructor.
8834 if (type_ == kStatic) {
8836 ::InterlockedCompareExchange(&critical_section_init_phase_, 1L, 0L)) {
8838 // If critical_section_init_phase_ was 0 before the exchange, we
8839 // are the first to test it and need to perform the initialization.
8840 owner_thread_id_ = 0;
8841 critical_section_ = new CRITICAL_SECTION;
8842 ::InitializeCriticalSection(critical_section_);
8843 // Updates the critical_section_init_phase_ to 2 to signal
8844 // initialization complete.
8845 GTEST_CHECK_(::InterlockedCompareExchange(
8846 &critical_section_init_phase_, 2L, 1L) ==
8850 // Somebody else is already initializing the mutex; spin until they
8852 while (::InterlockedCompareExchange(&critical_section_init_phase_,
8855 // Possibly yields the rest of the thread's time slice to other
8862 break; // The mutex is already initialized and ready for use.
8866 << "Unexpected value of critical_section_init_phase_ "
8867 << "while initializing a static mutex.";
8874 class ThreadWithParamSupport : public ThreadWithParamBase {
8876 static HANDLE CreateThread(Runnable* runnable,
8877 Notification* thread_can_start) {
8878 ThreadMainParam* param = new ThreadMainParam(runnable, thread_can_start);
8880 // TODO(yukawa): Consider to use _beginthreadex instead.
8881 HANDLE thread_handle = ::CreateThread(
8882 NULL, // Default security.
8883 0, // Default stack size.
8884 &ThreadWithParamSupport::ThreadMain,
8885 param, // Parameter to ThreadMainStatic
8886 0x0, // Default creation flags.
8887 &thread_id); // Need a valid pointer for the call to work under Win98.
8888 GTEST_CHECK_(thread_handle != NULL) << "CreateThread failed with error "
8889 << ::GetLastError() << ".";
8890 if (thread_handle == NULL) {
8893 return thread_handle;
8897 struct ThreadMainParam {
8898 ThreadMainParam(Runnable* runnable, Notification* thread_can_start)
8899 : runnable_(runnable),
8900 thread_can_start_(thread_can_start) {
8902 scoped_ptr<Runnable> runnable_;
8904 Notification* thread_can_start_;
8907 static DWORD WINAPI ThreadMain(void* ptr) {
8908 // Transfers ownership.
8909 scoped_ptr<ThreadMainParam> param(static_cast<ThreadMainParam*>(ptr));
8910 if (param->thread_can_start_ != NULL)
8911 param->thread_can_start_->WaitForNotification();
8912 param->runnable_->Run();
8916 // Prohibit instantiation.
8917 ThreadWithParamSupport();
8919 GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParamSupport);
8924 ThreadWithParamBase::ThreadWithParamBase(Runnable *runnable,
8925 Notification* thread_can_start)
8926 : thread_(ThreadWithParamSupport::CreateThread(runnable,
8927 thread_can_start)) {
8930 ThreadWithParamBase::~ThreadWithParamBase() {
8934 void ThreadWithParamBase::Join() {
8935 GTEST_CHECK_(::WaitForSingleObject(thread_.Get(), INFINITE) == WAIT_OBJECT_0)
8936 << "Failed to join the thread with error " << ::GetLastError() << ".";
8939 // Maps a thread to a set of ThreadIdToThreadLocals that have values
8940 // instantiated on that thread and notifies them when the thread exits. A
8941 // ThreadLocal instance is expected to persist until all threads it has
8942 // values on have terminated.
8943 class ThreadLocalRegistryImpl {
8945 // Registers thread_local_instance as having value on the current thread.
8946 // Returns a value that can be used to identify the thread from other threads.
8947 static ThreadLocalValueHolderBase* GetValueOnCurrentThread(
8948 const ThreadLocalBase* thread_local_instance) {
8949 DWORD current_thread = ::GetCurrentThreadId();
8950 MutexLock lock(&mutex_);
8951 ThreadIdToThreadLocals* const thread_to_thread_locals =
8952 GetThreadLocalsMapLocked();
8953 ThreadIdToThreadLocals::iterator thread_local_pos =
8954 thread_to_thread_locals->find(current_thread);
8955 if (thread_local_pos == thread_to_thread_locals->end()) {
8956 thread_local_pos = thread_to_thread_locals->insert(
8957 std::make_pair(current_thread, ThreadLocalValues())).first;
8958 StartWatcherThreadFor(current_thread);
8960 ThreadLocalValues& thread_local_values = thread_local_pos->second;
8961 ThreadLocalValues::iterator value_pos =
8962 thread_local_values.find(thread_local_instance);
8963 if (value_pos == thread_local_values.end()) {
8966 .insert(std::make_pair(
8967 thread_local_instance,
8968 linked_ptr<ThreadLocalValueHolderBase>(
8969 thread_local_instance->NewValueForCurrentThread())))
8972 return value_pos->second.get();
8975 static void OnThreadLocalDestroyed(
8976 const ThreadLocalBase* thread_local_instance) {
8977 std::vector<linked_ptr<ThreadLocalValueHolderBase> > value_holders;
8978 // Clean up the ThreadLocalValues data structure while holding the lock, but
8979 // defer the destruction of the ThreadLocalValueHolderBases.
8981 MutexLock lock(&mutex_);
8982 ThreadIdToThreadLocals* const thread_to_thread_locals =
8983 GetThreadLocalsMapLocked();
8984 for (ThreadIdToThreadLocals::iterator it =
8985 thread_to_thread_locals->begin();
8986 it != thread_to_thread_locals->end();
8988 ThreadLocalValues& thread_local_values = it->second;
8989 ThreadLocalValues::iterator value_pos =
8990 thread_local_values.find(thread_local_instance);
8991 if (value_pos != thread_local_values.end()) {
8992 value_holders.push_back(value_pos->second);
8993 thread_local_values.erase(value_pos);
8994 // This 'if' can only be successful at most once, so theoretically we
8995 // could break out of the loop here, but we don't bother doing so.
8999 // Outside the lock, let the destructor for 'value_holders' deallocate the
9000 // ThreadLocalValueHolderBases.
9003 static void OnThreadExit(DWORD thread_id) {
9004 GTEST_CHECK_(thread_id != 0) << ::GetLastError();
9005 std::vector<linked_ptr<ThreadLocalValueHolderBase> > value_holders;
9006 // Clean up the ThreadIdToThreadLocals data structure while holding the
9007 // lock, but defer the destruction of the ThreadLocalValueHolderBases.
9009 MutexLock lock(&mutex_);
9010 ThreadIdToThreadLocals* const thread_to_thread_locals =
9011 GetThreadLocalsMapLocked();
9012 ThreadIdToThreadLocals::iterator thread_local_pos =
9013 thread_to_thread_locals->find(thread_id);
9014 if (thread_local_pos != thread_to_thread_locals->end()) {
9015 ThreadLocalValues& thread_local_values = thread_local_pos->second;
9016 for (ThreadLocalValues::iterator value_pos =
9017 thread_local_values.begin();
9018 value_pos != thread_local_values.end();
9020 value_holders.push_back(value_pos->second);
9022 thread_to_thread_locals->erase(thread_local_pos);
9025 // Outside the lock, let the destructor for 'value_holders' deallocate the
9026 // ThreadLocalValueHolderBases.
9030 // In a particular thread, maps a ThreadLocal object to its value.
9031 typedef std::map<const ThreadLocalBase*,
9032 linked_ptr<ThreadLocalValueHolderBase> > ThreadLocalValues;
9033 // Stores all ThreadIdToThreadLocals having values in a thread, indexed by
9035 typedef std::map<DWORD, ThreadLocalValues> ThreadIdToThreadLocals;
9037 // Holds the thread id and thread handle that we pass from
9038 // StartWatcherThreadFor to WatcherThreadFunc.
9039 typedef std::pair<DWORD, HANDLE> ThreadIdAndHandle;
9041 static void StartWatcherThreadFor(DWORD thread_id) {
9042 // The returned handle will be kept in thread_map and closed by
9043 // watcher_thread in WatcherThreadFunc.
9044 HANDLE thread = ::OpenThread(SYNCHRONIZE | THREAD_QUERY_INFORMATION,
9047 GTEST_CHECK_(thread != NULL);
9048 // We need to to pass a valid thread ID pointer into CreateThread for it
9049 // to work correctly under Win98.
9050 DWORD watcher_thread_id;
9051 HANDLE watcher_thread = ::CreateThread(
9052 NULL, // Default security.
9053 0, // Default stack size
9054 &ThreadLocalRegistryImpl::WatcherThreadFunc,
9055 reinterpret_cast<LPVOID>(new ThreadIdAndHandle(thread_id, thread)),
9057 &watcher_thread_id);
9058 GTEST_CHECK_(watcher_thread != NULL);
9059 // Give the watcher thread the same priority as ours to avoid being
9061 ::SetThreadPriority(watcher_thread,
9062 ::GetThreadPriority(::GetCurrentThread()));
9063 ::ResumeThread(watcher_thread);
9064 ::CloseHandle(watcher_thread);
9067 // Monitors exit from a given thread and notifies those
9068 // ThreadIdToThreadLocals about thread termination.
9069 static DWORD WINAPI WatcherThreadFunc(LPVOID param) {
9070 const ThreadIdAndHandle* tah =
9071 reinterpret_cast<const ThreadIdAndHandle*>(param);
9073 ::WaitForSingleObject(tah->second, INFINITE) == WAIT_OBJECT_0);
9074 OnThreadExit(tah->first);
9075 ::CloseHandle(tah->second);
9080 // Returns map of thread local instances.
9081 static ThreadIdToThreadLocals* GetThreadLocalsMapLocked() {
9082 mutex_.AssertHeld();
9083 static ThreadIdToThreadLocals* map = new ThreadIdToThreadLocals;
9087 // Protects access to GetThreadLocalsMapLocked() and its return value.
9088 static Mutex mutex_;
9089 // Protects access to GetThreadMapLocked() and its return value.
9090 static Mutex thread_map_mutex_;
9093 Mutex ThreadLocalRegistryImpl::mutex_(Mutex::kStaticMutex);
9094 Mutex ThreadLocalRegistryImpl::thread_map_mutex_(Mutex::kStaticMutex);
9096 ThreadLocalValueHolderBase* ThreadLocalRegistry::GetValueOnCurrentThread(
9097 const ThreadLocalBase* thread_local_instance) {
9098 return ThreadLocalRegistryImpl::GetValueOnCurrentThread(
9099 thread_local_instance);
9102 void ThreadLocalRegistry::OnThreadLocalDestroyed(
9103 const ThreadLocalBase* thread_local_instance) {
9104 ThreadLocalRegistryImpl::OnThreadLocalDestroyed(thread_local_instance);
9107 #endif // GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS
9109 #if GTEST_USES_POSIX_RE
9111 // Implements RE. Currently only needed for death tests.
9115 // regfree'ing an invalid regex might crash because the content
9116 // of the regex is undefined. Since the regex's are essentially
9117 // the same, one cannot be valid (or invalid) without the other
9119 regfree(&partial_regex_);
9120 regfree(&full_regex_);
9122 free(const_cast<char*>(pattern_));
9125 // Returns true iff regular expression re matches the entire str.
9126 bool RE::FullMatch(const char* str, const RE& re) {
9127 if (!re.is_valid_) return false;
9130 return regexec(&re.full_regex_, str, 1, &match, 0) == 0;
9133 // Returns true iff regular expression re matches a substring of str
9134 // (including str itself).
9135 bool RE::PartialMatch(const char* str, const RE& re) {
9136 if (!re.is_valid_) return false;
9139 return regexec(&re.partial_regex_, str, 1, &match, 0) == 0;
9142 // Initializes an RE from its string representation.
9143 void RE::Init(const char* regex) {
9144 pattern_ = posix::StrDup(regex);
9146 // Reserves enough bytes to hold the regular expression used for a
9148 const size_t full_regex_len = strlen(regex) + 10;
9149 char* const full_pattern = new char[full_regex_len];
9151 snprintf(full_pattern, full_regex_len, "^(%s)$", regex);
9152 is_valid_ = regcomp(&full_regex_, full_pattern, REG_EXTENDED) == 0;
9153 // We want to call regcomp(&partial_regex_, ...) even if the
9154 // previous expression returns false. Otherwise partial_regex_ may
9155 // not be properly initialized can may cause trouble when it's
9158 // Some implementation of POSIX regex (e.g. on at least some
9159 // versions of Cygwin) doesn't accept the empty string as a valid
9160 // regex. We change it to an equivalent form "()" to be safe.
9162 const char* const partial_regex = (*regex == '\0') ? "()" : regex;
9163 is_valid_ = regcomp(&partial_regex_, partial_regex, REG_EXTENDED) == 0;
9165 EXPECT_TRUE(is_valid_)
9166 << "Regular expression \"" << regex
9167 << "\" is not a valid POSIX Extended regular expression.";
9169 delete[] full_pattern;
9172 #elif GTEST_USES_SIMPLE_RE
9174 // Returns true iff ch appears anywhere in str (excluding the
9175 // terminating '\0' character).
9176 bool IsInSet(char ch, const char* str) {
9177 return ch != '\0' && strchr(str, ch) != NULL;
9180 // Returns true iff ch belongs to the given classification. Unlike
9181 // similar functions in <ctype.h>, these aren't affected by the
9183 bool IsAsciiDigit(char ch) { return '0' <= ch && ch <= '9'; }
9184 bool IsAsciiPunct(char ch) {
9185 return IsInSet(ch, "^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~");
9187 bool IsRepeat(char ch) { return IsInSet(ch, "?*+"); }
9188 bool IsAsciiWhiteSpace(char ch) { return IsInSet(ch, " \f\n\r\t\v"); }
9189 bool IsAsciiWordChar(char ch) {
9190 return ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') ||
9191 ('0' <= ch && ch <= '9') || ch == '_';
9194 // Returns true iff "\\c" is a supported escape sequence.
9195 bool IsValidEscape(char c) {
9196 return (IsAsciiPunct(c) || IsInSet(c, "dDfnrsStvwW"));
9199 // Returns true iff the given atom (specified by escaped and pattern)
9200 // matches ch. The result is undefined if the atom is invalid.
9201 bool AtomMatchesChar(bool escaped, char pattern_char, char ch) {
9202 if (escaped) { // "\\p" where p is pattern_char.
9203 switch (pattern_char) {
9204 case 'd': return IsAsciiDigit(ch);
9205 case 'D': return !IsAsciiDigit(ch);
9206 case 'f': return ch == '\f';
9207 case 'n': return ch == '\n';
9208 case 'r': return ch == '\r';
9209 case 's': return IsAsciiWhiteSpace(ch);
9210 case 'S': return !IsAsciiWhiteSpace(ch);
9211 case 't': return ch == '\t';
9212 case 'v': return ch == '\v';
9213 case 'w': return IsAsciiWordChar(ch);
9214 case 'W': return !IsAsciiWordChar(ch);
9216 return IsAsciiPunct(pattern_char) && pattern_char == ch;
9219 return (pattern_char == '.' && ch != '\n') || pattern_char == ch;
9222 // Helper function used by ValidateRegex() to format error messages.
9223 std::string FormatRegexSyntaxError(const char* regex, int index) {
9224 return (Message() << "Syntax error at index " << index
9225 << " in simple regular expression \"" << regex << "\": ").GetString();
9228 // Generates non-fatal failures and returns false if regex is invalid;
9229 // otherwise returns true.
9230 bool ValidateRegex(const char* regex) {
9231 if (regex == NULL) {
9232 // TODO(wan@google.com): fix the source file location in the
9233 // assertion failures to match where the regex is used in user
9235 ADD_FAILURE() << "NULL is not a valid simple regular expression.";
9239 bool is_valid = true;
9241 // True iff ?, *, or + can follow the previous atom.
9242 bool prev_repeatable = false;
9243 for (int i = 0; regex[i]; i++) {
9244 if (regex[i] == '\\') { // An escape sequence
9246 if (regex[i] == '\0') {
9247 ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
9248 << "'\\' cannot appear at the end.";
9252 if (!IsValidEscape(regex[i])) {
9253 ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
9254 << "invalid escape sequence \"\\" << regex[i] << "\".";
9257 prev_repeatable = true;
9258 } else { // Not an escape sequence.
9259 const char ch = regex[i];
9261 if (ch == '^' && i > 0) {
9262 ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
9263 << "'^' can only appear at the beginning.";
9265 } else if (ch == '$' && regex[i + 1] != '\0') {
9266 ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
9267 << "'$' can only appear at the end.";
9269 } else if (IsInSet(ch, "()[]{}|")) {
9270 ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
9271 << "'" << ch << "' is unsupported.";
9273 } else if (IsRepeat(ch) && !prev_repeatable) {
9274 ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
9275 << "'" << ch << "' can only follow a repeatable token.";
9279 prev_repeatable = !IsInSet(ch, "^$?*+");
9286 // Matches a repeated regex atom followed by a valid simple regular
9287 // expression. The regex atom is defined as c if escaped is false,
9288 // or \c otherwise. repeat is the repetition meta character (?, *,
9289 // or +). The behavior is undefined if str contains too many
9290 // characters to be indexable by size_t, in which case the test will
9291 // probably time out anyway. We are fine with this limitation as
9292 // std::string has it too.
9293 bool MatchRepetitionAndRegexAtHead(
9294 bool escaped, char c, char repeat, const char* regex,
9296 const size_t min_count = (repeat == '+') ? 1 : 0;
9297 const size_t max_count = (repeat == '?') ? 1 :
9298 static_cast<size_t>(-1) - 1;
9299 // We cannot call numeric_limits::max() as it conflicts with the
9300 // max() macro on Windows.
9302 for (size_t i = 0; i <= max_count; ++i) {
9303 // We know that the atom matches each of the first i characters in str.
9304 if (i >= min_count && MatchRegexAtHead(regex, str + i)) {
9305 // We have enough matches at the head, and the tail matches too.
9306 // Since we only care about *whether* the pattern matches str
9307 // (as opposed to *how* it matches), there is no need to find a
9311 if (str[i] == '\0' || !AtomMatchesChar(escaped, c, str[i]))
9317 // Returns true iff regex matches a prefix of str. regex must be a
9318 // valid simple regular expression and not start with "^", or the
9319 // result is undefined.
9320 bool MatchRegexAtHead(const char* regex, const char* str) {
9321 if (*regex == '\0') // An empty regex matches a prefix of anything.
9324 // "$" only matches the end of a string. Note that regex being
9325 // valid guarantees that there's nothing after "$" in it.
9327 return *str == '\0';
9329 // Is the first thing in regex an escape sequence?
9330 const bool escaped = *regex == '\\';
9333 if (IsRepeat(regex[1])) {
9334 // MatchRepetitionAndRegexAtHead() calls MatchRegexAtHead(), so
9335 // here's an indirect recursion. It terminates as the regex gets
9336 // shorter in each recursion.
9337 return MatchRepetitionAndRegexAtHead(
9338 escaped, regex[0], regex[1], regex + 2, str);
9340 // regex isn't empty, isn't "$", and doesn't start with a
9341 // repetition. We match the first atom of regex with the first
9342 // character of str and recurse.
9343 return (*str != '\0') && AtomMatchesChar(escaped, *regex, *str) &&
9344 MatchRegexAtHead(regex + 1, str + 1);
9348 // Returns true iff regex matches any substring of str. regex must be
9349 // a valid simple regular expression, or the result is undefined.
9351 // The algorithm is recursive, but the recursion depth doesn't exceed
9352 // the regex length, so we won't need to worry about running out of
9353 // stack space normally. In rare cases the time complexity can be
9354 // exponential with respect to the regex length + the string length,
9355 // but usually it's must faster (often close to linear).
9356 bool MatchRegexAnywhere(const char* regex, const char* str) {
9357 if (regex == NULL || str == NULL)
9361 return MatchRegexAtHead(regex + 1, str);
9363 // A successful match can be anywhere in str.
9365 if (MatchRegexAtHead(regex, str))
9367 } while (*str++ != '\0');
9371 // Implements the RE class.
9374 free(const_cast<char*>(pattern_));
9375 free(const_cast<char*>(full_pattern_));
9378 // Returns true iff regular expression re matches the entire str.
9379 bool RE::FullMatch(const char* str, const RE& re) {
9380 return re.is_valid_ && MatchRegexAnywhere(re.full_pattern_, str);
9383 // Returns true iff regular expression re matches a substring of str
9384 // (including str itself).
9385 bool RE::PartialMatch(const char* str, const RE& re) {
9386 return re.is_valid_ && MatchRegexAnywhere(re.pattern_, str);
9389 // Initializes an RE from its string representation.
9390 void RE::Init(const char* regex) {
9391 pattern_ = full_pattern_ = NULL;
9392 if (regex != NULL) {
9393 pattern_ = posix::StrDup(regex);
9396 is_valid_ = ValidateRegex(regex);
9398 // No need to calculate the full pattern when the regex is invalid.
9402 const size_t len = strlen(regex);
9403 // Reserves enough bytes to hold the regular expression used for a
9404 // full match: we need space to prepend a '^', append a '$', and
9405 // terminate the string with '\0'.
9406 char* buffer = static_cast<char*>(malloc(len + 3));
9407 full_pattern_ = buffer;
9410 *buffer++ = '^'; // Makes sure full_pattern_ starts with '^'.
9412 // We don't use snprintf or strncpy, as they trigger a warning when
9413 // compiled with VC++ 8.0.
9414 memcpy(buffer, regex, len);
9417 if (len == 0 || regex[len - 1] != '$')
9418 *buffer++ = '$'; // Makes sure full_pattern_ ends with '$'.
9423 #endif // GTEST_USES_POSIX_RE
9425 const char kUnknownFile[] = "unknown file";
9427 // Formats a source file path and a line number as they would appear
9428 // in an error message from the compiler used to compile this code.
9429 GTEST_API_ ::std::string FormatFileLocation(const char* file, int line) {
9430 const std::string file_name(file == NULL ? kUnknownFile : file);
9433 return file_name + ":";
9436 return file_name + "(" + StreamableToString(line) + "):";
9438 return file_name + ":" + StreamableToString(line) + ":";
9442 // Formats a file location for compiler-independent XML output.
9443 // Although this function is not platform dependent, we put it next to
9444 // FormatFileLocation in order to contrast the two functions.
9445 // Note that FormatCompilerIndependentFileLocation() does NOT append colon
9446 // to the file location it produces, unlike FormatFileLocation().
9447 GTEST_API_ ::std::string FormatCompilerIndependentFileLocation(
9448 const char* file, int line) {
9449 const std::string file_name(file == NULL ? kUnknownFile : file);
9454 return file_name + ":" + StreamableToString(line);
9457 GTestLog::GTestLog(GTestLogSeverity severity, const char* file, int line)
9458 : severity_(severity) {
9459 const char* const marker =
9460 severity == GTEST_INFO ? "[ INFO ]" :
9461 severity == GTEST_WARNING ? "[WARNING]" :
9462 severity == GTEST_ERROR ? "[ ERROR ]" : "[ FATAL ]";
9463 GetStream() << ::std::endl << marker << " "
9464 << FormatFileLocation(file, line).c_str() << ": ";
9467 // Flushes the buffers and, if severity is GTEST_FATAL, aborts the program.
9468 GTestLog::~GTestLog() {
9469 GetStream() << ::std::endl;
9470 if (severity_ == GTEST_FATAL) {
9475 // Disable Microsoft deprecation warnings for POSIX functions called from
9476 // this class (creat, dup, dup2, and close)
9477 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4996)
9479 #if GTEST_HAS_STREAM_REDIRECTION
9481 // Object that captures an output stream (stdout/stderr).
9482 class CapturedStream {
9484 // The ctor redirects the stream to a temporary file.
9485 explicit CapturedStream(int fd) : fd_(fd), uncaptured_fd_(dup(fd)) {
9486 # if GTEST_OS_WINDOWS
9487 char temp_dir_path[MAX_PATH + 1] = { '\0' }; // NOLINT
9488 char temp_file_path[MAX_PATH + 1] = { '\0' }; // NOLINT
9490 ::GetTempPathA(sizeof(temp_dir_path), temp_dir_path);
9491 const UINT success = ::GetTempFileNameA(temp_dir_path,
9493 0, // Generate unique file name.
9495 GTEST_CHECK_(success != 0)
9496 << "Unable to create a temporary file in " << temp_dir_path;
9497 const int captured_fd = creat(temp_file_path, _S_IREAD | _S_IWRITE);
9498 GTEST_CHECK_(captured_fd != -1) << "Unable to open temporary file "
9500 filename_ = temp_file_path;
9502 // There's no guarantee that a test has write access to the current
9503 // directory, so we create the temporary file in the /tmp directory
9504 // instead. We use /tmp on most systems, and /sdcard on Android.
9505 // That's because Android doesn't have /tmp.
9506 # if GTEST_OS_LINUX_ANDROID
9507 // Note: Android applications are expected to call the framework's
9508 // Context.getExternalStorageDirectory() method through JNI to get
9509 // the location of the world-writable SD Card directory. However,
9510 // this requires a Context handle, which cannot be retrieved
9511 // globally from native code. Doing so also precludes running the
9512 // code as part of a regular standalone executable, which doesn't
9513 // run in a Dalvik process (e.g. when running it through 'adb shell').
9515 // The location /sdcard is directly accessible from native code
9516 // and is the only location (unofficially) supported by the Android
9517 // team. It's generally a symlink to the real SD Card mount point
9518 // which can be /mnt/sdcard, /mnt/sdcard0, /system/media/sdcard, or
9519 // other OEM-customized locations. Never rely on these, and always
9521 char name_template[] = "/sdcard/gtest_captured_stream.XXXXXX";
9523 char name_template[] = "/tmp/captured_stream.XXXXXX";
9524 # endif // GTEST_OS_LINUX_ANDROID
9525 const int captured_fd = mkstemp(name_template);
9526 filename_ = name_template;
9527 # endif // GTEST_OS_WINDOWS
9529 dup2(captured_fd, fd_);
9534 remove(filename_.c_str());
9537 std::string GetCapturedString() {
9538 if (uncaptured_fd_ != -1) {
9539 // Restores the original stream.
9541 dup2(uncaptured_fd_, fd_);
9542 close(uncaptured_fd_);
9543 uncaptured_fd_ = -1;
9546 FILE* const file = posix::FOpen(filename_.c_str(), "r");
9547 const std::string content = ReadEntireFile(file);
9548 posix::FClose(file);
9553 const int fd_; // A stream to capture.
9555 // Name of the temporary file holding the stderr output.
9556 ::std::string filename_;
9558 GTEST_DISALLOW_COPY_AND_ASSIGN_(CapturedStream);
9561 GTEST_DISABLE_MSC_WARNINGS_POP_()
9563 static CapturedStream* g_captured_stderr = NULL;
9564 static CapturedStream* g_captured_stdout = NULL;
9566 // Starts capturing an output stream (stdout/stderr).
9567 void CaptureStream(int fd, const char* stream_name, CapturedStream** stream) {
9568 if (*stream != NULL) {
9569 GTEST_LOG_(FATAL) << "Only one " << stream_name
9570 << " capturer can exist at a time.";
9572 *stream = new CapturedStream(fd);
9575 // Stops capturing the output stream and returns the captured string.
9576 std::string GetCapturedStream(CapturedStream** captured_stream) {
9577 const std::string content = (*captured_stream)->GetCapturedString();
9579 delete *captured_stream;
9580 *captured_stream = NULL;
9585 // Starts capturing stdout.
9586 void CaptureStdout() {
9587 CaptureStream(kStdOutFileno, "stdout", &g_captured_stdout);
9590 // Starts capturing stderr.
9591 void CaptureStderr() {
9592 CaptureStream(kStdErrFileno, "stderr", &g_captured_stderr);
9595 // Stops capturing stdout and returns the captured string.
9596 std::string GetCapturedStdout() {
9597 return GetCapturedStream(&g_captured_stdout);
9600 // Stops capturing stderr and returns the captured string.
9601 std::string GetCapturedStderr() {
9602 return GetCapturedStream(&g_captured_stderr);
9605 #endif // GTEST_HAS_STREAM_REDIRECTION
9607 std::string TempDir() {
9608 #if GTEST_OS_WINDOWS_MOBILE
9610 #elif GTEST_OS_WINDOWS
9611 const char* temp_dir = posix::GetEnv("TEMP");
9612 if (temp_dir == NULL || temp_dir[0] == '\0')
9614 else if (temp_dir[strlen(temp_dir) - 1] == '\\')
9617 return std::string(temp_dir) + "\\";
9618 #elif GTEST_OS_LINUX_ANDROID
9622 #endif // GTEST_OS_WINDOWS_MOBILE
9625 size_t GetFileSize(FILE* file) {
9626 fseek(file, 0, SEEK_END);
9627 return static_cast<size_t>(ftell(file));
9630 std::string ReadEntireFile(FILE* file) {
9631 const size_t file_size = GetFileSize(file);
9632 char* const buffer = new char[file_size];
9634 size_t bytes_last_read = 0; // # of bytes read in the last fread()
9635 size_t bytes_read = 0; // # of bytes read so far
9637 fseek(file, 0, SEEK_SET);
9639 // Keeps reading the file until we cannot read further or the
9640 // pre-determined file size is reached.
9642 bytes_last_read = fread(buffer+bytes_read, 1, file_size-bytes_read, file);
9643 bytes_read += bytes_last_read;
9644 } while (bytes_last_read > 0 && bytes_read < file_size);
9646 const std::string content(buffer, bytes_read);
9652 #if GTEST_HAS_DEATH_TEST
9654 static const ::std::vector<testing::internal::string>* g_injected_test_argvs =
9657 void SetInjectableArgvs(const ::std::vector<testing::internal::string>* argvs) {
9658 if (g_injected_test_argvs != argvs)
9659 delete g_injected_test_argvs;
9660 g_injected_test_argvs = argvs;
9663 const ::std::vector<testing::internal::string>& GetInjectableArgvs() {
9664 if (g_injected_test_argvs != NULL) {
9665 return *g_injected_test_argvs;
9669 #endif // GTEST_HAS_DEATH_TEST
9671 #if GTEST_OS_WINDOWS_MOBILE
9675 TerminateProcess(GetCurrentProcess(), 1);
9677 } // namespace posix
9678 #endif // GTEST_OS_WINDOWS_MOBILE
9680 // Returns the name of the environment variable corresponding to the
9681 // given flag. For example, FlagToEnvVar("foo") will return
9682 // "GTEST_FOO" in the open-source version.
9683 static std::string FlagToEnvVar(const char* flag) {
9684 const std::string full_flag =
9685 (Message() << GTEST_FLAG_PREFIX_ << flag).GetString();
9688 for (size_t i = 0; i != full_flag.length(); i++) {
9689 env_var << ToUpper(full_flag.c_str()[i]);
9692 return env_var.GetString();
9695 // Parses 'str' for a 32-bit signed integer. If successful, writes
9696 // the result to *value and returns true; otherwise leaves *value
9697 // unchanged and returns false.
9698 bool ParseInt32(const Message& src_text, const char* str, Int32* value) {
9699 // Parses the environment variable as a decimal integer.
9701 const long long_value = strtol(str, &end, 10); // NOLINT
9703 // Has strtol() consumed all characters in the string?
9705 // No - an invalid character was encountered.
9707 msg << "WARNING: " << src_text
9708 << " is expected to be a 32-bit integer, but actually"
9709 << " has value \"" << str << "\".\n";
9710 printf("%s", msg.GetString().c_str());
9715 // Is the parsed value in the range of an Int32?
9716 const Int32 result = static_cast<Int32>(long_value);
9717 if (long_value == LONG_MAX || long_value == LONG_MIN ||
9718 // The parsed value overflows as a long. (strtol() returns
9719 // LONG_MAX or LONG_MIN when the input overflows.)
9720 result != long_value
9721 // The parsed value overflows as an Int32.
9724 msg << "WARNING: " << src_text
9725 << " is expected to be a 32-bit integer, but actually"
9726 << " has value " << str << ", which overflows.\n";
9727 printf("%s", msg.GetString().c_str());
9736 // Reads and returns the Boolean environment variable corresponding to
9737 // the given flag; if it's not set, returns default_value.
9739 // The value is considered true iff it's not "0".
9740 bool BoolFromGTestEnv(const char* flag, bool default_value) {
9741 #if defined(GTEST_GET_BOOL_FROM_ENV_)
9742 return GTEST_GET_BOOL_FROM_ENV_(flag, default_value);
9743 #endif // defined(GTEST_GET_BOOL_FROM_ENV_)
9744 const std::string env_var = FlagToEnvVar(flag);
9745 const char* const string_value = posix::GetEnv(env_var.c_str());
9746 return string_value == NULL ?
9747 default_value : strcmp(string_value, "0") != 0;
9750 // Reads and returns a 32-bit integer stored in the environment
9751 // variable corresponding to the given flag; if it isn't set or
9752 // doesn't represent a valid 32-bit integer, returns default_value.
9753 Int32 Int32FromGTestEnv(const char* flag, Int32 default_value) {
9754 #if defined(GTEST_GET_INT32_FROM_ENV_)
9755 return GTEST_GET_INT32_FROM_ENV_(flag, default_value);
9756 #endif // defined(GTEST_GET_INT32_FROM_ENV_)
9757 const std::string env_var = FlagToEnvVar(flag);
9758 const char* const string_value = posix::GetEnv(env_var.c_str());
9759 if (string_value == NULL) {
9760 // The environment variable is not set.
9761 return default_value;
9764 Int32 result = default_value;
9765 if (!ParseInt32(Message() << "Environment variable " << env_var,
9766 string_value, &result)) {
9767 printf("The default value %s is used.\n",
9768 (Message() << default_value).GetString().c_str());
9770 return default_value;
9776 // Reads and returns the string environment variable corresponding to
9777 // the given flag; if it's not set, returns default_value.
9778 std::string StringFromGTestEnv(const char* flag, const char* default_value) {
9779 #if defined(GTEST_GET_STRING_FROM_ENV_)
9780 return GTEST_GET_STRING_FROM_ENV_(flag, default_value);
9781 #endif // defined(GTEST_GET_STRING_FROM_ENV_)
9782 const std::string env_var = FlagToEnvVar(flag);
9783 const char* value = posix::GetEnv(env_var.c_str());
9784 if (value != NULL) {
9788 // As a special case for the 'output' flag, if GTEST_OUTPUT is not
9789 // set, we look for XML_OUTPUT_FILE, which is set by the Bazel build
9790 // system. The value of XML_OUTPUT_FILE is a filename without the
9791 // "xml:" prefix of GTEST_OUTPUT.
9793 // The net priority order after flag processing is thus:
9794 // --gtest_output command line flag
9795 // GTEST_OUTPUT environment variable
9796 // XML_OUTPUT_FILE environment variable
9798 if (strcmp(flag, "output") == 0) {
9799 value = posix::GetEnv("XML_OUTPUT_FILE");
9800 if (value != NULL) {
9801 return std::string("xml:") + value;
9804 return default_value;
9807 } // namespace internal
9808 } // namespace testing
9809 // Copyright 2007, Google Inc.
9810 // All rights reserved.
9812 // Redistribution and use in source and binary forms, with or without
9813 // modification, are permitted provided that the following conditions are
9816 // * Redistributions of source code must retain the above copyright
9817 // notice, this list of conditions and the following disclaimer.
9818 // * Redistributions in binary form must reproduce the above
9819 // copyright notice, this list of conditions and the following disclaimer
9820 // in the documentation and/or other materials provided with the
9822 // * Neither the name of Google Inc. nor the names of its
9823 // contributors may be used to endorse or promote products derived from
9824 // this software without specific prior written permission.
9826 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
9827 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
9828 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
9829 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9830 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
9831 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9832 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
9833 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
9834 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
9835 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
9836 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
9838 // Author: wan@google.com (Zhanyong Wan)
9840 // Google Test - The Google C++ Testing Framework
9842 // This file implements a universal value printer that can print a
9843 // value of any type T:
9845 // void ::testing::internal::UniversalPrinter<T>::Print(value, ostream_ptr);
9847 // It uses the << operator when possible, and prints the bytes in the
9848 // object otherwise. A user can override its behavior for a class
9849 // type Foo by defining either operator<<(::std::ostream&, const Foo&)
9850 // or void PrintTo(const Foo&, ::std::ostream*) in the namespace that
9856 #include <ostream> // NOLINT
9863 using ::std::ostream;
9865 // Prints a segment of bytes in the given object.
9866 GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
9867 GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
9868 GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
9869 void PrintByteSegmentInObjectTo(const unsigned char* obj_bytes, size_t start,
9870 size_t count, ostream* os) {
9872 for (size_t i = 0; i != count; i++) {
9873 const size_t j = start + i;
9875 // Organizes the bytes into groups of 2 for easy parsing by
9882 GTEST_SNPRINTF_(text, sizeof(text), "%02X", obj_bytes[j]);
9887 // Prints the bytes in the given value to the given ostream.
9888 void PrintBytesInObjectToImpl(const unsigned char* obj_bytes, size_t count,
9890 // Tells the user how big the object is.
9891 *os << count << "-byte object <";
9893 const size_t kThreshold = 132;
9894 const size_t kChunkSize = 64;
9895 // If the object size is bigger than kThreshold, we'll have to omit
9896 // some details by printing only the first and the last kChunkSize
9898 // TODO(wan): let the user control the threshold using a flag.
9899 if (count < kThreshold) {
9900 PrintByteSegmentInObjectTo(obj_bytes, 0, count, os);
9902 PrintByteSegmentInObjectTo(obj_bytes, 0, kChunkSize, os);
9904 // Rounds up to 2-byte boundary.
9905 const size_t resume_pos = (count - kChunkSize + 1)/2*2;
9906 PrintByteSegmentInObjectTo(obj_bytes, resume_pos, count - resume_pos, os);
9913 namespace internal2 {
9915 // Delegates to PrintBytesInObjectToImpl() to print the bytes in the
9916 // given object. The delegation simplifies the implementation, which
9917 // uses the << operator and thus is easier done outside of the
9918 // ::testing::internal namespace, which contains a << operator that
9919 // sometimes conflicts with the one in STL.
9920 void PrintBytesInObjectTo(const unsigned char* obj_bytes, size_t count,
9922 PrintBytesInObjectToImpl(obj_bytes, count, os);
9925 } // namespace internal2
9927 namespace internal {
9929 // Depending on the value of a char (or wchar_t), we print it in one
9930 // of three formats:
9931 // - as is if it's a printable ASCII (e.g. 'a', '2', ' '),
9932 // - as a hexidecimal escape sequence (e.g. '\x7F'), or
9933 // - as a special escape sequence (e.g. '\r', '\n').
9940 // Returns true if c is a printable ASCII character. We test the
9941 // value of c directly instead of calling isprint(), which is buggy on
9943 inline bool IsPrintableAscii(wchar_t c) {
9944 return 0x20 <= c && c <= 0x7E;
9947 // Prints a wide or narrow char c as a character literal without the
9948 // quotes, escaping it when necessary; returns how c was formatted.
9949 // The template argument UnsignedChar is the unsigned version of Char,
9950 // which is the type of c.
9951 template <typename UnsignedChar, typename Char>
9952 static CharFormat PrintAsCharLiteralTo(Char c, ostream* os) {
9953 switch (static_cast<wchar_t>(c)) {
9985 if (IsPrintableAscii(c)) {
9986 *os << static_cast<char>(c);
9989 *os << "\\x" + String::FormatHexInt(static_cast<UnsignedChar>(c));
9993 return kSpecialEscape;
9996 // Prints a wchar_t c as if it's part of a string literal, escaping it when
9997 // necessary; returns how c was formatted.
9998 static CharFormat PrintAsStringLiteralTo(wchar_t c, ostream* os) {
10005 return kSpecialEscape;
10007 return PrintAsCharLiteralTo<wchar_t>(c, os);
10011 // Prints a char c as if it's part of a string literal, escaping it when
10012 // necessary; returns how c was formatted.
10013 static CharFormat PrintAsStringLiteralTo(char c, ostream* os) {
10014 return PrintAsStringLiteralTo(
10015 static_cast<wchar_t>(static_cast<unsigned char>(c)), os);
10018 // Prints a wide or narrow character c and its code. '\0' is printed
10019 // as "'\\0'", other unprintable characters are also properly escaped
10020 // using the standard C++ escape sequence. The template argument
10021 // UnsignedChar is the unsigned version of Char, which is the type of c.
10022 template <typename UnsignedChar, typename Char>
10023 void PrintCharAndCodeTo(Char c, ostream* os) {
10024 // First, print c as a literal in the most readable form we can find.
10025 *os << ((sizeof(c) > 1) ? "L'" : "'");
10026 const CharFormat format = PrintAsCharLiteralTo<UnsignedChar>(c, os);
10029 // To aid user debugging, we also print c's code in decimal, unless
10030 // it's 0 (in which case c was printed as '\\0', making the code
10034 *os << " (" << static_cast<int>(c);
10036 // For more convenience, we print c's code again in hexidecimal,
10037 // unless c was already printed in the form '\x##' or the code is in
10039 if (format == kHexEscape || (1 <= c && c <= 9)) {
10042 *os << ", 0x" << String::FormatHexInt(static_cast<UnsignedChar>(c));
10047 void PrintTo(unsigned char c, ::std::ostream* os) {
10048 PrintCharAndCodeTo<unsigned char>(c, os);
10050 void PrintTo(signed char c, ::std::ostream* os) {
10051 PrintCharAndCodeTo<unsigned char>(c, os);
10054 // Prints a wchar_t as a symbol if it is printable or as its internal
10055 // code otherwise and also as its code. L'\0' is printed as "L'\\0'".
10056 void PrintTo(wchar_t wc, ostream* os) {
10057 PrintCharAndCodeTo<wchar_t>(wc, os);
10060 // Prints the given array of characters to the ostream. CharType must be either
10061 // char or wchar_t.
10062 // The array starts at begin, the length is len, it may include '\0' characters
10063 // and may not be NUL-terminated.
10064 template <typename CharType>
10065 GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
10066 GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
10067 GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
10068 static void PrintCharsAsStringTo(
10069 const CharType* begin, size_t len, ostream* os) {
10070 const char* const kQuoteBegin = sizeof(CharType) == 1 ? "\"" : "L\"";
10071 *os << kQuoteBegin;
10072 bool is_previous_hex = false;
10073 for (size_t index = 0; index < len; ++index) {
10074 const CharType cur = begin[index];
10075 if (is_previous_hex && IsXDigit(cur)) {
10076 // Previous character is of '\x..' form and this character can be
10077 // interpreted as another hexadecimal digit in its number. Break string to
10079 *os << "\" " << kQuoteBegin;
10081 is_previous_hex = PrintAsStringLiteralTo(cur, os) == kHexEscape;
10086 // Prints a (const) char/wchar_t array of 'len' elements, starting at address
10087 // 'begin'. CharType must be either char or wchar_t.
10088 template <typename CharType>
10089 GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
10090 GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
10091 GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
10092 static void UniversalPrintCharArray(
10093 const CharType* begin, size_t len, ostream* os) {
10095 // const char kFoo[] = "foo";
10096 // generates an array of 4, not 3, elements, with the last one being '\0'.
10098 // Therefore when printing a char array, we don't print the last element if
10099 // it's '\0', such that the output matches the string literal as it's
10100 // written in the source code.
10101 if (len > 0 && begin[len - 1] == '\0') {
10102 PrintCharsAsStringTo(begin, len - 1, os);
10106 // If, however, the last element in the array is not '\0', e.g.
10107 // const char kFoo[] = { 'f', 'o', 'o' };
10108 // we must print the entire array. We also print a message to indicate
10109 // that the array is not NUL-terminated.
10110 PrintCharsAsStringTo(begin, len, os);
10111 *os << " (no terminating NUL)";
10114 // Prints a (const) char array of 'len' elements, starting at address 'begin'.
10115 void UniversalPrintArray(const char* begin, size_t len, ostream* os) {
10116 UniversalPrintCharArray(begin, len, os);
10119 // Prints a (const) wchar_t array of 'len' elements, starting at address
10121 void UniversalPrintArray(const wchar_t* begin, size_t len, ostream* os) {
10122 UniversalPrintCharArray(begin, len, os);
10125 // Prints the given C string to the ostream.
10126 void PrintTo(const char* s, ostream* os) {
10130 *os << ImplicitCast_<const void*>(s) << " pointing to ";
10131 PrintCharsAsStringTo(s, strlen(s), os);
10135 // MSVC compiler can be configured to define whar_t as a typedef
10136 // of unsigned short. Defining an overload for const wchar_t* in that case
10137 // would cause pointers to unsigned shorts be printed as wide strings,
10138 // possibly accessing more memory than intended and causing invalid
10139 // memory accesses. MSVC defines _NATIVE_WCHAR_T_DEFINED symbol when
10140 // wchar_t is implemented as a native type.
10141 #if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED)
10142 // Prints the given wide C string to the ostream.
10143 void PrintTo(const wchar_t* s, ostream* os) {
10147 *os << ImplicitCast_<const void*>(s) << " pointing to ";
10148 PrintCharsAsStringTo(s, std::wcslen(s), os);
10151 #endif // wchar_t is native
10153 // Prints a ::string object.
10154 #if GTEST_HAS_GLOBAL_STRING
10155 void PrintStringTo(const ::string& s, ostream* os) {
10156 PrintCharsAsStringTo(s.data(), s.size(), os);
10158 #endif // GTEST_HAS_GLOBAL_STRING
10160 void PrintStringTo(const ::std::string& s, ostream* os) {
10161 PrintCharsAsStringTo(s.data(), s.size(), os);
10164 // Prints a ::wstring object.
10165 #if GTEST_HAS_GLOBAL_WSTRING
10166 void PrintWideStringTo(const ::wstring& s, ostream* os) {
10167 PrintCharsAsStringTo(s.data(), s.size(), os);
10169 #endif // GTEST_HAS_GLOBAL_WSTRING
10171 #if GTEST_HAS_STD_WSTRING
10172 void PrintWideStringTo(const ::std::wstring& s, ostream* os) {
10173 PrintCharsAsStringTo(s.data(), s.size(), os);
10175 #endif // GTEST_HAS_STD_WSTRING
10177 } // namespace internal
10179 } // namespace testing
10180 // Copyright 2008, Google Inc.
10181 // All rights reserved.
10183 // Redistribution and use in source and binary forms, with or without
10184 // modification, are permitted provided that the following conditions are
10187 // * Redistributions of source code must retain the above copyright
10188 // notice, this list of conditions and the following disclaimer.
10189 // * Redistributions in binary form must reproduce the above
10190 // copyright notice, this list of conditions and the following disclaimer
10191 // in the documentation and/or other materials provided with the
10193 // * Neither the name of Google Inc. nor the names of its
10194 // contributors may be used to endorse or promote products derived from
10195 // this software without specific prior written permission.
10197 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
10198 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
10199 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
10200 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
10201 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
10202 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
10203 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
10204 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
10205 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
10206 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
10207 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
10209 // Author: mheule@google.com (Markus Heule)
10211 // The Google C++ Testing Framework (Google Test)
10214 // Indicates that this translation unit is part of Google Test's
10215 // implementation. It must come before gtest-internal-inl.h is
10216 // included, or there will be a compiler error. This trick exists to
10217 // prevent the accidental inclusion of gtest-internal-inl.h in the
10219 #define GTEST_IMPLEMENTATION_ 1
10220 #undef GTEST_IMPLEMENTATION_
10222 namespace testing {
10224 using internal::GetUnitTestImpl;
10226 // Gets the summary of the failure message by omitting the stack trace
10228 std::string TestPartResult::ExtractSummary(const char* message) {
10229 const char* const stack_trace = strstr(message, internal::kStackTraceMarker);
10230 return stack_trace == NULL ? message :
10231 std::string(message, stack_trace);
10234 // Prints a TestPartResult object.
10235 std::ostream& operator<<(std::ostream& os, const TestPartResult& result) {
10237 << result.file_name() << ":" << result.line_number() << ": "
10238 << (result.type() == TestPartResult::kSuccess ? "Success" :
10239 result.type() == TestPartResult::kFatalFailure ? "Fatal failure" :
10240 "Non-fatal failure") << ":\n"
10241 << result.message() << std::endl;
10244 // Appends a TestPartResult to the array.
10245 void TestPartResultArray::Append(const TestPartResult& result) {
10246 array_.push_back(result);
10249 // Returns the TestPartResult at the given index (0-based).
10250 const TestPartResult& TestPartResultArray::GetTestPartResult(int index) const {
10251 if (index < 0 || index >= size()) {
10252 printf("\nInvalid index (%d) into TestPartResultArray.\n", index);
10253 internal::posix::Abort();
10256 return array_[index];
10259 // Returns the number of TestPartResult objects in the array.
10260 int TestPartResultArray::size() const {
10261 return static_cast<int>(array_.size());
10264 namespace internal {
10266 HasNewFatalFailureHelper::HasNewFatalFailureHelper()
10267 : has_new_fatal_failure_(false),
10268 original_reporter_(GetUnitTestImpl()->
10269 GetTestPartResultReporterForCurrentThread()) {
10270 GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(this);
10273 HasNewFatalFailureHelper::~HasNewFatalFailureHelper() {
10274 GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(
10275 original_reporter_);
10278 void HasNewFatalFailureHelper::ReportTestPartResult(
10279 const TestPartResult& result) {
10280 if (result.fatally_failed())
10281 has_new_fatal_failure_ = true;
10282 original_reporter_->ReportTestPartResult(result);
10285 } // namespace internal
10287 } // namespace testing
10288 // Copyright 2008 Google Inc.
10289 // All Rights Reserved.
10291 // Redistribution and use in source and binary forms, with or without
10292 // modification, are permitted provided that the following conditions are
10295 // * Redistributions of source code must retain the above copyright
10296 // notice, this list of conditions and the following disclaimer.
10297 // * Redistributions in binary form must reproduce the above
10298 // copyright notice, this list of conditions and the following disclaimer
10299 // in the documentation and/or other materials provided with the
10301 // * Neither the name of Google Inc. nor the names of its
10302 // contributors may be used to endorse or promote products derived from
10303 // this software without specific prior written permission.
10305 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
10306 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
10307 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
10308 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
10309 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
10310 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
10311 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
10312 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
10313 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
10314 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
10315 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
10317 // Author: wan@google.com (Zhanyong Wan)
10320 namespace testing {
10321 namespace internal {
10323 #if GTEST_HAS_TYPED_TEST_P
10325 // Skips to the first non-space char in str. Returns an empty string if str
10326 // contains only whitespace characters.
10327 static const char* SkipSpaces(const char* str) {
10328 while (IsSpace(*str))
10333 static std::vector<std::string> SplitIntoTestNames(const char* src) {
10334 std::vector<std::string> name_vec;
10335 src = SkipSpaces(src);
10336 for (; src != NULL; src = SkipComma(src)) {
10337 name_vec.push_back(StripTrailingSpaces(GetPrefixUntilComma(src)));
10342 // Verifies that registered_tests match the test names in
10343 // registered_tests_; returns registered_tests if successful, or
10344 // aborts the program otherwise.
10345 const char* TypedTestCasePState::VerifyRegisteredTestNames(
10346 const char* file, int line, const char* registered_tests) {
10347 typedef RegisteredTestsMap::const_iterator RegisteredTestIter;
10348 registered_ = true;
10350 std::vector<std::string> name_vec = SplitIntoTestNames(registered_tests);
10354 std::set<std::string> tests;
10355 for (std::vector<std::string>::const_iterator name_it = name_vec.begin();
10356 name_it != name_vec.end(); ++name_it) {
10357 const std::string& name = *name_it;
10358 if (tests.count(name) != 0) {
10359 errors << "Test " << name << " is listed more than once.\n";
10363 bool found = false;
10364 for (RegisteredTestIter it = registered_tests_.begin();
10365 it != registered_tests_.end();
10367 if (name == it->first) {
10374 tests.insert(name);
10376 errors << "No test named " << name
10377 << " can be found in this test case.\n";
10381 for (RegisteredTestIter it = registered_tests_.begin();
10382 it != registered_tests_.end();
10384 if (tests.count(it->first) == 0) {
10385 errors << "You forgot to list test " << it->first << ".\n";
10389 const std::string& errors_str = errors.GetString();
10390 if (errors_str != "") {
10391 fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(),
10392 errors_str.c_str());
10397 return registered_tests;
10400 #endif // GTEST_HAS_TYPED_TEST_P
10402 } // namespace internal
10403 } // namespace testing
10404 // Copyright 2008, Google Inc.
10405 // All rights reserved.
10407 // Redistribution and use in source and binary forms, with or without
10408 // modification, are permitted provided that the following conditions are
10411 // * Redistributions of source code must retain the above copyright
10412 // notice, this list of conditions and the following disclaimer.
10413 // * Redistributions in binary form must reproduce the above
10414 // copyright notice, this list of conditions and the following disclaimer
10415 // in the documentation and/or other materials provided with the
10417 // * Neither the name of Google Inc. nor the names of its
10418 // contributors may be used to endorse or promote products derived from
10419 // this software without specific prior written permission.
10421 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
10422 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
10423 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
10424 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
10425 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
10426 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
10427 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
10428 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
10429 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
10430 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
10431 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
10433 // Author: wan@google.com (Zhanyong Wan)
10435 // Google C++ Mocking Framework (Google Mock)
10437 // This file #includes all Google Mock implementation .cc files. The
10438 // purpose is to allow a user to build Google Mock by compiling this
10441 // This line ensures that gmock.h can be compiled on its own, even
10442 // when it's fused.
10443 #include "gmock/gmock.h"
10445 // The following lines pull in the real gmock *.cc files.
10446 // Copyright 2007, Google Inc.
10447 // All rights reserved.
10449 // Redistribution and use in source and binary forms, with or without
10450 // modification, are permitted provided that the following conditions are
10453 // * Redistributions of source code must retain the above copyright
10454 // notice, this list of conditions and the following disclaimer.
10455 // * Redistributions in binary form must reproduce the above
10456 // copyright notice, this list of conditions and the following disclaimer
10457 // in the documentation and/or other materials provided with the
10459 // * Neither the name of Google Inc. nor the names of its
10460 // contributors may be used to endorse or promote products derived from
10461 // this software without specific prior written permission.
10463 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
10464 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
10465 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
10466 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
10467 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
10468 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
10469 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
10470 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
10471 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
10472 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
10473 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
10475 // Author: wan@google.com (Zhanyong Wan)
10477 // Google Mock - a framework for writing C++ mock classes.
10479 // This file implements cardinalities.
10482 #include <limits.h>
10483 #include <ostream> // NOLINT
10487 namespace testing {
10491 // Implements the Between(m, n) cardinality.
10492 class BetweenCardinalityImpl : public CardinalityInterface {
10494 BetweenCardinalityImpl(int min, int max)
10495 : min_(min >= 0 ? min : 0),
10496 max_(max >= min_ ? max : min_) {
10497 std::stringstream ss;
10499 ss << "The invocation lower bound must be >= 0, "
10500 << "but is actually " << min << ".";
10501 internal::Expect(false, __FILE__, __LINE__, ss.str());
10502 } else if (max < 0) {
10503 ss << "The invocation upper bound must be >= 0, "
10504 << "but is actually " << max << ".";
10505 internal::Expect(false, __FILE__, __LINE__, ss.str());
10506 } else if (min > max) {
10507 ss << "The invocation upper bound (" << max
10508 << ") must be >= the invocation lower bound (" << min
10510 internal::Expect(false, __FILE__, __LINE__, ss.str());
10514 // Conservative estimate on the lower/upper bound of the number of
10516 virtual int ConservativeLowerBound() const { return min_; }
10517 virtual int ConservativeUpperBound() const { return max_; }
10519 virtual bool IsSatisfiedByCallCount(int call_count) const {
10520 return min_ <= call_count && call_count <= max_;
10523 virtual bool IsSaturatedByCallCount(int call_count) const {
10524 return call_count >= max_;
10527 virtual void DescribeTo(::std::ostream* os) const;
10533 GTEST_DISALLOW_COPY_AND_ASSIGN_(BetweenCardinalityImpl);
10536 // Formats "n times" in a human-friendly way.
10537 inline internal::string FormatTimes(int n) {
10540 } else if (n == 2) {
10543 std::stringstream ss;
10544 ss << n << " times";
10549 // Describes the Between(m, n) cardinality in human-friendly text.
10550 void BetweenCardinalityImpl::DescribeTo(::std::ostream* os) const {
10553 *os << "never called";
10554 } else if (max_ == INT_MAX) {
10555 *os << "called any number of times";
10557 *os << "called at most " << FormatTimes(max_);
10559 } else if (min_ == max_) {
10560 *os << "called " << FormatTimes(min_);
10561 } else if (max_ == INT_MAX) {
10562 *os << "called at least " << FormatTimes(min_);
10564 // 0 < min_ < max_ < INT_MAX
10565 *os << "called between " << min_ << " and " << max_ << " times";
10569 } // Unnamed namespace
10571 // Describes the given call count to an ostream.
10572 void Cardinality::DescribeActualCallCountTo(int actual_call_count,
10573 ::std::ostream* os) {
10574 if (actual_call_count > 0) {
10575 *os << "called " << FormatTimes(actual_call_count);
10577 *os << "never called";
10581 // Creates a cardinality that allows at least n calls.
10582 GTEST_API_ Cardinality AtLeast(int n) { return Between(n, INT_MAX); }
10584 // Creates a cardinality that allows at most n calls.
10585 GTEST_API_ Cardinality AtMost(int n) { return Between(0, n); }
10587 // Creates a cardinality that allows any number of calls.
10588 GTEST_API_ Cardinality AnyNumber() { return AtLeast(0); }
10590 // Creates a cardinality that allows between min and max calls.
10591 GTEST_API_ Cardinality Between(int min, int max) {
10592 return Cardinality(new BetweenCardinalityImpl(min, max));
10595 // Creates a cardinality that allows exactly n calls.
10596 GTEST_API_ Cardinality Exactly(int n) { return Between(n, n); }
10598 } // namespace testing
10599 // Copyright 2007, Google Inc.
10600 // All rights reserved.
10602 // Redistribution and use in source and binary forms, with or without
10603 // modification, are permitted provided that the following conditions are
10606 // * Redistributions of source code must retain the above copyright
10607 // notice, this list of conditions and the following disclaimer.
10608 // * Redistributions in binary form must reproduce the above
10609 // copyright notice, this list of conditions and the following disclaimer
10610 // in the documentation and/or other materials provided with the
10612 // * Neither the name of Google Inc. nor the names of its
10613 // contributors may be used to endorse or promote products derived from
10614 // this software without specific prior written permission.
10616 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
10617 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
10618 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
10619 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
10620 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
10621 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
10622 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
10623 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
10624 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
10625 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
10626 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
10628 // Author: wan@google.com (Zhanyong Wan)
10630 // Google Mock - a framework for writing C++ mock classes.
10632 // This file defines some utilities useful for implementing Google
10633 // Mock. They are subject to change without notice, so please DO NOT
10634 // USE THEM IN USER CODE.
10638 #include <ostream> // NOLINT
10641 namespace testing {
10642 namespace internal {
10644 // Converts an identifier name to a space-separated list of lower-case
10645 // words. Each maximum substring of the form [A-Za-z][a-z]*|\d+ is
10646 // treated as one word. For example, both "FooBar123" and
10647 // "foo_bar_123" are converted to "foo bar 123".
10648 GTEST_API_ string ConvertIdentifierNameToWords(const char* id_name) {
10650 char prev_char = '\0';
10651 for (const char* p = id_name; *p != '\0'; prev_char = *(p++)) {
10652 // We don't care about the current locale as the input is
10653 // guaranteed to be a valid C++ identifier name.
10654 const bool starts_new_word = IsUpper(*p) ||
10655 (!IsAlpha(prev_char) && IsLower(*p)) ||
10656 (!IsDigit(prev_char) && IsDigit(*p));
10659 if (starts_new_word && result != "")
10661 result += ToLower(*p);
10667 // This class reports Google Mock failures as Google Test failures. A
10668 // user can define another class in a similar fashion if he intends to
10669 // use Google Mock with a testing framework other than Google Test.
10670 class GoogleTestFailureReporter : public FailureReporterInterface {
10672 virtual void ReportFailure(FailureType type, const char* file, int line,
10673 const string& message) {
10674 AssertHelper(type == kFatal ?
10675 TestPartResult::kFatalFailure :
10676 TestPartResult::kNonFatalFailure,
10679 message.c_str()) = Message();
10680 if (type == kFatal) {
10686 // Returns the global failure reporter. Will create a
10687 // GoogleTestFailureReporter and return it the first time called.
10688 GTEST_API_ FailureReporterInterface* GetFailureReporter() {
10689 // Points to the global failure reporter used by Google Mock. gcc
10690 // guarantees that the following use of failure_reporter is
10691 // thread-safe. We may need to add additional synchronization to
10692 // protect failure_reporter if we port Google Mock to other
10694 static FailureReporterInterface* const failure_reporter =
10695 new GoogleTestFailureReporter();
10696 return failure_reporter;
10699 // Protects global resources (stdout in particular) used by Log().
10700 static GTEST_DEFINE_STATIC_MUTEX_(g_log_mutex);
10702 // Returns true iff a log with the given severity is visible according
10703 // to the --gmock_verbose flag.
10704 GTEST_API_ bool LogIsVisible(LogSeverity severity) {
10705 if (GMOCK_FLAG(verbose) == kInfoVerbosity) {
10706 // Always show the log if --gmock_verbose=info.
10708 } else if (GMOCK_FLAG(verbose) == kErrorVerbosity) {
10709 // Always hide it if --gmock_verbose=error.
10712 // If --gmock_verbose is neither "info" nor "error", we treat it
10713 // as "warning" (its default value).
10714 return severity == kWarning;
10718 // Prints the given message to stdout iff 'severity' >= the level
10719 // specified by the --gmock_verbose flag. If stack_frames_to_skip >=
10720 // 0, also prints the stack trace excluding the top
10721 // stack_frames_to_skip frames. In opt mode, any positive
10722 // stack_frames_to_skip is treated as 0, since we don't know which
10723 // function calls will be inlined by the compiler and need to be
10725 GTEST_API_ void Log(LogSeverity severity,
10726 const string& message,
10727 int stack_frames_to_skip) {
10728 if (!LogIsVisible(severity))
10731 // Ensures that logs from different threads don't interleave.
10732 MutexLock l(&g_log_mutex);
10734 // "using ::std::cout;" doesn't work with Symbian's STLport, where cout is a
10737 if (severity == kWarning) {
10738 // Prints a GMOCK WARNING marker to make the warnings easily searchable.
10739 std::cout << "\nGMOCK WARNING:";
10741 // Pre-pends a new-line to message if it doesn't start with one.
10742 if (message.empty() || message[0] != '\n') {
10745 std::cout << message;
10746 if (stack_frames_to_skip >= 0) {
10748 // In opt mode, we have to be conservative and skip no stack frame.
10749 const int actual_to_skip = 0;
10751 // In dbg mode, we can do what the caller tell us to do (plus one
10752 // for skipping this function's stack frame).
10753 const int actual_to_skip = stack_frames_to_skip + 1;
10756 // Appends a new-line to message if it doesn't end with one.
10757 if (!message.empty() && *message.rbegin() != '\n') {
10760 std::cout << "Stack trace:\n"
10761 << ::testing::internal::GetCurrentOsStackTraceExceptTop(
10762 ::testing::UnitTest::GetInstance(), actual_to_skip);
10764 std::cout << ::std::flush;
10767 } // namespace internal
10768 } // namespace testing
10769 // Copyright 2007, Google Inc.
10770 // All rights reserved.
10772 // Redistribution and use in source and binary forms, with or without
10773 // modification, are permitted provided that the following conditions are
10776 // * Redistributions of source code must retain the above copyright
10777 // notice, this list of conditions and the following disclaimer.
10778 // * Redistributions in binary form must reproduce the above
10779 // copyright notice, this list of conditions and the following disclaimer
10780 // in the documentation and/or other materials provided with the
10782 // * Neither the name of Google Inc. nor the names of its
10783 // contributors may be used to endorse or promote products derived from
10784 // this software without specific prior written permission.
10786 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
10787 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
10788 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
10789 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
10790 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
10791 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
10792 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
10793 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
10794 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
10795 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
10796 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
10798 // Author: wan@google.com (Zhanyong Wan)
10800 // Google Mock - a framework for writing C++ mock classes.
10802 // This file implements Matcher<const string&>, Matcher<string>, and
10803 // utilities for defining matchers.
10806 #include <string.h>
10810 namespace testing {
10812 // Constructs a matcher that matches a const string& whose value is
10814 Matcher<const internal::string&>::Matcher(const internal::string& s) {
10818 // Constructs a matcher that matches a const string& whose value is
10820 Matcher<const internal::string&>::Matcher(const char* s) {
10821 *this = Eq(internal::string(s));
10824 // Constructs a matcher that matches a string whose value is equal to s.
10825 Matcher<internal::string>::Matcher(const internal::string& s) { *this = Eq(s); }
10827 // Constructs a matcher that matches a string whose value is equal to s.
10828 Matcher<internal::string>::Matcher(const char* s) {
10829 *this = Eq(internal::string(s));
10832 #if GTEST_HAS_STRING_PIECE_
10833 // Constructs a matcher that matches a const StringPiece& whose value is
10835 Matcher<const StringPiece&>::Matcher(const internal::string& s) {
10839 // Constructs a matcher that matches a const StringPiece& whose value is
10841 Matcher<const StringPiece&>::Matcher(const char* s) {
10842 *this = Eq(internal::string(s));
10845 // Constructs a matcher that matches a const StringPiece& whose value is
10847 Matcher<const StringPiece&>::Matcher(StringPiece s) {
10848 *this = Eq(s.ToString());
10851 // Constructs a matcher that matches a StringPiece whose value is equal to s.
10852 Matcher<StringPiece>::Matcher(const internal::string& s) {
10856 // Constructs a matcher that matches a StringPiece whose value is equal to s.
10857 Matcher<StringPiece>::Matcher(const char* s) {
10858 *this = Eq(internal::string(s));
10861 // Constructs a matcher that matches a StringPiece whose value is equal to s.
10862 Matcher<StringPiece>::Matcher(StringPiece s) {
10863 *this = Eq(s.ToString());
10865 #endif // GTEST_HAS_STRING_PIECE_
10867 namespace internal {
10869 // Joins a vector of strings as if they are fields of a tuple; returns
10870 // the joined string.
10871 GTEST_API_ string JoinAsTuple(const Strings& fields) {
10872 switch (fields.size()) {
10878 string result = "(" + fields[0];
10879 for (size_t i = 1; i < fields.size(); i++) {
10881 result += fields[i];
10888 // Returns the description for a matcher defined using the MATCHER*()
10889 // macro where the user-supplied description string is "", if
10890 // 'negation' is false; otherwise returns the description of the
10891 // negation of the matcher. 'param_values' contains a list of strings
10892 // that are the print-out of the matcher's parameters.
10893 GTEST_API_ string FormatMatcherDescription(bool negation,
10894 const char* matcher_name,
10895 const Strings& param_values) {
10896 string result = ConvertIdentifierNameToWords(matcher_name);
10897 if (param_values.size() >= 1)
10898 result += " " + JoinAsTuple(param_values);
10899 return negation ? "not (" + result + ")" : result;
10902 // FindMaxBipartiteMatching and its helper class.
10904 // Uses the well-known Ford-Fulkerson max flow method to find a maximum
10905 // bipartite matching. Flow is considered to be from left to right.
10906 // There is an implicit source node that is connected to all of the left
10907 // nodes, and an implicit sink node that is connected to all of the
10908 // right nodes. All edges have unit capacity.
10910 // Neither the flow graph nor the residual flow graph are represented
10911 // explicitly. Instead, they are implied by the information in 'graph' and
10912 // a vector<int> called 'left_' whose elements are initialized to the
10913 // value kUnused. This represents the initial state of the algorithm,
10914 // where the flow graph is empty, and the residual flow graph has the
10915 // following edges:
10916 // - An edge from source to each left_ node
10917 // - An edge from each right_ node to sink
10918 // - An edge from each left_ node to each right_ node, if the
10919 // corresponding edge exists in 'graph'.
10921 // When the TryAugment() method adds a flow, it sets left_[l] = r for some
10922 // nodes l and r. This induces the following changes:
10923 // - The edges (source, l), (l, r), and (r, sink) are added to the
10925 // - The same three edges are removed from the residual flow graph.
10926 // - The reverse edges (l, source), (r, l), and (sink, r) are added
10927 // to the residual flow graph, which is a directional graph
10928 // representing unused flow capacity.
10930 // When the method augments a flow (moving left_[l] from some r1 to some
10931 // other r2), this can be thought of as "undoing" the above steps with
10932 // respect to r1 and "redoing" them with respect to r2.
10934 // It bears repeating that the flow graph and residual flow graph are
10935 // never represented explicitly, but can be derived by looking at the
10936 // information in 'graph' and in left_.
10938 // As an optimization, there is a second vector<int> called right_ which
10939 // does not provide any new information. Instead, it enables more
10940 // efficient queries about edges entering or leaving the right-side nodes
10941 // of the flow or residual flow graphs. The following invariants are
10944 // left[l] == kUnused or right[left[l]] == l
10945 // right[r] == kUnused or left[right[r]] == r
10950 // . ||\--> left[0]=1 ---\ right[0]=-1 ----\ .
10952 // . |\---> left[1]=-1 \--> right[1]=0 ---\| .
10954 // . \----> left[2]=2 ------> right[2]=2 --\|| .
10956 // . elements matchers vvv .
10960 // [1] Cormen, et al (2001). "Section 26.2: The Ford-Fulkerson method".
10961 // "Introduction to Algorithms (Second ed.)", pp. 651-664.
10962 // [2] "Ford-Fulkerson algorithm", Wikipedia,
10963 // 'http://en.wikipedia.org/wiki/Ford%E2%80%93Fulkerson_algorithm'
10964 class MaxBipartiteMatchState {
10966 explicit MaxBipartiteMatchState(const MatchMatrix& graph)
10968 left_(graph_->LhsSize(), kUnused),
10969 right_(graph_->RhsSize(), kUnused) {
10972 // Returns the edges of a maximal match, each in the form {left, right}.
10973 ElementMatcherPairs Compute() {
10974 // 'seen' is used for path finding { 0: unseen, 1: seen }.
10975 ::std::vector<char> seen;
10976 // Searches the residual flow graph for a path from each left node to
10977 // the sink in the residual flow graph, and if one is found, add flow
10978 // to the graph. It's okay to search through the left nodes once. The
10979 // edge from the implicit source node to each previously-visited left
10980 // node will have flow if that left node has any path to the sink
10981 // whatsoever. Subsequent augmentations can only add flow to the
10982 // network, and cannot take away that previous flow unit from the source.
10983 // Since the source-to-left edge can only carry one flow unit (or,
10984 // each element can be matched to only one matcher), there is no need
10985 // to visit the left nodes more than once looking for augmented paths.
10986 // The flow is known to be possible or impossible by looking at the
10988 for (size_t ilhs = 0; ilhs < graph_->LhsSize(); ++ilhs) {
10989 // Reset the path-marking vector and try to find a path from
10990 // source to sink starting at the left_[ilhs] node.
10991 GTEST_CHECK_(left_[ilhs] == kUnused)
10992 << "ilhs: " << ilhs << ", left_[ilhs]: " << left_[ilhs];
10993 // 'seen' initialized to 'graph_->RhsSize()' copies of 0.
10994 seen.assign(graph_->RhsSize(), 0);
10995 TryAugment(ilhs, &seen);
10997 ElementMatcherPairs result;
10998 for (size_t ilhs = 0; ilhs < left_.size(); ++ilhs) {
10999 size_t irhs = left_[ilhs];
11000 if (irhs == kUnused) continue;
11001 result.push_back(ElementMatcherPair(ilhs, irhs));
11007 static const size_t kUnused = static_cast<size_t>(-1);
11009 // Perform a depth-first search from left node ilhs to the sink. If a
11010 // path is found, flow is added to the network by linking the left and
11011 // right vector elements corresponding each segment of the path.
11012 // Returns true if a path to sink was found, which means that a unit of
11013 // flow was added to the network. The 'seen' vector elements correspond
11014 // to right nodes and are marked to eliminate cycles from the search.
11016 // Left nodes will only be explored at most once because they
11017 // are accessible from at most one right node in the residual flow
11020 // Note that left_[ilhs] is the only element of left_ that TryAugment will
11021 // potentially transition from kUnused to another value. Any other
11022 // left_ element holding kUnused before TryAugment will be holding it
11023 // when TryAugment returns.
11025 bool TryAugment(size_t ilhs, ::std::vector<char>* seen) {
11026 for (size_t irhs = 0; irhs < graph_->RhsSize(); ++irhs) {
11029 if (!graph_->HasEdge(ilhs, irhs))
11031 // There's an available edge from ilhs to irhs.
11033 // Next a search is performed to determine whether
11034 // this edge is a dead end or leads to the sink.
11036 // right_[irhs] == kUnused means that there is residual flow from
11037 // right node irhs to the sink, so we can use that to finish this
11038 // flow path and return success.
11040 // Otherwise there is residual flow to some ilhs. We push flow
11041 // along that path and call ourselves recursively to see if this
11042 // ultimately leads to sink.
11043 if (right_[irhs] == kUnused || TryAugment(right_[irhs], seen)) {
11044 // Add flow from left_[ilhs] to right_[irhs].
11045 left_[ilhs] = irhs;
11046 right_[irhs] = ilhs;
11053 const MatchMatrix* graph_; // not owned
11054 // Each element of the left_ vector represents a left hand side node
11055 // (i.e. an element) and each element of right_ is a right hand side
11056 // node (i.e. a matcher). The values in the left_ vector indicate
11057 // outflow from that node to a node on the the right_ side. The values
11058 // in the right_ indicate inflow, and specify which left_ node is
11059 // feeding that right_ node, if any. For example, left_[3] == 1 means
11060 // there's a flow from element #3 to matcher #1. Such a flow would also
11061 // be redundantly represented in the right_ vector as right_[1] == 3.
11062 // Elements of left_ and right_ are either kUnused or mutually
11063 // referent. Mutually referent means that left_[right_[i]] = i and
11064 // right_[left_[i]] = i.
11065 ::std::vector<size_t> left_;
11066 ::std::vector<size_t> right_;
11068 GTEST_DISALLOW_ASSIGN_(MaxBipartiteMatchState);
11071 const size_t MaxBipartiteMatchState::kUnused;
11073 GTEST_API_ ElementMatcherPairs
11074 FindMaxBipartiteMatching(const MatchMatrix& g) {
11075 return MaxBipartiteMatchState(g).Compute();
11078 static void LogElementMatcherPairVec(const ElementMatcherPairs& pairs,
11079 ::std::ostream* stream) {
11080 typedef ElementMatcherPairs::const_iterator Iter;
11081 ::std::ostream& os = *stream;
11083 const char *sep = "";
11084 for (Iter it = pairs.begin(); it != pairs.end(); ++it) {
11085 os << sep << "\n ("
11086 << "element #" << it->first << ", "
11087 << "matcher #" << it->second << ")";
11093 // Tries to find a pairing, and explains the result.
11094 GTEST_API_ bool FindPairing(const MatchMatrix& matrix,
11095 MatchResultListener* listener) {
11096 ElementMatcherPairs matches = FindMaxBipartiteMatching(matrix);
11098 size_t max_flow = matches.size();
11099 bool result = (max_flow == matrix.RhsSize());
11102 if (listener->IsInterested()) {
11103 *listener << "where no permutation of the elements can "
11104 "satisfy all matchers, and the closest match is "
11105 << max_flow << " of " << matrix.RhsSize()
11106 << " matchers with the pairings:\n";
11107 LogElementMatcherPairVec(matches, listener->stream());
11112 if (matches.size() > 1) {
11113 if (listener->IsInterested()) {
11114 const char *sep = "where:\n";
11115 for (size_t mi = 0; mi < matches.size(); ++mi) {
11116 *listener << sep << " - element #" << matches[mi].first
11117 << " is matched by matcher #" << matches[mi].second;
11125 bool MatchMatrix::NextGraph() {
11126 for (size_t ilhs = 0; ilhs < LhsSize(); ++ilhs) {
11127 for (size_t irhs = 0; irhs < RhsSize(); ++irhs) {
11128 char& b = matched_[SpaceIndex(ilhs, irhs)];
11139 void MatchMatrix::Randomize() {
11140 for (size_t ilhs = 0; ilhs < LhsSize(); ++ilhs) {
11141 for (size_t irhs = 0; irhs < RhsSize(); ++irhs) {
11142 char& b = matched_[SpaceIndex(ilhs, irhs)];
11143 b = static_cast<char>(rand() & 1); // NOLINT
11148 string MatchMatrix::DebugString() const {
11149 ::std::stringstream ss;
11150 const char *sep = "";
11151 for (size_t i = 0; i < LhsSize(); ++i) {
11153 for (size_t j = 0; j < RhsSize(); ++j) {
11154 ss << HasEdge(i, j);
11161 void UnorderedElementsAreMatcherImplBase::DescribeToImpl(
11162 ::std::ostream* os) const {
11163 if (matcher_describers_.empty()) {
11167 if (matcher_describers_.size() == 1) {
11168 *os << "has " << Elements(1) << " and that element ";
11169 matcher_describers_[0]->DescribeTo(os);
11172 *os << "has " << Elements(matcher_describers_.size())
11173 << " and there exists some permutation of elements such that:\n";
11174 const char* sep = "";
11175 for (size_t i = 0; i != matcher_describers_.size(); ++i) {
11176 *os << sep << " - element #" << i << " ";
11177 matcher_describers_[i]->DescribeTo(os);
11182 void UnorderedElementsAreMatcherImplBase::DescribeNegationToImpl(
11183 ::std::ostream* os) const {
11184 if (matcher_describers_.empty()) {
11185 *os << "isn't empty";
11188 if (matcher_describers_.size() == 1) {
11189 *os << "doesn't have " << Elements(1)
11190 << ", or has " << Elements(1) << " that ";
11191 matcher_describers_[0]->DescribeNegationTo(os);
11194 *os << "doesn't have " << Elements(matcher_describers_.size())
11195 << ", or there exists no permutation of elements such that:\n";
11196 const char* sep = "";
11197 for (size_t i = 0; i != matcher_describers_.size(); ++i) {
11198 *os << sep << " - element #" << i << " ";
11199 matcher_describers_[i]->DescribeTo(os);
11204 // Checks that all matchers match at least one element, and that all
11205 // elements match at least one matcher. This enables faster matching
11206 // and better error reporting.
11207 // Returns false, writing an explanation to 'listener', if and only
11208 // if the success criteria are not met.
11209 bool UnorderedElementsAreMatcherImplBase::
11210 VerifyAllElementsAndMatchersAreMatched(
11211 const ::std::vector<string>& element_printouts,
11212 const MatchMatrix& matrix,
11213 MatchResultListener* listener) const {
11214 bool result = true;
11215 ::std::vector<char> element_matched(matrix.LhsSize(), 0);
11216 ::std::vector<char> matcher_matched(matrix.RhsSize(), 0);
11218 for (size_t ilhs = 0; ilhs < matrix.LhsSize(); ilhs++) {
11219 for (size_t irhs = 0; irhs < matrix.RhsSize(); irhs++) {
11220 char matched = matrix.HasEdge(ilhs, irhs);
11221 element_matched[ilhs] |= matched;
11222 matcher_matched[irhs] |= matched;
11228 "where the following matchers don't match any elements:\n";
11229 for (size_t mi = 0; mi < matcher_matched.size(); ++mi) {
11230 if (matcher_matched[mi])
11233 if (listener->IsInterested()) {
11234 *listener << sep << "matcher #" << mi << ": ";
11235 matcher_describers_[mi]->DescribeTo(listener->stream());
11243 "where the following elements don't match any matchers:\n";
11244 const char* outer_sep = "";
11246 outer_sep = "\nand ";
11248 for (size_t ei = 0; ei < element_matched.size(); ++ei) {
11249 if (element_matched[ei])
11252 if (listener->IsInterested()) {
11253 *listener << outer_sep << sep << "element #" << ei << ": "
11254 << element_printouts[ei];
11263 } // namespace internal
11264 } // namespace testing
11265 // Copyright 2007, Google Inc.
11266 // All rights reserved.
11268 // Redistribution and use in source and binary forms, with or without
11269 // modification, are permitted provided that the following conditions are
11272 // * Redistributions of source code must retain the above copyright
11273 // notice, this list of conditions and the following disclaimer.
11274 // * Redistributions in binary form must reproduce the above
11275 // copyright notice, this list of conditions and the following disclaimer
11276 // in the documentation and/or other materials provided with the
11278 // * Neither the name of Google Inc. nor the names of its
11279 // contributors may be used to endorse or promote products derived from
11280 // this software without specific prior written permission.
11282 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
11283 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
11284 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
11285 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
11286 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
11287 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
11288 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
11289 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
11290 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
11291 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
11292 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
11294 // Author: wan@google.com (Zhanyong Wan)
11296 // Google Mock - a framework for writing C++ mock classes.
11298 // This file implements the spec builder syntax (ON_CALL and
11302 #include <stdlib.h>
11303 #include <iostream> // NOLINT
11308 #if GTEST_OS_CYGWIN || GTEST_OS_LINUX || GTEST_OS_MAC
11309 # include <unistd.h> // NOLINT
11312 namespace testing {
11313 namespace internal {
11315 // Protects the mock object registry (in class Mock), all function
11316 // mockers, and all expectations.
11317 GTEST_API_ GTEST_DEFINE_STATIC_MUTEX_(g_gmock_mutex);
11319 // Logs a message including file and line number information.
11320 GTEST_API_ void LogWithLocation(testing::internal::LogSeverity severity,
11321 const char* file, int line,
11322 const string& message) {
11323 ::std::ostringstream s;
11324 s << file << ":" << line << ": " << message << ::std::endl;
11325 Log(severity, s.str(), 0);
11328 // Constructs an ExpectationBase object.
11329 ExpectationBase::ExpectationBase(const char* a_file,
11331 const string& a_source_text)
11334 source_text_(a_source_text),
11335 cardinality_specified_(false),
11336 cardinality_(Exactly(1)),
11339 extra_matcher_specified_(false),
11340 repeated_action_specified_(false),
11341 retires_on_saturation_(false),
11342 last_clause_(kNone),
11343 action_count_checked_(false) {}
11345 // Destructs an ExpectationBase object.
11346 ExpectationBase::~ExpectationBase() {}
11348 // Explicitly specifies the cardinality of this expectation. Used by
11349 // the subclasses to implement the .Times() clause.
11350 void ExpectationBase::SpecifyCardinality(const Cardinality& a_cardinality) {
11351 cardinality_specified_ = true;
11352 cardinality_ = a_cardinality;
11355 // Retires all pre-requisites of this expectation.
11356 void ExpectationBase::RetireAllPreRequisites()
11357 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
11358 if (is_retired()) {
11359 // We can take this short-cut as we never retire an expectation
11360 // until we have retired all its pre-requisites.
11364 for (ExpectationSet::const_iterator it = immediate_prerequisites_.begin();
11365 it != immediate_prerequisites_.end(); ++it) {
11366 ExpectationBase* const prerequisite = it->expectation_base().get();
11367 if (!prerequisite->is_retired()) {
11368 prerequisite->RetireAllPreRequisites();
11369 prerequisite->Retire();
11374 // Returns true iff all pre-requisites of this expectation have been
11376 bool ExpectationBase::AllPrerequisitesAreSatisfied() const
11377 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
11378 g_gmock_mutex.AssertHeld();
11379 for (ExpectationSet::const_iterator it = immediate_prerequisites_.begin();
11380 it != immediate_prerequisites_.end(); ++it) {
11381 if (!(it->expectation_base()->IsSatisfied()) ||
11382 !(it->expectation_base()->AllPrerequisitesAreSatisfied()))
11388 // Adds unsatisfied pre-requisites of this expectation to 'result'.
11389 void ExpectationBase::FindUnsatisfiedPrerequisites(ExpectationSet* result) const
11390 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
11391 g_gmock_mutex.AssertHeld();
11392 for (ExpectationSet::const_iterator it = immediate_prerequisites_.begin();
11393 it != immediate_prerequisites_.end(); ++it) {
11394 if (it->expectation_base()->IsSatisfied()) {
11395 // If *it is satisfied and has a call count of 0, some of its
11396 // pre-requisites may not be satisfied yet.
11397 if (it->expectation_base()->call_count_ == 0) {
11398 it->expectation_base()->FindUnsatisfiedPrerequisites(result);
11401 // Now that we know *it is unsatisfied, we are not so interested
11402 // in whether its pre-requisites are satisfied. Therefore we
11403 // don't recursively call FindUnsatisfiedPrerequisites() here.
11409 // Describes how many times a function call matching this
11410 // expectation has occurred.
11411 void ExpectationBase::DescribeCallCountTo(::std::ostream* os) const
11412 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
11413 g_gmock_mutex.AssertHeld();
11415 // Describes how many times the function is expected to be called.
11416 *os << " Expected: to be ";
11417 cardinality().DescribeTo(os);
11418 *os << "\n Actual: ";
11419 Cardinality::DescribeActualCallCountTo(call_count(), os);
11421 // Describes the state of the expectation (e.g. is it satisfied?
11423 *os << " - " << (IsOverSaturated() ? "over-saturated" :
11424 IsSaturated() ? "saturated" :
11425 IsSatisfied() ? "satisfied" : "unsatisfied")
11427 << (is_retired() ? "retired" : "active");
11430 // Checks the action count (i.e. the number of WillOnce() and
11431 // WillRepeatedly() clauses) against the cardinality if this hasn't
11432 // been done before. Prints a warning if there are too many or too
11434 void ExpectationBase::CheckActionCountIfNotDone() const
11435 GTEST_LOCK_EXCLUDED_(mutex_) {
11436 bool should_check = false;
11438 MutexLock l(&mutex_);
11439 if (!action_count_checked_) {
11440 action_count_checked_ = true;
11441 should_check = true;
11445 if (should_check) {
11446 if (!cardinality_specified_) {
11447 // The cardinality was inferred - no need to check the action
11448 // count against it.
11452 // The cardinality was explicitly specified.
11453 const int action_count = static_cast<int>(untyped_actions_.size());
11454 const int upper_bound = cardinality().ConservativeUpperBound();
11455 const int lower_bound = cardinality().ConservativeLowerBound();
11456 bool too_many; // True if there are too many actions, or false
11457 // if there are too few.
11458 if (action_count > upper_bound ||
11459 (action_count == upper_bound && repeated_action_specified_)) {
11461 } else if (0 < action_count && action_count < lower_bound &&
11462 !repeated_action_specified_) {
11468 ::std::stringstream ss;
11469 DescribeLocationTo(&ss);
11470 ss << "Too " << (too_many ? "many" : "few")
11471 << " actions specified in " << source_text() << "...\n"
11472 << "Expected to be ";
11473 cardinality().DescribeTo(&ss);
11474 ss << ", but has " << (too_many ? "" : "only ")
11475 << action_count << " WillOnce()"
11476 << (action_count == 1 ? "" : "s");
11477 if (repeated_action_specified_) {
11478 ss << " and a WillRepeatedly()";
11481 Log(kWarning, ss.str(), -1); // -1 means "don't print stack trace".
11485 // Implements the .Times() clause.
11486 void ExpectationBase::UntypedTimes(const Cardinality& a_cardinality) {
11487 if (last_clause_ == kTimes) {
11488 ExpectSpecProperty(false,
11489 ".Times() cannot appear "
11490 "more than once in an EXPECT_CALL().");
11492 ExpectSpecProperty(last_clause_ < kTimes,
11493 ".Times() cannot appear after "
11494 ".InSequence(), .WillOnce(), .WillRepeatedly(), "
11495 "or .RetiresOnSaturation().");
11497 last_clause_ = kTimes;
11499 SpecifyCardinality(a_cardinality);
11502 // Points to the implicit sequence introduced by a living InSequence
11503 // object (if any) in the current thread or NULL.
11504 GTEST_API_ ThreadLocal<Sequence*> g_gmock_implicit_sequence;
11506 // Reports an uninteresting call (whose description is in msg) in the
11507 // manner specified by 'reaction'.
11508 void ReportUninterestingCall(CallReaction reaction, const string& msg) {
11509 // Include a stack trace only if --gmock_verbose=info is specified.
11510 const int stack_frames_to_skip =
11511 GMOCK_FLAG(verbose) == kInfoVerbosity ? 3 : -1;
11512 switch (reaction) {
11514 Log(kInfo, msg, stack_frames_to_skip);
11519 "\nNOTE: You can safely ignore the above warning unless this "
11520 "call should not happen. Do not suppress it by blindly adding "
11521 "an EXPECT_CALL() if you don't mean to enforce the call. "
11522 "See https://github.com/google/googletest/blob/master/googlemock/docs/CookBook.md#"
11523 "knowing-when-to-expect for details.\n",
11524 stack_frames_to_skip);
11527 Expect(false, NULL, -1, msg);
11531 UntypedFunctionMockerBase::UntypedFunctionMockerBase()
11532 : mock_obj_(NULL), name_("") {}
11534 UntypedFunctionMockerBase::~UntypedFunctionMockerBase() {}
11536 // Sets the mock object this mock method belongs to, and registers
11537 // this information in the global mock registry. Will be called
11538 // whenever an EXPECT_CALL() or ON_CALL() is executed on this mock
11540 void UntypedFunctionMockerBase::RegisterOwner(const void* mock_obj)
11541 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
11543 MutexLock l(&g_gmock_mutex);
11544 mock_obj_ = mock_obj;
11546 Mock::Register(mock_obj, this);
11549 // Sets the mock object this mock method belongs to, and sets the name
11550 // of the mock function. Will be called upon each invocation of this
11552 void UntypedFunctionMockerBase::SetOwnerAndName(const void* mock_obj,
11554 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
11555 // We protect name_ under g_gmock_mutex in case this mock function
11556 // is called from two threads concurrently.
11557 MutexLock l(&g_gmock_mutex);
11558 mock_obj_ = mock_obj;
11562 // Returns the name of the function being mocked. Must be called
11563 // after RegisterOwner() or SetOwnerAndName() has been called.
11564 const void* UntypedFunctionMockerBase::MockObject() const
11565 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
11566 const void* mock_obj;
11568 // We protect mock_obj_ under g_gmock_mutex in case this mock
11569 // function is called from two threads concurrently.
11570 MutexLock l(&g_gmock_mutex);
11571 Assert(mock_obj_ != NULL, __FILE__, __LINE__,
11572 "MockObject() must not be called before RegisterOwner() or "
11573 "SetOwnerAndName() has been called.");
11574 mock_obj = mock_obj_;
11579 // Returns the name of this mock method. Must be called after
11580 // SetOwnerAndName() has been called.
11581 const char* UntypedFunctionMockerBase::Name() const
11582 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
11585 // We protect name_ under g_gmock_mutex in case this mock
11586 // function is called from two threads concurrently.
11587 MutexLock l(&g_gmock_mutex);
11588 Assert(name_ != NULL, __FILE__, __LINE__,
11589 "Name() must not be called before SetOwnerAndName() has "
11596 // Calculates the result of invoking this mock function with the given
11597 // arguments, prints it, and returns it. The caller is responsible
11598 // for deleting the result.
11599 UntypedActionResultHolderBase*
11600 UntypedFunctionMockerBase::UntypedInvokeWith(const void* const untyped_args)
11601 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
11602 if (untyped_expectations_.size() == 0) {
11603 // No expectation is set on this mock method - we have an
11604 // uninteresting call.
11606 // We must get Google Mock's reaction on uninteresting calls
11607 // made on this mock object BEFORE performing the action,
11608 // because the action may DELETE the mock object and make the
11609 // following expression meaningless.
11610 const CallReaction reaction =
11611 Mock::GetReactionOnUninterestingCalls(MockObject());
11613 // True iff we need to print this call's arguments and return
11614 // value. This definition must be kept in sync with
11615 // the behavior of ReportUninterestingCall().
11616 const bool need_to_report_uninteresting_call =
11617 // If the user allows this uninteresting call, we print it
11618 // only when he wants informational messages.
11619 reaction == kAllow ? LogIsVisible(kInfo) :
11620 // If the user wants this to be a warning, we print it only
11621 // when he wants to see warnings.
11622 reaction == kWarn ? LogIsVisible(kWarning) :
11623 // Otherwise, the user wants this to be an error, and we
11624 // should always print detailed information in the error.
11627 if (!need_to_report_uninteresting_call) {
11628 // Perform the action without printing the call information.
11629 return this->UntypedPerformDefaultAction(untyped_args, "");
11632 // Warns about the uninteresting call.
11633 ::std::stringstream ss;
11634 this->UntypedDescribeUninterestingCall(untyped_args, &ss);
11636 // Calculates the function result.
11637 UntypedActionResultHolderBase* const result =
11638 this->UntypedPerformDefaultAction(untyped_args, ss.str());
11640 // Prints the function result.
11641 if (result != NULL)
11642 result->PrintAsActionResult(&ss);
11644 ReportUninterestingCall(reaction, ss.str());
11648 bool is_excessive = false;
11649 ::std::stringstream ss;
11650 ::std::stringstream why;
11651 ::std::stringstream loc;
11652 const void* untyped_action = NULL;
11654 // The UntypedFindMatchingExpectation() function acquires and
11655 // releases g_gmock_mutex.
11656 const ExpectationBase* const untyped_expectation =
11657 this->UntypedFindMatchingExpectation(
11658 untyped_args, &untyped_action, &is_excessive,
11660 const bool found = untyped_expectation != NULL;
11662 // True iff we need to print the call's arguments and return value.
11663 // This definition must be kept in sync with the uses of Expect()
11664 // and Log() in this function.
11665 const bool need_to_report_call =
11666 !found || is_excessive || LogIsVisible(kInfo);
11667 if (!need_to_report_call) {
11668 // Perform the action without printing the call information.
11670 untyped_action == NULL ?
11671 this->UntypedPerformDefaultAction(untyped_args, "") :
11672 this->UntypedPerformAction(untyped_action, untyped_args);
11675 ss << " Function call: " << Name();
11676 this->UntypedPrintArgs(untyped_args, &ss);
11678 // In case the action deletes a piece of the expectation, we
11679 // generate the message beforehand.
11680 if (found && !is_excessive) {
11681 untyped_expectation->DescribeLocationTo(&loc);
11684 UntypedActionResultHolderBase* const result =
11685 untyped_action == NULL ?
11686 this->UntypedPerformDefaultAction(untyped_args, ss.str()) :
11687 this->UntypedPerformAction(untyped_action, untyped_args);
11688 if (result != NULL)
11689 result->PrintAsActionResult(&ss);
11690 ss << "\n" << why.str();
11693 // No expectation matches this call - reports a failure.
11694 Expect(false, NULL, -1, ss.str());
11695 } else if (is_excessive) {
11696 // We had an upper-bound violation and the failure message is in ss.
11697 Expect(false, untyped_expectation->file(),
11698 untyped_expectation->line(), ss.str());
11700 // We had an expected call and the matching expectation is
11701 // described in ss.
11702 Log(kInfo, loc.str() + ss.str(), 2);
11708 // Returns an Expectation object that references and co-owns exp,
11709 // which must be an expectation on this mock function.
11710 Expectation UntypedFunctionMockerBase::GetHandleOf(ExpectationBase* exp) {
11711 for (UntypedExpectations::const_iterator it =
11712 untyped_expectations_.begin();
11713 it != untyped_expectations_.end(); ++it) {
11714 if (it->get() == exp) {
11715 return Expectation(*it);
11719 Assert(false, __FILE__, __LINE__, "Cannot find expectation.");
11720 return Expectation();
11721 // The above statement is just to make the code compile, and will
11722 // never be executed.
11725 // Verifies that all expectations on this mock function have been
11726 // satisfied. Reports one or more Google Test non-fatal failures
11727 // and returns false if not.
11728 bool UntypedFunctionMockerBase::VerifyAndClearExpectationsLocked()
11729 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
11730 g_gmock_mutex.AssertHeld();
11731 bool expectations_met = true;
11732 for (UntypedExpectations::const_iterator it =
11733 untyped_expectations_.begin();
11734 it != untyped_expectations_.end(); ++it) {
11735 ExpectationBase* const untyped_expectation = it->get();
11736 if (untyped_expectation->IsOverSaturated()) {
11737 // There was an upper-bound violation. Since the error was
11738 // already reported when it occurred, there is no need to do
11740 expectations_met = false;
11741 } else if (!untyped_expectation->IsSatisfied()) {
11742 expectations_met = false;
11743 ::std::stringstream ss;
11744 ss << "Actual function call count doesn't match "
11745 << untyped_expectation->source_text() << "...\n";
11746 // No need to show the source file location of the expectation
11747 // in the description, as the Expect() call that follows already
11748 // takes care of it.
11749 untyped_expectation->MaybeDescribeExtraMatcherTo(&ss);
11750 untyped_expectation->DescribeCallCountTo(&ss);
11751 Expect(false, untyped_expectation->file(),
11752 untyped_expectation->line(), ss.str());
11756 // Deleting our expectations may trigger other mock objects to be deleted, for
11757 // example if an action contains a reference counted smart pointer to that
11758 // mock object, and that is the last reference. So if we delete our
11759 // expectations within the context of the global mutex we may deadlock when
11760 // this method is called again. Instead, make a copy of the set of
11761 // expectations to delete, clear our set within the mutex, and then clear the
11762 // copied set outside of it.
11763 UntypedExpectations expectations_to_delete;
11764 untyped_expectations_.swap(expectations_to_delete);
11766 g_gmock_mutex.Unlock();
11767 expectations_to_delete.clear();
11768 g_gmock_mutex.Lock();
11770 return expectations_met;
11773 } // namespace internal
11779 typedef std::set<internal::UntypedFunctionMockerBase*> FunctionMockers;
11781 // The current state of a mock object. Such information is needed for
11782 // detecting leaked mock objects and explicitly verifying a mock's
11784 struct MockObjectState {
11786 : first_used_file(NULL), first_used_line(-1), leakable(false) {}
11788 // Where in the source file an ON_CALL or EXPECT_CALL is first
11789 // invoked on this mock object.
11790 const char* first_used_file;
11791 int first_used_line;
11792 ::std::string first_used_test_case;
11793 ::std::string first_used_test;
11794 bool leakable; // true iff it's OK to leak the object.
11795 FunctionMockers function_mockers; // All registered methods of the object.
11798 // A global registry holding the state of all mock objects that are
11799 // alive. A mock object is added to this registry the first time
11800 // Mock::AllowLeak(), ON_CALL(), or EXPECT_CALL() is called on it. It
11801 // is removed from the registry in the mock object's destructor.
11802 class MockObjectRegistry {
11804 // Maps a mock object (identified by its address) to its state.
11805 typedef std::map<const void*, MockObjectState> StateMap;
11807 // This destructor will be called when a program exits, after all
11808 // tests in it have been run. By then, there should be no mock
11809 // object alive. Therefore we report any living object as test
11810 // failure, unless the user explicitly asked us to ignore it.
11811 ~MockObjectRegistry() {
11812 // "using ::std::cout;" doesn't work with Symbian's STLport, where cout is
11815 if (!GMOCK_FLAG(catch_leaked_mocks))
11818 int leaked_count = 0;
11819 for (StateMap::const_iterator it = states_.begin(); it != states_.end();
11821 if (it->second.leakable) // The user said it's fine to leak this object.
11824 // TODO(wan@google.com): Print the type of the leaked object.
11825 // This can help the user identify the leaked object.
11827 const MockObjectState& state = it->second;
11828 std::cout << internal::FormatFileLocation(state.first_used_file,
11829 state.first_used_line);
11830 std::cout << " ERROR: this mock object";
11831 if (state.first_used_test != "") {
11832 std::cout << " (used in test " << state.first_used_test_case << "."
11833 << state.first_used_test << ")";
11835 std::cout << " should be deleted but never is. Its address is @"
11836 << it->first << ".";
11839 if (leaked_count > 0) {
11840 std::cout << "\nERROR: " << leaked_count
11841 << " leaked mock " << (leaked_count == 1 ? "object" : "objects")
11842 << " found at program exit.\n";
11844 ::std::cerr.flush();
11845 // RUN_ALL_TESTS() has already returned when this destructor is
11846 // called. Therefore we cannot use the normal Google Test
11847 // failure reporting mechanism.
11848 _exit(1); // We cannot call exit() as it is not reentrant and
11849 // may already have been called.
11853 StateMap& states() { return states_; }
11859 // Protected by g_gmock_mutex.
11860 MockObjectRegistry g_mock_object_registry;
11862 // Maps a mock object to the reaction Google Mock should have when an
11863 // uninteresting method is called. Protected by g_gmock_mutex.
11864 std::map<const void*, internal::CallReaction> g_uninteresting_call_reaction;
11866 // Sets the reaction Google Mock should have when an uninteresting
11867 // method of the given mock object is called.
11868 void SetReactionOnUninterestingCalls(const void* mock_obj,
11869 internal::CallReaction reaction)
11870 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
11871 internal::MutexLock l(&internal::g_gmock_mutex);
11872 g_uninteresting_call_reaction[mock_obj] = reaction;
11877 // Tells Google Mock to allow uninteresting calls on the given mock
11879 void Mock::AllowUninterestingCalls(const void* mock_obj)
11880 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
11881 SetReactionOnUninterestingCalls(mock_obj, internal::kAllow);
11884 // Tells Google Mock to warn the user about uninteresting calls on the
11885 // given mock object.
11886 void Mock::WarnUninterestingCalls(const void* mock_obj)
11887 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
11888 SetReactionOnUninterestingCalls(mock_obj, internal::kWarn);
11891 // Tells Google Mock to fail uninteresting calls on the given mock
11893 void Mock::FailUninterestingCalls(const void* mock_obj)
11894 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
11895 SetReactionOnUninterestingCalls(mock_obj, internal::kFail);
11898 // Tells Google Mock the given mock object is being destroyed and its
11899 // entry in the call-reaction table should be removed.
11900 void Mock::UnregisterCallReaction(const void* mock_obj)
11901 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
11902 internal::MutexLock l(&internal::g_gmock_mutex);
11903 g_uninteresting_call_reaction.erase(mock_obj);
11906 // Returns the reaction Google Mock will have on uninteresting calls
11907 // made on the given mock object.
11908 internal::CallReaction Mock::GetReactionOnUninterestingCalls(
11909 const void* mock_obj)
11910 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
11911 internal::MutexLock l(&internal::g_gmock_mutex);
11912 return (g_uninteresting_call_reaction.count(mock_obj) == 0) ?
11913 internal::kDefault : g_uninteresting_call_reaction[mock_obj];
11916 // Tells Google Mock to ignore mock_obj when checking for leaked mock
11918 void Mock::AllowLeak(const void* mock_obj)
11919 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
11920 internal::MutexLock l(&internal::g_gmock_mutex);
11921 g_mock_object_registry.states()[mock_obj].leakable = true;
11924 // Verifies and clears all expectations on the given mock object. If
11925 // the expectations aren't satisfied, generates one or more Google
11926 // Test non-fatal failures and returns false.
11927 bool Mock::VerifyAndClearExpectations(void* mock_obj)
11928 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
11929 internal::MutexLock l(&internal::g_gmock_mutex);
11930 return VerifyAndClearExpectationsLocked(mock_obj);
11933 // Verifies all expectations on the given mock object and clears its
11934 // default actions and expectations. Returns true iff the
11935 // verification was successful.
11936 bool Mock::VerifyAndClear(void* mock_obj)
11937 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
11938 internal::MutexLock l(&internal::g_gmock_mutex);
11939 ClearDefaultActionsLocked(mock_obj);
11940 return VerifyAndClearExpectationsLocked(mock_obj);
11943 // Verifies and clears all expectations on the given mock object. If
11944 // the expectations aren't satisfied, generates one or more Google
11945 // Test non-fatal failures and returns false.
11946 bool Mock::VerifyAndClearExpectationsLocked(void* mock_obj)
11947 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) {
11948 internal::g_gmock_mutex.AssertHeld();
11949 if (g_mock_object_registry.states().count(mock_obj) == 0) {
11950 // No EXPECT_CALL() was set on the given mock object.
11954 // Verifies and clears the expectations on each mock method in the
11955 // given mock object.
11956 bool expectations_met = true;
11957 FunctionMockers& mockers =
11958 g_mock_object_registry.states()[mock_obj].function_mockers;
11959 for (FunctionMockers::const_iterator it = mockers.begin();
11960 it != mockers.end(); ++it) {
11961 if (!(*it)->VerifyAndClearExpectationsLocked()) {
11962 expectations_met = false;
11966 // We don't clear the content of mockers, as they may still be
11967 // needed by ClearDefaultActionsLocked().
11968 return expectations_met;
11971 // Registers a mock object and a mock method it owns.
11972 void Mock::Register(const void* mock_obj,
11973 internal::UntypedFunctionMockerBase* mocker)
11974 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
11975 internal::MutexLock l(&internal::g_gmock_mutex);
11976 g_mock_object_registry.states()[mock_obj].function_mockers.insert(mocker);
11979 // Tells Google Mock where in the source code mock_obj is used in an
11980 // ON_CALL or EXPECT_CALL. In case mock_obj is leaked, this
11981 // information helps the user identify which object it is.
11982 void Mock::RegisterUseByOnCallOrExpectCall(const void* mock_obj,
11983 const char* file, int line)
11984 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
11985 internal::MutexLock l(&internal::g_gmock_mutex);
11986 MockObjectState& state = g_mock_object_registry.states()[mock_obj];
11987 if (state.first_used_file == NULL) {
11988 state.first_used_file = file;
11989 state.first_used_line = line;
11990 const TestInfo* const test_info =
11991 UnitTest::GetInstance()->current_test_info();
11992 if (test_info != NULL) {
11993 // TODO(wan@google.com): record the test case name when the
11994 // ON_CALL or EXPECT_CALL is invoked from SetUpTestCase() or
11995 // TearDownTestCase().
11996 state.first_used_test_case = test_info->test_case_name();
11997 state.first_used_test = test_info->name();
12002 // Unregisters a mock method; removes the owning mock object from the
12003 // registry when the last mock method associated with it has been
12004 // unregistered. This is called only in the destructor of
12005 // FunctionMockerBase.
12006 void Mock::UnregisterLocked(internal::UntypedFunctionMockerBase* mocker)
12007 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) {
12008 internal::g_gmock_mutex.AssertHeld();
12009 for (MockObjectRegistry::StateMap::iterator it =
12010 g_mock_object_registry.states().begin();
12011 it != g_mock_object_registry.states().end(); ++it) {
12012 FunctionMockers& mockers = it->second.function_mockers;
12013 if (mockers.erase(mocker) > 0) {
12014 // mocker was in mockers and has been just removed.
12015 if (mockers.empty()) {
12016 g_mock_object_registry.states().erase(it);
12023 // Clears all ON_CALL()s set on the given mock object.
12024 void Mock::ClearDefaultActionsLocked(void* mock_obj)
12025 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) {
12026 internal::g_gmock_mutex.AssertHeld();
12028 if (g_mock_object_registry.states().count(mock_obj) == 0) {
12029 // No ON_CALL() was set on the given mock object.
12033 // Clears the default actions for each mock method in the given mock
12035 FunctionMockers& mockers =
12036 g_mock_object_registry.states()[mock_obj].function_mockers;
12037 for (FunctionMockers::const_iterator it = mockers.begin();
12038 it != mockers.end(); ++it) {
12039 (*it)->ClearDefaultActionsLocked();
12042 // We don't clear the content of mockers, as they may still be
12043 // needed by VerifyAndClearExpectationsLocked().
12046 Expectation::Expectation() {}
12048 Expectation::Expectation(
12049 const internal::linked_ptr<internal::ExpectationBase>& an_expectation_base)
12050 : expectation_base_(an_expectation_base) {}
12052 Expectation::~Expectation() {}
12054 // Adds an expectation to a sequence.
12055 void Sequence::AddExpectation(const Expectation& expectation) const {
12056 if (*last_expectation_ != expectation) {
12057 if (last_expectation_->expectation_base() != NULL) {
12058 expectation.expectation_base()->immediate_prerequisites_
12059 += *last_expectation_;
12061 *last_expectation_ = expectation;
12065 // Creates the implicit sequence if there isn't one.
12066 InSequence::InSequence() {
12067 if (internal::g_gmock_implicit_sequence.get() == NULL) {
12068 internal::g_gmock_implicit_sequence.set(new Sequence);
12069 sequence_created_ = true;
12071 sequence_created_ = false;
12075 // Deletes the implicit sequence if it was created by the constructor
12077 InSequence::~InSequence() {
12078 if (sequence_created_) {
12079 delete internal::g_gmock_implicit_sequence.get();
12080 internal::g_gmock_implicit_sequence.set(NULL);
12084 } // namespace testing
12085 // Copyright 2008, Google Inc.
12086 // All rights reserved.
12088 // Redistribution and use in source and binary forms, with or without
12089 // modification, are permitted provided that the following conditions are
12092 // * Redistributions of source code must retain the above copyright
12093 // notice, this list of conditions and the following disclaimer.
12094 // * Redistributions in binary form must reproduce the above
12095 // copyright notice, this list of conditions and the following disclaimer
12096 // in the documentation and/or other materials provided with the
12098 // * Neither the name of Google Inc. nor the names of its
12099 // contributors may be used to endorse or promote products derived from
12100 // this software without specific prior written permission.
12102 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
12103 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
12104 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
12105 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
12106 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
12107 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
12108 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
12109 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
12110 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
12111 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
12112 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
12114 // Author: wan@google.com (Zhanyong Wan)
12117 namespace testing {
12119 // TODO(wan@google.com): support using environment variables to
12120 // control the flag values, like what Google Test does.
12122 GMOCK_DEFINE_bool_(catch_leaked_mocks, true,
12123 "true iff Google Mock should report leaked mock objects "
12126 GMOCK_DEFINE_string_(verbose, internal::kWarningVerbosity,
12127 "Controls how verbose Google Mock's output is."
12129 " info - prints all messages.\n"
12130 " warning - prints warnings and errors.\n"
12131 " error - prints errors only.");
12133 namespace internal {
12135 // Parses a string as a command line flag. The string should have the
12136 // format "--gmock_flag=value". When def_optional is true, the
12137 // "=value" part can be omitted.
12139 // Returns the value of the flag, or NULL if the parsing failed.
12140 static const char* ParseGoogleMockFlagValue(const char* str,
12142 bool def_optional) {
12143 // str and flag must not be NULL.
12144 if (str == NULL || flag == NULL) return NULL;
12146 // The flag must start with "--gmock_".
12147 const std::string flag_str = std::string("--gmock_") + flag;
12148 const size_t flag_len = flag_str.length();
12149 if (strncmp(str, flag_str.c_str(), flag_len) != 0) return NULL;
12151 // Skips the flag name.
12152 const char* flag_end = str + flag_len;
12154 // When def_optional is true, it's OK to not have a "=value" part.
12155 if (def_optional && (flag_end[0] == '\0')) {
12159 // If def_optional is true and there are more characters after the
12160 // flag name, or if def_optional is false, there must be a '=' after
12162 if (flag_end[0] != '=') return NULL;
12164 // Returns the string after "=".
12165 return flag_end + 1;
12168 // Parses a string for a Google Mock bool flag, in the form of
12169 // "--gmock_flag=value".
12171 // On success, stores the value of the flag in *value, and returns
12172 // true. On failure, returns false without changing *value.
12173 static bool ParseGoogleMockBoolFlag(const char* str, const char* flag,
12175 // Gets the value of the flag as a string.
12176 const char* const value_str = ParseGoogleMockFlagValue(str, flag, true);
12178 // Aborts if the parsing failed.
12179 if (value_str == NULL) return false;
12181 // Converts the string value to a bool.
12182 *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F');
12186 // Parses a string for a Google Mock string flag, in the form of
12187 // "--gmock_flag=value".
12189 // On success, stores the value of the flag in *value, and returns
12190 // true. On failure, returns false without changing *value.
12191 template <typename String>
12192 static bool ParseGoogleMockStringFlag(const char* str, const char* flag,
12194 // Gets the value of the flag as a string.
12195 const char* const value_str = ParseGoogleMockFlagValue(str, flag, false);
12197 // Aborts if the parsing failed.
12198 if (value_str == NULL) return false;
12200 // Sets *value to the value of the flag.
12201 *value = value_str;
12205 // The internal implementation of InitGoogleMock().
12207 // The type parameter CharType can be instantiated to either char or
12209 template <typename CharType>
12210 void InitGoogleMockImpl(int* argc, CharType** argv) {
12211 // Makes sure Google Test is initialized. InitGoogleTest() is
12212 // idempotent, so it's fine if the user has already called it.
12213 InitGoogleTest(argc, argv);
12214 if (*argc <= 0) return;
12216 for (int i = 1; i != *argc; i++) {
12217 const std::string arg_string = StreamableToString(argv[i]);
12218 const char* const arg = arg_string.c_str();
12220 // Do we see a Google Mock flag?
12221 if (ParseGoogleMockBoolFlag(arg, "catch_leaked_mocks",
12222 &GMOCK_FLAG(catch_leaked_mocks)) ||
12223 ParseGoogleMockStringFlag(arg, "verbose", &GMOCK_FLAG(verbose))) {
12224 // Yes. Shift the remainder of the argv list left by one. Note
12225 // that argv has (*argc + 1) elements, the last one always being
12226 // NULL. The following loop moves the trailing NULL element as
12228 for (int j = i; j != *argc; j++) {
12229 argv[j] = argv[j + 1];
12232 // Decrements the argument count.
12235 // We also need to decrement the iterator as we just removed
12242 } // namespace internal
12244 // Initializes Google Mock. This must be called before running the
12245 // tests. In particular, it parses a command line for the flags that
12246 // Google Mock recognizes. Whenever a Google Mock flag is seen, it is
12247 // removed from argv, and *argc is decremented.
12249 // No value is returned. Instead, the Google Mock flag variables are
12252 // Since Google Test is needed for Google Mock to work, this function
12253 // also initializes Google Test and parses its flags, if that hasn't
12255 GTEST_API_ void InitGoogleMock(int* argc, char** argv) {
12256 internal::InitGoogleMockImpl(argc, argv);
12259 // This overloaded version can be used in Windows programs compiled in
12261 GTEST_API_ void InitGoogleMock(int* argc, wchar_t** argv) {
12262 internal::InitGoogleMockImpl(argc, argv);
12265 } // namespace testing