1 // Copyright 2008, Google Inc.
2 // All rights reserved.
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
8 // * Redistributions of source code must retain the above copyright
9 // notice, this list of conditions and the following disclaimer.
10 // * Redistributions in binary form must reproduce the above
11 // copyright notice, this list of conditions and the following disclaimer
12 // in the documentation and/or other materials provided with the
14 // * Neither the name of Google Inc. nor the names of its
15 // contributors may be used to endorse or promote products derived from
16 // this software without specific prior written permission.
18 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 // Author: mheule@google.com (Markus Heule)
32 // Google C++ Testing Framework (Google Test)
34 // Sometimes it's desirable to build Google Test by compiling a single file.
35 // This file serves this purpose.
37 // This line ensures that gtest.h can be compiled on its own, even
39 #include "precomp.hpp"
42 # pragma GCC diagnostic ignored "-Wmissing-declarations"
43 # pragma GCC diagnostic ignored "-Wmissing-field-initializers"
46 // The following lines pull in the real gtest *.cc files.
47 // Copyright 2005, Google Inc.
48 // All rights reserved.
50 // Redistribution and use in source and binary forms, with or without
51 // modification, are permitted provided that the following conditions are
54 // * Redistributions of source code must retain the above copyright
55 // notice, this list of conditions and the following disclaimer.
56 // * Redistributions in binary form must reproduce the above
57 // copyright notice, this list of conditions and the following disclaimer
58 // in the documentation and/or other materials provided with the
60 // * Neither the name of Google Inc. nor the names of its
61 // contributors may be used to endorse or promote products derived from
62 // this software without specific prior written permission.
64 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
65 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
66 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
67 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
68 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
69 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
70 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
71 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
72 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
73 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
74 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
76 // Author: wan@google.com (Zhanyong Wan)
78 // The Google C++ Testing Framework (Google Test)
80 // Copyright 2007, Google Inc.
81 // All rights reserved.
83 // Redistribution and use in source and binary forms, with or without
84 // modification, are permitted provided that the following conditions are
87 // * Redistributions of source code must retain the above copyright
88 // notice, this list of conditions and the following disclaimer.
89 // * Redistributions in binary form must reproduce the above
90 // copyright notice, this list of conditions and the following disclaimer
91 // in the documentation and/or other materials provided with the
93 // * Neither the name of Google Inc. nor the names of its
94 // contributors may be used to endorse or promote products derived from
95 // this software without specific prior written permission.
97 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
98 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
99 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
100 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
101 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
102 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
103 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
104 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
105 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
106 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
107 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
109 // Author: wan@google.com (Zhanyong Wan)
111 // Utilities for testing Google Test itself and code that uses Google Test
112 // (e.g. frameworks built on top of Google Test).
114 #ifndef GTEST_INCLUDE_GTEST_GTEST_SPI_H_
115 #define GTEST_INCLUDE_GTEST_GTEST_SPI_H_
120 // This helper class can be used to mock out Google Test failure reporting
121 // so that we can test Google Test or code that builds on Google Test.
123 // An object of this class appends a TestPartResult object to the
124 // TestPartResultArray object given in the constructor whenever a Google Test
125 // failure is reported. It can either intercept only failures that are
126 // generated in the same thread that created this object or it can intercept
127 // all generated failures. The scope of this mock object can be controlled with
128 // the second argument to the two arguments constructor.
129 class GTEST_API_ ScopedFakeTestPartResultReporter
130 : public TestPartResultReporterInterface {
132 // The two possible mocking modes of this object.
134 INTERCEPT_ONLY_CURRENT_THREAD, // Intercepts only thread local failures.
135 INTERCEPT_ALL_THREADS // Intercepts all failures.
138 // The c'tor sets this object as the test part result reporter used
139 // by Google Test. The 'result' parameter specifies where to report the
140 // results. This reporter will only catch failures generated in the current
141 // thread. DEPRECATED
142 explicit ScopedFakeTestPartResultReporter(TestPartResultArray* result);
144 // Same as above, but you can choose the interception scope of this object.
145 ScopedFakeTestPartResultReporter(InterceptMode intercept_mode,
146 TestPartResultArray* result);
148 // The d'tor restores the previous test part result reporter.
149 virtual ~ScopedFakeTestPartResultReporter();
151 // Appends the TestPartResult object to the TestPartResultArray
152 // received in the constructor.
154 // This method is from the TestPartResultReporterInterface
156 virtual void ReportTestPartResult(const TestPartResult& result);
160 const InterceptMode intercept_mode_;
161 TestPartResultReporterInterface* old_reporter_;
162 TestPartResultArray* const result_;
164 GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedFakeTestPartResultReporter);
169 // A helper class for implementing EXPECT_FATAL_FAILURE() and
170 // EXPECT_NONFATAL_FAILURE(). Its destructor verifies that the given
171 // TestPartResultArray contains exactly one failure that has the given
172 // type and contains the given substring. If that's not the case, a
173 // non-fatal failure will be generated.
174 class GTEST_API_ SingleFailureChecker {
176 // The constructor remembers the arguments.
177 SingleFailureChecker(const TestPartResultArray* results,
178 TestPartResult::Type type,
179 const string& substr);
180 ~SingleFailureChecker();
182 const TestPartResultArray* const results_;
183 const TestPartResult::Type type_;
184 const string substr_;
186 GTEST_DISALLOW_COPY_AND_ASSIGN_(SingleFailureChecker);
189 } // namespace internal
191 } // namespace testing
193 // A set of macros for testing Google Test assertions or code that's expected
194 // to generate Google Test fatal failures. It verifies that the given
195 // statement will cause exactly one fatal Google Test failure with 'substr'
196 // being part of the failure message.
198 // There are two different versions of this macro. EXPECT_FATAL_FAILURE only
199 // affects and considers failures generated in the current thread and
200 // EXPECT_FATAL_FAILURE_ON_ALL_THREADS does the same but for all threads.
202 // The verification of the assertion is done correctly even when the statement
203 // throws an exception or aborts the current function.
205 // Known restrictions:
206 // - 'statement' cannot reference local non-static variables or
207 // non-static members of the current object.
208 // - 'statement' cannot return a value.
209 // - You cannot stream a failure message to this macro.
211 // Note that even though the implementations of the following two
212 // macros are much alike, we cannot refactor them to use a common
213 // helper macro, due to some peculiarity in how the preprocessor
214 // works. The AcceptsMacroThatExpandsToUnprotectedComma test in
215 // gtest_unittest.cc will fail to compile if we do that.
216 #define EXPECT_FATAL_FAILURE(statement, substr) \
218 class GTestExpectFatalFailureHelper {\
220 static void Execute() { statement; }\
222 ::testing::TestPartResultArray gtest_failures;\
223 ::testing::internal::SingleFailureChecker gtest_checker(\
224 >est_failures, ::testing::TestPartResult::kFatalFailure, (substr));\
226 ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
227 ::testing::ScopedFakeTestPartResultReporter:: \
228 INTERCEPT_ONLY_CURRENT_THREAD, >est_failures);\
229 GTestExpectFatalFailureHelper::Execute();\
231 } while (::testing::internal::AlwaysFalse())
233 #define EXPECT_FATAL_FAILURE_ON_ALL_THREADS(statement, substr) \
235 class GTestExpectFatalFailureHelper {\
237 static void Execute() { statement; }\
239 ::testing::TestPartResultArray gtest_failures;\
240 ::testing::internal::SingleFailureChecker gtest_checker(\
241 >est_failures, ::testing::TestPartResult::kFatalFailure, (substr));\
243 ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
244 ::testing::ScopedFakeTestPartResultReporter:: \
245 INTERCEPT_ALL_THREADS, >est_failures);\
246 GTestExpectFatalFailureHelper::Execute();\
248 } while (::testing::internal::AlwaysFalse())
250 // A macro for testing Google Test assertions or code that's expected to
251 // generate Google Test non-fatal failures. It asserts that the given
252 // statement will cause exactly one non-fatal Google Test failure with 'substr'
253 // being part of the failure message.
255 // There are two different versions of this macro. EXPECT_NONFATAL_FAILURE only
256 // affects and considers failures generated in the current thread and
257 // EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS does the same but for all threads.
259 // 'statement' is allowed to reference local variables and members of
260 // the current object.
262 // The verification of the assertion is done correctly even when the statement
263 // throws an exception or aborts the current function.
265 // Known restrictions:
266 // - You cannot stream a failure message to this macro.
268 // Note that even though the implementations of the following two
269 // macros are much alike, we cannot refactor them to use a common
270 // helper macro, due to some peculiarity in how the preprocessor
271 // works. If we do that, the code won't compile when the user gives
272 // EXPECT_NONFATAL_FAILURE() a statement that contains a macro that
273 // expands to code containing an unprotected comma. The
274 // AcceptsMacroThatExpandsToUnprotectedComma test in gtest_unittest.cc
277 // For the same reason, we have to write
278 // if (::testing::internal::AlwaysTrue()) { statement; }
280 // GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement)
281 // to avoid an MSVC warning on unreachable code.
282 #define EXPECT_NONFATAL_FAILURE(statement, substr) \
284 ::testing::TestPartResultArray gtest_failures;\
285 ::testing::internal::SingleFailureChecker gtest_checker(\
286 >est_failures, ::testing::TestPartResult::kNonFatalFailure, \
289 ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
290 ::testing::ScopedFakeTestPartResultReporter:: \
291 INTERCEPT_ONLY_CURRENT_THREAD, >est_failures);\
292 if (::testing::internal::AlwaysTrue()) { statement; }\
294 } while (::testing::internal::AlwaysFalse())
296 #define EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(statement, substr) \
298 ::testing::TestPartResultArray gtest_failures;\
299 ::testing::internal::SingleFailureChecker gtest_checker(\
300 >est_failures, ::testing::TestPartResult::kNonFatalFailure, \
303 ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
304 ::testing::ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, \
306 if (::testing::internal::AlwaysTrue()) { statement; }\
308 } while (::testing::internal::AlwaysFalse())
310 #endif // GTEST_INCLUDE_GTEST_GTEST_SPI_H_
324 #include <ostream> // NOLINT
330 // TODO(kenton@google.com): Use autoconf to detect availability of
332 # define GTEST_HAS_GETTIMEOFDAY_ 1
334 # include <fcntl.h> // NOLINT
335 # include <limits.h> // NOLINT
336 # include <sched.h> // NOLINT
337 // Declares vsnprintf(). This header is not available on Windows.
338 # include <strings.h> // NOLINT
339 # include <sys/mman.h> // NOLINT
340 # include <sys/time.h> // NOLINT
341 # include <unistd.h> // NOLINT
344 #elif GTEST_OS_SYMBIAN
345 # define GTEST_HAS_GETTIMEOFDAY_ 1
346 # include <sys/time.h> // NOLINT
349 # define GTEST_HAS_GETTIMEOFDAY_ 1
350 # include <sys/time.h> // NOLINT
352 // On z/OS we additionally need strings.h for strcasecmp.
353 # include <strings.h> // NOLINT
355 #elif GTEST_OS_WINDOWS_MOBILE // We are on Windows CE.
357 # include <windows.h> // NOLINT
359 #elif GTEST_OS_WINDOWS // We are on Windows proper.
361 # include <io.h> // NOLINT
362 # include <sys/timeb.h> // NOLINT
363 # include <sys/types.h> // NOLINT
364 # include <sys/stat.h> // NOLINT
366 # if GTEST_OS_WINDOWS_MINGW
367 // MinGW has gettimeofday() but not _ftime64().
368 // TODO(kenton@google.com): Use autoconf to detect availability of
370 // TODO(kenton@google.com): There are other ways to get the time on
371 // Windows, like GetTickCount() or GetSystemTimeAsFileTime(). MinGW
372 // supports these. consider using them instead.
373 # define GTEST_HAS_GETTIMEOFDAY_ 1
374 # include <sys/time.h> // NOLINT
375 # endif // GTEST_OS_WINDOWS_MINGW
377 // cpplint thinks that the header is already included, so we want to
379 # include <windows.h> // NOLINT
383 // Assume other platforms have gettimeofday().
384 // TODO(kenton@google.com): Use autoconf to detect availability of
386 # define GTEST_HAS_GETTIMEOFDAY_ 1
388 // cpplint thinks that the header is already included, so we want to
390 # include <sys/time.h> // NOLINT
391 # include <unistd.h> // NOLINT
393 #endif // GTEST_OS_LINUX
395 #if GTEST_HAS_EXCEPTIONS
396 # include <stdexcept>
399 #if GTEST_CAN_STREAM_RESULTS_
400 # include <arpa/inet.h> // NOLINT
401 # include <netdb.h> // NOLINT
404 // Indicates that this translation unit is part of Google Test's
405 // implementation. It must come before gtest-internal-inl.h is
406 // included, or there will be a compiler error. This trick is to
407 // prevent a user from accidentally including gtest-internal-inl.h in
409 #define GTEST_IMPLEMENTATION_ 1
410 // Copyright 2005, Google Inc.
411 // All rights reserved.
413 // Redistribution and use in source and binary forms, with or without
414 // modification, are permitted provided that the following conditions are
417 // * Redistributions of source code must retain the above copyright
418 // notice, this list of conditions and the following disclaimer.
419 // * Redistributions in binary form must reproduce the above
420 // copyright notice, this list of conditions and the following disclaimer
421 // in the documentation and/or other materials provided with the
423 // * Neither the name of Google Inc. nor the names of its
424 // contributors may be used to endorse or promote products derived from
425 // this software without specific prior written permission.
427 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
428 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
429 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
430 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
431 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
432 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
433 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
434 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
435 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
436 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
437 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
439 // Utility functions and classes used by the Google C++ testing framework.
441 // Author: wan@google.com (Zhanyong Wan)
443 // This file contains purely Google Test's internal implementation. Please
444 // DO NOT #INCLUDE IT IN A USER PROGRAM.
446 #ifndef GTEST_SRC_GTEST_INTERNAL_INL_H_
447 #define GTEST_SRC_GTEST_INTERNAL_INL_H_
449 // GTEST_IMPLEMENTATION_ is defined to 1 iff the current translation unit is
450 // part of Google Test's implementation; otherwise it's undefined.
451 #if !GTEST_IMPLEMENTATION_
452 // A user is trying to include this from his code - just say no.
453 # error "gtest-internal-inl.h is part of Google Test's internal implementation."
454 # error "It must not be included except by Google Test itself."
455 #endif // GTEST_IMPLEMENTATION_
459 #endif // !_WIN32_WCE
461 #include <stdlib.h> // For strtoll/_strtoul64/malloc/free.
462 #include <string.h> // For memmove.
469 #if GTEST_CAN_STREAM_RESULTS_
470 # include <arpa/inet.h> // NOLINT
471 # include <netdb.h> // NOLINT
475 # include <windows.h> // NOLINT
476 #endif // GTEST_OS_WINDOWS
481 // Declares the flags.
483 // We don't want the users to modify this flag in the code, but want
484 // Google Test's own unit tests to be able to access it. Therefore we
485 // declare it here as opposed to in gtest.h.
486 GTEST_DECLARE_bool_(death_test_use_fork);
490 // The value of GetTestTypeId() as seen from within the Google Test
491 // library. This is solely for testing GetTestTypeId().
492 GTEST_API_ extern const TypeId kTestTypeIdInGoogleTest;
494 // Names of the flags (needed for parsing Google Test flags).
495 const char kAlsoRunDisabledTestsFlag[] = "also_run_disabled_tests";
496 const char kBreakOnFailureFlag[] = "break_on_failure";
497 const char kCatchExceptionsFlag[] = "catch_exceptions";
498 const char kColorFlag[] = "color";
499 const char kFilterFlag[] = "filter";
500 const char kListTestsFlag[] = "list_tests";
501 const char kOutputFlag[] = "output";
502 const char kPrintTimeFlag[] = "print_time";
503 const char kRandomSeedFlag[] = "random_seed";
504 const char kRepeatFlag[] = "repeat";
505 const char kShuffleFlag[] = "shuffle";
506 const char kStackTraceDepthFlag[] = "stack_trace_depth";
507 const char kStreamResultToFlag[] = "stream_result_to";
508 const char kThrowOnFailureFlag[] = "throw_on_failure";
510 // A valid random seed must be in [1, kMaxRandomSeed].
511 const int kMaxRandomSeed = 99999;
513 // g_help_flag is true iff the --help flag or an equivalent form is
514 // specified on the command line.
515 GTEST_API_ extern bool g_help_flag;
517 // Returns the current time in milliseconds.
518 GTEST_API_ TimeInMillis GetTimeInMillis();
520 // Returns true iff Google Test should use colors in the output.
521 GTEST_API_ bool ShouldUseColor(bool stdout_is_tty);
523 // Formats the given time in milliseconds as seconds.
524 GTEST_API_ std::string FormatTimeInMillisAsSeconds(TimeInMillis ms);
526 // Converts the given time in milliseconds to a date string in the ISO 8601
527 // format, without the timezone information. N.B.: due to the use the
528 // non-reentrant localtime() function, this function is not thread safe. Do
529 // not use it in any code that can be called from multiple threads.
530 GTEST_API_ std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms);
532 // Parses a string for an Int32 flag, in the form of "--flag=value".
534 // On success, stores the value of the flag in *value, and returns
535 // true. On failure, returns false without changing *value.
536 GTEST_API_ bool ParseInt32Flag(
537 const char* str, const char* flag, Int32* value);
539 // Returns a random seed in range [1, kMaxRandomSeed] based on the
540 // given --gtest_random_seed flag value.
541 inline int GetRandomSeedFromFlag(Int32 random_seed_flag) {
542 const unsigned int raw_seed = (random_seed_flag == 0) ?
543 static_cast<unsigned int>(GetTimeInMillis()) :
544 static_cast<unsigned int>(random_seed_flag);
546 // Normalizes the actual seed to range [1, kMaxRandomSeed] such that
547 // it's easy to type.
548 const int normalized_seed =
549 static_cast<int>((raw_seed - 1U) %
550 static_cast<unsigned int>(kMaxRandomSeed)) + 1;
551 return normalized_seed;
554 // Returns the first valid random seed after 'seed'. The behavior is
555 // undefined if 'seed' is invalid. The seed after kMaxRandomSeed is
556 // considered to be 1.
557 inline int GetNextRandomSeed(int seed) {
558 GTEST_CHECK_(1 <= seed && seed <= kMaxRandomSeed)
559 << "Invalid random seed " << seed << " - must be in [1, "
560 << kMaxRandomSeed << "].";
561 const int next_seed = seed + 1;
562 return (next_seed > kMaxRandomSeed) ? 1 : next_seed;
565 // This class saves the values of all Google Test flags in its c'tor, and
566 // restores them in its d'tor.
567 class GTestFlagSaver {
571 also_run_disabled_tests_ = GTEST_FLAG(also_run_disabled_tests);
572 break_on_failure_ = GTEST_FLAG(break_on_failure);
573 catch_exceptions_ = GTEST_FLAG(catch_exceptions);
574 color_ = GTEST_FLAG(color);
575 death_test_style_ = GTEST_FLAG(death_test_style);
576 death_test_use_fork_ = GTEST_FLAG(death_test_use_fork);
577 filter_ = GTEST_FLAG(filter);
578 internal_run_death_test_ = GTEST_FLAG(internal_run_death_test);
579 list_tests_ = GTEST_FLAG(list_tests);
580 output_ = GTEST_FLAG(output);
581 print_time_ = GTEST_FLAG(print_time);
582 random_seed_ = GTEST_FLAG(random_seed);
583 repeat_ = GTEST_FLAG(repeat);
584 shuffle_ = GTEST_FLAG(shuffle);
585 stack_trace_depth_ = GTEST_FLAG(stack_trace_depth);
586 stream_result_to_ = GTEST_FLAG(stream_result_to);
587 throw_on_failure_ = GTEST_FLAG(throw_on_failure);
590 // The d'tor is not virtual. DO NOT INHERIT FROM THIS CLASS.
592 GTEST_FLAG(also_run_disabled_tests) = also_run_disabled_tests_;
593 GTEST_FLAG(break_on_failure) = break_on_failure_;
594 GTEST_FLAG(catch_exceptions) = catch_exceptions_;
595 GTEST_FLAG(color) = color_;
596 GTEST_FLAG(death_test_style) = death_test_style_;
597 GTEST_FLAG(death_test_use_fork) = death_test_use_fork_;
598 GTEST_FLAG(filter) = filter_;
599 GTEST_FLAG(internal_run_death_test) = internal_run_death_test_;
600 GTEST_FLAG(list_tests) = list_tests_;
601 GTEST_FLAG(output) = output_;
602 GTEST_FLAG(print_time) = print_time_;
603 GTEST_FLAG(random_seed) = random_seed_;
604 GTEST_FLAG(repeat) = repeat_;
605 GTEST_FLAG(shuffle) = shuffle_;
606 GTEST_FLAG(stack_trace_depth) = stack_trace_depth_;
607 GTEST_FLAG(stream_result_to) = stream_result_to_;
608 GTEST_FLAG(throw_on_failure) = throw_on_failure_;
612 // Fields for saving the original values of flags.
613 bool also_run_disabled_tests_;
614 bool break_on_failure_;
615 bool catch_exceptions_;
617 std::string death_test_style_;
618 bool death_test_use_fork_;
620 std::string internal_run_death_test_;
624 internal::Int32 random_seed_;
625 internal::Int32 repeat_;
627 internal::Int32 stack_trace_depth_;
628 std::string stream_result_to_;
629 bool throw_on_failure_;
630 } GTEST_ATTRIBUTE_UNUSED_;
632 // Converts a Unicode code point to a narrow string in UTF-8 encoding.
633 // code_point parameter is of type UInt32 because wchar_t may not be
634 // wide enough to contain a code point.
635 // If the code_point is not a valid Unicode code point
636 // (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted
637 // to "(Invalid Unicode 0xXXXXXXXX)".
638 GTEST_API_ std::string CodePointToUtf8(UInt32 code_point);
640 // Converts a wide string to a narrow string in UTF-8 encoding.
641 // The wide string is assumed to have the following encoding:
642 // UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS)
643 // UTF-32 if sizeof(wchar_t) == 4 (on Linux)
644 // Parameter str points to a null-terminated wide string.
645 // Parameter num_chars may additionally limit the number
646 // of wchar_t characters processed. -1 is used when the entire string
647 // should be processed.
648 // If the string contains code points that are not valid Unicode code points
649 // (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
650 // as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
651 // and contains invalid UTF-16 surrogate pairs, values in those pairs
652 // will be encoded as individual Unicode characters from Basic Normal Plane.
653 GTEST_API_ std::string WideStringToUtf8(const wchar_t* str, int num_chars);
655 // Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
656 // if the variable is present. If a file already exists at this location, this
657 // function will write over it. If the variable is present, but the file cannot
658 // be created, prints an error and exits.
659 void WriteToShardStatusFileIfNeeded();
661 // Checks whether sharding is enabled by examining the relevant
662 // environment variable values. If the variables are present,
663 // but inconsistent (e.g., shard_index >= total_shards), prints
664 // an error and exits. If in_subprocess_for_death_test, sharding is
665 // disabled because it must only be applied to the original test
666 // process. Otherwise, we could filter out death tests we intended to execute.
667 GTEST_API_ bool ShouldShard(const char* total_shards_str,
668 const char* shard_index_str,
669 bool in_subprocess_for_death_test);
671 // Parses the environment variable var as an Int32. If it is unset,
672 // returns default_val. If it is not an Int32, prints an error and
674 GTEST_API_ Int32 Int32FromEnvOrDie(const char* env_var, Int32 default_val);
676 // Given the total number of shards, the shard index, and the test id,
677 // returns true iff the test should be run on this shard. The test id is
678 // some arbitrary but unique non-negative integer assigned to each test
679 // method. Assumes that 0 <= shard_index < total_shards.
680 GTEST_API_ bool ShouldRunTestOnShard(
681 int total_shards, int shard_index, int test_id);
683 // STL container utilities.
685 // Returns the number of elements in the given container that satisfy
686 // the given predicate.
687 template <class Container, typename Predicate>
688 inline int CountIf(const Container& c, Predicate predicate) {
689 // Implemented as an explicit loop since std::count_if() in libCstd on
690 // Solaris has a non-standard signature.
692 for (typename Container::const_iterator it = c.begin(); it != c.end(); ++it) {
699 // Applies a function/functor to each element in the container.
700 template <class Container, typename Functor>
701 void ForEach(const Container& c, Functor functor) {
702 std::for_each(c.begin(), c.end(), functor);
705 // Returns the i-th element of the vector, or default_value if i is not
706 // in range [0, v.size()).
707 template <typename E>
708 inline E GetElementOr(const std::vector<E>& v, int i, E default_value) {
709 return (i < 0 || i >= static_cast<int>(v.size())) ? default_value : v[i];
712 // Performs an in-place shuffle of a range of the vector's elements.
713 // 'begin' and 'end' are element indices as an STL-style range;
714 // i.e. [begin, end) are shuffled, where 'end' == size() means to
715 // shuffle to the end of the vector.
716 template <typename E>
717 void ShuffleRange(internal::Random* random, int begin, int end,
719 const int size = static_cast<int>(v->size());
720 GTEST_CHECK_(0 <= begin && begin <= size)
721 << "Invalid shuffle range start " << begin << ": must be in range [0, "
723 GTEST_CHECK_(begin <= end && end <= size)
724 << "Invalid shuffle range finish " << end << ": must be in range ["
725 << begin << ", " << size << "].";
727 // Fisher-Yates shuffle, from
728 // http://en.wikipedia.org/wiki/Fisher-Yates_shuffle
729 for (int range_width = end - begin; range_width >= 2; range_width--) {
730 const int last_in_range = begin + range_width - 1;
731 const int selected = begin + random->Generate(range_width);
732 std::swap((*v)[selected], (*v)[last_in_range]);
736 // Performs an in-place shuffle of the vector's elements.
737 template <typename E>
738 inline void Shuffle(internal::Random* random, std::vector<E>* v) {
739 ShuffleRange(random, 0, static_cast<int>(v->size()), v);
742 // A function for deleting an object. Handy for being used as a
744 template <typename T>
745 static void Delete(T* x) {
749 // A predicate that checks the key of a TestProperty against a known key.
751 // TestPropertyKeyIs is copyable.
752 class TestPropertyKeyIs {
756 // TestPropertyKeyIs has NO default constructor.
757 explicit TestPropertyKeyIs(const std::string& key) : key_(key) {}
759 // Returns true iff the test name of test property matches on key_.
760 bool operator()(const TestProperty& test_property) const {
761 return test_property.key() == key_;
768 // Class UnitTestOptions.
770 // This class contains functions for processing options the user
771 // specifies when running the tests. It has only static members.
773 // In most cases, the user can specify an option using either an
774 // environment variable or a command line flag. E.g. you can set the
775 // test filter using either GTEST_FILTER or --gtest_filter. If both
776 // the variable and the flag are present, the latter overrides the
778 class GTEST_API_ UnitTestOptions {
780 // Functions for processing the gtest_output flag.
782 // Returns the output format, or "" for normal printed output.
783 static std::string GetOutputFormat();
785 // Returns the absolute path of the requested output file, or the
786 // default (test_detail.xml in the original working directory) if
787 // none was explicitly specified.
788 static std::string GetAbsolutePathToOutputFile();
790 // Functions for processing the gtest_filter flag.
792 // Returns true iff the wildcard pattern matches the string. The
793 // first ':' or '\0' character in pattern marks the end of it.
795 // This recursive algorithm isn't very efficient, but is clear and
796 // works well enough for matching test names, which are short.
797 static bool PatternMatchesString(const char *pattern, const char *str);
799 // Returns true iff the user-specified filter matches the test case
800 // name and the test name.
801 static bool FilterMatchesTest(const std::string &test_case_name,
802 const std::string &test_name);
805 // Function for supporting the gtest_catch_exception flag.
807 // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
808 // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
809 // This function is useful as an __except condition.
810 static int GTestShouldProcessSEH(DWORD exception_code);
811 #endif // GTEST_OS_WINDOWS
813 // Returns true if "name" matches the ':' separated list of glob-style
814 // filters in "filter".
815 static bool MatchesFilter(const std::string& name, const char* filter);
818 // Returns the current application's name, removing directory path if that
819 // is present. Used by UnitTestOptions::GetOutputFile.
820 GTEST_API_ FilePath GetCurrentExecutableName();
822 // The role interface for getting the OS stack trace as a string.
823 class OsStackTraceGetterInterface {
825 OsStackTraceGetterInterface() {}
826 virtual ~OsStackTraceGetterInterface() {}
828 // Returns the current OS stack trace as an std::string. Parameters:
830 // max_depth - the maximum number of stack frames to be included
832 // skip_count - the number of top frames to be skipped; doesn't count
833 // against max_depth.
834 virtual string CurrentStackTrace(int max_depth, int skip_count) = 0;
836 // UponLeavingGTest() should be called immediately before Google Test calls
837 // user code. It saves some information about the current stack that
838 // CurrentStackTrace() will use to find and hide Google Test stack frames.
839 virtual void UponLeavingGTest() = 0;
842 GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetterInterface);
845 // A working implementation of the OsStackTraceGetterInterface interface.
846 class OsStackTraceGetter : public OsStackTraceGetterInterface {
848 OsStackTraceGetter() : caller_frame_(NULL) {}
850 virtual string CurrentStackTrace(int max_depth, int skip_count)
851 GTEST_LOCK_EXCLUDED_(mutex_);
853 virtual void UponLeavingGTest() GTEST_LOCK_EXCLUDED_(mutex_);
855 // This string is inserted in place of stack frames that are part of
856 // Google Test's implementation.
857 static const char* const kElidedFramesMarker;
860 Mutex mutex_; // protects all internal state
862 // We save the stack frame below the frame that calls user code.
863 // We do this because the address of the frame immediately below
864 // the user code changes between the call to UponLeavingGTest()
865 // and any calls to CurrentStackTrace() from within the user code.
868 GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetter);
871 // Information about a Google Test trace point.
878 // This is the default global test part result reporter used in UnitTestImpl.
879 // This class should only be used by UnitTestImpl.
880 class DefaultGlobalTestPartResultReporter
881 : public TestPartResultReporterInterface {
883 explicit DefaultGlobalTestPartResultReporter(UnitTestImpl* unit_test);
884 // Implements the TestPartResultReporterInterface. Reports the test part
885 // result in the current test.
886 virtual void ReportTestPartResult(const TestPartResult& result);
889 UnitTestImpl* const unit_test_;
891 GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultGlobalTestPartResultReporter);
894 // This is the default per thread test part result reporter used in
895 // UnitTestImpl. This class should only be used by UnitTestImpl.
896 class DefaultPerThreadTestPartResultReporter
897 : public TestPartResultReporterInterface {
899 explicit DefaultPerThreadTestPartResultReporter(UnitTestImpl* unit_test);
900 // Implements the TestPartResultReporterInterface. The implementation just
901 // delegates to the current global test part result reporter of *unit_test_.
902 virtual void ReportTestPartResult(const TestPartResult& result);
905 UnitTestImpl* const unit_test_;
907 GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultPerThreadTestPartResultReporter);
910 // The private implementation of the UnitTest class. We don't protect
911 // the methods under a mutex, as this class is not accessible by a
912 // user and the UnitTest class that delegates work to this class does
914 class GTEST_API_ UnitTestImpl {
916 explicit UnitTestImpl(UnitTest* parent);
917 virtual ~UnitTestImpl();
919 // There are two different ways to register your own TestPartResultReporter.
920 // You can register your own repoter to listen either only for test results
921 // from the current thread or for results from all threads.
922 // By default, each per-thread test result repoter just passes a new
923 // TestPartResult to the global test result reporter, which registers the
924 // test part result for the currently running test.
926 // Returns the global test part result reporter.
927 TestPartResultReporterInterface* GetGlobalTestPartResultReporter();
929 // Sets the global test part result reporter.
930 void SetGlobalTestPartResultReporter(
931 TestPartResultReporterInterface* reporter);
933 // Returns the test part result reporter for the current thread.
934 TestPartResultReporterInterface* GetTestPartResultReporterForCurrentThread();
936 // Sets the test part result reporter for the current thread.
937 void SetTestPartResultReporterForCurrentThread(
938 TestPartResultReporterInterface* reporter);
940 // Gets the number of successful test cases.
941 int successful_test_case_count() const;
943 // Gets the number of failed test cases.
944 int failed_test_case_count() const;
946 // Gets the number of all test cases.
947 int total_test_case_count() const;
949 // Gets the number of all test cases that contain at least one test
951 int test_case_to_run_count() const;
953 // Gets the number of successful tests.
954 int successful_test_count() const;
956 // Gets the number of failed tests.
957 int failed_test_count() const;
959 // Gets the number of disabled tests.
960 int disabled_test_count() const;
962 // Gets the number of all tests.
963 int total_test_count() const;
965 // Gets the number of tests that should run.
966 int test_to_run_count() const;
968 // Gets the time of the test program start, in ms from the start of the
970 TimeInMillis start_timestamp() const { return start_timestamp_; }
972 // Gets the elapsed time, in milliseconds.
973 TimeInMillis elapsed_time() const { return elapsed_time_; }
975 // Returns true iff the unit test passed (i.e. all test cases passed).
976 bool Passed() const { return !Failed(); }
978 // Returns true iff the unit test failed (i.e. some test case failed
979 // or something outside of all tests failed).
980 bool Failed() const {
981 return failed_test_case_count() > 0 || ad_hoc_test_result()->Failed();
984 // Gets the i-th test case among all the test cases. i can range from 0 to
985 // total_test_case_count() - 1. If i is not in that range, returns NULL.
986 const TestCase* GetTestCase(int i) const {
987 const int index = GetElementOr(test_case_indices_, i, -1);
988 return index < 0 ? NULL : test_cases_[i];
991 // Gets the i-th test case among all the test cases. i can range from 0 to
992 // total_test_case_count() - 1. If i is not in that range, returns NULL.
993 TestCase* GetMutableTestCase(int i) {
994 const int index = GetElementOr(test_case_indices_, i, -1);
995 return index < 0 ? NULL : test_cases_[index];
998 // Provides access to the event listener list.
999 TestEventListeners* listeners() { return &listeners_; }
1001 // Returns the TestResult for the test that's currently running, or
1002 // the TestResult for the ad hoc test if no test is running.
1003 TestResult* current_test_result();
1005 // Returns the TestResult for the ad hoc test.
1006 const TestResult* ad_hoc_test_result() const { return &ad_hoc_test_result_; }
1008 // Sets the OS stack trace getter.
1010 // Does nothing if the input and the current OS stack trace getter
1011 // are the same; otherwise, deletes the old getter and makes the
1012 // input the current getter.
1013 void set_os_stack_trace_getter(OsStackTraceGetterInterface* getter);
1015 // Returns the current OS stack trace getter if it is not NULL;
1016 // otherwise, creates an OsStackTraceGetter, makes it the current
1017 // getter, and returns it.
1018 OsStackTraceGetterInterface* os_stack_trace_getter();
1020 // Returns the current OS stack trace as an std::string.
1022 // The maximum number of stack frames to be included is specified by
1023 // the gtest_stack_trace_depth flag. The skip_count parameter
1024 // specifies the number of top frames to be skipped, which doesn't
1025 // count against the number of frames to be included.
1027 // For example, if Foo() calls Bar(), which in turn calls
1028 // CurrentOsStackTraceExceptTop(1), Foo() will be included in the
1029 // trace but Bar() and CurrentOsStackTraceExceptTop() won't.
1030 std::string CurrentOsStackTraceExceptTop(int skip_count) GTEST_NO_INLINE_;
1032 // Finds and returns a TestCase with the given name. If one doesn't
1033 // exist, creates one and returns it.
1037 // test_case_name: name of the test case
1038 // type_param: the name of the test's type parameter, or NULL if
1039 // this is not a typed or a type-parameterized test.
1040 // set_up_tc: pointer to the function that sets up the test case
1041 // tear_down_tc: pointer to the function that tears down the test case
1042 TestCase* GetTestCase(const char* test_case_name,
1043 const char* type_param,
1044 Test::SetUpTestCaseFunc set_up_tc,
1045 Test::TearDownTestCaseFunc tear_down_tc);
1047 // Adds a TestInfo to the unit test.
1051 // set_up_tc: pointer to the function that sets up the test case
1052 // tear_down_tc: pointer to the function that tears down the test case
1053 // test_info: the TestInfo object
1054 void AddTestInfo(Test::SetUpTestCaseFunc set_up_tc,
1055 Test::TearDownTestCaseFunc tear_down_tc,
1056 TestInfo* test_info) {
1057 // In order to support thread-safe death tests, we need to
1058 // remember the original working directory when the test program
1059 // was first invoked. We cannot do this in RUN_ALL_TESTS(), as
1060 // the user may have changed the current directory before calling
1061 // RUN_ALL_TESTS(). Therefore we capture the current directory in
1062 // AddTestInfo(), which is called to register a TEST or TEST_F
1063 // before main() is reached.
1064 if (original_working_dir_.IsEmpty()) {
1065 original_working_dir_.Set(FilePath::GetCurrentDir());
1066 GTEST_CHECK_(!original_working_dir_.IsEmpty())
1067 << "Failed to get the current working directory.";
1070 GetTestCase(test_info->test_case_name(),
1071 test_info->type_param(),
1073 tear_down_tc)->AddTestInfo(test_info);
1076 #if GTEST_HAS_PARAM_TEST
1077 // Returns ParameterizedTestCaseRegistry object used to keep track of
1078 // value-parameterized tests and instantiate and register them.
1079 internal::ParameterizedTestCaseRegistry& parameterized_test_registry() {
1080 return parameterized_test_registry_;
1082 #endif // GTEST_HAS_PARAM_TEST
1084 // Sets the TestCase object for the test that's currently running.
1085 void set_current_test_case(TestCase* a_current_test_case) {
1086 current_test_case_ = a_current_test_case;
1089 // Sets the TestInfo object for the test that's currently running. If
1090 // current_test_info is NULL, the assertion results will be stored in
1091 // ad_hoc_test_result_.
1092 void set_current_test_info(TestInfo* a_current_test_info) {
1093 current_test_info_ = a_current_test_info;
1096 // Registers all parameterized tests defined using TEST_P and
1097 // INSTANTIATE_TEST_CASE_P, creating regular tests for each test/parameter
1098 // combination. This method can be called more then once; it has guards
1099 // protecting from registering the tests more then once. If
1100 // value-parameterized tests are disabled, RegisterParameterizedTests is
1101 // present but does nothing.
1102 void RegisterParameterizedTests();
1104 // Runs all tests in this UnitTest object, prints the result, and
1105 // returns true if all tests are successful. If any exception is
1106 // thrown during a test, this test is considered to be failed, but
1107 // the rest of the tests will still be run.
1110 // Clears the results of all tests, except the ad hoc tests.
1111 void ClearNonAdHocTestResult() {
1112 ForEach(test_cases_, TestCase::ClearTestCaseResult);
1115 // Clears the results of ad-hoc test assertions.
1116 void ClearAdHocTestResult() {
1117 ad_hoc_test_result_.Clear();
1120 // Adds a TestProperty to the current TestResult object when invoked in a
1121 // context of a test or a test case, or to the global property set. If the
1122 // result already contains a property with the same key, the value will be
1124 void RecordProperty(const TestProperty& test_property);
1126 enum ReactionToSharding {
1127 HONOR_SHARDING_PROTOCOL,
1128 IGNORE_SHARDING_PROTOCOL
1131 // Matches the full name of each test against the user-specified
1132 // filter to decide whether the test should run, then records the
1133 // result in each TestCase and TestInfo object.
1134 // If shard_tests == HONOR_SHARDING_PROTOCOL, further filters tests
1135 // based on sharding variables in the environment.
1136 // Returns the number of tests that should run.
1137 int FilterTests(ReactionToSharding shard_tests);
1139 // Prints the names of the tests matching the user-specified filter flag.
1140 void ListTestsMatchingFilter();
1142 const TestCase* current_test_case() const { return current_test_case_; }
1143 TestInfo* current_test_info() { return current_test_info_; }
1144 const TestInfo* current_test_info() const { return current_test_info_; }
1146 // Returns the vector of environments that need to be set-up/torn-down
1147 // before/after the tests are run.
1148 std::vector<Environment*>& environments() { return environments_; }
1150 // Getters for the per-thread Google Test trace stack.
1151 std::vector<TraceInfo>& gtest_trace_stack() {
1152 return *(gtest_trace_stack_.pointer());
1154 const std::vector<TraceInfo>& gtest_trace_stack() const {
1155 return gtest_trace_stack_.get();
1158 #if GTEST_HAS_DEATH_TEST
1159 void InitDeathTestSubprocessControlInfo() {
1160 internal_run_death_test_flag_.reset(ParseInternalRunDeathTestFlag());
1162 // Returns a pointer to the parsed --gtest_internal_run_death_test
1163 // flag, or NULL if that flag was not specified.
1164 // This information is useful only in a death test child process.
1165 // Must not be called before a call to InitGoogleTest.
1166 const InternalRunDeathTestFlag* internal_run_death_test_flag() const {
1167 return internal_run_death_test_flag_.get();
1170 // Returns a pointer to the current death test factory.
1171 internal::DeathTestFactory* death_test_factory() {
1172 return death_test_factory_.get();
1175 void SuppressTestEventsIfInSubprocess();
1177 friend class ReplaceDeathTestFactory;
1178 #endif // GTEST_HAS_DEATH_TEST
1180 // Initializes the event listener performing XML output as specified by
1181 // UnitTestOptions. Must not be called before InitGoogleTest.
1182 void ConfigureXmlOutput();
1184 #if GTEST_CAN_STREAM_RESULTS_
1185 // Initializes the event listener for streaming test results to a socket.
1186 // Must not be called before InitGoogleTest.
1187 void ConfigureStreamingOutput();
1190 // Performs initialization dependent upon flag values obtained in
1191 // ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to
1192 // ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest
1193 // this function is also called from RunAllTests. Since this function can be
1194 // called more than once, it has to be idempotent.
1195 void PostFlagParsingInit();
1197 // Gets the random seed used at the start of the current test iteration.
1198 int random_seed() const { return random_seed_; }
1200 // Gets the random number generator.
1201 internal::Random* random() { return &random_; }
1203 // Shuffles all test cases, and the tests within each test case,
1204 // making sure that death tests are still run first.
1205 void ShuffleTests();
1207 // Restores the test cases and tests to their order before the first shuffle.
1208 void UnshuffleTests();
1210 // Returns the value of GTEST_FLAG(catch_exceptions) at the moment
1211 // UnitTest::Run() starts.
1212 bool catch_exceptions() const { return catch_exceptions_; }
1215 friend class ::testing::UnitTest;
1217 // Used by UnitTest::Run() to capture the state of
1218 // GTEST_FLAG(catch_exceptions) at the moment it starts.
1219 void set_catch_exceptions(bool value) { catch_exceptions_ = value; }
1221 // The UnitTest object that owns this implementation object.
1222 UnitTest* const parent_;
1224 // The working directory when the first TEST() or TEST_F() was
1226 internal::FilePath original_working_dir_;
1228 // The default test part result reporters.
1229 DefaultGlobalTestPartResultReporter default_global_test_part_result_reporter_;
1230 DefaultPerThreadTestPartResultReporter
1231 default_per_thread_test_part_result_reporter_;
1233 // Points to (but doesn't own) the global test part result reporter.
1234 TestPartResultReporterInterface* global_test_part_result_repoter_;
1236 // Protects read and write access to global_test_part_result_reporter_.
1237 internal::Mutex global_test_part_result_reporter_mutex_;
1239 // Points to (but doesn't own) the per-thread test part result reporter.
1240 internal::ThreadLocal<TestPartResultReporterInterface*>
1241 per_thread_test_part_result_reporter_;
1243 // The vector of environments that need to be set-up/torn-down
1244 // before/after the tests are run.
1245 std::vector<Environment*> environments_;
1247 // The vector of TestCases in their original order. It owns the
1248 // elements in the vector.
1249 std::vector<TestCase*> test_cases_;
1251 // Provides a level of indirection for the test case list to allow
1252 // easy shuffling and restoring the test case order. The i-th
1253 // element of this vector is the index of the i-th test case in the
1255 std::vector<int> test_case_indices_;
1257 #if GTEST_HAS_PARAM_TEST
1258 // ParameterizedTestRegistry object used to register value-parameterized
1260 internal::ParameterizedTestCaseRegistry parameterized_test_registry_;
1262 // Indicates whether RegisterParameterizedTests() has been called already.
1263 bool parameterized_tests_registered_;
1264 #endif // GTEST_HAS_PARAM_TEST
1266 // Index of the last death test case registered. Initially -1.
1267 int last_death_test_case_;
1269 // This points to the TestCase for the currently running test. It
1270 // changes as Google Test goes through one test case after another.
1271 // When no test is running, this is set to NULL and Google Test
1272 // stores assertion results in ad_hoc_test_result_. Initially NULL.
1273 TestCase* current_test_case_;
1275 // This points to the TestInfo for the currently running test. It
1276 // changes as Google Test goes through one test after another. When
1277 // no test is running, this is set to NULL and Google Test stores
1278 // assertion results in ad_hoc_test_result_. Initially NULL.
1279 TestInfo* current_test_info_;
1281 // Normally, a user only writes assertions inside a TEST or TEST_F,
1282 // or inside a function called by a TEST or TEST_F. Since Google
1283 // Test keeps track of which test is current running, it can
1284 // associate such an assertion with the test it belongs to.
1286 // If an assertion is encountered when no TEST or TEST_F is running,
1287 // Google Test attributes the assertion result to an imaginary "ad hoc"
1288 // test, and records the result in ad_hoc_test_result_.
1289 TestResult ad_hoc_test_result_;
1291 // The list of event listeners that can be used to track events inside
1293 TestEventListeners listeners_;
1295 // The OS stack trace getter. Will be deleted when the UnitTest
1296 // object is destructed. By default, an OsStackTraceGetter is used,
1297 // but the user can set this field to use a custom getter if that is
1299 OsStackTraceGetterInterface* os_stack_trace_getter_;
1301 // True iff PostFlagParsingInit() has been called.
1302 bool post_flag_parse_init_performed_;
1304 // The random number seed used at the beginning of the test run.
1307 // Our random number generator.
1308 internal::Random random_;
1310 // The time of the test program start, in ms from the start of the
1312 TimeInMillis start_timestamp_;
1314 // How long the test took to run, in milliseconds.
1315 TimeInMillis elapsed_time_;
1317 #if GTEST_HAS_DEATH_TEST
1318 // The decomposed components of the gtest_internal_run_death_test flag,
1319 // parsed when RUN_ALL_TESTS is called.
1320 internal::scoped_ptr<InternalRunDeathTestFlag> internal_run_death_test_flag_;
1321 internal::scoped_ptr<internal::DeathTestFactory> death_test_factory_;
1322 #endif // GTEST_HAS_DEATH_TEST
1324 // A per-thread stack of traces created by the SCOPED_TRACE() macro.
1325 internal::ThreadLocal<std::vector<TraceInfo> > gtest_trace_stack_;
1327 // The value of GTEST_FLAG(catch_exceptions) at the moment RunAllTests()
1329 bool catch_exceptions_;
1331 GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTestImpl);
1332 }; // class UnitTestImpl
1334 // Convenience function for accessing the global UnitTest
1335 // implementation object.
1336 inline UnitTestImpl* GetUnitTestImpl() {
1337 return UnitTest::GetInstance()->impl();
1340 #if GTEST_USES_SIMPLE_RE
1342 // Internal helper functions for implementing the simple regular
1343 // expression matcher.
1344 GTEST_API_ bool IsInSet(char ch, const char* str);
1345 GTEST_API_ bool IsAsciiDigit(char ch);
1346 GTEST_API_ bool IsAsciiPunct(char ch);
1347 GTEST_API_ bool IsRepeat(char ch);
1348 GTEST_API_ bool IsAsciiWhiteSpace(char ch);
1349 GTEST_API_ bool IsAsciiWordChar(char ch);
1350 GTEST_API_ bool IsValidEscape(char ch);
1351 GTEST_API_ bool AtomMatchesChar(bool escaped, char pattern, char ch);
1352 GTEST_API_ std::string FormatRegexSyntaxError(const char* regex, int index);
1353 GTEST_API_ bool ValidateRegex(const char* regex);
1354 GTEST_API_ bool MatchRegexAtHead(const char* regex, const char* str);
1355 GTEST_API_ bool MatchRepetitionAndRegexAtHead(
1356 bool escaped, char ch, char repeat, const char* regex, const char* str);
1357 GTEST_API_ bool MatchRegexAnywhere(const char* regex, const char* str);
1359 #endif // GTEST_USES_SIMPLE_RE
1361 // Parses the command line for Google Test flags, without initializing
1362 // other parts of Google Test.
1363 GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, char** argv);
1364 GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv);
1366 #if GTEST_HAS_DEATH_TEST
1368 // Returns the message describing the last system error, regardless of the
1370 GTEST_API_ std::string GetLastErrnoDescription();
1372 # if GTEST_OS_WINDOWS
1373 // Provides leak-safe Windows kernel handle ownership.
1376 AutoHandle() : handle_(INVALID_HANDLE_VALUE) {}
1377 explicit AutoHandle(HANDLE handle) : handle_(handle) {}
1379 ~AutoHandle() { Reset(); }
1381 HANDLE Get() const { return handle_; }
1382 void Reset() { Reset(INVALID_HANDLE_VALUE); }
1383 void Reset(HANDLE handle) {
1384 if (handle != handle_) {
1385 if (handle_ != INVALID_HANDLE_VALUE)
1386 ::CloseHandle(handle_);
1394 GTEST_DISALLOW_COPY_AND_ASSIGN_(AutoHandle);
1396 # endif // GTEST_OS_WINDOWS
1398 // Attempts to parse a string into a positive integer pointed to by the
1399 // number parameter. Returns true if that is possible.
1400 // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we can use
1402 template <typename Integer>
1403 bool ParseNaturalNumber(const ::std::string& str, Integer* number) {
1404 // Fail fast if the given string does not begin with a digit;
1405 // this bypasses strtoXXX's "optional leading whitespace and plus
1406 // or minus sign" semantics, which are undesirable here.
1407 if (str.empty() || !IsDigit(str[0])) {
1413 // BiggestConvertible is the largest integer type that system-provided
1414 // string-to-number conversion routines can return.
1416 # if GTEST_OS_WINDOWS && !defined(__GNUC__)
1418 // MSVC and C++ Builder define __int64 instead of the standard long long.
1419 typedef unsigned __int64 BiggestConvertible;
1420 const BiggestConvertible parsed = _strtoui64(str.c_str(), &end, 10);
1424 typedef unsigned long long BiggestConvertible; // NOLINT
1425 const BiggestConvertible parsed = strtoull(str.c_str(), &end, 10);
1427 # endif // GTEST_OS_WINDOWS && !defined(__GNUC__)
1429 const bool parse_success = *end == '\0' && errno == 0;
1431 // TODO(vladl@google.com): Convert this to compile time assertion when it is
1433 GTEST_CHECK_(sizeof(Integer) <= sizeof(parsed));
1435 const Integer result = static_cast<Integer>(parsed);
1436 if (parse_success && static_cast<BiggestConvertible>(result) == parsed) {
1442 #endif // GTEST_HAS_DEATH_TEST
1444 // TestResult contains some private methods that should be hidden from
1445 // Google Test user but are required for testing. This class allow our tests
1448 // This class is supplied only for the purpose of testing Google Test's own
1449 // constructs. Do not use it in user tests, either directly or indirectly.
1450 class TestResultAccessor {
1452 static void RecordProperty(TestResult* test_result,
1453 const std::string& xml_element,
1454 const TestProperty& property) {
1455 test_result->RecordProperty(xml_element, property);
1458 static void ClearTestPartResults(TestResult* test_result) {
1459 test_result->ClearTestPartResults();
1462 static const std::vector<testing::TestPartResult>& test_part_results(
1463 const TestResult& test_result) {
1464 return test_result.test_part_results();
1468 #if GTEST_CAN_STREAM_RESULTS_
1470 // Streams test results to the given port on the given host machine.
1471 class StreamingListener : public EmptyTestEventListener {
1473 // Abstract base class for writing strings to a socket.
1474 class AbstractSocketWriter {
1476 virtual ~AbstractSocketWriter() {}
1478 // Sends a string to the socket.
1479 virtual void Send(const string& message) = 0;
1481 // Closes the socket.
1482 virtual void CloseConnection() {}
1484 // Sends a string and a newline to the socket.
1485 void SendLn(const string& message) {
1486 Send(message + "\n");
1490 // Concrete class for actually writing strings to a socket.
1491 class SocketWriter : public AbstractSocketWriter {
1493 SocketWriter(const string& host, const string& port)
1494 : sockfd_(-1), host_name_(host), port_num_(port) {
1498 virtual ~SocketWriter() {
1503 // Sends a string to the socket.
1504 virtual void Send(const string& message) {
1505 GTEST_CHECK_(sockfd_ != -1)
1506 << "Send() can be called only when there is a connection.";
1508 const int len = static_cast<int>(message.length());
1509 if (write(sockfd_, message.c_str(), len) != len) {
1511 << "stream_result_to: failed to stream to "
1512 << host_name_ << ":" << port_num_;
1517 // Creates a client socket and connects to the server.
1518 void MakeConnection();
1520 // Closes the socket.
1521 void CloseConnection() {
1522 GTEST_CHECK_(sockfd_ != -1)
1523 << "CloseConnection() can be called only when there is a connection.";
1529 int sockfd_; // socket file descriptor
1530 const string host_name_;
1531 const string port_num_;
1533 GTEST_DISALLOW_COPY_AND_ASSIGN_(SocketWriter);
1534 }; // class SocketWriter
1536 // Escapes '=', '&', '%', and '\n' characters in str as "%xx".
1537 static string UrlEncode(const char* str);
1539 StreamingListener(const string& host, const string& port)
1540 : socket_writer_(new SocketWriter(host, port)) { Start(); }
1542 explicit StreamingListener(AbstractSocketWriter* socket_writer)
1543 : socket_writer_(socket_writer) { Start(); }
1545 void OnTestProgramStart(const UnitTest& /* unit_test */) {
1546 SendLn("event=TestProgramStart");
1549 void OnTestProgramEnd(const UnitTest& unit_test) {
1550 // Note that Google Test current only report elapsed time for each
1551 // test iteration, not for the entire test program.
1552 SendLn("event=TestProgramEnd&passed=" + FormatBool(unit_test.Passed()));
1554 // Notify the streaming server to stop.
1555 socket_writer_->CloseConnection();
1558 void OnTestIterationStart(const UnitTest& /* unit_test */, int iteration) {
1559 SendLn("event=TestIterationStart&iteration=" +
1560 StreamableToString(iteration));
1563 void OnTestIterationEnd(const UnitTest& unit_test, int /* iteration */) {
1564 SendLn("event=TestIterationEnd&passed=" +
1565 FormatBool(unit_test.Passed()) + "&elapsed_time=" +
1566 StreamableToString(unit_test.elapsed_time()) + "ms");
1569 void OnTestCaseStart(const TestCase& test_case) {
1570 SendLn(std::string("event=TestCaseStart&name=") + test_case.name());
1573 void OnTestCaseEnd(const TestCase& test_case) {
1574 SendLn("event=TestCaseEnd&passed=" + FormatBool(test_case.Passed())
1575 + "&elapsed_time=" + StreamableToString(test_case.elapsed_time())
1579 void OnTestStart(const TestInfo& test_info) {
1580 SendLn(std::string("event=TestStart&name=") + test_info.name());
1583 void OnTestEnd(const TestInfo& test_info) {
1584 SendLn("event=TestEnd&passed=" +
1585 FormatBool((test_info.result())->Passed()) +
1587 StreamableToString((test_info.result())->elapsed_time()) + "ms");
1590 void OnTestPartResult(const TestPartResult& test_part_result) {
1591 const char* file_name = test_part_result.file_name();
1592 if (file_name == NULL)
1594 SendLn("event=TestPartResult&file=" + UrlEncode(file_name) +
1595 "&line=" + StreamableToString(test_part_result.line_number()) +
1596 "&message=" + UrlEncode(test_part_result.message()));
1600 // Sends the given message and a newline to the socket.
1601 void SendLn(const string& message) { socket_writer_->SendLn(message); }
1603 // Called at the start of streaming to notify the receiver what
1604 // protocol we are using.
1605 void Start() { SendLn("gtest_streaming_protocol_version=1.0"); }
1607 string FormatBool(bool value) { return value ? "1" : "0"; }
1609 const scoped_ptr<AbstractSocketWriter> socket_writer_;
1611 GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamingListener);
1612 }; // class StreamingListener
1614 #endif // GTEST_CAN_STREAM_RESULTS_
1616 } // namespace internal
1617 } // namespace testing
1619 #endif // GTEST_SRC_GTEST_INTERNAL_INL_H_
1620 #undef GTEST_IMPLEMENTATION_
1622 #if GTEST_OS_WINDOWS
1623 # define vsnprintf _vsnprintf
1624 #endif // GTEST_OS_WINDOWS
1628 using internal::CountIf;
1629 using internal::ForEach;
1630 using internal::GetElementOr;
1631 using internal::Shuffle;
1635 // A test whose test case name or test name matches this filter is
1636 // disabled and not run.
1637 static const char kDisableTestFilter[] = "DISABLED_*:*/DISABLED_*";
1639 // A test case whose name matches this filter is considered a death
1640 // test case and will be run before test cases whose name doesn't
1641 // match this filter.
1642 static const char kDeathTestCaseFilter[] = "*DeathTest:*DeathTest/*";
1644 // A test filter that matches everything.
1645 static const char kUniversalFilter[] = "*";
1647 // The default output file for XML output.
1648 static const char kDefaultOutputFile[] = "test_detail.xml";
1650 // The environment variable name for the test shard index.
1651 static const char kTestShardIndex[] = "GTEST_SHARD_INDEX";
1652 // The environment variable name for the total number of test shards.
1653 static const char kTestTotalShards[] = "GTEST_TOTAL_SHARDS";
1654 // The environment variable name for the test shard status file.
1655 static const char kTestShardStatusFile[] = "GTEST_SHARD_STATUS_FILE";
1657 namespace internal {
1659 // The text used in failure messages to indicate the start of the
1661 const char kStackTraceMarker[] = "\nStack trace:\n";
1663 // g_help_flag is true iff the --help flag or an equivalent form is
1664 // specified on the command line.
1665 bool g_help_flag = false;
1667 } // namespace internal
1670 also_run_disabled_tests,
1671 internal::BoolFromGTestEnv("also_run_disabled_tests", false),
1672 "Run disabled tests too, in addition to the tests normally being run.");
1676 internal::BoolFromGTestEnv("break_on_failure", false),
1677 "True iff a failed assertion should be a debugger break-point.");
1681 internal::BoolFromGTestEnv("catch_exceptions", true),
1682 "True iff " GTEST_NAME_
1683 " should catch exceptions and treat them as test failures.");
1685 GTEST_DEFINE_string_(
1687 internal::StringFromGTestEnv("color", "auto"),
1688 "Whether to use colors in the output. Valid values: yes, no, "
1689 "and auto. 'auto' means to use colors if the output is "
1690 "being sent to a terminal and the TERM environment variable "
1691 "is set to a terminal type that supports colors.");
1693 GTEST_DEFINE_string_(
1695 internal::StringFromGTestEnv("filter", kUniversalFilter),
1696 "A colon-separated list of glob (not regex) patterns "
1697 "for filtering the tests to run, optionally followed by a "
1698 "'-' and a : separated list of negative patterns (tests to "
1699 "exclude). A test is run if it matches one of the positive "
1700 "patterns and does not match any of the negative patterns.");
1702 GTEST_DEFINE_bool_(list_tests, false,
1703 "List all tests without running them.");
1705 GTEST_DEFINE_string_(
1707 internal::StringFromGTestEnv("output", ""),
1708 "A format (currently must be \"xml\"), optionally followed "
1709 "by a colon and an output file name or directory. A directory "
1710 "is indicated by a trailing pathname separator. "
1711 "Examples: \"xml:filename.xml\", \"xml::directoryname/\". "
1712 "If a directory is specified, output files will be created "
1713 "within that directory, with file-names based on the test "
1714 "executable's name and, if necessary, made unique by adding "
1719 internal::BoolFromGTestEnv("print_time", true),
1720 "True iff " GTEST_NAME_
1721 " should display elapsed time in text output.");
1723 GTEST_DEFINE_int32_(
1725 internal::Int32FromGTestEnv("random_seed", 0),
1726 "Random number seed to use when shuffling test orders. Must be in range "
1727 "[1, 99999], or 0 to use a seed based on the current time.");
1729 GTEST_DEFINE_int32_(
1731 internal::Int32FromGTestEnv("repeat", 1),
1732 "How many times to repeat each test. Specify a negative number "
1733 "for repeating forever. Useful for shaking out flaky tests.");
1736 show_internal_stack_frames, false,
1737 "True iff " GTEST_NAME_ " should include internal stack frames when "
1738 "printing test failure stack traces.");
1742 internal::BoolFromGTestEnv("shuffle", false),
1743 "True iff " GTEST_NAME_
1744 " should randomize tests' order on every run.");
1746 GTEST_DEFINE_int32_(
1748 internal::Int32FromGTestEnv("stack_trace_depth", kMaxStackTraceDepth),
1749 "The maximum number of stack frames to print when an "
1750 "assertion fails. The valid range is 0 through 100, inclusive.");
1752 GTEST_DEFINE_string_(
1754 internal::StringFromGTestEnv("stream_result_to", ""),
1755 "This flag specifies the host name and the port number on which to stream "
1756 "test results. Example: \"localhost:555\". The flag is effective only on "
1761 internal::BoolFromGTestEnv("throw_on_failure", false),
1762 "When this flag is specified, a failed assertion will throw an exception "
1763 "if exceptions are enabled or exit the program with a non-zero code "
1766 namespace internal {
1768 // Generates a random number from [0, range), using a Linear
1769 // Congruential Generator (LCG). Crashes if 'range' is 0 or greater
1771 UInt32 Random::Generate(UInt32 range) {
1772 // These constants are the same as are used in glibc's rand(3).
1773 state_ = (1103515245U*state_ + 12345U) % kMaxRange;
1775 GTEST_CHECK_(range > 0)
1776 << "Cannot generate a number in the range [0, 0).";
1777 GTEST_CHECK_(range <= kMaxRange)
1778 << "Generation of a number in [0, " << range << ") was requested, "
1779 << "but this can only generate numbers in [0, " << kMaxRange << ").";
1781 // Converting via modulus introduces a bit of downward bias, but
1782 // it's simple, and a linear congruential generator isn't too good
1784 return state_ % range;
1787 // GTestIsInitialized() returns true iff the user has initialized
1788 // Google Test. Useful for catching the user mistake of not initializing
1789 // Google Test before calling RUN_ALL_TESTS().
1791 // A user must call testing::InitGoogleTest() to initialize Google
1792 // Test. g_init_gtest_count is set to the number of times
1793 // InitGoogleTest() has been called. We don't protect this variable
1794 // under a mutex as it is only accessed in the main thread.
1795 GTEST_API_ int g_init_gtest_count = 0;
1796 static bool GTestIsInitialized() { return g_init_gtest_count != 0; }
1798 // Iterates over a vector of TestCases, keeping a running sum of the
1799 // results of calling a given int-returning method on each.
1801 static int SumOverTestCaseList(const std::vector<TestCase*>& case_list,
1802 int (TestCase::*method)() const) {
1804 for (size_t i = 0; i < case_list.size(); i++) {
1805 sum += (case_list[i]->*method)();
1810 // Returns true iff the test case passed.
1811 static bool TestCasePassed(const TestCase* test_case) {
1812 return test_case->should_run() && test_case->Passed();
1815 // Returns true iff the test case failed.
1816 static bool TestCaseFailed(const TestCase* test_case) {
1817 return test_case->should_run() && test_case->Failed();
1820 // Returns true iff test_case contains at least one test that should
1822 static bool ShouldRunTestCase(const TestCase* test_case) {
1823 return test_case->should_run();
1826 // AssertHelper constructor.
1827 AssertHelper::AssertHelper(TestPartResult::Type type,
1830 const char* message)
1831 : data_(new AssertHelperData(type, file, line, message)) {
1834 AssertHelper::~AssertHelper() {
1838 // Message assignment, for assertion streaming support.
1839 void AssertHelper::operator=(const Message& message) const {
1840 UnitTest::GetInstance()->
1841 AddTestPartResult(data_->type, data_->file, data_->line,
1842 AppendUserMessage(data_->message, message),
1843 UnitTest::GetInstance()->impl()
1844 ->CurrentOsStackTraceExceptTop(1)
1845 // Skips the stack frame for this function itself.
1849 // Mutex for linked pointers.
1850 GTEST_API_ GTEST_DEFINE_STATIC_MUTEX_(g_linked_ptr_mutex);
1852 // Application pathname gotten in InitGoogleTest.
1853 std::string g_executable_path;
1855 // Returns the current application's name, removing directory path if that
1857 FilePath GetCurrentExecutableName() {
1860 #if GTEST_OS_WINDOWS
1861 result.Set(FilePath(g_executable_path).RemoveExtension("exe"));
1863 result.Set(FilePath(g_executable_path));
1864 #endif // GTEST_OS_WINDOWS
1866 return result.RemoveDirectoryName();
1869 // Functions for processing the gtest_output flag.
1871 // Returns the output format, or "" for normal printed output.
1872 std::string UnitTestOptions::GetOutputFormat() {
1873 const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
1874 if (gtest_output_flag == NULL) return std::string("");
1876 const char* const colon = strchr(gtest_output_flag, ':');
1877 return (colon == NULL) ?
1878 std::string(gtest_output_flag) :
1879 std::string(gtest_output_flag, colon - gtest_output_flag);
1882 // Returns the name of the requested output file, or the default if none
1883 // was explicitly specified.
1884 std::string UnitTestOptions::GetAbsolutePathToOutputFile() {
1885 const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
1886 if (gtest_output_flag == NULL)
1889 const char* const colon = strchr(gtest_output_flag, ':');
1891 return internal::FilePath::ConcatPaths(
1893 UnitTest::GetInstance()->original_working_dir()),
1894 internal::FilePath(kDefaultOutputFile)).string();
1896 internal::FilePath output_name(colon + 1);
1897 if (!output_name.IsAbsolutePath())
1898 // TODO(wan@google.com): on Windows \some\path is not an absolute
1899 // path (as its meaning depends on the current drive), yet the
1900 // following logic for turning it into an absolute path is wrong.
1902 output_name = internal::FilePath::ConcatPaths(
1903 internal::FilePath(UnitTest::GetInstance()->original_working_dir()),
1904 internal::FilePath(colon + 1));
1906 if (!output_name.IsDirectory())
1907 return output_name.string();
1909 internal::FilePath result(internal::FilePath::GenerateUniqueFileName(
1910 output_name, internal::GetCurrentExecutableName(),
1911 GetOutputFormat().c_str()));
1912 return result.string();
1915 // Returns true iff the wildcard pattern matches the string. The
1916 // first ':' or '\0' character in pattern marks the end of it.
1918 // This recursive algorithm isn't very efficient, but is clear and
1919 // works well enough for matching test names, which are short.
1920 bool UnitTestOptions::PatternMatchesString(const char *pattern,
1924 case ':': // Either ':' or '\0' marks the end of the pattern.
1925 return *str == '\0';
1926 case '?': // Matches any single character.
1927 return *str != '\0' && PatternMatchesString(pattern + 1, str + 1);
1928 case '*': // Matches any string (possibly empty) of characters.
1929 return (*str != '\0' && PatternMatchesString(pattern, str + 1)) ||
1930 PatternMatchesString(pattern + 1, str);
1931 default: // Non-special character. Matches itself.
1932 return *pattern == *str &&
1933 PatternMatchesString(pattern + 1, str + 1);
1937 bool UnitTestOptions::MatchesFilter(
1938 const std::string& name, const char* filter) {
1939 const char *cur_pattern = filter;
1941 if (PatternMatchesString(cur_pattern, name.c_str())) {
1945 // Finds the next pattern in the filter.
1946 cur_pattern = strchr(cur_pattern, ':');
1948 // Returns if no more pattern can be found.
1949 if (cur_pattern == NULL) {
1953 // Skips the pattern separater (the ':' character).
1958 // Returns true iff the user-specified filter matches the test case
1959 // name and the test name.
1960 bool UnitTestOptions::FilterMatchesTest(const std::string &test_case_name,
1961 const std::string &test_name) {
1962 const std::string& full_name = test_case_name + "." + test_name.c_str();
1964 // Split --gtest_filter at '-', if there is one, to separate into
1965 // positive filter and negative filter portions
1966 const char* const p = GTEST_FLAG(filter).c_str();
1967 const char* const dash = strchr(p, '-');
1968 std::string positive;
1969 std::string negative;
1971 positive = GTEST_FLAG(filter).c_str(); // Whole string is a positive filter
1974 positive = std::string(p, dash); // Everything up to the dash
1975 negative = std::string(dash + 1); // Everything after the dash
1976 if (positive.empty()) {
1977 // Treat '-test1' as the same as '*-test1'
1978 positive = kUniversalFilter;
1982 // A filter is a colon-separated list of patterns. It matches a
1983 // test if any pattern in it matches the test.
1984 return (MatchesFilter(full_name, positive.c_str()) &&
1985 !MatchesFilter(full_name, negative.c_str()));
1989 // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
1990 // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
1991 // This function is useful as an __except condition.
1992 int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) {
1993 // Google Test should handle a SEH exception if:
1994 // 1. the user wants it to, AND
1995 // 2. this is not a breakpoint exception, AND
1996 // 3. this is not a C++ exception (VC++ implements them via SEH,
1999 // SEH exception code for C++ exceptions.
2000 // (see http://support.microsoft.com/kb/185294 for more information).
2001 const DWORD kCxxExceptionCode = 0xe06d7363;
2003 bool should_handle = true;
2005 if (!GTEST_FLAG(catch_exceptions))
2006 should_handle = false;
2007 else if (exception_code == EXCEPTION_BREAKPOINT)
2008 should_handle = false;
2009 else if (exception_code == kCxxExceptionCode)
2010 should_handle = false;
2012 return should_handle ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH;
2014 #endif // GTEST_HAS_SEH
2016 } // namespace internal
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
2020 // results. Intercepts only failures from the current thread.
2021 ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
2022 TestPartResultArray* result)
2023 : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD),
2028 // The c'tor sets this object as the test part result reporter used by
2029 // Google Test. The 'result' parameter specifies where to report the
2031 ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
2032 InterceptMode intercept_mode, TestPartResultArray* result)
2033 : intercept_mode_(intercept_mode),
2038 void ScopedFakeTestPartResultReporter::Init() {
2039 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
2040 if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
2041 old_reporter_ = impl->GetGlobalTestPartResultReporter();
2042 impl->SetGlobalTestPartResultReporter(this);
2044 old_reporter_ = impl->GetTestPartResultReporterForCurrentThread();
2045 impl->SetTestPartResultReporterForCurrentThread(this);
2049 // The d'tor restores the test part result reporter used by Google Test
2051 ScopedFakeTestPartResultReporter::~ScopedFakeTestPartResultReporter() {
2052 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
2053 if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
2054 impl->SetGlobalTestPartResultReporter(old_reporter_);
2056 impl->SetTestPartResultReporterForCurrentThread(old_reporter_);
2060 // Increments the test part result count and remembers the result.
2061 // This method is from the TestPartResultReporterInterface interface.
2062 void ScopedFakeTestPartResultReporter::ReportTestPartResult(
2063 const TestPartResult& result) {
2064 result_->Append(result);
2067 namespace internal {
2069 // Returns the type ID of ::testing::Test. We should always call this
2070 // instead of GetTypeId< ::testing::Test>() to get the type ID of
2071 // testing::Test. This is to work around a suspected linker bug when
2072 // using Google Test as a framework on Mac OS X. The bug causes
2073 // GetTypeId< ::testing::Test>() to return different values depending
2074 // on whether the call is from the Google Test framework itself or
2075 // from user test code. GetTestTypeId() is guaranteed to always
2076 // return the same value, as it always calls GetTypeId<>() from the
2077 // gtest.cc, which is within the Google Test framework.
2078 TypeId GetTestTypeId() {
2079 return GetTypeId<Test>();
2082 // The value of GetTestTypeId() as seen from within the Google Test
2083 // library. This is solely for testing GetTestTypeId().
2084 extern const TypeId kTestTypeIdInGoogleTest = GetTestTypeId();
2086 // This predicate-formatter checks that 'results' contains a test part
2087 // failure of the given type and that the failure message contains the
2089 static AssertionResult HasOneFailure(const char* /* results_expr */,
2090 const char* /* type_expr */,
2091 const char* /* substr_expr */,
2092 const TestPartResultArray& results,
2093 TestPartResult::Type type,
2094 const string& substr) {
2095 const std::string expected(type == TestPartResult::kFatalFailure ?
2097 "1 non-fatal failure");
2099 if (results.size() != 1) {
2100 msg << "Expected: " << expected << "\n"
2101 << " Actual: " << results.size() << " failures";
2102 for (int i = 0; i < results.size(); i++) {
2103 msg << "\n" << results.GetTestPartResult(i);
2105 return AssertionFailure() << msg;
2108 const TestPartResult& r = results.GetTestPartResult(0);
2109 if (r.type() != type) {
2110 return AssertionFailure() << "Expected: " << expected << "\n"
2115 if (strstr(r.message(), substr.c_str()) == NULL) {
2116 return AssertionFailure() << "Expected: " << expected << " containing \""
2122 return AssertionSuccess();
2125 // The constructor of SingleFailureChecker remembers where to look up
2126 // test part results, what type of failure we expect, and what
2127 // substring the failure message should contain.
2128 SingleFailureChecker:: SingleFailureChecker(
2129 const TestPartResultArray* results,
2130 TestPartResult::Type type,
2131 const string& substr)
2132 : results_(results),
2136 // The destructor of SingleFailureChecker verifies that the given
2137 // TestPartResultArray contains exactly one failure that has the given
2138 // type and contains the given substring. If that's not the case, a
2139 // non-fatal failure will be generated.
2140 SingleFailureChecker::~SingleFailureChecker() {
2141 EXPECT_PRED_FORMAT3(HasOneFailure, *results_, type_, substr_);
2144 DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter(
2145 UnitTestImpl* unit_test) : unit_test_(unit_test) {}
2147 void DefaultGlobalTestPartResultReporter::ReportTestPartResult(
2148 const TestPartResult& result) {
2149 unit_test_->current_test_result()->AddTestPartResult(result);
2150 unit_test_->listeners()->repeater()->OnTestPartResult(result);
2153 DefaultPerThreadTestPartResultReporter::DefaultPerThreadTestPartResultReporter(
2154 UnitTestImpl* unit_test) : unit_test_(unit_test) {}
2156 void DefaultPerThreadTestPartResultReporter::ReportTestPartResult(
2157 const TestPartResult& result) {
2158 unit_test_->GetGlobalTestPartResultReporter()->ReportTestPartResult(result);
2161 // Returns the global test part result reporter.
2162 TestPartResultReporterInterface*
2163 UnitTestImpl::GetGlobalTestPartResultReporter() {
2164 internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
2165 return global_test_part_result_repoter_;
2168 // Sets the global test part result reporter.
2169 void UnitTestImpl::SetGlobalTestPartResultReporter(
2170 TestPartResultReporterInterface* reporter) {
2171 internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
2172 global_test_part_result_repoter_ = reporter;
2175 // Returns the test part result reporter for the current thread.
2176 TestPartResultReporterInterface*
2177 UnitTestImpl::GetTestPartResultReporterForCurrentThread() {
2178 return per_thread_test_part_result_reporter_.get();
2181 // Sets the test part result reporter for the current thread.
2182 void UnitTestImpl::SetTestPartResultReporterForCurrentThread(
2183 TestPartResultReporterInterface* reporter) {
2184 per_thread_test_part_result_reporter_.set(reporter);
2187 // Gets the number of successful test cases.
2188 int UnitTestImpl::successful_test_case_count() const {
2189 return CountIf(test_cases_, TestCasePassed);
2192 // Gets the number of failed test cases.
2193 int UnitTestImpl::failed_test_case_count() const {
2194 return CountIf(test_cases_, TestCaseFailed);
2197 // Gets the number of all test cases.
2198 int UnitTestImpl::total_test_case_count() const {
2199 return static_cast<int>(test_cases_.size());
2202 // Gets the number of all test cases that contain at least one test
2204 int UnitTestImpl::test_case_to_run_count() const {
2205 return CountIf(test_cases_, ShouldRunTestCase);
2208 // Gets the number of successful tests.
2209 int UnitTestImpl::successful_test_count() const {
2210 return SumOverTestCaseList(test_cases_, &TestCase::successful_test_count);
2213 // Gets the number of failed tests.
2214 int UnitTestImpl::failed_test_count() const {
2215 return SumOverTestCaseList(test_cases_, &TestCase::failed_test_count);
2218 // Gets the number of disabled tests.
2219 int UnitTestImpl::disabled_test_count() const {
2220 return SumOverTestCaseList(test_cases_, &TestCase::disabled_test_count);
2223 // Gets the number of all tests.
2224 int UnitTestImpl::total_test_count() const {
2225 return SumOverTestCaseList(test_cases_, &TestCase::total_test_count);
2228 // Gets the number of tests that should run.
2229 int UnitTestImpl::test_to_run_count() const {
2230 return SumOverTestCaseList(test_cases_, &TestCase::test_to_run_count);
2233 // Returns the current OS stack trace as an std::string.
2235 // The maximum number of stack frames to be included is specified by
2236 // the gtest_stack_trace_depth flag. The skip_count parameter
2237 // specifies the number of top frames to be skipped, which doesn't
2238 // count against the number of frames to be included.
2240 // For example, if Foo() calls Bar(), which in turn calls
2241 // CurrentOsStackTraceExceptTop(1), Foo() will be included in the
2242 // trace but Bar() and CurrentOsStackTraceExceptTop() won't.
2243 std::string UnitTestImpl::CurrentOsStackTraceExceptTop(int skip_count) {
2248 // Returns the current time in milliseconds.
2249 TimeInMillis GetTimeInMillis() {
2250 #if GTEST_OS_WINDOWS_MOBILE || defined(__BORLANDC__)
2251 // Difference between 1970-01-01 and 1601-01-01 in milliseconds.
2252 // http://analogous.blogspot.com/2005/04/epoch.html
2253 const TimeInMillis kJavaEpochToWinFileTimeDelta =
2254 static_cast<TimeInMillis>(116444736UL) * 100000UL;
2255 const DWORD kTenthMicrosInMilliSecond = 10000;
2257 SYSTEMTIME now_systime;
2258 FILETIME now_filetime;
2259 ULARGE_INTEGER now_int64;
2260 // TODO(kenton@google.com): Shouldn't this just use
2261 // GetSystemTimeAsFileTime()?
2262 GetSystemTime(&now_systime);
2263 if (SystemTimeToFileTime(&now_systime, &now_filetime)) {
2264 now_int64.LowPart = now_filetime.dwLowDateTime;
2265 now_int64.HighPart = now_filetime.dwHighDateTime;
2266 now_int64.QuadPart = (now_int64.QuadPart / kTenthMicrosInMilliSecond) -
2267 kJavaEpochToWinFileTimeDelta;
2268 return now_int64.QuadPart;
2271 #elif GTEST_OS_WINDOWS && !GTEST_HAS_GETTIMEOFDAY_
2276 // MSVC 8 deprecates _ftime64(), so we want to suppress warning 4996
2277 // (deprecated function) there.
2278 // TODO(kenton@google.com): Use GetTickCount()? Or use
2279 // SystemTimeToFileTime()
2280 # pragma warning(push) // Saves the current warning state.
2281 # pragma warning(disable:4996) // Temporarily disables warning 4996.
2283 # pragma warning(pop) // Restores the warning state.
2290 return static_cast<TimeInMillis>(now.time) * 1000 + now.millitm;
2291 #elif GTEST_HAS_GETTIMEOFDAY_
2293 gettimeofday(&now, NULL);
2294 return static_cast<TimeInMillis>(now.tv_sec) * 1000 + now.tv_usec / 1000;
2296 # error "Don't know how to get the current time on your system."
2304 #if GTEST_OS_WINDOWS_MOBILE
2305 // Creates a UTF-16 wide string from the given ANSI string, allocating
2306 // memory using new. The caller is responsible for deleting the return
2307 // value using delete[]. Returns the wide string, or NULL if the
2309 LPCWSTR String::AnsiToUtf16(const char* ansi) {
2310 if (!ansi) return NULL;
2311 const int length = strlen(ansi);
2312 const int unicode_length =
2313 MultiByteToWideChar(CP_ACP, 0, ansi, length,
2315 WCHAR* unicode = new WCHAR[unicode_length + 1];
2316 MultiByteToWideChar(CP_ACP, 0, ansi, length,
2317 unicode, unicode_length);
2318 unicode[unicode_length] = 0;
2322 // Creates an ANSI string from the given wide string, allocating
2323 // memory using new. The caller is responsible for deleting the return
2324 // value using delete[]. Returns the ANSI string, or NULL if the
2326 const char* String::Utf16ToAnsi(LPCWSTR utf16_str) {
2327 if (!utf16_str) return NULL;
2328 const int ansi_length =
2329 WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
2330 NULL, 0, NULL, NULL);
2331 char* ansi = new char[ansi_length + 1];
2332 WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
2333 ansi, ansi_length, NULL, NULL);
2334 ansi[ansi_length] = 0;
2338 #endif // GTEST_OS_WINDOWS_MOBILE
2340 // Compares two C strings. Returns true iff they have the same content.
2342 // Unlike strcmp(), this function can handle NULL argument(s). A NULL
2343 // C string is considered different to any non-NULL C string,
2344 // including the empty string.
2345 bool String::CStringEquals(const char * lhs, const char * rhs) {
2346 if ( lhs == NULL ) return rhs == NULL;
2348 if ( rhs == NULL ) return false;
2350 return strcmp(lhs, rhs) == 0;
2353 #if GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
2355 // Converts an array of wide chars to a narrow string using the UTF-8
2356 // encoding, and streams the result to the given Message object.
2357 static void StreamWideCharsToMessage(const wchar_t* wstr, size_t length,
2359 for (size_t i = 0; i != length; ) { // NOLINT
2360 if (wstr[i] != L'\0') {
2361 *msg << WideStringToUtf8(wstr + i, static_cast<int>(length - i));
2362 while (i != length && wstr[i] != L'\0')
2371 #endif // GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
2373 } // namespace internal
2375 // Constructs an empty Message.
2376 // We allocate the stringstream separately because otherwise each use of
2377 // ASSERT/EXPECT in a procedure adds over 200 bytes to the procedure's
2378 // stack frame leading to huge stack frames in some cases; gcc does not reuse
2380 Message::Message() : ss_(new ::std::stringstream) {
2381 // By default, we want there to be enough precision when printing
2382 // a double to a Message.
2383 *ss_ << std::setprecision(std::numeric_limits<double>::digits10 + 2);
2386 // These two overloads allow streaming a wide C string to a Message
2387 // using the UTF-8 encoding.
2388 Message& Message::operator <<(const wchar_t* wide_c_str) {
2389 return *this << internal::String::ShowWideCString(wide_c_str);
2391 Message& Message::operator <<(wchar_t* wide_c_str) {
2392 return *this << internal::String::ShowWideCString(wide_c_str);
2395 #if GTEST_HAS_STD_WSTRING
2396 // Converts the given wide string to a narrow string using the UTF-8
2397 // encoding, and streams the result to this Message object.
2398 Message& Message::operator <<(const ::std::wstring& wstr) {
2399 internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
2402 #endif // GTEST_HAS_STD_WSTRING
2404 #if GTEST_HAS_GLOBAL_WSTRING
2405 // Converts the given wide string to a narrow string using the UTF-8
2406 // encoding, and streams the result to this Message object.
2407 Message& Message::operator <<(const ::wstring& wstr) {
2408 internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
2411 #endif // GTEST_HAS_GLOBAL_WSTRING
2413 // Gets the text streamed to this object so far as an std::string.
2414 // Each '\0' character in the buffer is replaced with "\\0".
2415 std::string Message::GetString() const {
2416 return internal::StringStreamToString(ss_.get());
2419 // AssertionResult constructors.
2420 // Used in EXPECT_TRUE/FALSE(assertion_result).
2421 AssertionResult::AssertionResult(const AssertionResult& other)
2422 : success_(other.success_),
2423 message_(other.message_.get() != NULL ?
2424 new ::std::string(*other.message_) :
2425 static_cast< ::std::string*>(NULL)) {
2428 // Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE.
2429 AssertionResult AssertionResult::operator!() const {
2430 AssertionResult negation(!success_);
2431 if (message_.get() != NULL)
2432 negation << *message_;
2436 // Makes a successful assertion result.
2437 AssertionResult AssertionSuccess() {
2438 return AssertionResult(true);
2441 // Makes a failed assertion result.
2442 AssertionResult AssertionFailure() {
2443 return AssertionResult(false);
2446 // Makes a failed assertion result with the given failure message.
2447 // Deprecated; use AssertionFailure() << message.
2448 AssertionResult AssertionFailure(const Message& message) {
2449 return AssertionFailure() << message;
2452 namespace internal {
2454 // Constructs and returns the message for an equality assertion
2455 // (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure.
2457 // The first four parameters are the expressions used in the assertion
2458 // and their values, as strings. For example, for ASSERT_EQ(foo, bar)
2459 // where foo is 5 and bar is 6, we have:
2461 // expected_expression: "foo"
2462 // actual_expression: "bar"
2463 // expected_value: "5"
2464 // actual_value: "6"
2466 // The ignoring_case parameter is true iff the assertion is a
2467 // *_STRCASEEQ*. When it's true, the string " (ignoring case)" will
2468 // be inserted into the message.
2469 AssertionResult EqFailure(const char* expected_expression,
2470 const char* actual_expression,
2471 const std::string& expected_value,
2472 const std::string& actual_value,
2473 bool ignoring_case) {
2475 msg << "Value of: " << actual_expression;
2476 if (actual_value != actual_expression) {
2477 msg << "\n Actual: " << actual_value;
2480 msg << "\nExpected: " << expected_expression;
2481 if (ignoring_case) {
2482 msg << " (ignoring case)";
2484 if (expected_value != expected_expression) {
2485 msg << "\nWhich is: " << expected_value;
2488 return AssertionFailure() << msg;
2491 // Constructs a failure message for Boolean assertions such as EXPECT_TRUE.
2492 std::string GetBoolAssertionFailureMessage(
2493 const AssertionResult& assertion_result,
2494 const char* expression_text,
2495 const char* actual_predicate_value,
2496 const char* expected_predicate_value) {
2497 const char* actual_message = assertion_result.message();
2499 msg << "Value of: " << expression_text
2500 << "\n Actual: " << actual_predicate_value;
2501 if (actual_message[0] != '\0')
2502 msg << " (" << actual_message << ")";
2503 msg << "\nExpected: " << expected_predicate_value;
2504 return msg.GetString();
2507 // Helper function for implementing ASSERT_NEAR.
2508 AssertionResult DoubleNearPredFormat(const char* expr1,
2510 const char* abs_error_expr,
2514 const double diff = fabs(val1 - val2);
2515 if (diff <= abs_error) return AssertionSuccess();
2517 // TODO(wan): do not print the value of an expression if it's
2518 // already a literal.
2519 return AssertionFailure()
2520 << "The difference between " << expr1 << " and " << expr2
2521 << " is " << diff << ", which exceeds " << abs_error_expr << ", where\n"
2522 << expr1 << " evaluates to " << val1 << ",\n"
2523 << expr2 << " evaluates to " << val2 << ", and\n"
2524 << abs_error_expr << " evaluates to " << abs_error << ".";
2528 // Helper template for implementing FloatLE() and DoubleLE().
2529 template <typename RawType>
2530 AssertionResult FloatingPointLE(const char* expr1,
2534 // Returns success if val1 is less than val2,
2536 return AssertionSuccess();
2539 // or if val1 is almost equal to val2.
2540 const FloatingPoint<RawType> lhs(val1), rhs(val2);
2541 if (lhs.AlmostEquals(rhs)) {
2542 return AssertionSuccess();
2545 // Note that the above two checks will both fail if either val1 or
2546 // val2 is NaN, as the IEEE floating-point standard requires that
2547 // any predicate involving a NaN must return false.
2549 ::std::stringstream val1_ss;
2550 val1_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
2553 ::std::stringstream val2_ss;
2554 val2_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
2557 return AssertionFailure()
2558 << "Expected: (" << expr1 << ") <= (" << expr2 << ")\n"
2559 << " Actual: " << StringStreamToString(&val1_ss) << " vs "
2560 << StringStreamToString(&val2_ss);
2563 } // namespace internal
2565 // Asserts that val1 is less than, or almost equal to, val2. Fails
2566 // otherwise. In particular, it fails if either val1 or val2 is NaN.
2567 AssertionResult FloatLE(const char* expr1, const char* expr2,
2568 float val1, float val2) {
2569 return internal::FloatingPointLE<float>(expr1, expr2, val1, val2);
2572 // Asserts that val1 is less than, or almost equal to, val2. Fails
2573 // otherwise. In particular, it fails if either val1 or val2 is NaN.
2574 AssertionResult DoubleLE(const char* expr1, const char* expr2,
2575 double val1, double val2) {
2576 return internal::FloatingPointLE<double>(expr1, expr2, val1, val2);
2579 namespace internal {
2581 // The helper function for {ASSERT|EXPECT}_EQ with int or enum
2583 AssertionResult CmpHelperEQ(const char* expected_expression,
2584 const char* actual_expression,
2585 BiggestInt expected,
2586 BiggestInt actual) {
2587 if (expected == actual) {
2588 return AssertionSuccess();
2591 return EqFailure(expected_expression,
2593 FormatForComparisonFailureMessage(expected, actual),
2594 FormatForComparisonFailureMessage(actual, expected),
2598 // A macro for implementing the helper functions needed to implement
2599 // ASSERT_?? and EXPECT_?? with integer or enum arguments. It is here
2600 // just to avoid copy-and-paste of similar code.
2601 #define GTEST_IMPL_CMP_HELPER_(op_name, op)\
2602 AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \
2603 BiggestInt val1, BiggestInt val2) {\
2604 if (val1 op val2) {\
2605 return AssertionSuccess();\
2607 return AssertionFailure() \
2608 << "Expected: (" << expr1 << ") " #op " (" << expr2\
2609 << "), actual: " << FormatForComparisonFailureMessage(val1, val2)\
2610 << " vs " << FormatForComparisonFailureMessage(val2, val1);\
2614 // Implements the helper function for {ASSERT|EXPECT}_NE with int or
2616 GTEST_IMPL_CMP_HELPER_(NE, !=)
2617 // Implements the helper function for {ASSERT|EXPECT}_LE with int or
2619 GTEST_IMPL_CMP_HELPER_(LE, <=)
2620 // Implements the helper function for {ASSERT|EXPECT}_LT with int or
2622 GTEST_IMPL_CMP_HELPER_(LT, < )
2623 // Implements the helper function for {ASSERT|EXPECT}_GE with int or
2625 GTEST_IMPL_CMP_HELPER_(GE, >=)
2626 // Implements the helper function for {ASSERT|EXPECT}_GT with int or
2628 GTEST_IMPL_CMP_HELPER_(GT, > )
2630 #undef GTEST_IMPL_CMP_HELPER_
2632 // The helper function for {ASSERT|EXPECT}_STREQ.
2633 AssertionResult CmpHelperSTREQ(const char* expected_expression,
2634 const char* actual_expression,
2635 const char* expected,
2636 const char* actual) {
2637 if (String::CStringEquals(expected, actual)) {
2638 return AssertionSuccess();
2641 return EqFailure(expected_expression,
2643 PrintToString(expected),
2644 PrintToString(actual),
2648 // The helper function for {ASSERT|EXPECT}_STRCASEEQ.
2649 AssertionResult CmpHelperSTRCASEEQ(const char* expected_expression,
2650 const char* actual_expression,
2651 const char* expected,
2652 const char* actual) {
2653 if (String::CaseInsensitiveCStringEquals(expected, actual)) {
2654 return AssertionSuccess();
2657 return EqFailure(expected_expression,
2659 PrintToString(expected),
2660 PrintToString(actual),
2664 // The helper function for {ASSERT|EXPECT}_STRNE.
2665 AssertionResult CmpHelperSTRNE(const char* s1_expression,
2666 const char* s2_expression,
2669 if (!String::CStringEquals(s1, s2)) {
2670 return AssertionSuccess();
2672 return AssertionFailure() << "Expected: (" << s1_expression << ") != ("
2673 << s2_expression << "), actual: \""
2674 << s1 << "\" vs \"" << s2 << "\"";
2678 // The helper function for {ASSERT|EXPECT}_STRCASENE.
2679 AssertionResult CmpHelperSTRCASENE(const char* s1_expression,
2680 const char* s2_expression,
2683 if (!String::CaseInsensitiveCStringEquals(s1, s2)) {
2684 return AssertionSuccess();
2686 return AssertionFailure()
2687 << "Expected: (" << s1_expression << ") != ("
2688 << s2_expression << ") (ignoring case), actual: \""
2689 << s1 << "\" vs \"" << s2 << "\"";
2693 } // namespace internal
2697 // Helper functions for implementing IsSubString() and IsNotSubstring().
2699 // This group of overloaded functions return true iff needle is a
2700 // substring of haystack. NULL is considered a substring of itself
2703 bool IsSubstringPred(const char* needle, const char* haystack) {
2704 if (needle == NULL || haystack == NULL)
2705 return needle == haystack;
2707 return strstr(haystack, needle) != NULL;
2710 bool IsSubstringPred(const wchar_t* needle, const wchar_t* haystack) {
2711 if (needle == NULL || haystack == NULL)
2712 return needle == haystack;
2714 return wcsstr(haystack, needle) != NULL;
2717 // StringType here can be either ::std::string or ::std::wstring.
2718 template <typename StringType>
2719 bool IsSubstringPred(const StringType& needle,
2720 const StringType& haystack) {
2721 return haystack.find(needle) != StringType::npos;
2724 // This function implements either IsSubstring() or IsNotSubstring(),
2725 // depending on the value of the expected_to_be_substring parameter.
2726 // StringType here can be const char*, const wchar_t*, ::std::string,
2727 // or ::std::wstring.
2728 template <typename StringType>
2729 AssertionResult IsSubstringImpl(
2730 bool expected_to_be_substring,
2731 const char* needle_expr, const char* haystack_expr,
2732 const StringType& needle, const StringType& haystack) {
2733 if (IsSubstringPred(needle, haystack) == expected_to_be_substring)
2734 return AssertionSuccess();
2736 const bool is_wide_string = sizeof(needle[0]) > 1;
2737 const char* const begin_string_quote = is_wide_string ? "L\"" : "\"";
2738 return AssertionFailure()
2739 << "Value of: " << needle_expr << "\n"
2740 << " Actual: " << begin_string_quote << needle << "\"\n"
2741 << "Expected: " << (expected_to_be_substring ? "" : "not ")
2742 << "a substring of " << haystack_expr << "\n"
2743 << "Which is: " << begin_string_quote << haystack << "\"";
2748 // IsSubstring() and IsNotSubstring() check whether needle is a
2749 // substring of haystack (NULL is considered a substring of itself
2750 // only), and return an appropriate error message when they fail.
2752 AssertionResult IsSubstring(
2753 const char* needle_expr, const char* haystack_expr,
2754 const char* needle, const char* haystack) {
2755 return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
2758 AssertionResult IsSubstring(
2759 const char* needle_expr, const char* haystack_expr,
2760 const wchar_t* needle, const wchar_t* haystack) {
2761 return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
2764 AssertionResult IsNotSubstring(
2765 const char* needle_expr, const char* haystack_expr,
2766 const char* needle, const char* haystack) {
2767 return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
2770 AssertionResult IsNotSubstring(
2771 const char* needle_expr, const char* haystack_expr,
2772 const wchar_t* needle, const wchar_t* haystack) {
2773 return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
2776 AssertionResult IsSubstring(
2777 const char* needle_expr, const char* haystack_expr,
2778 const ::std::string& needle, const ::std::string& haystack) {
2779 return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
2782 AssertionResult IsNotSubstring(
2783 const char* needle_expr, const char* haystack_expr,
2784 const ::std::string& needle, const ::std::string& haystack) {
2785 return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
2788 #if GTEST_HAS_STD_WSTRING
2789 AssertionResult IsSubstring(
2790 const char* needle_expr, const char* haystack_expr,
2791 const ::std::wstring& needle, const ::std::wstring& haystack) {
2792 return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
2795 AssertionResult IsNotSubstring(
2796 const char* needle_expr, const char* haystack_expr,
2797 const ::std::wstring& needle, const ::std::wstring& haystack) {
2798 return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
2800 #endif // GTEST_HAS_STD_WSTRING
2802 namespace internal {
2804 #if GTEST_OS_WINDOWS
2808 // Helper function for IsHRESULT{SuccessFailure} predicates
2809 AssertionResult HRESULTFailureHelper(const char* expr,
2810 const char* expected,
2811 long hr) { // NOLINT
2812 # if GTEST_OS_WINDOWS_MOBILE
2814 // Windows CE doesn't support FormatMessage.
2815 const char error_text[] = "";
2819 // Looks up the human-readable system message for the HRESULT code
2820 // and since we're not passing any params to FormatMessage, we don't
2821 // want inserts expanded.
2822 const DWORD kFlags = FORMAT_MESSAGE_FROM_SYSTEM |
2823 FORMAT_MESSAGE_IGNORE_INSERTS;
2824 const DWORD kBufSize = 4096;
2825 // Gets the system's human readable message string for this HRESULT.
2826 char error_text[kBufSize] = { '\0' };
2827 DWORD message_length = ::FormatMessageA(kFlags,
2828 0, // no source, we're asking system
2830 0, // no line width restrictions
2831 error_text, // output buffer
2832 kBufSize, // buf size
2833 NULL); // no arguments for inserts
2834 // Trims tailing white space (FormatMessage leaves a trailing CR-LF)
2835 for (; message_length && IsSpace(error_text[message_length - 1]);
2837 error_text[message_length - 1] = '\0';
2840 # endif // GTEST_OS_WINDOWS_MOBILE
2842 const std::string error_hex("0x" + String::FormatHexInt(hr));
2843 return ::testing::AssertionFailure()
2844 << "Expected: " << expr << " " << expected << ".\n"
2845 << " Actual: " << error_hex << " " << error_text << "\n";
2850 AssertionResult IsHRESULTSuccess(const char* expr, long hr) { // NOLINT
2851 if (SUCCEEDED(hr)) {
2852 return AssertionSuccess();
2854 return HRESULTFailureHelper(expr, "succeeds", hr);
2857 AssertionResult IsHRESULTFailure(const char* expr, long hr) { // NOLINT
2859 return AssertionSuccess();
2861 return HRESULTFailureHelper(expr, "fails", hr);
2864 #endif // GTEST_OS_WINDOWS
2866 // Utility functions for encoding Unicode text (wide strings) in
2869 // A Unicode code-point can have upto 21 bits, and is encoded in UTF-8
2872 // Code-point length Encoding
2873 // 0 - 7 bits 0xxxxxxx
2874 // 8 - 11 bits 110xxxxx 10xxxxxx
2875 // 12 - 16 bits 1110xxxx 10xxxxxx 10xxxxxx
2876 // 17 - 21 bits 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
2878 // The maximum code-point a one-byte UTF-8 sequence can represent.
2879 const UInt32 kMaxCodePoint1 = (static_cast<UInt32>(1) << 7) - 1;
2881 // The maximum code-point a two-byte UTF-8 sequence can represent.
2882 const UInt32 kMaxCodePoint2 = (static_cast<UInt32>(1) << (5 + 6)) - 1;
2884 // The maximum code-point a three-byte UTF-8 sequence can represent.
2885 const UInt32 kMaxCodePoint3 = (static_cast<UInt32>(1) << (4 + 2*6)) - 1;
2887 // The maximum code-point a four-byte UTF-8 sequence can represent.
2888 const UInt32 kMaxCodePoint4 = (static_cast<UInt32>(1) << (3 + 3*6)) - 1;
2890 // Chops off the n lowest bits from a bit pattern. Returns the n
2891 // lowest bits. As a side effect, the original bit pattern will be
2892 // shifted to the right by n bits.
2893 inline UInt32 ChopLowBits(UInt32* bits, int n) {
2894 const UInt32 low_bits = *bits & ((static_cast<UInt32>(1) << n) - 1);
2899 // Converts a Unicode code point to a narrow string in UTF-8 encoding.
2900 // code_point parameter is of type UInt32 because wchar_t may not be
2901 // wide enough to contain a code point.
2902 // If the code_point is not a valid Unicode code point
2903 // (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted
2904 // to "(Invalid Unicode 0xXXXXXXXX)".
2905 std::string CodePointToUtf8(UInt32 code_point) {
2906 if (code_point > kMaxCodePoint4) {
2907 return "(Invalid Unicode 0x" + String::FormatHexInt(code_point) + ")";
2910 char str[5]; // Big enough for the largest valid code point.
2911 if (code_point <= kMaxCodePoint1) {
2913 str[0] = static_cast<char>(code_point); // 0xxxxxxx
2914 } else if (code_point <= kMaxCodePoint2) {
2916 str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
2917 str[0] = static_cast<char>(0xC0 | code_point); // 110xxxxx
2918 } else if (code_point <= kMaxCodePoint3) {
2920 str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
2921 str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
2922 str[0] = static_cast<char>(0xE0 | code_point); // 1110xxxx
2923 } else { // code_point <= kMaxCodePoint4
2925 str[3] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
2926 str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
2927 str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
2928 str[0] = static_cast<char>(0xF0 | code_point); // 11110xxx
2933 // The following two functions only make sense if the the system
2934 // uses UTF-16 for wide string encoding. All supported systems
2935 // with 16 bit wchar_t (Windows, Cygwin, Symbian OS) do use UTF-16.
2937 // Determines if the arguments constitute UTF-16 surrogate pair
2938 // and thus should be combined into a single Unicode code point
2939 // using CreateCodePointFromUtf16SurrogatePair.
2940 inline bool IsUtf16SurrogatePair(wchar_t first, wchar_t second) {
2941 return sizeof(wchar_t) == 2 &&
2942 (first & 0xFC00) == 0xD800 && (second & 0xFC00) == 0xDC00;
2945 // Creates a Unicode code point from UTF16 surrogate pair.
2946 inline UInt32 CreateCodePointFromUtf16SurrogatePair(wchar_t first,
2948 const UInt32 mask = (1 << 10) - 1;
2949 return (sizeof(wchar_t) == 2) ?
2950 (((first & mask) << 10) | (second & mask)) + 0x10000 :
2951 // This function should not be called when the condition is
2952 // false, but we provide a sensible default in case it is.
2953 static_cast<UInt32>(first);
2956 // Converts a wide string to a narrow string in UTF-8 encoding.
2957 // The wide string is assumed to have the following encoding:
2958 // UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS)
2959 // UTF-32 if sizeof(wchar_t) == 4 (on Linux)
2960 // Parameter str points to a null-terminated wide string.
2961 // Parameter num_chars may additionally limit the number
2962 // of wchar_t characters processed. -1 is used when the entire string
2963 // should be processed.
2964 // If the string contains code points that are not valid Unicode code points
2965 // (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
2966 // as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
2967 // and contains invalid UTF-16 surrogate pairs, values in those pairs
2968 // will be encoded as individual Unicode characters from Basic Normal Plane.
2969 std::string WideStringToUtf8(const wchar_t* str, int num_chars) {
2970 if (num_chars == -1)
2971 num_chars = static_cast<int>(wcslen(str));
2973 ::std::stringstream stream;
2974 for (int i = 0; i < num_chars; ++i) {
2975 UInt32 unicode_code_point;
2977 if (str[i] == L'\0') {
2979 } else if (i + 1 < num_chars && IsUtf16SurrogatePair(str[i], str[i + 1])) {
2980 unicode_code_point = CreateCodePointFromUtf16SurrogatePair(str[i],
2984 unicode_code_point = static_cast<UInt32>(str[i]);
2987 stream << CodePointToUtf8(unicode_code_point);
2989 return StringStreamToString(&stream);
2992 // Converts a wide C string to an std::string using the UTF-8 encoding.
2993 // NULL will be converted to "(null)".
2994 std::string String::ShowWideCString(const wchar_t * wide_c_str) {
2995 if (wide_c_str == NULL) return "(null)";
2997 return internal::WideStringToUtf8(wide_c_str, -1);
3000 // Compares two wide C strings. Returns true iff they have the same
3003 // Unlike wcscmp(), this function can handle NULL argument(s). A NULL
3004 // C string is considered different to any non-NULL C string,
3005 // including the empty string.
3006 bool String::WideCStringEquals(const wchar_t * lhs, const wchar_t * rhs) {
3007 if (lhs == NULL) return rhs == NULL;
3009 if (rhs == NULL) return false;
3011 return wcscmp(lhs, rhs) == 0;
3014 // Helper function for *_STREQ on wide strings.
3015 AssertionResult CmpHelperSTREQ(const char* expected_expression,
3016 const char* actual_expression,
3017 const wchar_t* expected,
3018 const wchar_t* actual) {
3019 if (String::WideCStringEquals(expected, actual)) {
3020 return AssertionSuccess();
3023 return EqFailure(expected_expression,
3025 PrintToString(expected),
3026 PrintToString(actual),
3030 // Helper function for *_STRNE on wide strings.
3031 AssertionResult CmpHelperSTRNE(const char* s1_expression,
3032 const char* s2_expression,
3034 const wchar_t* s2) {
3035 if (!String::WideCStringEquals(s1, s2)) {
3036 return AssertionSuccess();
3039 return AssertionFailure() << "Expected: (" << s1_expression << ") != ("
3040 << s2_expression << "), actual: "
3041 << PrintToString(s1)
3042 << " vs " << PrintToString(s2);
3045 // Compares two C strings, ignoring case. Returns true iff they have
3046 // the same content.
3048 // Unlike strcasecmp(), this function can handle NULL argument(s). A
3049 // NULL C string is considered different to any non-NULL C string,
3050 // including the empty string.
3051 bool String::CaseInsensitiveCStringEquals(const char * lhs, const char * rhs) {
3056 return posix::StrCaseCmp(lhs, rhs) == 0;
3059 // Compares two wide C strings, ignoring case. Returns true iff they
3060 // have the same content.
3062 // Unlike wcscasecmp(), this function can handle NULL argument(s).
3063 // A NULL C string is considered different to any non-NULL wide C string,
3064 // including the empty string.
3065 // NB: The implementations on different platforms slightly differ.
3066 // On windows, this method uses _wcsicmp which compares according to LC_CTYPE
3067 // environment variable. On GNU platform this method uses wcscasecmp
3068 // which compares according to LC_CTYPE category of the current locale.
3069 // On MacOS X, it uses towlower, which also uses LC_CTYPE category of the
3071 bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs,
3072 const wchar_t* rhs) {
3073 if (lhs == NULL) return rhs == NULL;
3075 if (rhs == NULL) return false;
3077 #if GTEST_OS_WINDOWS
3078 return _wcsicmp(lhs, rhs) == 0;
3079 #elif GTEST_OS_LINUX && !GTEST_OS_LINUX_ANDROID
3080 return wcscasecmp(lhs, rhs) == 0;
3082 // Android, Mac OS X and Cygwin don't define wcscasecmp.
3083 // Other unknown OSes may not define it either.
3086 left = towlower(*lhs++);
3087 right = towlower(*rhs++);
3088 } while (left && left == right);
3089 return left == right;
3090 #endif // OS selector
3093 // Returns true iff str ends with the given suffix, ignoring case.
3094 // Any string is considered to end with an empty suffix.
3095 bool String::EndsWithCaseInsensitive(
3096 const std::string& str, const std::string& suffix) {
3097 const size_t str_len = str.length();
3098 const size_t suffix_len = suffix.length();
3099 return (str_len >= suffix_len) &&
3100 CaseInsensitiveCStringEquals(str.c_str() + str_len - suffix_len,
3104 // Formats an int value as "%02d".
3105 std::string String::FormatIntWidth2(int value) {
3106 std::stringstream ss;
3107 ss << std::setfill('0') << std::setw(2) << value;
3111 // Formats an int value as "%X".
3112 std::string String::FormatHexInt(int value) {
3113 std::stringstream ss;
3114 ss << std::hex << std::uppercase << value;
3118 // Formats a byte as "%02X".
3119 std::string String::FormatByte(unsigned char value) {
3120 std::stringstream ss;
3121 ss << std::setfill('0') << std::setw(2) << std::hex << std::uppercase
3122 << static_cast<unsigned int>(value);
3126 // Converts the buffer in a stringstream to an std::string, converting NUL
3127 // bytes to "\\0" along the way.
3128 std::string StringStreamToString(::std::stringstream* ss) {
3129 const ::std::string& str = ss->str();
3130 const char* const start = str.c_str();
3131 const char* const end = start + str.length();
3134 result.reserve(2 * (end - start));
3135 for (const char* ch = start; ch != end; ++ch) {
3137 result += "\\0"; // Replaces NUL with "\\0";
3146 // Appends the user-supplied message to the Google-Test-generated message.
3147 std::string AppendUserMessage(const std::string& gtest_msg,
3148 const Message& user_msg) {
3149 // Appends the user message if it's non-empty.
3150 const std::string user_msg_string = user_msg.GetString();
3151 if (user_msg_string.empty()) {
3155 return gtest_msg + "\n" + user_msg_string;
3158 } // namespace internal
3162 // Creates an empty TestResult.
3163 TestResult::TestResult()
3164 : death_test_count_(0),
3169 TestResult::~TestResult() {
3172 // Returns the i-th test part result among all the results. i can
3173 // range from 0 to total_part_count() - 1. If i is not in that range,
3174 // aborts the program.
3175 const TestPartResult& TestResult::GetTestPartResult(int i) const {
3176 if (i < 0 || i >= total_part_count())
3177 internal::posix::Abort();
3178 return test_part_results_.at(i);
3181 // Returns the i-th test property. i can range from 0 to
3182 // test_property_count() - 1. If i is not in that range, aborts the
3184 const TestProperty& TestResult::GetTestProperty(int i) const {
3185 if (i < 0 || i >= test_property_count())
3186 internal::posix::Abort();
3187 return test_properties_.at(i);
3190 // Clears the test part results.
3191 void TestResult::ClearTestPartResults() {
3192 test_part_results_.clear();
3195 // Adds a test part result to the list.
3196 void TestResult::AddTestPartResult(const TestPartResult& test_part_result) {
3197 test_part_results_.push_back(test_part_result);
3200 // Adds a test property to the list. If a property with the same key as the
3201 // supplied property is already represented, the value of this test_property
3202 // replaces the old value for that key.
3203 void TestResult::RecordProperty(const std::string& xml_element,
3204 const TestProperty& test_property) {
3205 if (!ValidateTestProperty(xml_element, test_property)) {
3208 internal::MutexLock lock(&test_properites_mutex_);
3209 const std::vector<TestProperty>::iterator property_with_matching_key =
3210 std::find_if(test_properties_.begin(), test_properties_.end(),
3211 internal::TestPropertyKeyIs(test_property.key()));
3212 if (property_with_matching_key == test_properties_.end()) {
3213 test_properties_.push_back(test_property);
3216 property_with_matching_key->SetValue(test_property.value());
3219 // The list of reserved attributes used in the <testsuites> element of XML
3221 static const char* const kReservedTestSuitesAttributes[] = {
3232 // The list of reserved attributes used in the <testsuite> element of XML
3234 static const char* const kReservedTestSuiteAttributes[] = {
3243 // The list of reserved attributes used in the <testcase> element of XML output.
3244 static const char* const kReservedTestCaseAttributes[] = {
3253 template <int kSize>
3254 std::vector<std::string> ArrayAsVector(const char* const (&array)[kSize]) {
3255 return std::vector<std::string>(array, array + kSize);
3258 static std::vector<std::string> GetReservedAttributesForElement(
3259 const std::string& xml_element) {
3260 if (xml_element == "testsuites") {
3261 return ArrayAsVector(kReservedTestSuitesAttributes);
3262 } else if (xml_element == "testsuite") {
3263 return ArrayAsVector(kReservedTestSuiteAttributes);
3264 } else if (xml_element == "testcase") {
3265 return ArrayAsVector(kReservedTestCaseAttributes);
3267 GTEST_CHECK_(false) << "Unrecognized xml_element provided: " << xml_element;
3269 // This code is unreachable but some compilers may not realizes that.
3270 return std::vector<std::string>();
3273 static std::string FormatWordList(const std::vector<std::string>& words) {
3275 for (size_t i = 0; i < words.size(); ++i) {
3276 if (i > 0 && words.size() > 2) {
3279 if (i == words.size() - 1) {
3280 word_list << "and ";
3282 word_list << "'" << words[i] << "'";
3284 return word_list.GetString();
3287 static bool ValidateTestPropertyName(const std::string& property_name,
3288 const std::vector<std::string>& reserved_names) {
3289 if (std::find(reserved_names.begin(), reserved_names.end(), property_name) !=
3290 reserved_names.end()) {
3291 ADD_FAILURE() << "Reserved key used in RecordProperty(): " << property_name
3292 << " (" << FormatWordList(reserved_names)
3293 << " are reserved by " << GTEST_NAME_ << ")";
3299 // Adds a failure if the key is a reserved attribute of the element named
3300 // xml_element. Returns true if the property is valid.
3301 bool TestResult::ValidateTestProperty(const std::string& xml_element,
3302 const TestProperty& test_property) {
3303 return ValidateTestPropertyName(test_property.key(),
3304 GetReservedAttributesForElement(xml_element));
3307 // Clears the object.
3308 void TestResult::Clear() {
3309 test_part_results_.clear();
3310 test_properties_.clear();
3311 death_test_count_ = 0;
3315 // Returns true iff the test failed.
3316 bool TestResult::Failed() const {
3317 for (int i = 0; i < total_part_count(); ++i) {
3318 if (GetTestPartResult(i).failed())
3324 // Returns true iff the test part fatally failed.
3325 static bool TestPartFatallyFailed(const TestPartResult& result) {
3326 return result.fatally_failed();
3329 // Returns true iff the test fatally failed.
3330 bool TestResult::HasFatalFailure() const {
3331 return CountIf(test_part_results_, TestPartFatallyFailed) > 0;
3334 // Returns true iff the test part non-fatally failed.
3335 static bool TestPartNonfatallyFailed(const TestPartResult& result) {
3336 return result.nonfatally_failed();
3339 // Returns true iff the test has a non-fatal failure.
3340 bool TestResult::HasNonfatalFailure() const {
3341 return CountIf(test_part_results_, TestPartNonfatallyFailed) > 0;
3344 // Gets the number of all test parts. This is the sum of the number
3345 // of successful test parts and the number of failed test parts.
3346 int TestResult::total_part_count() const {
3347 return static_cast<int>(test_part_results_.size());
3350 // Returns the number of the test properties.
3351 int TestResult::test_property_count() const {
3352 return static_cast<int>(test_properties_.size());
3357 // Creates a Test object.
3359 // The c'tor saves the values of all Google Test flags.
3361 : gtest_flag_saver_(new internal::GTestFlagSaver) {
3364 // The d'tor restores the values of all Google Test flags.
3366 delete gtest_flag_saver_;
3369 // Sets up the test fixture.
3371 // A sub-class may override this.
3372 void Test::SetUp() {
3375 // Tears down the test fixture.
3377 // A sub-class may override this.
3378 void Test::TearDown() {
3381 // Allows user supplied key value pairs to be recorded for later output.
3382 void Test::RecordProperty(const std::string& key, const std::string& value) {
3383 UnitTest::GetInstance()->RecordProperty(key, value);
3386 // Allows user supplied key value pairs to be recorded for later output.
3387 void Test::RecordProperty(const std::string& key, int value) {
3388 Message value_message;
3389 value_message << value;
3390 RecordProperty(key, value_message.GetString().c_str());
3393 namespace internal {
3395 void ReportFailureInUnknownLocation(TestPartResult::Type result_type,
3396 const std::string& message) {
3397 // This function is a friend of UnitTest and as such has access to
3398 // AddTestPartResult.
3399 UnitTest::GetInstance()->AddTestPartResult(
3401 NULL, // No info about the source file where the exception occurred.
3402 -1, // We have no info on which line caused the exception.
3404 ""); // No stack trace, either.
3407 } // namespace internal
3409 // Google Test requires all tests in the same test case to use the same test
3410 // fixture class. This function checks if the current test has the
3411 // same fixture class as the first test in the current test case. If
3412 // yes, it returns true; otherwise it generates a Google Test failure and
3414 bool Test::HasSameFixtureClass() {
3415 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
3416 const TestCase* const test_case = impl->current_test_case();
3418 // Info about the first test in the current test case.
3419 const TestInfo* const first_test_info = test_case->test_info_list()[0];
3420 const internal::TypeId first_fixture_id = first_test_info->fixture_class_id_;
3421 const char* const first_test_name = first_test_info->name();
3423 // Info about the current test.
3424 const TestInfo* const this_test_info = impl->current_test_info();
3425 const internal::TypeId this_fixture_id = this_test_info->fixture_class_id_;
3426 const char* const this_test_name = this_test_info->name();
3428 if (this_fixture_id != first_fixture_id) {
3429 // Is the first test defined using TEST?
3430 const bool first_is_TEST = first_fixture_id == internal::GetTestTypeId();
3431 // Is this test defined using TEST?
3432 const bool this_is_TEST = this_fixture_id == internal::GetTestTypeId();
3434 if (first_is_TEST || this_is_TEST) {
3435 // The user mixed TEST and TEST_F in this test case - we'll tell
3436 // him/her how to fix it.
3438 // Gets the name of the TEST and the name of the TEST_F. Note
3439 // that first_is_TEST and this_is_TEST cannot both be true, as
3440 // the fixture IDs are different for the two tests.
3441 const char* const TEST_name =
3442 first_is_TEST ? first_test_name : this_test_name;
3443 const char* const TEST_F_name =
3444 first_is_TEST ? this_test_name : first_test_name;
3447 << "All tests in the same test case must use the same test fixture\n"
3448 << "class, so mixing TEST_F and TEST in the same test case is\n"
3449 << "illegal. In test case " << this_test_info->test_case_name()
3451 << "test " << TEST_F_name << " is defined using TEST_F but\n"
3452 << "test " << TEST_name << " is defined using TEST. You probably\n"
3453 << "want to change the TEST to TEST_F or move it to another test\n"
3456 // The user defined two fixture classes with the same name in
3457 // two namespaces - we'll tell him/her how to fix it.
3459 << "All tests in the same test case must use the same test fixture\n"
3460 << "class. However, in test case "
3461 << this_test_info->test_case_name() << ",\n"
3462 << "you defined test " << first_test_name
3463 << " and test " << this_test_name << "\n"
3464 << "using two different test fixture classes. This can happen if\n"
3465 << "the two classes are from different namespaces or translation\n"
3466 << "units and have the same name. You should probably rename one\n"
3467 << "of the classes to put the tests into different test cases.";
3477 // Adds an "exception thrown" fatal failure to the current test. This
3478 // function returns its result via an output parameter pointer because VC++
3479 // prohibits creation of objects with destructors on stack in functions
3480 // using __try (see error C2712).
3481 static std::string* FormatSehExceptionMessage(DWORD exception_code,
3482 const char* location) {
3484 message << "SEH exception with code 0x" << std::setbase(16) <<
3485 exception_code << std::setbase(10) << " thrown in " << location << ".";
3487 return new std::string(message.GetString());
3490 #endif // GTEST_HAS_SEH
3492 namespace internal {
3494 #if GTEST_HAS_EXCEPTIONS
3496 // Adds an "exception thrown" fatal failure to the current test.
3497 static std::string FormatCxxExceptionMessage(const char* description,
3498 const char* location) {
3500 if (description != NULL) {
3501 message << "C++ exception with description \"" << description << "\"";
3503 message << "Unknown C++ exception";
3505 message << " thrown in " << location << ".";
3507 return message.GetString();
3510 static std::string PrintTestPartResultToString(
3511 const TestPartResult& test_part_result);
3513 GoogleTestFailureException::GoogleTestFailureException(
3514 const TestPartResult& failure)
3515 : ::std::runtime_error(PrintTestPartResultToString(failure).c_str()) {}
3517 #endif // GTEST_HAS_EXCEPTIONS
3519 // We put these helper functions in the internal namespace as IBM's xlC
3520 // compiler rejects the code if they were declared static.
3522 // Runs the given method and handles SEH exceptions it throws, when
3523 // SEH is supported; returns the 0-value for type Result in case of an
3524 // SEH exception. (Microsoft compilers cannot handle SEH and C++
3525 // exceptions in the same function. Therefore, we provide a separate
3526 // wrapper function for handling SEH exceptions.)
3527 template <class T, typename Result>
3528 Result HandleSehExceptionsInMethodIfSupported(
3529 T* object, Result (T::*method)(), const char* location) {
3532 return (object->*method)();
3533 } __except (internal::UnitTestOptions::GTestShouldProcessSEH( // NOLINT
3534 GetExceptionCode())) {
3535 // We create the exception message on the heap because VC++ prohibits
3536 // creation of objects with destructors on stack in functions using __try
3537 // (see error C2712).
3538 std::string* exception_message = FormatSehExceptionMessage(
3539 GetExceptionCode(), location);
3540 internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure,
3541 *exception_message);
3542 delete exception_message;
3543 return static_cast<Result>(0);
3547 return (object->*method)();
3548 #endif // GTEST_HAS_SEH
3551 // Runs the given method and catches and reports C++ and/or SEH-style
3552 // exceptions, if they are supported; returns the 0-value for type
3553 // Result in case of an SEH exception.
3554 template <class T, typename Result>
3555 Result HandleExceptionsInMethodIfSupported(
3556 T* object, Result (T::*method)(), const char* location) {
3557 // NOTE: The user code can affect the way in which Google Test handles
3558 // exceptions by setting GTEST_FLAG(catch_exceptions), but only before
3559 // RUN_ALL_TESTS() starts. It is technically possible to check the flag
3560 // after the exception is caught and either report or re-throw the
3561 // exception based on the flag's value:
3564 // // Perform the test method.
3566 // if (GTEST_FLAG(catch_exceptions))
3567 // // Report the exception as failure.
3569 // throw; // Re-throws the original exception.
3572 // However, the purpose of this flag is to allow the program to drop into
3573 // the debugger when the exception is thrown. On most platforms, once the
3574 // control enters the catch block, the exception origin information is
3575 // lost and the debugger will stop the program at the point of the
3576 // re-throw in this function -- instead of at the point of the original
3577 // throw statement in the code under test. For this reason, we perform
3578 // the check early, sacrificing the ability to affect Google Test's
3579 // exception handling in the method where the exception is thrown.
3580 if (internal::GetUnitTestImpl()->catch_exceptions()) {
3581 #if GTEST_HAS_EXCEPTIONS
3583 return HandleSehExceptionsInMethodIfSupported(object, method, location);
3584 } catch (const internal::GoogleTestFailureException&) { // NOLINT
3585 // This exception type can only be thrown by a failed Google
3586 // Test assertion with the intention of letting another testing
3587 // framework catch it. Therefore we just re-throw it.
3589 } catch (const std::exception& e) { // NOLINT
3590 internal::ReportFailureInUnknownLocation(
3591 TestPartResult::kFatalFailure,
3592 FormatCxxExceptionMessage(e.what(), location));
3593 } catch (...) { // NOLINT
3594 internal::ReportFailureInUnknownLocation(
3595 TestPartResult::kFatalFailure,
3596 FormatCxxExceptionMessage(NULL, location));
3598 return static_cast<Result>(0);
3600 return HandleSehExceptionsInMethodIfSupported(object, method, location);
3601 #endif // GTEST_HAS_EXCEPTIONS
3603 return (object->*method)();
3607 } // namespace internal
3609 // Runs the test and updates the test result.
3611 if (!HasSameFixtureClass()) return;
3613 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
3614 impl->os_stack_trace_getter()->UponLeavingGTest();
3615 internal::HandleExceptionsInMethodIfSupported(this, &Test::SetUp, "SetUp()");
3616 // We will run the test only if SetUp() was successful.
3617 if (!HasFatalFailure()) {
3618 impl->os_stack_trace_getter()->UponLeavingGTest();
3619 internal::HandleExceptionsInMethodIfSupported(
3620 this, &Test::TestBody, "the test body");
3623 // However, we want to clean up as much as possible. Hence we will
3624 // always call TearDown(), even if SetUp() or the test body has
3626 impl->os_stack_trace_getter()->UponLeavingGTest();
3627 internal::HandleExceptionsInMethodIfSupported(
3628 this, &Test::TearDown, "TearDown()");
3631 // Returns true iff the current test has a fatal failure.
3632 bool Test::HasFatalFailure() {
3633 return internal::GetUnitTestImpl()->current_test_result()->HasFatalFailure();
3636 // Returns true iff the current test has a non-fatal failure.
3637 bool Test::HasNonfatalFailure() {
3638 return internal::GetUnitTestImpl()->current_test_result()->
3639 HasNonfatalFailure();
3644 // Constructs a TestInfo object. It assumes ownership of the test factory
3646 TestInfo::TestInfo(const std::string& a_test_case_name,
3647 const std::string& a_name,
3648 const char* a_type_param,
3649 const char* a_value_param,
3650 internal::TypeId fixture_class_id,
3651 internal::TestFactoryBase* factory)
3652 : test_case_name_(a_test_case_name),
3654 type_param_(a_type_param ? new std::string(a_type_param) : NULL),
3655 value_param_(a_value_param ? new std::string(a_value_param) : NULL),
3656 fixture_class_id_(fixture_class_id),
3658 is_disabled_(false),
3659 matches_filter_(false),
3663 // Destructs a TestInfo object.
3664 TestInfo::~TestInfo() { delete factory_; }
3666 namespace internal {
3668 // Creates a new TestInfo object and registers it with Google Test;
3669 // returns the created object.
3673 // test_case_name: name of the test case
3674 // name: name of the test
3675 // type_param: the name of the test's type parameter, or NULL if
3676 // this is not a typed or a type-parameterized test.
3677 // value_param: text representation of the test's value parameter,
3678 // or NULL if this is not a value-parameterized test.
3679 // fixture_class_id: ID of the test fixture class
3680 // set_up_tc: pointer to the function that sets up the test case
3681 // tear_down_tc: pointer to the function that tears down the test case
3682 // factory: pointer to the factory that creates a test object.
3683 // The newly created TestInfo instance will assume
3684 // ownership of the factory object.
3685 TestInfo* MakeAndRegisterTestInfo(
3686 const char* test_case_name,
3688 const char* type_param,
3689 const char* value_param,
3690 TypeId fixture_class_id,
3691 SetUpTestCaseFunc set_up_tc,
3692 TearDownTestCaseFunc tear_down_tc,
3693 TestFactoryBase* factory) {
3694 TestInfo* const test_info =
3695 new TestInfo(test_case_name, name, type_param, value_param,
3696 fixture_class_id, factory);
3697 GetUnitTestImpl()->AddTestInfo(set_up_tc, tear_down_tc, test_info);
3701 #if GTEST_HAS_PARAM_TEST
3702 void ReportInvalidTestCaseType(const char* test_case_name,
3703 const char* file, int line) {
3706 << "Attempted redefinition of test case " << test_case_name << ".\n"
3707 << "All tests in the same test case must use the same test fixture\n"
3708 << "class. However, in test case " << test_case_name << ", you tried\n"
3709 << "to define a test using a fixture class different from the one\n"
3710 << "used earlier. This can happen if the two fixture classes are\n"
3711 << "from different namespaces and have the same name. You should\n"
3712 << "probably rename one of the classes to put the tests into different\n"
3715 fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(),
3716 errors.GetString().c_str());
3718 #endif // GTEST_HAS_PARAM_TEST
3720 } // namespace internal
3724 // A predicate that checks the test name of a TestInfo against a known
3727 // This is used for implementation of the TestCase class only. We put
3728 // it in the anonymous namespace to prevent polluting the outer
3731 // TestNameIs is copyable.
3736 // TestNameIs has NO default constructor.
3737 explicit TestNameIs(const char* name)
3740 // Returns true iff the test name of test_info matches name_.
3741 bool operator()(const TestInfo * test_info) const {
3742 return test_info && test_info->name() == name_;
3751 namespace internal {
3753 // This method expands all parameterized tests registered with macros TEST_P
3754 // and INSTANTIATE_TEST_CASE_P into regular tests and registers those.
3755 // This will be done just once during the program runtime.
3756 void UnitTestImpl::RegisterParameterizedTests() {
3757 #if GTEST_HAS_PARAM_TEST
3758 if (!parameterized_tests_registered_) {
3759 parameterized_test_registry_.RegisterTests();
3760 parameterized_tests_registered_ = true;
3765 } // namespace internal
3767 // Creates the test object, runs it, records its result, and then
3769 void TestInfo::Run() {
3770 if (!should_run_) return;
3772 // Tells UnitTest where to store test result.
3773 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
3774 impl->set_current_test_info(this);
3776 TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
3778 // Notifies the unit test event listeners that a test is about to start.
3779 repeater->OnTestStart(*this);
3781 const TimeInMillis start = internal::GetTimeInMillis();
3783 impl->os_stack_trace_getter()->UponLeavingGTest();
3785 // Creates the test object.
3786 Test* const test = internal::HandleExceptionsInMethodIfSupported(
3787 factory_, &internal::TestFactoryBase::CreateTest,
3788 "the test fixture's constructor");
3790 // Runs the test only if the test object was created and its
3791 // constructor didn't generate a fatal failure.
3792 if ((test != NULL) && !Test::HasFatalFailure()) {
3793 // This doesn't throw as all user code that can throw are wrapped into
3794 // exception handling code.
3798 // Deletes the test object.
3799 impl->os_stack_trace_getter()->UponLeavingGTest();
3800 internal::HandleExceptionsInMethodIfSupported(
3801 test, &Test::DeleteSelf_, "the test fixture's destructor");
3803 result_.set_elapsed_time(internal::GetTimeInMillis() - start);
3805 // Notifies the unit test event listener that a test has just finished.
3806 repeater->OnTestEnd(*this);
3808 // Tells UnitTest to stop associating assertion results to this
3810 impl->set_current_test_info(NULL);
3815 // Gets the number of successful tests in this test case.
3816 int TestCase::successful_test_count() const {
3817 return CountIf(test_info_list_, TestPassed);
3820 // Gets the number of failed tests in this test case.
3821 int TestCase::failed_test_count() const {
3822 return CountIf(test_info_list_, TestFailed);
3825 int TestCase::disabled_test_count() const {
3826 return CountIf(test_info_list_, TestDisabled);
3829 // Get the number of tests in this test case that should run.
3830 int TestCase::test_to_run_count() const {
3831 return CountIf(test_info_list_, ShouldRunTest);
3834 // Gets the number of all tests.
3835 int TestCase::total_test_count() const {
3836 return static_cast<int>(test_info_list_.size());
3839 // Creates a TestCase with the given name.
3843 // name: name of the test case
3844 // a_type_param: the name of the test case's type parameter, or NULL if
3845 // this is not a typed or a type-parameterized test case.
3846 // set_up_tc: pointer to the function that sets up the test case
3847 // tear_down_tc: pointer to the function that tears down the test case
3848 TestCase::TestCase(const char* a_name, const char* a_type_param,
3849 Test::SetUpTestCaseFunc set_up_tc,
3850 Test::TearDownTestCaseFunc tear_down_tc)
3852 type_param_(a_type_param ? new std::string(a_type_param) : NULL),
3853 set_up_tc_(set_up_tc),
3854 tear_down_tc_(tear_down_tc),
3859 // Destructor of TestCase.
3860 TestCase::~TestCase() {
3861 // Deletes every Test in the collection.
3862 ForEach(test_info_list_, internal::Delete<TestInfo>);
3865 // Returns the i-th test among all the tests. i can range from 0 to
3866 // total_test_count() - 1. If i is not in that range, returns NULL.
3867 const TestInfo* TestCase::GetTestInfo(int i) const {
3868 const int index = GetElementOr(test_indices_, i, -1);
3869 return index < 0 ? NULL : test_info_list_[index];
3872 // Returns the i-th test among all the tests. i can range from 0 to
3873 // total_test_count() - 1. If i is not in that range, returns NULL.
3874 TestInfo* TestCase::GetMutableTestInfo(int i) {
3875 const int index = GetElementOr(test_indices_, i, -1);
3876 return index < 0 ? NULL : test_info_list_[index];
3879 // Adds a test to this test case. Will delete the test upon
3880 // destruction of the TestCase object.
3881 void TestCase::AddTestInfo(TestInfo * test_info) {
3882 test_info_list_.push_back(test_info);
3883 test_indices_.push_back(static_cast<int>(test_indices_.size()));
3886 // Runs every test in this TestCase.
3887 void TestCase::Run() {
3888 if (!should_run_) return;
3890 internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
3891 impl->set_current_test_case(this);
3893 TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
3895 repeater->OnTestCaseStart(*this);
3896 impl->os_stack_trace_getter()->UponLeavingGTest();
3897 internal::HandleExceptionsInMethodIfSupported(
3898 this, &TestCase::RunSetUpTestCase, "SetUpTestCase()");
3900 const internal::TimeInMillis start = internal::GetTimeInMillis();
3901 for (int i = 0; i < total_test_count(); i++) {
3902 GetMutableTestInfo(i)->Run();
3904 elapsed_time_ = internal::GetTimeInMillis() - start;
3906 impl->os_stack_trace_getter()->UponLeavingGTest();
3907 internal::HandleExceptionsInMethodIfSupported(
3908 this, &TestCase::RunTearDownTestCase, "TearDownTestCase()");
3910 repeater->OnTestCaseEnd(*this);
3911 impl->set_current_test_case(NULL);
3914 // Clears the results of all tests in this test case.
3915 void TestCase::ClearResult() {
3916 ad_hoc_test_result_.Clear();
3917 ForEach(test_info_list_, TestInfo::ClearTestResult);
3920 // Shuffles the tests in this test case.
3921 void TestCase::ShuffleTests(internal::Random* random) {
3922 Shuffle(random, &test_indices_);
3925 // Restores the test order to before the first shuffle.
3926 void TestCase::UnshuffleTests() {
3927 for (size_t i = 0; i < test_indices_.size(); i++) {
3928 test_indices_[i] = static_cast<int>(i);
3932 // Formats a countable noun. Depending on its quantity, either the
3933 // singular form or the plural form is used. e.g.
3935 // FormatCountableNoun(1, "formula", "formuli") returns "1 formula".
3936 // FormatCountableNoun(5, "book", "books") returns "5 books".
3937 static std::string FormatCountableNoun(int count,
3938 const char * singular_form,
3939 const char * plural_form) {
3940 return internal::StreamableToString(count) + " " +
3941 (count == 1 ? singular_form : plural_form);
3944 // Formats the count of tests.
3945 static std::string FormatTestCount(int test_count) {
3946 return FormatCountableNoun(test_count, "test", "tests");
3949 // Formats the count of test cases.
3950 static std::string FormatTestCaseCount(int test_case_count) {
3951 return FormatCountableNoun(test_case_count, "test case", "test cases");
3954 // Converts a TestPartResult::Type enum to human-friendly string
3955 // representation. Both kNonFatalFailure and kFatalFailure are translated
3956 // to "Failure", as the user usually doesn't care about the difference
3957 // between the two when viewing the test result.
3958 static const char * TestPartResultTypeToString(TestPartResult::Type type) {
3960 case TestPartResult::kSuccess:
3963 case TestPartResult::kNonFatalFailure:
3964 case TestPartResult::kFatalFailure:
3971 return "Unknown result type";
3975 namespace internal {
3977 // Prints a TestPartResult to an std::string.
3978 static std::string PrintTestPartResultToString(
3979 const TestPartResult& test_part_result) {
3981 << internal::FormatFileLocation(test_part_result.file_name(),
3982 test_part_result.line_number())
3983 << " " << TestPartResultTypeToString(test_part_result.type())
3984 << test_part_result.message()).GetString();
3987 // Prints a TestPartResult.
3988 static void PrintTestPartResult(const TestPartResult& test_part_result) {
3989 const std::string& result =
3990 PrintTestPartResultToString(test_part_result);
3991 printf("%s\n", result.c_str());
3993 // If the test program runs in Visual Studio or a debugger, the
3994 // following statements add the test part result message to the Output
3995 // window such that the user can double-click on it to jump to the
3996 // corresponding source code location; otherwise they do nothing.
3997 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
3998 // We don't call OutputDebugString*() on Windows Mobile, as printing
3999 // to stdout is done by OutputDebugString() there already - we don't
4000 // want the same message printed twice.
4001 ::OutputDebugStringA(result.c_str());
4002 ::OutputDebugStringA("\n");
4006 // class PrettyUnitTestResultPrinter
4015 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
4017 // Returns the character attribute for the given color.
4018 WORD GetColorAttribute(GTestColor color) {
4020 case COLOR_RED: return FOREGROUND_RED;
4021 case COLOR_GREEN: return FOREGROUND_GREEN;
4022 case COLOR_YELLOW: return FOREGROUND_RED | FOREGROUND_GREEN;
4029 // Returns the ANSI color code for the given color. COLOR_DEFAULT is
4030 // an invalid input.
4031 static const char* GetAnsiColorCode(GTestColor color) {
4033 case COLOR_RED: return "1";
4034 case COLOR_GREEN: return "2";
4035 case COLOR_YELLOW: return "3";
4036 default: return NULL;
4040 #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
4042 // Returns true iff Google Test should use colors in the output.
4043 bool ShouldUseColor(bool stdout_is_tty) {
4044 const char* const gtest_color = GTEST_FLAG(color).c_str();
4046 if (String::CaseInsensitiveCStringEquals(gtest_color, "auto")) {
4047 #if GTEST_OS_WINDOWS
4048 // On Windows the TERM variable is usually not set, but the
4049 // console there does support colors.
4050 return stdout_is_tty;
4052 // On non-Windows platforms, we rely on the TERM variable.
4053 const char* const term = posix::GetEnv("TERM");
4054 const bool term_supports_color =
4055 String::CStringEquals(term, "xterm") ||
4056 String::CStringEquals(term, "xterm-color") ||
4057 String::CStringEquals(term, "xterm-256color") ||
4058 String::CStringEquals(term, "screen") ||
4059 String::CStringEquals(term, "screen-256color") ||
4060 String::CStringEquals(term, "linux") ||
4061 String::CStringEquals(term, "cygwin");
4062 return stdout_is_tty && term_supports_color;
4063 #endif // GTEST_OS_WINDOWS
4066 return String::CaseInsensitiveCStringEquals(gtest_color, "yes") ||
4067 String::CaseInsensitiveCStringEquals(gtest_color, "true") ||
4068 String::CaseInsensitiveCStringEquals(gtest_color, "t") ||
4069 String::CStringEquals(gtest_color, "1");
4070 // We take "yes", "true", "t", and "1" as meaning "yes". If the
4071 // value is neither one of these nor "auto", we treat it as "no" to
4075 // Helpers for printing colored strings to stdout. Note that on Windows, we
4076 // cannot simply emit special characters and have the terminal change colors.
4077 // This routine must actually emit the characters rather than return a string
4078 // that would be colored when printed, as can be done on Linux.
4079 static void ColoredPrintf(GTestColor color, const char* fmt, ...) {
4081 va_start(args, fmt);
4083 #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS || GTEST_OS_IOS
4084 const bool use_color = false;
4086 static const bool in_color_mode =
4087 ShouldUseColor(posix::IsATTY(posix::FileNo(stdout)) != 0);
4088 const bool use_color = in_color_mode && (color != COLOR_DEFAULT);
4089 #endif // GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS
4090 // The '!= 0' comparison is necessary to satisfy MSVC 7.1.
4098 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
4099 const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
4101 // Gets the current text color.
4102 CONSOLE_SCREEN_BUFFER_INFO buffer_info;
4103 GetConsoleScreenBufferInfo(stdout_handle, &buffer_info);
4104 const WORD old_color_attrs = buffer_info.wAttributes;
4106 // We need to flush the stream buffers into the console before each
4107 // SetConsoleTextAttribute call lest it affect the text that is already
4108 // printed but has not yet reached the console.
4110 SetConsoleTextAttribute(stdout_handle,
4111 GetColorAttribute(color) | FOREGROUND_INTENSITY);
4115 // Restores the text color.
4116 SetConsoleTextAttribute(stdout_handle, old_color_attrs);
4118 printf("\033[0;3%sm", GetAnsiColorCode(color));
4120 printf("\033[m"); // Resets the terminal to default.
4121 #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
4125 // Text printed in Google Test's text output and --gunit_list_tests
4126 // output to label the type parameter and value parameter for a test.
4127 static const char kTypeParamLabel[] = "TypeParam";
4128 static const char kValueParamLabel[] = "GetParam()";
4130 static void PrintFullTestCommentIfPresent(const TestInfo& test_info) {
4131 const char* const type_param = test_info.type_param();
4132 const char* const value_param = test_info.value_param();
4134 if (type_param != NULL || value_param != NULL) {
4136 if (type_param != NULL) {
4137 printf("%s = %s", kTypeParamLabel, type_param);
4138 if (value_param != NULL)
4141 if (value_param != NULL) {
4142 printf("%s = %s", kValueParamLabel, value_param);
4147 // This class implements the TestEventListener interface.
4149 // Class PrettyUnitTestResultPrinter is copyable.
4150 class PrettyUnitTestResultPrinter : public TestEventListener {
4152 PrettyUnitTestResultPrinter() {}
4153 static void PrintTestName(const char * test_case, const char * test) {
4154 printf("%s.%s", test_case, test);
4157 // The following methods override what's in the TestEventListener class.
4158 virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {}
4159 virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration);
4160 virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test);
4161 virtual void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) {}
4162 virtual void OnTestCaseStart(const TestCase& test_case);
4163 virtual void OnTestStart(const TestInfo& test_info);
4164 virtual void OnTestPartResult(const TestPartResult& result);
4165 virtual void OnTestEnd(const TestInfo& test_info);
4166 virtual void OnTestCaseEnd(const TestCase& test_case);
4167 virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test);
4168 virtual void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) {}
4169 virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
4170 virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) {}
4173 static void PrintFailedTests(const UnitTest& unit_test);
4176 // Fired before each iteration of tests starts.
4177 void PrettyUnitTestResultPrinter::OnTestIterationStart(
4178 const UnitTest& unit_test, int iteration) {
4179 if (GTEST_FLAG(repeat) != 1)
4180 printf("\nRepeating all tests (iteration %d) . . .\n\n", iteration + 1);
4182 const char* const filter = GTEST_FLAG(filter).c_str();
4184 // Prints the filter if it's not *. This reminds the user that some
4185 // tests may be skipped.
4186 if (!String::CStringEquals(filter, kUniversalFilter)) {
4187 ColoredPrintf(COLOR_YELLOW,
4188 "Note: %s filter = %s\n", GTEST_NAME_, filter);
4191 if (internal::ShouldShard(kTestTotalShards, kTestShardIndex, false)) {
4192 const Int32 shard_index = Int32FromEnvOrDie(kTestShardIndex, -1);
4193 ColoredPrintf(COLOR_YELLOW,
4194 "Note: This is test shard %d of %s.\n",
4195 static_cast<int>(shard_index) + 1,
4196 internal::posix::GetEnv(kTestTotalShards));
4199 if (GTEST_FLAG(shuffle)) {
4200 ColoredPrintf(COLOR_YELLOW,
4201 "Note: Randomizing tests' orders with a seed of %d .\n",
4202 unit_test.random_seed());
4205 ColoredPrintf(COLOR_GREEN, "[==========] ");
4206 printf("Running %s from %s.\n",
4207 FormatTestCount(unit_test.test_to_run_count()).c_str(),
4208 FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str());
4212 void PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart(
4213 const UnitTest& /*unit_test*/) {
4214 ColoredPrintf(COLOR_GREEN, "[----------] ");
4215 printf("Global test environment set-up.\n");
4219 void PrettyUnitTestResultPrinter::OnTestCaseStart(const TestCase& test_case) {
4220 const std::string counts =
4221 FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
4222 ColoredPrintf(COLOR_GREEN, "[----------] ");
4223 printf("%s from %s", counts.c_str(), test_case.name());
4224 if (test_case.type_param() == NULL) {
4227 printf(", where %s = %s\n", kTypeParamLabel, test_case.type_param());
4232 void PrettyUnitTestResultPrinter::OnTestStart(const TestInfo& test_info) {
4233 ColoredPrintf(COLOR_GREEN, "[ RUN ] ");
4234 PrintTestName(test_info.test_case_name(), test_info.name());
4239 // Called after an assertion failure.
4240 void PrettyUnitTestResultPrinter::OnTestPartResult(
4241 const TestPartResult& result) {
4242 // If the test part succeeded, we don't need to do anything.
4243 if (result.type() == TestPartResult::kSuccess)
4246 // Print failure message from the assertion (e.g. expected this and got that).
4247 PrintTestPartResult(result);
4251 void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) {
4252 if (test_info.result()->Passed()) {
4253 ColoredPrintf(COLOR_GREEN, "[ OK ] ");
4255 ColoredPrintf(COLOR_RED, "[ FAILED ] ");
4257 PrintTestName(test_info.test_case_name(), test_info.name());
4258 if (test_info.result()->Failed())
4259 PrintFullTestCommentIfPresent(test_info);
4261 if (GTEST_FLAG(print_time)) {
4262 printf(" (%s ms)\n", internal::StreamableToString(
4263 test_info.result()->elapsed_time()).c_str());
4270 void PrettyUnitTestResultPrinter::OnTestCaseEnd(const TestCase& test_case) {
4271 if (!GTEST_FLAG(print_time)) return;
4273 const std::string counts =
4274 FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
4275 ColoredPrintf(COLOR_GREEN, "[----------] ");
4276 printf("%s from %s (%s ms total)\n\n",
4277 counts.c_str(), test_case.name(),
4278 internal::StreamableToString(test_case.elapsed_time()).c_str());
4282 void PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart(
4283 const UnitTest& /*unit_test*/) {
4284 ColoredPrintf(COLOR_GREEN, "[----------] ");
4285 printf("Global test environment tear-down\n");
4289 // Internal helper for printing the list of failed tests.
4290 void PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest& unit_test) {
4291 const int failed_test_count = unit_test.failed_test_count();
4292 if (failed_test_count == 0) {
4296 for (int i = 0; i < unit_test.total_test_case_count(); ++i) {
4297 const TestCase& test_case = *unit_test.GetTestCase(i);
4298 if (!test_case.should_run() || (test_case.failed_test_count() == 0)) {
4301 for (int j = 0; j < test_case.total_test_count(); ++j) {
4302 const TestInfo& test_info = *test_case.GetTestInfo(j);
4303 if (!test_info.should_run() || test_info.result()->Passed()) {
4306 ColoredPrintf(COLOR_RED, "[ FAILED ] ");
4307 printf("%s.%s", test_case.name(), test_info.name());
4308 PrintFullTestCommentIfPresent(test_info);
4314 void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
4315 int /*iteration*/) {
4316 ColoredPrintf(COLOR_GREEN, "[==========] ");
4317 printf("%s from %s ran.",
4318 FormatTestCount(unit_test.test_to_run_count()).c_str(),
4319 FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str());
4320 if (GTEST_FLAG(print_time)) {
4321 printf(" (%s ms total)",
4322 internal::StreamableToString(unit_test.elapsed_time()).c_str());
4325 ColoredPrintf(COLOR_GREEN, "[ PASSED ] ");
4326 printf("%s.\n", FormatTestCount(unit_test.successful_test_count()).c_str());
4328 int num_failures = unit_test.failed_test_count();
4329 if (!unit_test.Passed()) {
4330 const int failed_test_count = unit_test.failed_test_count();
4331 ColoredPrintf(COLOR_RED, "[ FAILED ] ");
4332 printf("%s, listed below:\n", FormatTestCount(failed_test_count).c_str());
4333 PrintFailedTests(unit_test);
4334 printf("\n%2d FAILED %s\n", num_failures,
4335 num_failures == 1 ? "TEST" : "TESTS");
4338 int num_disabled = unit_test.disabled_test_count();
4339 if (num_disabled && !GTEST_FLAG(also_run_disabled_tests)) {
4340 if (!num_failures) {
4341 printf("\n"); // Add a spacer if no FAILURE banner is displayed.
4343 ColoredPrintf(COLOR_YELLOW,
4344 " YOU HAVE %d DISABLED %s\n\n",
4346 num_disabled == 1 ? "TEST" : "TESTS");
4348 // Ensure that Google Test output is printed before, e.g., heapchecker output.
4352 // End PrettyUnitTestResultPrinter
4354 // class TestEventRepeater
4356 // This class forwards events to other event listeners.
4357 class TestEventRepeater : public TestEventListener {
4359 TestEventRepeater() : forwarding_enabled_(true) {}
4360 virtual ~TestEventRepeater();
4361 void Append(TestEventListener *listener);
4362 TestEventListener* Release(TestEventListener* listener);
4364 // Controls whether events will be forwarded to listeners_. Set to false
4365 // in death test child processes.
4366 bool forwarding_enabled() const { return forwarding_enabled_; }
4367 void set_forwarding_enabled(bool enable) { forwarding_enabled_ = enable; }
4369 virtual void OnTestProgramStart(const UnitTest& unit_test);
4370 virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration);
4371 virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test);
4372 virtual void OnEnvironmentsSetUpEnd(const UnitTest& unit_test);
4373 virtual void OnTestCaseStart(const TestCase& test_case);
4374 virtual void OnTestStart(const TestInfo& test_info);
4375 virtual void OnTestPartResult(const TestPartResult& result);
4376 virtual void OnTestEnd(const TestInfo& test_info);
4377 virtual void OnTestCaseEnd(const TestCase& test_case);
4378 virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test);
4379 virtual void OnEnvironmentsTearDownEnd(const UnitTest& unit_test);
4380 virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
4381 virtual void OnTestProgramEnd(const UnitTest& unit_test);
4384 // Controls whether events will be forwarded to listeners_. Set to false
4385 // in death test child processes.
4386 bool forwarding_enabled_;
4387 // The list of listeners that receive events.
4388 std::vector<TestEventListener*> listeners_;
4390 GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventRepeater);
4393 TestEventRepeater::~TestEventRepeater() {
4394 ForEach(listeners_, Delete<TestEventListener>);
4397 void TestEventRepeater::Append(TestEventListener *listener) {
4398 listeners_.push_back(listener);
4401 // TODO(vladl@google.com): Factor the search functionality into Vector::Find.
4402 TestEventListener* TestEventRepeater::Release(TestEventListener *listener) {
4403 for (size_t i = 0; i < listeners_.size(); ++i) {
4404 if (listeners_[i] == listener) {
4405 listeners_.erase(listeners_.begin() + i);
4413 // Since most methods are very similar, use macros to reduce boilerplate.
4414 // This defines a member that forwards the call to all listeners.
4415 #define GTEST_REPEATER_METHOD_(Name, Type) \
4416 void TestEventRepeater::Name(const Type& parameter) { \
4417 if (forwarding_enabled_) { \
4418 for (size_t i = 0; i < listeners_.size(); i++) { \
4419 listeners_[i]->Name(parameter); \
4423 // This defines a member that forwards the call to all listeners in reverse
4425 #define GTEST_REVERSE_REPEATER_METHOD_(Name, Type) \
4426 void TestEventRepeater::Name(const Type& parameter) { \
4427 if (forwarding_enabled_) { \
4428 for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) { \
4429 listeners_[i]->Name(parameter); \
4434 GTEST_REPEATER_METHOD_(OnTestProgramStart, UnitTest)
4435 GTEST_REPEATER_METHOD_(OnEnvironmentsSetUpStart, UnitTest)
4436 GTEST_REPEATER_METHOD_(OnTestCaseStart, TestCase)
4437 GTEST_REPEATER_METHOD_(OnTestStart, TestInfo)
4438 GTEST_REPEATER_METHOD_(OnTestPartResult, TestPartResult)
4439 GTEST_REPEATER_METHOD_(OnEnvironmentsTearDownStart, UnitTest)
4440 GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsSetUpEnd, UnitTest)
4441 GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsTearDownEnd, UnitTest)
4442 GTEST_REVERSE_REPEATER_METHOD_(OnTestEnd, TestInfo)
4443 GTEST_REVERSE_REPEATER_METHOD_(OnTestCaseEnd, TestCase)
4444 GTEST_REVERSE_REPEATER_METHOD_(OnTestProgramEnd, UnitTest)
4446 #undef GTEST_REPEATER_METHOD_
4447 #undef GTEST_REVERSE_REPEATER_METHOD_
4449 void TestEventRepeater::OnTestIterationStart(const UnitTest& unit_test,
4451 if (forwarding_enabled_) {
4452 for (size_t i = 0; i < listeners_.size(); i++) {
4453 listeners_[i]->OnTestIterationStart(unit_test, iteration);
4458 void TestEventRepeater::OnTestIterationEnd(const UnitTest& unit_test,
4460 if (forwarding_enabled_) {
4461 for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) {
4462 listeners_[i]->OnTestIterationEnd(unit_test, iteration);
4467 // End TestEventRepeater
4469 // This class generates an XML output file.
4470 class XmlUnitTestResultPrinter : public EmptyTestEventListener {
4472 explicit XmlUnitTestResultPrinter(const char* output_file);
4474 virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
4477 // Is c a whitespace character that is normalized to a space character
4478 // when it appears in an XML attribute value?
4479 static bool IsNormalizableWhitespace(char c) {
4480 return c == 0x9 || c == 0xA || c == 0xD;
4483 // May c appear in a well-formed XML document?
4484 static bool IsValidXmlCharacter(char c) {
4485 return IsNormalizableWhitespace(c) || c >= 0x20;
4488 // Returns an XML-escaped copy of the input string str. If
4489 // is_attribute is true, the text is meant to appear as an attribute
4490 // value, and normalizable whitespace is preserved by replacing it
4491 // with character references.
4492 static std::string EscapeXml(const std::string& str, bool is_attribute);
4494 // Returns the given string with all characters invalid in XML removed.
4495 static std::string RemoveInvalidXmlCharacters(const std::string& str);
4497 // Convenience wrapper around EscapeXml when str is an attribute value.
4498 static std::string EscapeXmlAttribute(const std::string& str) {
4499 return EscapeXml(str, true);
4502 // Convenience wrapper around EscapeXml when str is not an attribute value.
4503 static std::string EscapeXmlText(const char* str) {
4504 return EscapeXml(str, false);
4507 // Verifies that the given attribute belongs to the given element and
4508 // streams the attribute as XML.
4509 static void OutputXmlAttribute(std::ostream* stream,
4510 const std::string& element_name,
4511 const std::string& name,
4512 const std::string& value);
4514 // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
4515 static void OutputXmlCDataSection(::std::ostream* stream, const char* data);
4517 // Streams an XML representation of a TestInfo object.
4518 static void OutputXmlTestInfo(::std::ostream* stream,
4519 const char* test_case_name,
4520 const TestInfo& test_info);
4522 // Prints an XML representation of a TestCase object
4523 static void PrintXmlTestCase(::std::ostream* stream,
4524 const TestCase& test_case);
4526 // Prints an XML summary of unit_test to output stream out.
4527 static void PrintXmlUnitTest(::std::ostream* stream,
4528 const UnitTest& unit_test);
4530 // Produces a string representing the test properties in a result as space
4531 // delimited XML attributes based on the property key="value" pairs.
4532 // When the std::string is not empty, it includes a space at the beginning,
4533 // to delimit this attribute from prior attributes.
4534 static std::string TestPropertiesAsXmlAttributes(const TestResult& result);
4537 const std::string output_file_;
4539 GTEST_DISALLOW_COPY_AND_ASSIGN_(XmlUnitTestResultPrinter);
4542 // Creates a new XmlUnitTestResultPrinter.
4543 XmlUnitTestResultPrinter::XmlUnitTestResultPrinter(const char* output_file)
4544 : output_file_(output_file) {
4545 if (output_file_.c_str() == NULL || output_file_.empty()) {
4546 fprintf(stderr, "XML output file may not be null\n");
4552 // Called after the unit test ends.
4553 void XmlUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
4554 int /*iteration*/) {
4555 FILE* xmlout = NULL;
4556 FilePath output_file(output_file_);
4557 FilePath output_dir(output_file.RemoveFileName());
4559 if (output_dir.CreateDirectoriesRecursively()) {
4560 xmlout = posix::FOpen(output_file_.c_str(), "w");
4562 if (xmlout == NULL) {
4563 // TODO(wan): report the reason of the failure.
4565 // We don't do it for now as:
4567 // 1. There is no urgent need for it.
4568 // 2. It's a bit involved to make the errno variable thread-safe on
4569 // all three operating systems (Linux, Windows, and Mac OS).
4570 // 3. To interpret the meaning of errno in a thread-safe way,
4571 // we need the strerror_r() function, which is not available on
4574 "Unable to open file \"%s\"\n",
4575 output_file_.c_str());
4579 std::stringstream stream;
4580 PrintXmlUnitTest(&stream, unit_test);
4581 fprintf(xmlout, "%s", StringStreamToString(&stream).c_str());
4585 // Returns an XML-escaped copy of the input string str. If is_attribute
4586 // is true, the text is meant to appear as an attribute value, and
4587 // normalizable whitespace is preserved by replacing it with character
4590 // Invalid XML characters in str, if any, are stripped from the output.
4591 // It is expected that most, if not all, of the text processed by this
4592 // module will consist of ordinary English text.
4593 // If this module is ever modified to produce version 1.1 XML output,
4594 // most invalid characters can be retained using character references.
4595 // TODO(wan): It might be nice to have a minimally invasive, human-readable
4596 // escaping scheme for invalid characters, rather than dropping them.
4597 std::string XmlUnitTestResultPrinter::EscapeXml(
4598 const std::string& str, bool is_attribute) {
4601 for (size_t i = 0; i < str.size(); ++i) {
4602 const char ch = str[i];
4626 if (IsValidXmlCharacter(ch)) {
4627 if (is_attribute && IsNormalizableWhitespace(ch))
4628 m << "&#x" << String::FormatByte(static_cast<unsigned char>(ch))
4637 return m.GetString();
4640 // Returns the given string with all characters invalid in XML removed.
4641 // Currently invalid characters are dropped from the string. An
4642 // alternative is to replace them with certain characters such as . or ?.
4643 std::string XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters(
4644 const std::string& str) {
4646 output.reserve(str.size());
4647 for (std::string::const_iterator it = str.begin(); it != str.end(); ++it)
4648 if (IsValidXmlCharacter(*it))
4649 output.push_back(*it);
4654 // The following routines generate an XML representation of a UnitTest
4657 // This is how Google Test concepts map to the DTD:
4659 // <testsuites name="AllTests"> <-- corresponds to a UnitTest object
4660 // <testsuite name="testcase-name"> <-- corresponds to a TestCase object
4661 // <testcase name="test-name"> <-- corresponds to a TestInfo object
4662 // <failure message="...">...</failure>
4663 // <failure message="...">...</failure>
4664 // <failure message="...">...</failure>
4665 // <-- individual assertion failures
4670 // Formats the given time in milliseconds as seconds.
4671 std::string FormatTimeInMillisAsSeconds(TimeInMillis ms) {
4672 ::std::stringstream ss;
4677 // Converts the given epoch time in milliseconds to a date string in the ISO
4678 // 8601 format, without the timezone information.
4679 std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms) {
4680 // Using non-reentrant version as localtime_r is not portable.
4681 time_t seconds = static_cast<time_t>(ms / 1000);
4683 # pragma warning(push) // Saves the current warning state.
4684 # pragma warning(disable:4996) // Temporarily disables warning 4996
4685 // (function or variable may be unsafe).
4686 const struct tm* const time_struct = localtime(&seconds); // NOLINT
4687 # pragma warning(pop) // Restores the warning state again.
4689 const struct tm* const time_struct = localtime(&seconds); // NOLINT
4691 if (time_struct == NULL)
4692 return ""; // Invalid ms value
4694 // YYYY-MM-DDThh:mm:ss
4695 return StreamableToString(time_struct->tm_year + 1900) + "-" +
4696 String::FormatIntWidth2(time_struct->tm_mon + 1) + "-" +
4697 String::FormatIntWidth2(time_struct->tm_mday) + "T" +
4698 String::FormatIntWidth2(time_struct->tm_hour) + ":" +
4699 String::FormatIntWidth2(time_struct->tm_min) + ":" +
4700 String::FormatIntWidth2(time_struct->tm_sec);
4703 // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
4704 void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream,
4706 const char* segment = data;
4707 *stream << "<![CDATA[";
4709 const char* const next_segment = strstr(segment, "]]>");
4710 if (next_segment != NULL) {
4712 segment, static_cast<std::streamsize>(next_segment - segment));
4713 *stream << "]]>]]><![CDATA[";
4714 segment = next_segment + strlen("]]>");
4723 void XmlUnitTestResultPrinter::OutputXmlAttribute(
4724 std::ostream* stream,
4725 const std::string& element_name,
4726 const std::string& name,
4727 const std::string& value) {
4728 const std::vector<std::string>& allowed_names =
4729 GetReservedAttributesForElement(element_name);
4731 GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
4732 allowed_names.end())
4733 << "Attribute " << name << " is not allowed for element <" << element_name
4736 *stream << " " << name << "=\"" << EscapeXmlAttribute(value) << "\"";
4739 // Prints an XML representation of a TestInfo object.
4740 // TODO(wan): There is also value in printing properties with the plain printer.
4741 void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream,
4742 const char* test_case_name,
4743 const TestInfo& test_info) {
4744 const TestResult& result = *test_info.result();
4745 const std::string kTestcase = "testcase";
4747 *stream << " <testcase";
4748 OutputXmlAttribute(stream, kTestcase, "name", test_info.name());
4750 if (test_info.value_param() != NULL) {
4751 OutputXmlAttribute(stream, kTestcase, "value_param",
4752 test_info.value_param());
4754 if (test_info.type_param() != NULL) {
4755 OutputXmlAttribute(stream, kTestcase, "type_param", test_info.type_param());
4758 OutputXmlAttribute(stream, kTestcase, "status",
4759 test_info.should_run() ? "run" : "notrun");
4760 OutputXmlAttribute(stream, kTestcase, "time",
4761 FormatTimeInMillisAsSeconds(result.elapsed_time()));
4762 OutputXmlAttribute(stream, kTestcase, "classname", test_case_name);
4763 *stream << TestPropertiesAsXmlAttributes(result);
4766 for (int i = 0; i < result.total_part_count(); ++i) {
4767 const TestPartResult& part = result.GetTestPartResult(i);
4768 if (part.failed()) {
4769 if (++failures == 1) {
4772 const string location = internal::FormatCompilerIndependentFileLocation(
4773 part.file_name(), part.line_number());
4774 const string summary = location + "\n" + part.summary();
4775 *stream << " <failure message=\""
4776 << EscapeXmlAttribute(summary.c_str())
4778 const string detail = location + "\n" + part.message();
4779 OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str());
4780 *stream << "</failure>\n";
4787 *stream << " </testcase>\n";
4790 // Prints an XML representation of a TestCase object
4791 void XmlUnitTestResultPrinter::PrintXmlTestCase(std::ostream* stream,
4792 const TestCase& test_case) {
4793 const std::string kTestsuite = "testsuite";
4794 *stream << " <" << kTestsuite;
4795 OutputXmlAttribute(stream, kTestsuite, "name", test_case.name());
4796 OutputXmlAttribute(stream, kTestsuite, "tests",
4797 StreamableToString(test_case.total_test_count()));
4798 OutputXmlAttribute(stream, kTestsuite, "failures",
4799 StreamableToString(test_case.failed_test_count()));
4800 OutputXmlAttribute(stream, kTestsuite, "disabled",
4801 StreamableToString(test_case.disabled_test_count()));
4802 OutputXmlAttribute(stream, kTestsuite, "errors", "0");
4803 OutputXmlAttribute(stream, kTestsuite, "time",
4804 FormatTimeInMillisAsSeconds(test_case.elapsed_time()));
4805 *stream << TestPropertiesAsXmlAttributes(test_case.ad_hoc_test_result())
4808 for (int i = 0; i < test_case.total_test_count(); ++i)
4809 OutputXmlTestInfo(stream, test_case.name(), *test_case.GetTestInfo(i));
4810 *stream << " </" << kTestsuite << ">\n";
4813 // Prints an XML summary of unit_test to output stream out.
4814 void XmlUnitTestResultPrinter::PrintXmlUnitTest(std::ostream* stream,
4815 const UnitTest& unit_test) {
4816 const std::string kTestsuites = "testsuites";
4818 *stream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
4819 *stream << "<" << kTestsuites;
4821 OutputXmlAttribute(stream, kTestsuites, "tests",
4822 StreamableToString(unit_test.total_test_count()));
4823 OutputXmlAttribute(stream, kTestsuites, "failures",
4824 StreamableToString(unit_test.failed_test_count()));
4825 OutputXmlAttribute(stream, kTestsuites, "disabled",
4826 StreamableToString(unit_test.disabled_test_count()));
4827 OutputXmlAttribute(stream, kTestsuites, "errors", "0");
4829 stream, kTestsuites, "timestamp",
4830 FormatEpochTimeInMillisAsIso8601(unit_test.start_timestamp()));
4831 OutputXmlAttribute(stream, kTestsuites, "time",
4832 FormatTimeInMillisAsSeconds(unit_test.elapsed_time()));
4834 if (GTEST_FLAG(shuffle)) {
4835 OutputXmlAttribute(stream, kTestsuites, "random_seed",
4836 StreamableToString(unit_test.random_seed()));
4839 *stream << TestPropertiesAsXmlAttributes(unit_test.ad_hoc_test_result());
4841 OutputXmlAttribute(stream, kTestsuites, "name", "AllTests");
4845 for (int i = 0; i < unit_test.total_test_case_count(); ++i) {
4846 PrintXmlTestCase(stream, *unit_test.GetTestCase(i));
4848 *stream << "</" << kTestsuites << ">\n";
4851 // Produces a string representing the test properties in a result as space
4852 // delimited XML attributes based on the property key="value" pairs.
4853 std::string XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes(
4854 const TestResult& result) {
4856 for (int i = 0; i < result.test_property_count(); ++i) {
4857 const TestProperty& property = result.GetTestProperty(i);
4858 attributes << " " << property.key() << "="
4859 << "\"" << EscapeXmlAttribute(property.value()) << "\"";
4861 return attributes.GetString();
4864 // End XmlUnitTestResultPrinter
4866 #if GTEST_CAN_STREAM_RESULTS_
4868 // Checks if str contains '=', '&', '%' or '\n' characters. If yes,
4869 // replaces them by "%xx" where xx is their hexadecimal value. For
4870 // example, replaces "=" with "%3D". This algorithm is O(strlen(str))
4871 // in both time and space -- important as the input str may contain an
4872 // arbitrarily long test failure message and stack trace.
4873 string StreamingListener::UrlEncode(const char* str) {
4875 result.reserve(strlen(str) + 1);
4876 for (char ch = *str; ch != '\0'; ch = *++str) {
4882 result.append("%" + String::FormatByte(static_cast<unsigned char>(ch)));
4885 result.push_back(ch);
4892 void StreamingListener::SocketWriter::MakeConnection() {
4893 GTEST_CHECK_(sockfd_ == -1)
4894 << "MakeConnection() can't be called when there is already a connection.";
4897 memset(&hints, 0, sizeof(hints));
4898 hints.ai_family = AF_UNSPEC; // To allow both IPv4 and IPv6 addresses.
4899 hints.ai_socktype = SOCK_STREAM;
4900 addrinfo* servinfo = NULL;
4902 // Use the getaddrinfo() to get a linked list of IP addresses for
4903 // the given host name.
4904 const int error_num = getaddrinfo(
4905 host_name_.c_str(), port_num_.c_str(), &hints, &servinfo);
4906 if (error_num != 0) {
4907 GTEST_LOG_(WARNING) << "stream_result_to: getaddrinfo() failed: "
4908 << gai_strerror(error_num);
4911 // Loop through all the results and connect to the first we can.
4912 for (addrinfo* cur_addr = servinfo; sockfd_ == -1 && cur_addr != NULL;
4913 cur_addr = cur_addr->ai_next) {
4915 cur_addr->ai_family, cur_addr->ai_socktype, cur_addr->ai_protocol);
4916 if (sockfd_ != -1) {
4917 // Connect the client socket to the server socket.
4918 if (connect(sockfd_, cur_addr->ai_addr, cur_addr->ai_addrlen) == -1) {
4925 freeaddrinfo(servinfo); // all done with this structure
4927 if (sockfd_ == -1) {
4928 GTEST_LOG_(WARNING) << "stream_result_to: failed to connect to "
4929 << host_name_ << ":" << port_num_;
4933 // End of class Streaming Listener
4934 #endif // GTEST_CAN_STREAM_RESULTS__
4936 // Class ScopedTrace
4938 // Pushes the given source file location and message onto a per-thread
4939 // trace stack maintained by Google Test.
4940 ScopedTrace::ScopedTrace(const char* file, int line, const Message& message)
4941 GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) {
4945 trace.message = message.GetString();
4947 UnitTest::GetInstance()->PushGTestTrace(trace);
4950 // Pops the info pushed by the c'tor.
4951 ScopedTrace::~ScopedTrace()
4952 GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) {
4953 UnitTest::GetInstance()->PopGTestTrace();
4957 // class OsStackTraceGetter
4959 // Returns the current OS stack trace as an std::string. Parameters:
4961 // max_depth - the maximum number of stack frames to be included
4963 // skip_count - the number of top frames to be skipped; doesn't count
4964 // against max_depth.
4966 string OsStackTraceGetter::CurrentStackTrace(int /* max_depth */,
4967 int /* skip_count */)
4968 GTEST_LOCK_EXCLUDED_(mutex_) {
4972 void OsStackTraceGetter::UponLeavingGTest()
4973 GTEST_LOCK_EXCLUDED_(mutex_) {
4977 OsStackTraceGetter::kElidedFramesMarker =
4978 "... " GTEST_NAME_ " internal frames ...";
4980 } // namespace internal
4982 // class TestEventListeners
4984 TestEventListeners::TestEventListeners()
4985 : repeater_(new internal::TestEventRepeater()),
4986 default_result_printer_(NULL),
4987 default_xml_generator_(NULL) {
4990 TestEventListeners::~TestEventListeners() { delete repeater_; }
4992 // Returns the standard listener responsible for the default console
4993 // output. Can be removed from the listeners list to shut down default
4994 // console output. Note that removing this object from the listener list
4995 // with Release transfers its ownership to the user.
4996 void TestEventListeners::Append(TestEventListener* listener) {
4997 repeater_->Append(listener);
5000 // Removes the given event listener from the list and returns it. It then
5001 // becomes the caller's responsibility to delete the listener. Returns
5002 // NULL if the listener is not found in the list.
5003 TestEventListener* TestEventListeners::Release(TestEventListener* listener) {
5004 if (listener == default_result_printer_)
5005 default_result_printer_ = NULL;
5006 else if (listener == default_xml_generator_)
5007 default_xml_generator_ = NULL;
5008 return repeater_->Release(listener);
5011 // Returns repeater that broadcasts the TestEventListener events to all
5013 TestEventListener* TestEventListeners::repeater() { return repeater_; }
5015 // Sets the default_result_printer attribute to the provided listener.
5016 // The listener is also added to the listener list and previous
5017 // default_result_printer is removed from it and deleted. The listener can
5018 // also be NULL in which case it will not be added to the list. Does
5019 // nothing if the previous and the current listener objects are the same.
5020 void TestEventListeners::SetDefaultResultPrinter(TestEventListener* listener) {
5021 if (default_result_printer_ != listener) {
5022 // It is an error to pass this method a listener that is already in the
5024 delete Release(default_result_printer_);
5025 default_result_printer_ = listener;
5026 if (listener != NULL)
5031 // Sets the default_xml_generator attribute to the provided listener. The
5032 // listener is also added to the listener list and previous
5033 // default_xml_generator is removed from it and deleted. The listener can
5034 // also be NULL in which case it will not be added to the list. Does
5035 // nothing if the previous and the current listener objects are the same.
5036 void TestEventListeners::SetDefaultXmlGenerator(TestEventListener* listener) {
5037 if (default_xml_generator_ != listener) {
5038 // It is an error to pass this method a listener that is already in the
5040 delete Release(default_xml_generator_);
5041 default_xml_generator_ = listener;
5042 if (listener != NULL)
5047 // Controls whether events will be forwarded by the repeater to the
5048 // listeners in the list.
5049 bool TestEventListeners::EventForwardingEnabled() const {
5050 return repeater_->forwarding_enabled();
5053 void TestEventListeners::SuppressEventForwarding() {
5054 repeater_->set_forwarding_enabled(false);
5059 // Gets the singleton UnitTest object. The first time this method is
5060 // called, a UnitTest object is constructed and returned. Consecutive
5061 // calls will return the same object.
5063 // We don't protect this under mutex_ as a user is not supposed to
5064 // call this before main() starts, from which point on the return
5065 // value will never change.
5066 UnitTest * UnitTest::GetInstance() {
5067 // When compiled with MSVC 7.1 in optimized mode, destroying the
5068 // UnitTest object upon exiting the program messes up the exit code,
5069 // causing successful tests to appear failed. We have to use a
5070 // different implementation in this case to bypass the compiler bug.
5071 // This implementation makes the compiler happy, at the cost of
5072 // leaking the UnitTest object.
5074 // CodeGear C++Builder insists on a public destructor for the
5075 // default implementation. Use this implementation to keep good OO
5076 // design with private destructor.
5078 #if (defined(_MSC_VER) && _MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)
5079 static UnitTest* const instance = new UnitTest;
5082 static UnitTest instance;
5084 #endif // (defined(_MSC_VER) && _MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)
5087 // Gets the number of successful test cases.
5088 int UnitTest::successful_test_case_count() const {
5089 return impl()->successful_test_case_count();
5092 // Gets the number of failed test cases.
5093 int UnitTest::failed_test_case_count() const {
5094 return impl()->failed_test_case_count();
5097 // Gets the number of all test cases.
5098 int UnitTest::total_test_case_count() const {
5099 return impl()->total_test_case_count();
5102 // Gets the number of all test cases that contain at least one test
5104 int UnitTest::test_case_to_run_count() const {
5105 return impl()->test_case_to_run_count();
5108 // Gets the number of successful tests.
5109 int UnitTest::successful_test_count() const {
5110 return impl()->successful_test_count();
5113 // Gets the number of failed tests.
5114 int UnitTest::failed_test_count() const { return impl()->failed_test_count(); }
5116 // Gets the number of disabled tests.
5117 int UnitTest::disabled_test_count() const {
5118 return impl()->disabled_test_count();
5121 // Gets the number of all tests.
5122 int UnitTest::total_test_count() const { return impl()->total_test_count(); }
5124 // Gets the number of tests that should run.
5125 int UnitTest::test_to_run_count() const { return impl()->test_to_run_count(); }
5127 // Gets the time of the test program start, in ms from the start of the
5129 internal::TimeInMillis UnitTest::start_timestamp() const {
5130 return impl()->start_timestamp();
5133 // Gets the elapsed time, in milliseconds.
5134 internal::TimeInMillis UnitTest::elapsed_time() const {
5135 return impl()->elapsed_time();
5138 // Returns true iff the unit test passed (i.e. all test cases passed).
5139 bool UnitTest::Passed() const { return impl()->Passed(); }
5141 // Returns true iff the unit test failed (i.e. some test case failed
5142 // or something outside of all tests failed).
5143 bool UnitTest::Failed() const { return impl()->Failed(); }
5145 // Gets the i-th test case among all the test cases. i can range from 0 to
5146 // total_test_case_count() - 1. If i is not in that range, returns NULL.
5147 const TestCase* UnitTest::GetTestCase(int i) const {
5148 return impl()->GetTestCase(i);
5151 // Returns the TestResult containing information on test failures and
5152 // properties logged outside of individual test cases.
5153 const TestResult& UnitTest::ad_hoc_test_result() const {
5154 return *impl()->ad_hoc_test_result();
5157 // Gets the i-th test case among all the test cases. i can range from 0 to
5158 // total_test_case_count() - 1. If i is not in that range, returns NULL.
5159 TestCase* UnitTest::GetMutableTestCase(int i) {
5160 return impl()->GetMutableTestCase(i);
5163 // Returns the list of event listeners that can be used to track events
5164 // inside Google Test.
5165 TestEventListeners& UnitTest::listeners() {
5166 return *impl()->listeners();
5169 // Registers and returns a global test environment. When a test
5170 // program is run, all global test environments will be set-up in the
5171 // order they were registered. After all tests in the program have
5172 // finished, all global test environments will be torn-down in the
5173 // *reverse* order they were registered.
5175 // The UnitTest object takes ownership of the given environment.
5177 // We don't protect this under mutex_, as we only support calling it
5178 // from the main thread.
5179 Environment* UnitTest::AddEnvironment(Environment* env) {
5184 impl_->environments().push_back(env);
5188 // Adds a TestPartResult to the current TestResult object. All Google Test
5189 // assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) eventually call
5190 // this to report their results. The user code should use the
5191 // assertion macros instead of calling this directly.
5192 GTEST_LOCK_EXCLUDED_(mutex_)
5193 void UnitTest::AddTestPartResult(
5194 TestPartResult::Type result_type,
5195 const char* file_name,
5197 const std::string& message,
5198 const std::string& os_stack_trace) {
5202 internal::MutexLock lock(&mutex_);
5203 if (impl_->gtest_trace_stack().size() > 0) {
5204 msg << "\n" << GTEST_NAME_ << " trace:";
5206 for (int i = static_cast<int>(impl_->gtest_trace_stack().size());
5208 const internal::TraceInfo& trace = impl_->gtest_trace_stack()[i - 1];
5209 msg << "\n" << internal::FormatFileLocation(trace.file, trace.line)
5210 << " " << trace.message;
5214 if (os_stack_trace.c_str() != NULL && !os_stack_trace.empty()) {
5215 msg << internal::kStackTraceMarker << os_stack_trace;
5218 const TestPartResult result =
5219 TestPartResult(result_type, file_name, line_number,
5220 msg.GetString().c_str());
5221 impl_->GetTestPartResultReporterForCurrentThread()->
5222 ReportTestPartResult(result);
5224 if (result_type != TestPartResult::kSuccess) {
5225 // gtest_break_on_failure takes precedence over
5226 // gtest_throw_on_failure. This allows a user to set the latter
5227 // in the code (perhaps in order to use Google Test assertions
5228 // with another testing framework) and specify the former on the
5229 // command line for debugging.
5230 if (GTEST_FLAG(break_on_failure)) {
5231 #if GTEST_OS_WINDOWS
5232 // Using DebugBreak on Windows allows gtest to still break into a debugger
5233 // when a failure happens and both the --gtest_break_on_failure and
5234 // the --gtest_catch_exceptions flags are specified.
5237 // Dereference NULL through a volatile pointer to prevent the compiler
5238 // from removing. We use this rather than abort() or __builtin_trap() for
5239 // portability: Symbian doesn't implement abort() well, and some debuggers
5240 // don't correctly trap abort().
5241 *static_cast<volatile int*>(NULL) = 1;
5242 #endif // GTEST_OS_WINDOWS
5243 } else if (GTEST_FLAG(throw_on_failure)) {
5244 #if GTEST_HAS_EXCEPTIONS
5245 throw internal::GoogleTestFailureException(result);
5247 // We cannot call abort() as it generates a pop-up in debug mode
5248 // that cannot be suppressed in VC 7.1 or below.
5255 // Adds a TestProperty to the current TestResult object when invoked from
5256 // inside a test, to current TestCase's ad_hoc_test_result_ when invoked
5257 // from SetUpTestCase or TearDownTestCase, or to the global property set
5258 // when invoked elsewhere. If the result already contains a property with
5259 // the same key, the value will be updated.
5260 void UnitTest::RecordProperty(const std::string& key,
5261 const std::string& value) {
5262 impl_->RecordProperty(TestProperty(key, value));
5265 // Runs all tests in this UnitTest object and prints the result.
5266 // Returns 0 if successful, or 1 otherwise.
5268 // We don't protect this under mutex_, as we only support calling it
5269 // from the main thread.
5270 int UnitTest::Run() {
5271 // Captures the value of GTEST_FLAG(catch_exceptions). This value will be
5272 // used for the duration of the program.
5273 impl()->set_catch_exceptions(GTEST_FLAG(catch_exceptions));
5276 const bool in_death_test_child_process =
5277 internal::GTEST_FLAG(internal_run_death_test).length() > 0;
5279 // Either the user wants Google Test to catch exceptions thrown by the
5280 // tests or this is executing in the context of death test child
5281 // process. In either case the user does not want to see pop-up dialogs
5282 // about crashes - they are expected.
5283 if (impl()->catch_exceptions() || in_death_test_child_process) {
5284 # if !GTEST_OS_WINDOWS_MOBILE
5285 // SetErrorMode doesn't exist on CE.
5286 SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT |
5287 SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);
5288 # endif // !GTEST_OS_WINDOWS_MOBILE
5290 # if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE
5291 // Death test children can be terminated with _abort(). On Windows,
5292 // _abort() can show a dialog with a warning message. This forces the
5293 // abort message to go to stderr instead.
5294 _set_error_mode(_OUT_TO_STDERR);
5297 # if _MSC_VER >= 1400 && !GTEST_OS_WINDOWS_MOBILE
5298 // In the debug version, Visual Studio pops up a separate dialog
5299 // offering a choice to debug the aborted program. We need to suppress
5300 // this dialog or it will pop up for every EXPECT/ASSERT_DEATH statement
5301 // executed. Google Test will notify the user of any unexpected
5302 // failure via stderr.
5304 // VC++ doesn't define _set_abort_behavior() prior to the version 8.0.
5305 // Users of prior VC versions shall suffer the agony and pain of
5306 // clicking through the countless debug dialogs.
5307 // TODO(vladl@google.com): find a way to suppress the abort dialog() in the
5308 // debug mode when compiled with VC 7.1 or lower.
5309 if (!GTEST_FLAG(break_on_failure))
5310 _set_abort_behavior(
5311 0x0, // Clear the following flags:
5312 _WRITE_ABORT_MSG | _CALL_REPORTFAULT); // pop-up window, core dump.
5315 #endif // GTEST_HAS_SEH
5317 return internal::HandleExceptionsInMethodIfSupported(
5319 &internal::UnitTestImpl::RunAllTests,
5320 "auxiliary test code (environments or event listeners)") ? 0 : 1;
5323 // Returns the working directory when the first TEST() or TEST_F() was
5325 const char* UnitTest::original_working_dir() const {
5326 return impl_->original_working_dir_.c_str();
5329 // Returns the TestCase object for the test that's currently running,
5330 // or NULL if no test is running.
5331 const TestCase* UnitTest::current_test_case() const
5332 GTEST_LOCK_EXCLUDED_(mutex_) {
5333 internal::MutexLock lock(&mutex_);
5334 return impl_->current_test_case();
5337 // Returns the TestInfo object for the test that's currently running,
5338 // or NULL if no test is running.
5339 const TestInfo* UnitTest::current_test_info() const
5340 GTEST_LOCK_EXCLUDED_(mutex_) {
5341 internal::MutexLock lock(&mutex_);
5342 return impl_->current_test_info();
5345 // Returns the random seed used at the start of the current test run.
5346 int UnitTest::random_seed() const { return impl_->random_seed(); }
5348 #if GTEST_HAS_PARAM_TEST
5349 // Returns ParameterizedTestCaseRegistry object used to keep track of
5350 // value-parameterized tests and instantiate and register them.
5351 internal::ParameterizedTestCaseRegistry&
5352 UnitTest::parameterized_test_registry()
5353 GTEST_LOCK_EXCLUDED_(mutex_) {
5354 return impl_->parameterized_test_registry();
5356 #endif // GTEST_HAS_PARAM_TEST
5358 // Creates an empty UnitTest.
5359 UnitTest::UnitTest() {
5360 impl_ = new internal::UnitTestImpl(this);
5363 // Destructor of UnitTest.
5364 UnitTest::~UnitTest() {
5368 // Pushes a trace defined by SCOPED_TRACE() on to the per-thread
5369 // Google Test trace stack.
5370 void UnitTest::PushGTestTrace(const internal::TraceInfo& trace)
5371 GTEST_LOCK_EXCLUDED_(mutex_) {
5372 internal::MutexLock lock(&mutex_);
5373 impl_->gtest_trace_stack().push_back(trace);
5376 // Pops a trace from the per-thread Google Test trace stack.
5377 void UnitTest::PopGTestTrace()
5378 GTEST_LOCK_EXCLUDED_(mutex_) {
5379 internal::MutexLock lock(&mutex_);
5380 impl_->gtest_trace_stack().pop_back();
5383 namespace internal {
5385 UnitTestImpl::UnitTestImpl(UnitTest* parent)
5388 # pragma warning(push) // Saves the current warning state.
5389 # pragma warning(disable:4355) // Temporarily disables warning 4355
5390 // (using this in initializer).
5391 default_global_test_part_result_reporter_(this),
5392 default_per_thread_test_part_result_reporter_(this),
5393 # pragma warning(pop) // Restores the warning state again.
5395 default_global_test_part_result_reporter_(this),
5396 default_per_thread_test_part_result_reporter_(this),
5398 global_test_part_result_repoter_(
5399 &default_global_test_part_result_reporter_),
5400 per_thread_test_part_result_reporter_(
5401 &default_per_thread_test_part_result_reporter_),
5402 #if GTEST_HAS_PARAM_TEST
5403 parameterized_test_registry_(),
5404 parameterized_tests_registered_(false),
5405 #endif // GTEST_HAS_PARAM_TEST
5406 last_death_test_case_(-1),
5407 current_test_case_(NULL),
5408 current_test_info_(NULL),
5409 ad_hoc_test_result_(),
5410 os_stack_trace_getter_(NULL),
5411 post_flag_parse_init_performed_(false),
5412 random_seed_(0), // Will be overridden by the flag before first use.
5413 random_(0), // Will be reseeded before first use.
5414 start_timestamp_(0),
5416 #if GTEST_HAS_DEATH_TEST
5417 internal_run_death_test_flag_(NULL),
5418 death_test_factory_(new DefaultDeathTestFactory),
5420 // Will be overridden by the flag before first use.
5421 catch_exceptions_(false) {
5422 listeners()->SetDefaultResultPrinter(new PrettyUnitTestResultPrinter);
5425 UnitTestImpl::~UnitTestImpl() {
5426 // Deletes every TestCase.
5427 ForEach(test_cases_, internal::Delete<TestCase>);
5429 // Deletes every Environment.
5430 ForEach(environments_, internal::Delete<Environment>);
5432 delete os_stack_trace_getter_;
5435 // Adds a TestProperty to the current TestResult object when invoked in a
5436 // context of a test, to current test case's ad_hoc_test_result when invoke
5437 // from SetUpTestCase/TearDownTestCase, or to the global property set
5438 // otherwise. If the result already contains a property with the same key,
5439 // the value will be updated.
5440 void UnitTestImpl::RecordProperty(const TestProperty& test_property) {
5441 std::string xml_element;
5442 TestResult* test_result; // TestResult appropriate for property recording.
5444 if (current_test_info_ != NULL) {
5445 xml_element = "testcase";
5446 test_result = &(current_test_info_->result_);
5447 } else if (current_test_case_ != NULL) {
5448 xml_element = "testsuite";
5449 test_result = &(current_test_case_->ad_hoc_test_result_);
5451 xml_element = "testsuites";
5452 test_result = &ad_hoc_test_result_;
5454 test_result->RecordProperty(xml_element, test_property);
5457 #if GTEST_HAS_DEATH_TEST
5458 // Disables event forwarding if the control is currently in a death test
5459 // subprocess. Must not be called before InitGoogleTest.
5460 void UnitTestImpl::SuppressTestEventsIfInSubprocess() {
5461 if (internal_run_death_test_flag_.get() != NULL)
5462 listeners()->SuppressEventForwarding();
5464 #endif // GTEST_HAS_DEATH_TEST
5466 // Initializes event listeners performing XML output as specified by
5467 // UnitTestOptions. Must not be called before InitGoogleTest.
5468 void UnitTestImpl::ConfigureXmlOutput() {
5469 const std::string& output_format = UnitTestOptions::GetOutputFormat();
5470 if (output_format == "xml") {
5471 listeners()->SetDefaultXmlGenerator(new XmlUnitTestResultPrinter(
5472 UnitTestOptions::GetAbsolutePathToOutputFile().c_str()));
5473 } else if (output_format != "") {
5474 printf("WARNING: unrecognized output format \"%s\" ignored.\n",
5475 output_format.c_str());
5480 #if GTEST_CAN_STREAM_RESULTS_
5481 // Initializes event listeners for streaming test results in string form.
5482 // Must not be called before InitGoogleTest.
5483 void UnitTestImpl::ConfigureStreamingOutput() {
5484 const std::string& target = GTEST_FLAG(stream_result_to);
5485 if (!target.empty()) {
5486 const size_t pos = target.find(':');
5487 if (pos != std::string::npos) {
5488 listeners()->Append(new StreamingListener(target.substr(0, pos),
5489 target.substr(pos+1)));
5491 printf("WARNING: unrecognized streaming target \"%s\" ignored.\n",
5497 #endif // GTEST_CAN_STREAM_RESULTS_
5499 // Performs initialization dependent upon flag values obtained in
5500 // ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to
5501 // ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest
5502 // this function is also called from RunAllTests. Since this function can be
5503 // called more than once, it has to be idempotent.
5504 void UnitTestImpl::PostFlagParsingInit() {
5505 // Ensures that this function does not execute more than once.
5506 if (!post_flag_parse_init_performed_) {
5507 post_flag_parse_init_performed_ = true;
5509 #if GTEST_HAS_DEATH_TEST
5510 InitDeathTestSubprocessControlInfo();
5511 SuppressTestEventsIfInSubprocess();
5512 #endif // GTEST_HAS_DEATH_TEST
5514 // Registers parameterized tests. This makes parameterized tests
5515 // available to the UnitTest reflection API without running
5517 RegisterParameterizedTests();
5519 // Configures listeners for XML output. This makes it possible for users
5520 // to shut down the default XML output before invoking RUN_ALL_TESTS.
5521 ConfigureXmlOutput();
5523 #if GTEST_CAN_STREAM_RESULTS_
5524 // Configures listeners for streaming test results to the specified server.
5525 ConfigureStreamingOutput();
5526 #endif // GTEST_CAN_STREAM_RESULTS_
5530 // A predicate that checks the name of a TestCase against a known
5533 // This is used for implementation of the UnitTest class only. We put
5534 // it in the anonymous namespace to prevent polluting the outer
5537 // TestCaseNameIs is copyable.
5538 class TestCaseNameIs {
5541 explicit TestCaseNameIs(const std::string& name)
5544 // Returns true iff the name of test_case matches name_.
5545 bool operator()(const TestCase* test_case) const {
5546 return test_case != NULL && strcmp(test_case->name(), name_.c_str()) == 0;
5553 // Finds and returns a TestCase with the given name. If one doesn't
5554 // exist, creates one and returns it. It's the CALLER'S
5555 // RESPONSIBILITY to ensure that this function is only called WHEN THE
5556 // TESTS ARE NOT SHUFFLED.
5560 // test_case_name: name of the test case
5561 // type_param: the name of the test case's type parameter, or NULL if
5562 // this is not a typed or a type-parameterized test case.
5563 // set_up_tc: pointer to the function that sets up the test case
5564 // tear_down_tc: pointer to the function that tears down the test case
5565 TestCase* UnitTestImpl::GetTestCase(const char* test_case_name,
5566 const char* type_param,
5567 Test::SetUpTestCaseFunc set_up_tc,
5568 Test::TearDownTestCaseFunc tear_down_tc) {
5569 // Can we find a TestCase with the given name?
5570 const std::vector<TestCase*>::const_iterator test_case =
5571 std::find_if(test_cases_.begin(), test_cases_.end(),
5572 TestCaseNameIs(test_case_name));
5574 if (test_case != test_cases_.end())
5577 // No. Let's create one.
5578 TestCase* const new_test_case =
5579 new TestCase(test_case_name, type_param, set_up_tc, tear_down_tc);
5581 // Is this a death test case?
5582 if (internal::UnitTestOptions::MatchesFilter(test_case_name,
5583 kDeathTestCaseFilter)) {
5584 // Yes. Inserts the test case after the last death test case
5585 // defined so far. This only works when the test cases haven't
5586 // been shuffled. Otherwise we may end up running a death test
5587 // after a non-death test.
5588 ++last_death_test_case_;
5589 test_cases_.insert(test_cases_.begin() + last_death_test_case_,
5592 // No. Appends to the end of the list.
5593 test_cases_.push_back(new_test_case);
5596 test_case_indices_.push_back(static_cast<int>(test_case_indices_.size()));
5597 return new_test_case;
5600 // Helpers for setting up / tearing down the given environment. They
5601 // are for use in the ForEach() function.
5602 static void SetUpEnvironment(Environment* env) { env->SetUp(); }
5603 static void TearDownEnvironment(Environment* env) { env->TearDown(); }
5605 // Runs all tests in this UnitTest object, prints the result, and
5606 // returns true if all tests are successful. If any exception is
5607 // thrown during a test, the test is considered to be failed, but the
5608 // rest of the tests will still be run.
5610 // When parameterized tests are enabled, it expands and registers
5611 // parameterized tests first in RegisterParameterizedTests().
5612 // All other functions called from RunAllTests() may safely assume that
5613 // parameterized tests are ready to be counted and run.
5614 bool UnitTestImpl::RunAllTests() {
5615 // Makes sure InitGoogleTest() was called.
5616 if (!GTestIsInitialized()) {
5618 "\nThis test program did NOT call ::testing::InitGoogleTest "
5619 "before calling RUN_ALL_TESTS(). Please fix it.\n");
5623 // Do not run any test if the --help flag was specified.
5627 // Repeats the call to the post-flag parsing initialization in case the
5628 // user didn't call InitGoogleTest.
5629 PostFlagParsingInit();
5631 // Even if sharding is not on, test runners may want to use the
5632 // GTEST_SHARD_STATUS_FILE to query whether the test supports the sharding
5634 internal::WriteToShardStatusFileIfNeeded();
5636 // True iff we are in a subprocess for running a thread-safe-style
5638 bool in_subprocess_for_death_test = false;
5640 #if GTEST_HAS_DEATH_TEST
5641 in_subprocess_for_death_test = (internal_run_death_test_flag_.get() != NULL);
5642 #endif // GTEST_HAS_DEATH_TEST
5644 const bool should_shard = ShouldShard(kTestTotalShards, kTestShardIndex,
5645 in_subprocess_for_death_test);
5647 // Compares the full test names with the filter to decide which
5649 const bool has_tests_to_run = FilterTests(should_shard
5650 ? HONOR_SHARDING_PROTOCOL
5651 : IGNORE_SHARDING_PROTOCOL) > 0;
5653 // Lists the tests and exits if the --gtest_list_tests flag was specified.
5654 if (GTEST_FLAG(list_tests)) {
5655 // This must be called *after* FilterTests() has been called.
5656 ListTestsMatchingFilter();
5660 random_seed_ = GTEST_FLAG(shuffle) ?
5661 GetRandomSeedFromFlag(GTEST_FLAG(random_seed)) : 0;
5663 // True iff at least one test has failed.
5664 bool failed = false;
5666 TestEventListener* repeater = listeners()->repeater();
5668 start_timestamp_ = GetTimeInMillis();
5669 repeater->OnTestProgramStart(*parent_);
5671 // How many times to repeat the tests? We don't want to repeat them
5672 // when we are inside the subprocess of a death test.
5673 const int repeat = in_subprocess_for_death_test ? 1 : GTEST_FLAG(repeat);
5674 // Repeats forever if the repeat count is negative.
5675 const bool forever = repeat < 0;
5676 for (int i = 0; forever || i != repeat; i++) {
5677 // We want to preserve failures generated by ad-hoc test
5678 // assertions executed before RUN_ALL_TESTS().
5679 ClearNonAdHocTestResult();
5681 const TimeInMillis start = GetTimeInMillis();
5683 // Shuffles test cases and tests if requested.
5684 if (has_tests_to_run && GTEST_FLAG(shuffle)) {
5685 random()->Reseed(random_seed_);
5686 // This should be done before calling OnTestIterationStart(),
5687 // such that a test event listener can see the actual test order
5692 // Tells the unit test event listeners that the tests are about to start.
5693 repeater->OnTestIterationStart(*parent_, i);
5695 // Runs each test case if there is at least one test to run.
5696 if (has_tests_to_run) {
5697 // Sets up all environments beforehand.
5698 repeater->OnEnvironmentsSetUpStart(*parent_);
5699 ForEach(environments_, SetUpEnvironment);
5700 repeater->OnEnvironmentsSetUpEnd(*parent_);
5702 // Runs the tests only if there was no fatal failure during global
5704 if (!Test::HasFatalFailure()) {
5705 for (int test_index = 0; test_index < total_test_case_count();
5707 GetMutableTestCase(test_index)->Run();
5711 // Tears down all environments in reverse order afterwards.
5712 repeater->OnEnvironmentsTearDownStart(*parent_);
5713 std::for_each(environments_.rbegin(), environments_.rend(),
5714 TearDownEnvironment);
5715 repeater->OnEnvironmentsTearDownEnd(*parent_);
5718 elapsed_time_ = GetTimeInMillis() - start;
5720 // Tells the unit test event listener that the tests have just finished.
5721 repeater->OnTestIterationEnd(*parent_, i);
5723 // Gets the result and clears it.
5728 // Restores the original test order after the iteration. This
5729 // allows the user to quickly repro a failure that happens in the
5730 // N-th iteration without repeating the first (N - 1) iterations.
5731 // This is not enclosed in "if (GTEST_FLAG(shuffle)) { ... }", in
5732 // case the user somehow changes the value of the flag somewhere
5733 // (it's always safe to unshuffle the tests).
5736 if (GTEST_FLAG(shuffle)) {
5737 // Picks a new random seed for each iteration.
5738 random_seed_ = GetNextRandomSeed(random_seed_);
5742 repeater->OnTestProgramEnd(*parent_);
5747 // Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
5748 // if the variable is present. If a file already exists at this location, this
5749 // function will write over it. If the variable is present, but the file cannot
5750 // be created, prints an error and exits.
5751 void WriteToShardStatusFileIfNeeded() {
5752 const char* const test_shard_file = posix::GetEnv(kTestShardStatusFile);
5753 if (test_shard_file != NULL) {
5754 FILE* const file = posix::FOpen(test_shard_file, "w");
5756 ColoredPrintf(COLOR_RED,
5757 "Could not write to the test shard status file \"%s\" "
5758 "specified by the %s environment variable.\n",
5759 test_shard_file, kTestShardStatusFile);
5767 // Checks whether sharding is enabled by examining the relevant
5768 // environment variable values. If the variables are present,
5769 // but inconsistent (i.e., shard_index >= total_shards), prints
5770 // an error and exits. If in_subprocess_for_death_test, sharding is
5771 // disabled because it must only be applied to the original test
5772 // process. Otherwise, we could filter out death tests we intended to execute.
5773 bool ShouldShard(const char* total_shards_env,
5774 const char* shard_index_env,
5775 bool in_subprocess_for_death_test) {
5776 if (in_subprocess_for_death_test) {
5780 const Int32 total_shards = Int32FromEnvOrDie(total_shards_env, -1);
5781 const Int32 shard_index = Int32FromEnvOrDie(shard_index_env, -1);
5783 if (total_shards == -1 && shard_index == -1) {
5785 } else if (total_shards == -1 && shard_index != -1) {
5786 const Message msg = Message()
5787 << "Invalid environment variables: you have "
5788 << kTestShardIndex << " = " << shard_index
5789 << ", but have left " << kTestTotalShards << " unset.\n";
5790 ColoredPrintf(COLOR_RED, msg.GetString().c_str());
5793 } else if (total_shards != -1 && shard_index == -1) {
5794 const Message msg = Message()
5795 << "Invalid environment variables: you have "
5796 << kTestTotalShards << " = " << total_shards
5797 << ", but have left " << kTestShardIndex << " unset.\n";
5798 ColoredPrintf(COLOR_RED, msg.GetString().c_str());
5801 } else if (shard_index < 0 || shard_index >= total_shards) {
5802 const Message msg = Message()
5803 << "Invalid environment variables: we require 0 <= "
5804 << kTestShardIndex << " < " << kTestTotalShards
5805 << ", but you have " << kTestShardIndex << "=" << shard_index
5806 << ", " << kTestTotalShards << "=" << total_shards << ".\n";
5807 ColoredPrintf(COLOR_RED, msg.GetString().c_str());
5812 return total_shards > 1;
5815 // Parses the environment variable var as an Int32. If it is unset,
5816 // returns default_val. If it is not an Int32, prints an error
5818 Int32 Int32FromEnvOrDie(const char* var, Int32 default_val) {
5819 const char* str_val = posix::GetEnv(var);
5820 if (str_val == NULL) {
5825 if (!ParseInt32(Message() << "The value of environment variable " << var,
5826 str_val, &result)) {
5832 // Given the total number of shards, the shard index, and the test id,
5833 // returns true iff the test should be run on this shard. The test id is
5834 // some arbitrary but unique non-negative integer assigned to each test
5835 // method. Assumes that 0 <= shard_index < total_shards.
5836 bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) {
5837 return (test_id % total_shards) == shard_index;
5840 // Compares the name of each test with the user-specified filter to
5841 // decide whether the test should be run, then records the result in
5842 // each TestCase and TestInfo object.
5843 // If shard_tests == true, further filters tests based on sharding
5844 // variables in the environment - see
5845 // http://code.google.com/p/googletest/wiki/GoogleTestAdvancedGuide.
5846 // Returns the number of tests that should run.
5847 int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) {
5848 const Int32 total_shards = shard_tests == HONOR_SHARDING_PROTOCOL ?
5849 Int32FromEnvOrDie(kTestTotalShards, -1) : -1;
5850 const Int32 shard_index = shard_tests == HONOR_SHARDING_PROTOCOL ?
5851 Int32FromEnvOrDie(kTestShardIndex, -1) : -1;
5853 // num_runnable_tests are the number of tests that will
5854 // run across all shards (i.e., match filter and are not disabled).
5855 // num_selected_tests are the number of tests to be run on
5857 int num_runnable_tests = 0;
5858 int num_selected_tests = 0;
5859 for (size_t i = 0; i < test_cases_.size(); i++) {
5860 TestCase* const test_case = test_cases_[i];
5861 const std::string &test_case_name = test_case->name();
5862 test_case->set_should_run(false);
5864 for (size_t j = 0; j < test_case->test_info_list().size(); j++) {
5865 TestInfo* const test_info = test_case->test_info_list()[j];
5866 const std::string test_name(test_info->name());
5867 // A test is disabled if test case name or test name matches
5868 // kDisableTestFilter.
5869 const bool is_disabled =
5870 internal::UnitTestOptions::MatchesFilter(test_case_name,
5871 kDisableTestFilter) ||
5872 internal::UnitTestOptions::MatchesFilter(test_name,
5873 kDisableTestFilter);
5874 test_info->is_disabled_ = is_disabled;
5876 const bool matches_filter =
5877 internal::UnitTestOptions::FilterMatchesTest(test_case_name,
5879 test_info->matches_filter_ = matches_filter;
5881 const bool is_runnable =
5882 (GTEST_FLAG(also_run_disabled_tests) || !is_disabled) &&
5885 const bool is_selected = is_runnable &&
5886 (shard_tests == IGNORE_SHARDING_PROTOCOL ||
5887 ShouldRunTestOnShard(total_shards, shard_index,
5888 num_runnable_tests));
5890 num_runnable_tests += is_runnable;
5891 num_selected_tests += is_selected;
5893 test_info->should_run_ = is_selected;
5894 test_case->set_should_run(test_case->should_run() || is_selected);
5897 return num_selected_tests;
5900 // Prints the given C-string on a single line by replacing all '\n'
5901 // characters with string "\\n". If the output takes more than
5902 // max_length characters, only prints the first max_length characters
5904 static void PrintOnOneLine(const char* str, int max_length) {
5906 for (int i = 0; *str != '\0'; ++str) {
5907 if (i >= max_length) {
5922 // Prints the names of the tests matching the user-specified filter flag.
5923 void UnitTestImpl::ListTestsMatchingFilter() {
5924 // Print at most this many characters for each type/value parameter.
5925 const int kMaxParamLength = 250;
5927 for (size_t i = 0; i < test_cases_.size(); i++) {
5928 const TestCase* const test_case = test_cases_[i];
5929 bool printed_test_case_name = false;
5931 for (size_t j = 0; j < test_case->test_info_list().size(); j++) {
5932 const TestInfo* const test_info =
5933 test_case->test_info_list()[j];
5934 if (test_info->matches_filter_) {
5935 if (!printed_test_case_name) {
5936 printed_test_case_name = true;
5937 printf("%s.", test_case->name());
5938 if (test_case->type_param() != NULL) {
5939 printf(" # %s = ", kTypeParamLabel);
5940 // We print the type parameter on a single line to make
5941 // the output easy to parse by a program.
5942 PrintOnOneLine(test_case->type_param(), kMaxParamLength);
5946 printf(" %s", test_info->name());
5947 if (test_info->value_param() != NULL) {
5948 printf(" # %s = ", kValueParamLabel);
5949 // We print the value parameter on a single line to make the
5950 // output easy to parse by a program.
5951 PrintOnOneLine(test_info->value_param(), kMaxParamLength);
5960 // Sets the OS stack trace getter.
5962 // Does nothing if the input and the current OS stack trace getter are
5963 // the same; otherwise, deletes the old getter and makes the input the
5965 void UnitTestImpl::set_os_stack_trace_getter(
5966 OsStackTraceGetterInterface* getter) {
5967 if (os_stack_trace_getter_ != getter) {
5968 delete os_stack_trace_getter_;
5969 os_stack_trace_getter_ = getter;
5973 // Returns the current OS stack trace getter if it is not NULL;
5974 // otherwise, creates an OsStackTraceGetter, makes it the current
5975 // getter, and returns it.
5976 OsStackTraceGetterInterface* UnitTestImpl::os_stack_trace_getter() {
5977 if (os_stack_trace_getter_ == NULL) {
5978 os_stack_trace_getter_ = new OsStackTraceGetter;
5981 return os_stack_trace_getter_;
5984 // Returns the TestResult for the test that's currently running, or
5985 // the TestResult for the ad hoc test if no test is running.
5986 TestResult* UnitTestImpl::current_test_result() {
5987 return current_test_info_ ?
5988 &(current_test_info_->result_) : &ad_hoc_test_result_;
5991 // Shuffles all test cases, and the tests within each test case,
5992 // making sure that death tests are still run first.
5993 void UnitTestImpl::ShuffleTests() {
5994 // Shuffles the death test cases.
5995 ShuffleRange(random(), 0, last_death_test_case_ + 1, &test_case_indices_);
5997 // Shuffles the non-death test cases.
5998 ShuffleRange(random(), last_death_test_case_ + 1,
5999 static_cast<int>(test_cases_.size()), &test_case_indices_);
6001 // Shuffles the tests inside each test case.
6002 for (size_t i = 0; i < test_cases_.size(); i++) {
6003 test_cases_[i]->ShuffleTests(random());
6007 // Restores the test cases and tests to their order before the first shuffle.
6008 void UnitTestImpl::UnshuffleTests() {
6009 for (size_t i = 0; i < test_cases_.size(); i++) {
6010 // Unshuffles the tests in each test case.
6011 test_cases_[i]->UnshuffleTests();
6012 // Resets the index of each test case.
6013 test_case_indices_[i] = static_cast<int>(i);
6017 // Returns the current OS stack trace as an std::string.
6019 // The maximum number of stack frames to be included is specified by
6020 // the gtest_stack_trace_depth flag. The skip_count parameter
6021 // specifies the number of top frames to be skipped, which doesn't
6022 // count against the number of frames to be included.
6024 // For example, if Foo() calls Bar(), which in turn calls
6025 // GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in
6026 // the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.
6027 std::string GetCurrentOsStackTraceExceptTop(UnitTest* /*unit_test*/,
6029 // We pass skip_count + 1 to skip this wrapper function in addition
6030 // to what the user really wants to skip.
6031 return GetUnitTestImpl()->CurrentOsStackTraceExceptTop(skip_count + 1);
6034 // Used by the GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_ macro to
6035 // suppress unreachable code warnings.
6037 class ClassUniqueToAlwaysTrue {};
6040 bool IsTrue(bool condition) { return condition; }
6043 #if GTEST_HAS_EXCEPTIONS
6044 // This condition is always false so AlwaysTrue() never actually throws,
6045 // but it makes the compiler think that it may throw.
6047 throw ClassUniqueToAlwaysTrue();
6048 #endif // GTEST_HAS_EXCEPTIONS
6052 // If *pstr starts with the given prefix, modifies *pstr to be right
6053 // past the prefix and returns true; otherwise leaves *pstr unchanged
6054 // and returns false. None of pstr, *pstr, and prefix can be NULL.
6055 bool SkipPrefix(const char* prefix, const char** pstr) {
6056 const size_t prefix_len = strlen(prefix);
6057 if (strncmp(*pstr, prefix, prefix_len) == 0) {
6058 *pstr += prefix_len;
6064 // Parses a string as a command line flag. The string should have
6065 // the format "--flag=value". When def_optional is true, the "=value"
6066 // part can be omitted.
6068 // Returns the value of the flag, or NULL if the parsing failed.
6069 static const char* ParseFlagValue(const char* str,
6071 bool def_optional) {
6072 // str and flag must not be NULL.
6073 if (str == NULL || flag == NULL) return NULL;
6075 // The flag must start with "--" followed by GTEST_FLAG_PREFIX_.
6076 const std::string flag_str = std::string("--") + GTEST_FLAG_PREFIX_ + flag;
6077 const size_t flag_len = flag_str.length();
6078 if (strncmp(str, flag_str.c_str(), flag_len) != 0) return NULL;
6080 // Skips the flag name.
6081 const char* flag_end = str + flag_len;
6083 // When def_optional is true, it's OK to not have a "=value" part.
6084 if (def_optional && (flag_end[0] == '\0')) {
6088 // If def_optional is true and there are more characters after the
6089 // flag name, or if def_optional is false, there must be a '=' after
6091 if (flag_end[0] != '=') return NULL;
6093 // Returns the string after "=".
6094 return flag_end + 1;
6097 // Parses a string for a bool flag, in the form of either
6098 // "--flag=value" or "--flag".
6100 // In the former case, the value is taken as true as long as it does
6101 // not start with '0', 'f', or 'F'.
6103 // In the latter case, the value is taken as true.
6105 // On success, stores the value of the flag in *value, and returns
6106 // true. On failure, returns false without changing *value.
6107 static bool ParseBoolFlag(const char* str, const char* flag, bool* value) {
6108 // Gets the value of the flag as a string.
6109 const char* const value_str = ParseFlagValue(str, flag, true);
6111 // Aborts if the parsing failed.
6112 if (value_str == NULL) return false;
6114 // Converts the string value to a bool.
6115 *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F');
6119 // Parses a string for an Int32 flag, in the form of
6122 // On success, stores the value of the flag in *value, and returns
6123 // true. On failure, returns false without changing *value.
6124 bool ParseInt32Flag(const char* str, const char* flag, Int32* value) {
6125 // Gets the value of the flag as a string.
6126 const char* const value_str = ParseFlagValue(str, flag, false);
6128 // Aborts if the parsing failed.
6129 if (value_str == NULL) return false;
6131 // Sets *value to the value of the flag.
6132 return ParseInt32(Message() << "The value of flag --" << flag,
6136 // Parses a string for a string flag, in the form of
6139 // On success, stores the value of the flag in *value, and returns
6140 // true. On failure, returns false without changing *value.
6141 static bool ParseStringFlag(const char* str, const char* flag, std::string* value) {
6142 // Gets the value of the flag as a string.
6143 const char* const value_str = ParseFlagValue(str, flag, false);
6145 // Aborts if the parsing failed.
6146 if (value_str == NULL) return false;
6148 // Sets *value to the value of the flag.
6153 // Determines whether a string has a prefix that Google Test uses for its
6154 // flags, i.e., starts with GTEST_FLAG_PREFIX_ or GTEST_FLAG_PREFIX_DASH_.
6155 // If Google Test detects that a command line flag has its prefix but is not
6156 // recognized, it will print its help message. Flags starting with
6157 // GTEST_INTERNAL_PREFIX_ followed by "internal_" are considered Google Test
6158 // internal flags and do not trigger the help message.
6159 static bool HasGoogleTestFlagPrefix(const char* str) {
6160 return (SkipPrefix("--", &str) ||
6161 SkipPrefix("-", &str) ||
6162 SkipPrefix("/", &str)) &&
6163 !SkipPrefix(GTEST_FLAG_PREFIX_ "internal_", &str) &&
6164 (SkipPrefix(GTEST_FLAG_PREFIX_, &str) ||
6165 SkipPrefix(GTEST_FLAG_PREFIX_DASH_, &str));
6168 // Prints a string containing code-encoded text. The following escape
6169 // sequences can be used in the string to control the text color:
6171 // @@ prints a single '@' character.
6172 // @R changes the color to red.
6173 // @G changes the color to green.
6174 // @Y changes the color to yellow.
6175 // @D changes to the default terminal text color.
6177 // TODO(wan@google.com): Write tests for this once we add stdout
6178 // capturing to Google Test.
6179 static void PrintColorEncoded(const char* str) {
6180 GTestColor color = COLOR_DEFAULT; // The current color.
6182 // Conceptually, we split the string into segments divided by escape
6183 // sequences. Then we print one segment at a time. At the end of
6184 // each iteration, the str pointer advances to the beginning of the
6187 const char* p = strchr(str, '@');
6189 ColoredPrintf(color, "%s", str);
6193 ColoredPrintf(color, "%s", std::string(str, p).c_str());
6195 const char ch = p[1];
6198 ColoredPrintf(color, "@");
6199 } else if (ch == 'D') {
6200 color = COLOR_DEFAULT;
6201 } else if (ch == 'R') {
6203 } else if (ch == 'G') {
6204 color = COLOR_GREEN;
6205 } else if (ch == 'Y') {
6206 color = COLOR_YELLOW;
6213 static const char kColorEncodedHelpMessage[] =
6214 "This program contains tests written using " GTEST_NAME_ ". You can use the\n"
6215 "following command line flags to control its behavior:\n"
6218 " @G--" GTEST_FLAG_PREFIX_ "list_tests@D\n"
6219 " List the names of all tests instead of running them. The name of\n"
6220 " TEST(Foo, Bar) is \"Foo.Bar\".\n"
6221 " @G--" GTEST_FLAG_PREFIX_ "filter=@YPOSTIVE_PATTERNS"
6222 "[@G-@YNEGATIVE_PATTERNS]@D\n"
6223 " Run only the tests whose name matches one of the positive patterns but\n"
6224 " none of the negative patterns. '?' matches any single character; '*'\n"
6225 " matches any substring; ':' separates two patterns.\n"
6226 " @G--" GTEST_FLAG_PREFIX_ "also_run_disabled_tests@D\n"
6227 " Run all disabled tests too.\n"
6230 " @G--" GTEST_FLAG_PREFIX_ "repeat=@Y[COUNT]@D\n"
6231 " Run the tests repeatedly; use a negative count to repeat forever.\n"
6232 " @G--" GTEST_FLAG_PREFIX_ "shuffle@D\n"
6233 " Randomize tests' orders on every iteration.\n"
6234 " @G--" GTEST_FLAG_PREFIX_ "random_seed=@Y[NUMBER]@D\n"
6235 " Random number seed to use for shuffling test orders (between 1 and\n"
6236 " 99999, or 0 to use a seed based on the current time).\n"
6239 " @G--" GTEST_FLAG_PREFIX_ "color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\n"
6240 " Enable/disable colored output. The default is @Gauto@D.\n"
6241 " -@G-" GTEST_FLAG_PREFIX_ "print_time=0@D\n"
6242 " Don't print the elapsed time of each test.\n"
6243 " @G--" GTEST_FLAG_PREFIX_ "output=xml@Y[@G:@YDIRECTORY_PATH@G"
6244 GTEST_PATH_SEP_ "@Y|@G:@YFILE_PATH]@D\n"
6245 " Generate an XML report in the given directory or with the given file\n"
6246 " name. @YFILE_PATH@D defaults to @Gtest_details.xml@D.\n"
6247 #if GTEST_CAN_STREAM_RESULTS_
6248 " @G--" GTEST_FLAG_PREFIX_ "stream_result_to=@YHOST@G:@YPORT@D\n"
6249 " Stream test results to the given server.\n"
6250 #endif // GTEST_CAN_STREAM_RESULTS_
6252 "Assertion Behavior:\n"
6253 #if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
6254 " @G--" GTEST_FLAG_PREFIX_ "death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n"
6255 " Set the default death test style.\n"
6256 #endif // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
6257 " @G--" GTEST_FLAG_PREFIX_ "break_on_failure@D\n"
6258 " Turn assertion failures into debugger break-points.\n"
6259 " @G--" GTEST_FLAG_PREFIX_ "throw_on_failure@D\n"
6260 " Turn assertion failures into C++ exceptions.\n"
6261 " @G--" GTEST_FLAG_PREFIX_ "catch_exceptions=0@D\n"
6262 " Do not report exceptions as test failures. Instead, allow them\n"
6263 " to crash the program or throw a pop-up (on Windows).\n"
6265 "Except for @G--" GTEST_FLAG_PREFIX_ "list_tests@D, you can alternatively set "
6266 "the corresponding\n"
6267 "environment variable of a flag (all letters in upper-case). For example, to\n"
6268 "disable colored text output, you can either specify @G--" GTEST_FLAG_PREFIX_
6269 "color=no@D or set\n"
6270 "the @G" GTEST_FLAG_PREFIX_UPPER_ "COLOR@D environment variable to @Gno@D.\n"
6272 "For more information, please read the " GTEST_NAME_ " documentation at\n"
6273 "@G" GTEST_PROJECT_URL_ "@D. If you find a bug in " GTEST_NAME_ "\n"
6274 "(not one in your own code or tests), please report it to\n"
6275 "@G<" GTEST_DEV_EMAIL_ ">@D.\n";
6277 // Parses the command line for Google Test flags, without initializing
6278 // other parts of Google Test. The type parameter CharType can be
6279 // instantiated to either char or wchar_t.
6280 template <typename CharType>
6281 void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) {
6282 for (int i = 1; i < *argc; i++) {
6283 const std::string arg_string = StreamableToString(argv[i]);
6284 const char* const arg = arg_string.c_str();
6286 using internal::ParseBoolFlag;
6287 using internal::ParseInt32Flag;
6288 using internal::ParseStringFlag;
6290 // Do we see a Google Test flag?
6291 if (ParseBoolFlag(arg, kAlsoRunDisabledTestsFlag,
6292 >EST_FLAG(also_run_disabled_tests)) ||
6293 ParseBoolFlag(arg, kBreakOnFailureFlag,
6294 >EST_FLAG(break_on_failure)) ||
6295 ParseBoolFlag(arg, kCatchExceptionsFlag,
6296 >EST_FLAG(catch_exceptions)) ||
6297 ParseStringFlag(arg, kColorFlag, >EST_FLAG(color)) ||
6298 ParseStringFlag(arg, kDeathTestStyleFlag,
6299 >EST_FLAG(death_test_style)) ||
6300 ParseBoolFlag(arg, kDeathTestUseFork,
6301 >EST_FLAG(death_test_use_fork)) ||
6302 ParseStringFlag(arg, kFilterFlag, >EST_FLAG(filter)) ||
6303 ParseStringFlag(arg, kInternalRunDeathTestFlag,
6304 >EST_FLAG(internal_run_death_test)) ||
6305 ParseBoolFlag(arg, kListTestsFlag, >EST_FLAG(list_tests)) ||
6306 ParseStringFlag(arg, kOutputFlag, >EST_FLAG(output)) ||
6307 ParseBoolFlag(arg, kPrintTimeFlag, >EST_FLAG(print_time)) ||
6308 ParseInt32Flag(arg, kRandomSeedFlag, >EST_FLAG(random_seed)) ||
6309 ParseInt32Flag(arg, kRepeatFlag, >EST_FLAG(repeat)) ||
6310 ParseBoolFlag(arg, kShuffleFlag, >EST_FLAG(shuffle)) ||
6311 ParseInt32Flag(arg, kStackTraceDepthFlag,
6312 >EST_FLAG(stack_trace_depth)) ||
6313 ParseStringFlag(arg, kStreamResultToFlag,
6314 >EST_FLAG(stream_result_to)) ||
6315 ParseBoolFlag(arg, kThrowOnFailureFlag,
6316 >EST_FLAG(throw_on_failure))
6318 // Yes. Shift the remainder of the argv list left by one. Note
6319 // that argv has (*argc + 1) elements, the last one always being
6320 // NULL. The following loop moves the trailing NULL element as
6322 for (int j = i; j != *argc; j++) {
6323 argv[j] = argv[j + 1];
6326 // Decrements the argument count.
6329 // We also need to decrement the iterator as we just removed
6332 } else if (arg_string == "--help" || arg_string == "-h" ||
6333 arg_string == "-?" || arg_string == "/?" ||
6334 HasGoogleTestFlagPrefix(arg)) {
6335 // Both help flag and unrecognized Google Test flags (excluding
6336 // internal ones) trigger help display.
6342 // We print the help here instead of in RUN_ALL_TESTS(), as the
6343 // latter may not be called at all if the user is using Google
6344 // Test with another testing framework.
6345 PrintColorEncoded(kColorEncodedHelpMessage);
6349 // Parses the command line for Google Test flags, without initializing
6350 // other parts of Google Test.
6351 void ParseGoogleTestFlagsOnly(int* argc, char** argv) {
6352 ParseGoogleTestFlagsOnlyImpl(argc, argv);
6354 void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv) {
6355 ParseGoogleTestFlagsOnlyImpl(argc, argv);
6358 // The internal implementation of InitGoogleTest().
6360 // The type parameter CharType can be instantiated to either char or
6362 template <typename CharType>
6363 void InitGoogleTestImpl(int* argc, CharType** argv) {
6364 g_init_gtest_count++;
6366 // We don't want to run the initialization code twice.
6367 if (g_init_gtest_count != 1) return;
6369 if (*argc <= 0) return;
6371 internal::g_executable_path = internal::StreamableToString(argv[0]);
6373 #if GTEST_HAS_DEATH_TEST
6376 for (int i = 0; i != *argc; i++) {
6377 g_argvs.push_back(StreamableToString(argv[i]));
6380 #endif // GTEST_HAS_DEATH_TEST
6382 ParseGoogleTestFlagsOnly(argc, argv);
6383 GetUnitTestImpl()->PostFlagParsingInit();
6386 } // namespace internal
6388 // Initializes Google Test. This must be called before calling
6389 // RUN_ALL_TESTS(). In particular, it parses a command line for the
6390 // flags that Google Test recognizes. Whenever a Google Test flag is
6391 // seen, it is removed from argv, and *argc is decremented.
6393 // No value is returned. Instead, the Google Test flag variables are
6396 // Calling the function for the second time has no user-visible effect.
6397 void InitGoogleTest(int* argc, char** argv) {
6398 internal::InitGoogleTestImpl(argc, argv);
6401 // This overloaded version can be used in Windows programs compiled in
6403 void InitGoogleTest(int* argc, wchar_t** argv) {
6404 internal::InitGoogleTestImpl(argc, argv);
6407 } // namespace testing
6408 // Copyright 2005, Google Inc.
6409 // All rights reserved.
6411 // Redistribution and use in source and binary forms, with or without
6412 // modification, are permitted provided that the following conditions are
6415 // * Redistributions of source code must retain the above copyright
6416 // notice, this list of conditions and the following disclaimer.
6417 // * Redistributions in binary form must reproduce the above
6418 // copyright notice, this list of conditions and the following disclaimer
6419 // in the documentation and/or other materials provided with the
6421 // * Neither the name of Google Inc. nor the names of its
6422 // contributors may be used to endorse or promote products derived from
6423 // this software without specific prior written permission.
6425 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
6426 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
6427 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
6428 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
6429 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
6430 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
6431 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
6432 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
6433 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
6434 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
6435 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
6437 // Author: wan@google.com (Zhanyong Wan), vladl@google.com (Vlad Losev)
6439 // This file implements death tests.
6442 #if GTEST_HAS_DEATH_TEST
6445 # include <crt_externs.h>
6446 # endif // GTEST_OS_MAC
6450 # include <limits.h>
6453 # include <signal.h>
6454 # endif // GTEST_OS_LINUX
6456 # include <stdarg.h>
6458 # if GTEST_OS_WINDOWS
6459 # include <windows.h>
6461 # include <sys/mman.h>
6462 # include <sys/wait.h>
6463 # endif // GTEST_OS_WINDOWS
6467 # endif // GTEST_OS_QNX
6469 #endif // GTEST_HAS_DEATH_TEST
6472 // Indicates that this translation unit is part of Google Test's
6473 // implementation. It must come before gtest-internal-inl.h is
6474 // included, or there will be a compiler error. This trick is to
6475 // prevent a user from accidentally including gtest-internal-inl.h in
6477 #define GTEST_IMPLEMENTATION_ 1
6478 #undef GTEST_IMPLEMENTATION_
6484 // The default death test style.
6485 static const char kDefaultDeathTestStyle[] = "fast";
6487 GTEST_DEFINE_string_(
6489 internal::StringFromGTestEnv("death_test_style", kDefaultDeathTestStyle),
6490 "Indicates how to run a death test in a forked child process: "
6491 "\"threadsafe\" (child process re-executes the test binary "
6492 "from the beginning, running only the specific death test) or "
6493 "\"fast\" (child process runs the death test immediately "
6497 death_test_use_fork,
6498 internal::BoolFromGTestEnv("death_test_use_fork", false),
6499 "Instructs to use fork()/_exit() instead of clone() in death tests. "
6500 "Ignored and always uses fork() on POSIX systems where clone() is not "
6501 "implemented. Useful when running under valgrind or similar tools if "
6502 "those do not support clone(). Valgrind 3.3.1 will just fail if "
6503 "it sees an unsupported combination of clone() flags. "
6504 "It is not recommended to use this flag w/o valgrind though it will "
6505 "work in 99% of the cases. Once valgrind is fixed, this flag will "
6506 "most likely be removed.");
6508 namespace internal {
6509 GTEST_DEFINE_string_(
6510 internal_run_death_test, "",
6511 "Indicates the file, line number, temporal index of "
6512 "the single death test to run, and a file descriptor to "
6513 "which a success code may be sent, all separated by "
6514 "the '|' characters. This flag is specified if and only if the current "
6515 "process is a sub-process launched for running a thread-safe "
6516 "death test. FOR INTERNAL USE ONLY.");
6517 } // namespace internal
6519 #if GTEST_HAS_DEATH_TEST
6521 namespace internal {
6523 // Valid only for fast death tests. Indicates the code is running in the
6524 // child process of a fast style death test.
6525 # if !GTEST_OS_WINDOWS
6526 static bool g_in_fast_death_test_child = false;
6529 // Returns a Boolean value indicating whether the caller is currently
6530 // executing in the context of the death test child process. Tools such as
6531 // Valgrind heap checkers may need this to modify their behavior in death
6532 // tests. IMPORTANT: This is an internal utility. Using it may break the
6533 // implementation of death tests. User code MUST NOT use it.
6534 bool InDeathTestChild() {
6535 # if GTEST_OS_WINDOWS
6537 // On Windows, death tests are thread-safe regardless of the value of the
6538 // death_test_style flag.
6539 return !GTEST_FLAG(internal_run_death_test).empty();
6543 if (GTEST_FLAG(death_test_style) == "threadsafe")
6544 return !GTEST_FLAG(internal_run_death_test).empty();
6546 return g_in_fast_death_test_child;
6550 } // namespace internal
6552 // ExitedWithCode constructor.
6553 ExitedWithCode::ExitedWithCode(int exit_code) : exit_code_(exit_code) {
6556 // ExitedWithCode function-call operator.
6557 bool ExitedWithCode::operator()(int exit_status) const {
6558 # if GTEST_OS_WINDOWS
6560 return exit_status == exit_code_;
6564 return WIFEXITED(exit_status) && WEXITSTATUS(exit_status) == exit_code_;
6566 # endif // GTEST_OS_WINDOWS
6569 # if !GTEST_OS_WINDOWS
6570 // KilledBySignal constructor.
6571 KilledBySignal::KilledBySignal(int signum) : signum_(signum) {
6574 // KilledBySignal function-call operator.
6575 bool KilledBySignal::operator()(int exit_status) const {
6576 return WIFSIGNALED(exit_status) && WTERMSIG(exit_status) == signum_;
6578 # endif // !GTEST_OS_WINDOWS
6580 namespace internal {
6582 // Utilities needed for death tests.
6584 // Generates a textual description of a given exit code, in the format
6585 // specified by wait(2).
6586 static std::string ExitSummary(int exit_code) {
6589 # if GTEST_OS_WINDOWS
6591 m << "Exited with exit status " << exit_code;
6595 if (WIFEXITED(exit_code)) {
6596 m << "Exited with exit status " << WEXITSTATUS(exit_code);
6597 } else if (WIFSIGNALED(exit_code)) {
6598 m << "Terminated by signal " << WTERMSIG(exit_code);
6601 if (WCOREDUMP(exit_code)) {
6602 m << " (core dumped)";
6605 # endif // GTEST_OS_WINDOWS
6607 return m.GetString();
6610 // Returns true if exit_status describes a process that was terminated
6611 // by a signal, or exited normally with a nonzero exit code.
6612 bool ExitedUnsuccessfully(int exit_status) {
6613 return !ExitedWithCode(0)(exit_status);
6616 # if !GTEST_OS_WINDOWS
6617 // Generates a textual failure message when a death test finds more than
6618 // one thread running, or cannot determine the number of threads, prior
6619 // to executing the given statement. It is the responsibility of the
6620 // caller not to pass a thread_count of 1.
6621 static std::string DeathTestThreadWarning(size_t thread_count) {
6623 msg << "Death tests use fork(), which is unsafe particularly"
6624 << " in a threaded context. For this test, " << GTEST_NAME_ << " ";
6625 if (thread_count == 0)
6626 msg << "couldn't detect the number of threads.";
6628 msg << "detected " << thread_count << " threads.";
6629 return msg.GetString();
6631 # endif // !GTEST_OS_WINDOWS
6633 // Flag characters for reporting a death test that did not die.
6634 static const char kDeathTestLived = 'L';
6635 static const char kDeathTestReturned = 'R';
6636 static const char kDeathTestThrew = 'T';
6637 static const char kDeathTestInternalError = 'I';
6639 // An enumeration describing all of the possible ways that a death test can
6640 // conclude. DIED means that the process died while executing the test
6641 // code; LIVED means that process lived beyond the end of the test code;
6642 // RETURNED means that the test statement attempted to execute a return
6643 // statement, which is not allowed; THREW means that the test statement
6644 // returned control by throwing an exception. IN_PROGRESS means the test
6645 // has not yet concluded.
6646 // TODO(vladl@google.com): Unify names and possibly values for
6647 // AbortReason, DeathTestOutcome, and flag characters above.
6648 enum DeathTestOutcome { IN_PROGRESS, DIED, LIVED, RETURNED, THREW };
6650 // Routine for aborting the program which is safe to call from an
6651 // exec-style death test child process, in which case the error
6652 // message is propagated back to the parent process. Otherwise, the
6653 // message is simply printed to stderr. In either case, the program
6654 // then exits with status 1.
6655 static void DeathTestAbort(const std::string& message) {
6656 // On a POSIX system, this function may be called from a threadsafe-style
6657 // death test child process, which operates on a very small stack. Use
6658 // the heap for any additional non-minuscule memory requirements.
6659 const InternalRunDeathTestFlag* const flag =
6660 GetUnitTestImpl()->internal_run_death_test_flag();
6662 FILE* parent = posix::FDOpen(flag->write_fd(), "w");
6663 fputc(kDeathTestInternalError, parent);
6664 fprintf(parent, "%s", message.c_str());
6668 fprintf(stderr, "%s", message.c_str());
6674 // A replacement for CHECK that calls DeathTestAbort if the assertion
6676 # define GTEST_DEATH_TEST_CHECK_(expression) \
6678 if (!::testing::internal::IsTrue(expression)) { \
6680 ::std::string("CHECK failed: File ") + __FILE__ + ", line " \
6681 + ::testing::internal::StreamableToString(__LINE__) + ": " \
6684 } while (::testing::internal::AlwaysFalse())
6686 // This macro is similar to GTEST_DEATH_TEST_CHECK_, but it is meant for
6687 // evaluating any system call that fulfills two conditions: it must return
6688 // -1 on failure, and set errno to EINTR when it is interrupted and
6689 // should be tried again. The macro expands to a loop that repeatedly
6690 // evaluates the expression as long as it evaluates to -1 and sets
6691 // errno to EINTR. If the expression evaluates to -1 but errno is
6692 // something other than EINTR, DeathTestAbort is called.
6693 # define GTEST_DEATH_TEST_CHECK_SYSCALL_(expression) \
6697 gtest_retval = (expression); \
6698 } while (gtest_retval == -1 && errno == EINTR); \
6699 if (gtest_retval == -1) { \
6701 ::std::string("CHECK failed: File ") + __FILE__ + ", line " \
6702 + ::testing::internal::StreamableToString(__LINE__) + ": " \
6703 + #expression + " != -1"); \
6705 } while (::testing::internal::AlwaysFalse())
6707 // Returns the message describing the last system error in errno.
6708 std::string GetLastErrnoDescription() {
6709 return errno == 0 ? "" : posix::StrError(errno);
6712 // This is called from a death test parent process to read a failure
6713 // message from the death test child process and log it with the FATAL
6714 // severity. On Windows, the message is read from a pipe handle. On other
6715 // platforms, it is read from a file descriptor.
6716 static void FailFromInternalError(int fd) {
6722 while ((num_read = posix::Read(fd, buffer, 255)) > 0) {
6723 buffer[num_read] = '\0';
6726 } while (num_read == -1 && errno == EINTR);
6728 if (num_read == 0) {
6729 GTEST_LOG_(FATAL) << error.GetString();
6731 const int last_error = errno;
6732 GTEST_LOG_(FATAL) << "Error while reading death test internal: "
6733 << GetLastErrnoDescription() << " [" << last_error << "]";
6737 // Death test constructor. Increments the running death test count
6738 // for the current test.
6739 DeathTest::DeathTest() {
6740 TestInfo* const info = GetUnitTestImpl()->current_test_info();
6742 DeathTestAbort("Cannot run a death test outside of a TEST or "
6743 "TEST_F construct");
6747 // Creates and returns a death test by dispatching to the current
6748 // death test factory.
6749 bool DeathTest::Create(const char* statement, const RE* regex,
6750 const char* file, int line, DeathTest** test) {
6751 return GetUnitTestImpl()->death_test_factory()->Create(
6752 statement, regex, file, line, test);
6755 const char* DeathTest::LastMessage() {
6756 return last_death_test_message_.c_str();
6759 void DeathTest::set_last_death_test_message(const std::string& message) {
6760 last_death_test_message_ = message;
6763 std::string DeathTest::last_death_test_message_;
6765 // Provides cross platform implementation for some death functionality.
6766 class DeathTestImpl : public DeathTest {
6768 DeathTestImpl(const char* a_statement, const RE* a_regex)
6769 : statement_(a_statement),
6773 outcome_(IN_PROGRESS),
6777 // read_fd_ is expected to be closed and cleared by a derived class.
6778 ~DeathTestImpl() { GTEST_DEATH_TEST_CHECK_(read_fd_ == -1); }
6780 void Abort(AbortReason reason);
6781 virtual bool Passed(bool status_ok);
6783 const char* statement() const { return statement_; }
6784 const RE* regex() const { return regex_; }
6785 bool spawned() const { return spawned_; }
6786 void set_spawned(bool is_spawned) { spawned_ = is_spawned; }
6787 int status() const { return status_; }
6788 void set_status(int a_status) { status_ = a_status; }
6789 DeathTestOutcome outcome() const { return outcome_; }
6790 void set_outcome(DeathTestOutcome an_outcome) { outcome_ = an_outcome; }
6791 int read_fd() const { return read_fd_; }
6792 void set_read_fd(int fd) { read_fd_ = fd; }
6793 int write_fd() const { return write_fd_; }
6794 void set_write_fd(int fd) { write_fd_ = fd; }
6796 // Called in the parent process only. Reads the result code of the death
6797 // test child process via a pipe, interprets it to set the outcome_
6798 // member, and closes read_fd_. Outputs diagnostics and terminates in
6799 // case of unexpected codes.
6800 void ReadAndInterpretStatusByte();
6803 // The textual content of the code this object is testing. This class
6804 // doesn't own this string and should not attempt to delete it.
6805 const char* const statement_;
6806 // The regular expression which test output must match. DeathTestImpl
6807 // doesn't own this object and should not attempt to delete it.
6808 const RE* const regex_;
6809 // True if the death test child process has been successfully spawned.
6811 // The exit status of the child process.
6813 // How the death test concluded.
6814 DeathTestOutcome outcome_;
6815 // Descriptor to the read end of the pipe to the child process. It is
6816 // always -1 in the child process. The child keeps its write end of the
6817 // pipe in write_fd_.
6819 // Descriptor to the child's write end of the pipe to the parent process.
6820 // It is always -1 in the parent process. The parent keeps its end of the
6821 // pipe in read_fd_.
6825 // Called in the parent process only. Reads the result code of the death
6826 // test child process via a pipe, interprets it to set the outcome_
6827 // member, and closes read_fd_. Outputs diagnostics and terminates in
6828 // case of unexpected codes.
6829 void DeathTestImpl::ReadAndInterpretStatusByte() {
6833 // The read() here blocks until data is available (signifying the
6834 // failure of the death test) or until the pipe is closed (signifying
6835 // its success), so it's okay to call this in the parent before
6836 // the child process has exited.
6838 bytes_read = posix::Read(read_fd(), &flag, 1);
6839 } while (bytes_read == -1 && errno == EINTR);
6841 if (bytes_read == 0) {
6843 } else if (bytes_read == 1) {
6845 case kDeathTestReturned:
6846 set_outcome(RETURNED);
6848 case kDeathTestThrew:
6851 case kDeathTestLived:
6854 case kDeathTestInternalError:
6855 FailFromInternalError(read_fd()); // Does not return.
6858 GTEST_LOG_(FATAL) << "Death test child process reported "
6859 << "unexpected status byte ("
6860 << static_cast<unsigned int>(flag) << ")";
6863 GTEST_LOG_(FATAL) << "Read from death test child process failed: "
6864 << GetLastErrnoDescription();
6866 GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Close(read_fd()));
6870 // Signals that the death test code which should have exited, didn't.
6871 // Should be called only in a death test child process.
6872 // Writes a status byte to the child's status file descriptor, then
6874 void DeathTestImpl::Abort(AbortReason reason) {
6875 // The parent process considers the death test to be a failure if
6876 // it finds any data in our pipe. So, here we write a single flag byte
6877 // to the pipe, then exit.
6878 const char status_ch =
6879 reason == TEST_DID_NOT_DIE ? kDeathTestLived :
6880 reason == TEST_THREW_EXCEPTION ? kDeathTestThrew : kDeathTestReturned;
6882 GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Write(write_fd(), &status_ch, 1));
6883 // We are leaking the descriptor here because on some platforms (i.e.,
6884 // when built as Windows DLL), destructors of global objects will still
6885 // run after calling _exit(). On such systems, write_fd_ will be
6886 // indirectly closed from the destructor of UnitTestImpl, causing double
6887 // close if it is also closed here. On debug configurations, double close
6888 // may assert. As there are no in-process buffers to flush here, we are
6889 // relying on the OS to close the descriptor after the process terminates
6890 // when the destructors are not run.
6891 _exit(1); // Exits w/o any normal exit hooks (we were supposed to crash)
6894 // Returns an indented copy of stderr output for a death test.
6895 // This makes distinguishing death test output lines from regular log lines
6897 static ::std::string FormatDeathTestOutput(const ::std::string& output) {
6899 for (size_t at = 0; ; ) {
6900 const size_t line_end = output.find('\n', at);
6901 ret += "[ DEATH ] ";
6902 if (line_end == ::std::string::npos) {
6903 ret += output.substr(at);
6906 ret += output.substr(at, line_end + 1 - at);
6912 // Assesses the success or failure of a death test, using both private
6913 // members which have previously been set, and one argument:
6915 // Private data members:
6916 // outcome: An enumeration describing how the death test
6917 // concluded: DIED, LIVED, THREW, or RETURNED. The death test
6918 // fails in the latter three cases.
6919 // status: The exit status of the child process. On *nix, it is in the
6920 // in the format specified by wait(2). On Windows, this is the
6921 // value supplied to the ExitProcess() API or a numeric code
6922 // of the exception that terminated the program.
6923 // regex: A regular expression object to be applied to
6924 // the test's captured standard error output; the death test
6925 // fails if it does not match.
6928 // status_ok: true if exit_status is acceptable in the context of
6929 // this particular death test, which fails if it is false
6931 // Returns true iff all of the above conditions are met. Otherwise, the
6932 // first failing condition, in the order given above, is the one that is
6933 // reported. Also sets the last death test message string.
6934 bool DeathTestImpl::Passed(bool status_ok) {
6938 const std::string error_message = GetCapturedStderr();
6940 bool success = false;
6943 buffer << "Death test: " << statement() << "\n";
6944 switch (outcome()) {
6946 buffer << " Result: failed to die.\n"
6947 << " Error msg:\n" << FormatDeathTestOutput(error_message);
6950 buffer << " Result: threw an exception.\n"
6951 << " Error msg:\n" << FormatDeathTestOutput(error_message);
6954 buffer << " Result: illegal return in test statement.\n"
6955 << " Error msg:\n" << FormatDeathTestOutput(error_message);
6959 const bool matched = RE::PartialMatch(error_message.c_str(), *regex());
6963 buffer << " Result: died but not with expected error.\n"
6964 << " Expected: " << regex()->pattern() << "\n"
6965 << "Actual msg:\n" << FormatDeathTestOutput(error_message);
6968 buffer << " Result: died but not with expected exit code:\n"
6969 << " " << ExitSummary(status()) << "\n"
6970 << "Actual msg:\n" << FormatDeathTestOutput(error_message);
6976 << "DeathTest::Passed somehow called before conclusion of test";
6979 DeathTest::set_last_death_test_message(buffer.GetString());
6983 # if GTEST_OS_WINDOWS
6984 // WindowsDeathTest implements death tests on Windows. Due to the
6985 // specifics of starting new processes on Windows, death tests there are
6986 // always threadsafe, and Google Test considers the
6987 // --gtest_death_test_style=fast setting to be equivalent to
6988 // --gtest_death_test_style=threadsafe there.
6990 // A few implementation notes: Like the Linux version, the Windows
6991 // implementation uses pipes for child-to-parent communication. But due to
6992 // the specifics of pipes on Windows, some extra steps are required:
6994 // 1. The parent creates a communication pipe and stores handles to both
6996 // 2. The parent starts the child and provides it with the information
6997 // necessary to acquire the handle to the write end of the pipe.
6998 // 3. The child acquires the write end of the pipe and signals the parent
6999 // using a Windows event.
7000 // 4. Now the parent can release the write end of the pipe on its side. If
7001 // this is done before step 3, the object's reference count goes down to
7002 // 0 and it is destroyed, preventing the child from acquiring it. The
7003 // parent now has to release it, or read operations on the read end of
7004 // the pipe will not return when the child terminates.
7005 // 5. The parent reads child's output through the pipe (outcome code and
7006 // any possible error messages) from the pipe, and its stderr and then
7007 // determines whether to fail the test.
7009 // Note: to distinguish Win32 API calls from the local method and function
7010 // calls, the former are explicitly resolved in the global namespace.
7012 class WindowsDeathTest : public DeathTestImpl {
7014 WindowsDeathTest(const char* a_statement,
7018 : DeathTestImpl(a_statement, a_regex), file_(file), line_(line) {}
7020 // All of these virtual functions are inherited from DeathTest.
7022 virtual TestRole AssumeRole();
7025 // The name of the file in which the death test is located.
7026 const char* const file_;
7027 // The line number on which the death test is located.
7029 // Handle to the write end of the pipe to the child process.
7030 AutoHandle write_handle_;
7031 // Child process handle.
7032 AutoHandle child_handle_;
7033 // Event the child process uses to signal the parent that it has
7034 // acquired the handle to the write end of the pipe. After seeing this
7035 // event the parent can release its own handles to make sure its
7036 // ReadFile() calls return when the child terminates.
7037 AutoHandle event_handle_;
7040 // Waits for the child in a death test to exit, returning its exit
7041 // status, or 0 if no child process exists. As a side effect, sets the
7042 // outcome data member.
7043 int WindowsDeathTest::Wait() {
7047 // Wait until the child either signals that it has acquired the write end
7048 // of the pipe or it dies.
7049 const HANDLE wait_handles[2] = { child_handle_.Get(), event_handle_.Get() };
7050 switch (::WaitForMultipleObjects(2,
7052 FALSE, // Waits for any of the handles.
7055 case WAIT_OBJECT_0 + 1:
7058 GTEST_DEATH_TEST_CHECK_(false); // Should not get here.
7061 // The child has acquired the write end of the pipe or exited.
7062 // We release the handle on our side and continue.
7063 write_handle_.Reset();
7064 event_handle_.Reset();
7066 ReadAndInterpretStatusByte();
7068 // Waits for the child process to exit if it haven't already. This
7069 // returns immediately if the child has already exited, regardless of
7070 // whether previous calls to WaitForMultipleObjects synchronized on this
7072 GTEST_DEATH_TEST_CHECK_(
7073 WAIT_OBJECT_0 == ::WaitForSingleObject(child_handle_.Get(),
7076 GTEST_DEATH_TEST_CHECK_(
7077 ::GetExitCodeProcess(child_handle_.Get(), &status_code) != FALSE);
7078 child_handle_.Reset();
7079 set_status(static_cast<int>(status_code));
7083 // The AssumeRole process for a Windows death test. It creates a child
7084 // process with the same executable as the current process to run the
7085 // death test. The child process is given the --gtest_filter and
7086 // --gtest_internal_run_death_test flags such that it knows to run the
7087 // current death test only.
7088 DeathTest::TestRole WindowsDeathTest::AssumeRole() {
7089 const UnitTestImpl* const impl = GetUnitTestImpl();
7090 const InternalRunDeathTestFlag* const flag =
7091 impl->internal_run_death_test_flag();
7092 const TestInfo* const info = impl->current_test_info();
7093 const int death_test_index = info->result()->death_test_count();
7096 // ParseInternalRunDeathTestFlag() has performed all the necessary
7098 set_write_fd(flag->write_fd());
7099 return EXECUTE_TEST;
7102 // WindowsDeathTest uses an anonymous pipe to communicate results of
7104 SECURITY_ATTRIBUTES handles_are_inheritable = {
7105 sizeof(SECURITY_ATTRIBUTES), NULL, TRUE };
7106 HANDLE read_handle, write_handle;
7107 GTEST_DEATH_TEST_CHECK_(
7108 ::CreatePipe(&read_handle, &write_handle, &handles_are_inheritable,
7109 0) // Default buffer size.
7111 set_read_fd(::_open_osfhandle(reinterpret_cast<intptr_t>(read_handle),
7113 write_handle_.Reset(write_handle);
7114 event_handle_.Reset(::CreateEvent(
7115 &handles_are_inheritable,
7116 TRUE, // The event will automatically reset to non-signaled state.
7117 FALSE, // The initial state is non-signalled.
7118 NULL)); // The even is unnamed.
7119 GTEST_DEATH_TEST_CHECK_(event_handle_.Get() != NULL);
7120 const std::string filter_flag =
7121 std::string("--") + GTEST_FLAG_PREFIX_ + kFilterFlag + "=" +
7122 info->test_case_name() + "." + info->name();
7123 const std::string internal_flag =
7124 std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag +
7125 "=" + file_ + "|" + StreamableToString(line_) + "|" +
7126 StreamableToString(death_test_index) + "|" +
7127 StreamableToString(static_cast<unsigned int>(::GetCurrentProcessId())) +
7128 // size_t has the same width as pointers on both 32-bit and 64-bit
7129 // Windows platforms.
7130 // See http://msdn.microsoft.com/en-us/library/tcxf1dw6.aspx.
7131 "|" + StreamableToString(reinterpret_cast<size_t>(write_handle)) +
7132 "|" + StreamableToString(reinterpret_cast<size_t>(event_handle_.Get()));
7134 char executable_path[_MAX_PATH + 1]; // NOLINT
7135 GTEST_DEATH_TEST_CHECK_(
7136 _MAX_PATH + 1 != ::GetModuleFileNameA(NULL,
7140 std::string command_line =
7141 std::string(::GetCommandLineA()) + " " + filter_flag + " \"" +
7142 internal_flag + "\"";
7144 DeathTest::set_last_death_test_message("");
7147 // Flush the log buffers since the log streams are shared with the child.
7150 // The child process will share the standard handles with the parent.
7151 STARTUPINFOA startup_info;
7152 memset(&startup_info, 0, sizeof(STARTUPINFO));
7153 startup_info.dwFlags = STARTF_USESTDHANDLES;
7154 startup_info.hStdInput = ::GetStdHandle(STD_INPUT_HANDLE);
7155 startup_info.hStdOutput = ::GetStdHandle(STD_OUTPUT_HANDLE);
7156 startup_info.hStdError = ::GetStdHandle(STD_ERROR_HANDLE);
7158 PROCESS_INFORMATION process_info;
7159 GTEST_DEATH_TEST_CHECK_(::CreateProcessA(
7161 const_cast<char*>(command_line.c_str()),
7162 NULL, // Retuned process handle is not inheritable.
7163 NULL, // Retuned thread handle is not inheritable.
7164 TRUE, // Child inherits all inheritable handles (for write_handle_).
7165 0x0, // Default creation flags.
7166 NULL, // Inherit the parent's environment.
7167 UnitTest::GetInstance()->original_working_dir(),
7169 &process_info) != FALSE);
7170 child_handle_.Reset(process_info.hProcess);
7171 ::CloseHandle(process_info.hThread);
7173 return OVERSEE_TEST;
7175 # else // We are not on Windows.
7177 // ForkingDeathTest provides implementations for most of the abstract
7178 // methods of the DeathTest interface. Only the AssumeRole method is
7180 class ForkingDeathTest : public DeathTestImpl {
7182 ForkingDeathTest(const char* statement, const RE* regex);
7184 // All of these virtual functions are inherited from DeathTest.
7188 void set_child_pid(pid_t child_pid) { child_pid_ = child_pid; }
7191 // PID of child process during death test; 0 in the child process itself.
7195 // Constructs a ForkingDeathTest.
7196 ForkingDeathTest::ForkingDeathTest(const char* a_statement, const RE* a_regex)
7197 : DeathTestImpl(a_statement, a_regex),
7200 // Waits for the child in a death test to exit, returning its exit
7201 // status, or 0 if no child process exists. As a side effect, sets the
7202 // outcome data member.
7203 int ForkingDeathTest::Wait() {
7207 ReadAndInterpretStatusByte();
7210 GTEST_DEATH_TEST_CHECK_SYSCALL_(waitpid(child_pid_, &status_value, 0));
7211 set_status(status_value);
7212 return status_value;
7215 // A concrete death test class that forks, then immediately runs the test
7216 // in the child process.
7217 class NoExecDeathTest : public ForkingDeathTest {
7219 NoExecDeathTest(const char* a_statement, const RE* a_regex) :
7220 ForkingDeathTest(a_statement, a_regex) { }
7221 virtual TestRole AssumeRole();
7224 // The AssumeRole process for a fork-and-run death test. It implements a
7225 // straightforward fork, with a simple pipe to transmit the status byte.
7226 DeathTest::TestRole NoExecDeathTest::AssumeRole() {
7227 const size_t thread_count = GetThreadCount();
7228 if (thread_count != 1) {
7229 GTEST_LOG_(WARNING) << DeathTestThreadWarning(thread_count);
7233 GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
7235 DeathTest::set_last_death_test_message("");
7237 // When we fork the process below, the log file buffers are copied, but the
7238 // file descriptors are shared. We flush all log files here so that closing
7239 // the file descriptors in the child process doesn't throw off the
7240 // synchronization between descriptors and buffers in the parent process.
7241 // This is as close to the fork as possible to avoid a race condition in case
7242 // there are multiple threads running before the death test, and another
7243 // thread writes to the log file.
7246 const pid_t child_pid = fork();
7247 GTEST_DEATH_TEST_CHECK_(child_pid != -1);
7248 set_child_pid(child_pid);
7249 if (child_pid == 0) {
7250 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[0]));
7251 set_write_fd(pipe_fd[1]);
7252 // Redirects all logging to stderr in the child process to prevent
7253 // concurrent writes to the log files. We capture stderr in the parent
7254 // process and append the child process' output to a log.
7256 // Event forwarding to the listeners of event listener API mush be shut
7257 // down in death test subprocesses.
7258 GetUnitTestImpl()->listeners()->SuppressEventForwarding();
7259 g_in_fast_death_test_child = true;
7260 return EXECUTE_TEST;
7262 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
7263 set_read_fd(pipe_fd[0]);
7265 return OVERSEE_TEST;
7269 // A concrete death test class that forks and re-executes the main
7270 // program from the beginning, with command-line flags set that cause
7271 // only this specific death test to be run.
7272 class ExecDeathTest : public ForkingDeathTest {
7274 ExecDeathTest(const char* a_statement, const RE* a_regex,
7275 const char* file, int line) :
7276 ForkingDeathTest(a_statement, a_regex), file_(file), line_(line) { }
7277 virtual TestRole AssumeRole();
7279 static ::std::vector<testing::internal::string>
7280 GetArgvsForDeathTestChildProcess() {
7281 ::std::vector<testing::internal::string> args = GetInjectableArgvs();
7284 // The name of the file in which the death test is located.
7285 const char* const file_;
7286 // The line number on which the death test is located.
7290 // Utility class for accumulating command-line arguments.
7294 args_.push_back(NULL);
7298 for (std::vector<char*>::iterator i = args_.begin(); i != args_.end();
7303 void AddArgument(const char* argument) {
7304 args_.insert(args_.end() - 1, posix::StrDup(argument));
7307 template <typename Str>
7308 void AddArguments(const ::std::vector<Str>& arguments) {
7309 for (typename ::std::vector<Str>::const_iterator i = arguments.begin();
7310 i != arguments.end();
7312 args_.insert(args_.end() - 1, posix::StrDup(i->c_str()));
7315 char* const* Argv() {
7320 std::vector<char*> args_;
7323 // A struct that encompasses the arguments to the child process of a
7324 // threadsafe-style death test process.
7325 struct ExecDeathTestArgs {
7326 char* const* argv; // Command-line arguments for the child's call to exec
7327 int close_fd; // File descriptor to close; the read end of a pipe
7331 inline char** GetEnviron() {
7332 // When Google Test is built as a framework on MacOS X, the environ variable
7333 // is unavailable. Apple's documentation (man environ) recommends using
7334 // _NSGetEnviron() instead.
7335 return *_NSGetEnviron();
7338 // Some POSIX platforms expect you to declare environ. extern "C" makes
7339 // it reside in the global namespace.
7340 extern "C" char** environ;
7341 inline char** GetEnviron() { return environ; }
7342 # endif // GTEST_OS_MAC
7345 // The main function for a threadsafe-style death test child process.
7346 // This function is called in a clone()-ed process and thus must avoid
7347 // any potentially unsafe operations like malloc or libc functions.
7348 static int ExecDeathTestChildMain(void* child_arg) {
7349 ExecDeathTestArgs* const args = static_cast<ExecDeathTestArgs*>(child_arg);
7350 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(args->close_fd));
7352 // We need to execute the test program in the same environment where
7353 // it was originally invoked. Therefore we change to the original
7354 // working directory first.
7355 const char* const original_dir =
7356 UnitTest::GetInstance()->original_working_dir();
7357 // We can safely call chdir() as it's a direct system call.
7358 if (chdir(original_dir) != 0) {
7359 DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " +
7360 GetLastErrnoDescription());
7361 return EXIT_FAILURE;
7364 // We can safely call execve() as it's a direct system call. We
7365 // cannot use execvp() as it's a libc function and thus potentially
7366 // unsafe. Since execve() doesn't search the PATH, the user must
7367 // invoke the test program via a valid path that contains at least
7368 // one path separator.
7369 execve(args->argv[0], args->argv, GetEnviron());
7370 DeathTestAbort(std::string("execve(") + args->argv[0] + ", ...) in " +
7371 original_dir + " failed: " +
7372 GetLastErrnoDescription());
7373 return EXIT_FAILURE;
7375 # endif // !GTEST_OS_QNX
7377 // Two utility routines that together determine the direction the stack
7379 // This could be accomplished more elegantly by a single recursive
7380 // function, but we want to guard against the unlikely possibility of
7381 // a smart compiler optimizing the recursion away.
7383 // GTEST_NO_INLINE_ is required to prevent GCC 4.6 from inlining
7384 // StackLowerThanAddress into StackGrowsDown, which then doesn't give
7386 void StackLowerThanAddress(const void* ptr, bool* result) GTEST_NO_INLINE_;
7387 void StackLowerThanAddress(const void* ptr, bool* result) {
7389 *result = (&dummy < ptr);
7393 static bool StackGrowsDown() {
7396 StackLowerThanAddress(&dummy, &result);
7401 // Spawns a child process with the same executable as the current process in
7402 // a thread-safe manner and instructs it to run the death test. The
7403 // implementation uses fork(2) + exec. On systems where clone(2) is
7404 // available, it is used instead, being slightly more thread-safe. On QNX,
7405 // fork supports only single-threaded environments, so this function uses
7406 // spawn(2) there instead. The function dies with an error message if
7407 // anything goes wrong.
7408 static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) {
7409 ExecDeathTestArgs args = { argv, close_fd };
7410 pid_t child_pid = -1;
7413 // Obtains the current directory and sets it to be closed in the child
7415 const int cwd_fd = open(".", O_RDONLY);
7416 GTEST_DEATH_TEST_CHECK_(cwd_fd != -1);
7417 GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(cwd_fd, F_SETFD, FD_CLOEXEC));
7418 // We need to execute the test program in the same environment where
7419 // it was originally invoked. Therefore we change to the original
7420 // working directory first.
7421 const char* const original_dir =
7422 UnitTest::GetInstance()->original_working_dir();
7423 // We can safely call chdir() as it's a direct system call.
7424 if (chdir(original_dir) != 0) {
7425 DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " +
7426 GetLastErrnoDescription());
7427 return EXIT_FAILURE;
7431 // Set close_fd to be closed after spawn.
7432 GTEST_DEATH_TEST_CHECK_SYSCALL_(fd_flags = fcntl(close_fd, F_GETFD));
7433 GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(close_fd, F_SETFD,
7434 fd_flags | FD_CLOEXEC));
7435 struct inheritance inherit = {0};
7436 // spawn is a system call.
7437 child_pid = spawn(args.argv[0], 0, NULL, &inherit, args.argv, GetEnviron());
7438 // Restores the current working directory.
7439 GTEST_DEATH_TEST_CHECK_(fchdir(cwd_fd) != -1);
7440 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(cwd_fd));
7442 # else // GTEST_OS_QNX
7444 // When a SIGPROF signal is received while fork() or clone() are executing,
7445 // the process may hang. To avoid this, we ignore SIGPROF here and re-enable
7446 // it after the call to fork()/clone() is complete.
7447 struct sigaction saved_sigprof_action;
7448 struct sigaction ignore_sigprof_action;
7449 memset(&ignore_sigprof_action, 0, sizeof(ignore_sigprof_action));
7450 sigemptyset(&ignore_sigprof_action.sa_mask);
7451 ignore_sigprof_action.sa_handler = SIG_IGN;
7452 GTEST_DEATH_TEST_CHECK_SYSCALL_(sigaction(
7453 SIGPROF, &ignore_sigprof_action, &saved_sigprof_action));
7454 # endif // GTEST_OS_LINUX
7456 # if GTEST_HAS_CLONE
7457 const bool use_fork = GTEST_FLAG(death_test_use_fork);
7460 static const bool stack_grows_down = StackGrowsDown();
7461 const size_t stack_size = getpagesize();
7462 // MMAP_ANONYMOUS is not defined on Mac, so we use MAP_ANON instead.
7463 void* const stack = mmap(NULL, stack_size, PROT_READ | PROT_WRITE,
7464 MAP_ANON | MAP_PRIVATE, -1, 0);
7465 GTEST_DEATH_TEST_CHECK_(stack != MAP_FAILED);
7467 // Maximum stack alignment in bytes: For a downward-growing stack, this
7468 // amount is subtracted from size of the stack space to get an address
7469 // that is within the stack space and is aligned on all systems we care
7470 // about. As far as I know there is no ABI with stack alignment greater
7471 // than 64. We assume stack and stack_size already have alignment of
7472 // kMaxStackAlignment.
7473 const size_t kMaxStackAlignment = 64;
7474 void* const stack_top =
7475 static_cast<char*>(stack) +
7476 (stack_grows_down ? stack_size - kMaxStackAlignment : 0);
7477 GTEST_DEATH_TEST_CHECK_(stack_size > kMaxStackAlignment &&
7478 reinterpret_cast<intptr_t>(stack_top) % kMaxStackAlignment == 0);
7480 child_pid = clone(&ExecDeathTestChildMain, stack_top, SIGCHLD, &args);
7482 GTEST_DEATH_TEST_CHECK_(munmap(stack, stack_size) != -1);
7485 const bool use_fork = true;
7486 # endif // GTEST_HAS_CLONE
7488 if (use_fork && (child_pid = fork()) == 0) {
7489 ExecDeathTestChildMain(&args);
7492 # endif // GTEST_OS_QNX
7494 GTEST_DEATH_TEST_CHECK_SYSCALL_(
7495 sigaction(SIGPROF, &saved_sigprof_action, NULL));
7496 # endif // GTEST_OS_LINUX
7498 GTEST_DEATH_TEST_CHECK_(child_pid != -1);
7502 // The AssumeRole process for a fork-and-exec death test. It re-executes the
7503 // main program from the beginning, setting the --gtest_filter
7504 // and --gtest_internal_run_death_test flags to cause only the current
7505 // death test to be re-run.
7506 DeathTest::TestRole ExecDeathTest::AssumeRole() {
7507 const UnitTestImpl* const impl = GetUnitTestImpl();
7508 const InternalRunDeathTestFlag* const flag =
7509 impl->internal_run_death_test_flag();
7510 const TestInfo* const info = impl->current_test_info();
7511 const int death_test_index = info->result()->death_test_count();
7514 set_write_fd(flag->write_fd());
7515 return EXECUTE_TEST;
7519 GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
7520 // Clear the close-on-exec flag on the write end of the pipe, lest
7521 // it be closed when the child process does an exec:
7522 GTEST_DEATH_TEST_CHECK_(fcntl(pipe_fd[1], F_SETFD, 0) != -1);
7524 const std::string filter_flag =
7525 std::string("--") + GTEST_FLAG_PREFIX_ + kFilterFlag + "="
7526 + info->test_case_name() + "." + info->name();
7527 const std::string internal_flag =
7528 std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag + "="
7529 + file_ + "|" + StreamableToString(line_) + "|"
7530 + StreamableToString(death_test_index) + "|"
7531 + StreamableToString(pipe_fd[1]);
7533 args.AddArguments(GetArgvsForDeathTestChildProcess());
7534 args.AddArgument(filter_flag.c_str());
7535 args.AddArgument(internal_flag.c_str());
7537 DeathTest::set_last_death_test_message("");
7540 // See the comment in NoExecDeathTest::AssumeRole for why the next line
7544 const pid_t child_pid = ExecDeathTestSpawnChild(args.Argv(), pipe_fd[0]);
7545 GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
7546 set_child_pid(child_pid);
7547 set_read_fd(pipe_fd[0]);
7549 return OVERSEE_TEST;
7552 # endif // !GTEST_OS_WINDOWS
7554 // Creates a concrete DeathTest-derived class that depends on the
7555 // --gtest_death_test_style flag, and sets the pointer pointed to
7556 // by the "test" argument to its address. If the test should be
7557 // skipped, sets that pointer to NULL. Returns true, unless the
7558 // flag is set to an invalid value.
7559 bool DefaultDeathTestFactory::Create(const char* statement, const RE* regex,
7560 const char* file, int line,
7562 UnitTestImpl* const impl = GetUnitTestImpl();
7563 const InternalRunDeathTestFlag* const flag =
7564 impl->internal_run_death_test_flag();
7565 const int death_test_index = impl->current_test_info()
7566 ->increment_death_test_count();
7569 if (death_test_index > flag->index()) {
7570 DeathTest::set_last_death_test_message(
7571 "Death test count (" + StreamableToString(death_test_index)
7572 + ") somehow exceeded expected maximum ("
7573 + StreamableToString(flag->index()) + ")");
7577 if (!(flag->file() == file && flag->line() == line &&
7578 flag->index() == death_test_index)) {
7584 # if GTEST_OS_WINDOWS
7586 if (GTEST_FLAG(death_test_style) == "threadsafe" ||
7587 GTEST_FLAG(death_test_style) == "fast") {
7588 *test = new WindowsDeathTest(statement, regex, file, line);
7593 if (GTEST_FLAG(death_test_style) == "threadsafe") {
7594 *test = new ExecDeathTest(statement, regex, file, line);
7595 } else if (GTEST_FLAG(death_test_style) == "fast") {
7596 *test = new NoExecDeathTest(statement, regex);
7599 # endif // GTEST_OS_WINDOWS
7601 else { // NOLINT - this is more readable than unbalanced brackets inside #if.
7602 DeathTest::set_last_death_test_message(
7603 "Unknown death test style \"" + GTEST_FLAG(death_test_style)
7604 + "\" encountered");
7611 // Splits a given string on a given delimiter, populating a given
7612 // vector with the fields. GTEST_HAS_DEATH_TEST implies that we have
7613 // ::std::string, so we can use it here.
7614 static void SplitString(const ::std::string& str, char delimiter,
7615 ::std::vector< ::std::string>* dest) {
7616 ::std::vector< ::std::string> parsed;
7617 ::std::string::size_type pos = 0;
7618 while (::testing::internal::AlwaysTrue()) {
7619 const ::std::string::size_type colon = str.find(delimiter, pos);
7620 if (colon == ::std::string::npos) {
7621 parsed.push_back(str.substr(pos));
7624 parsed.push_back(str.substr(pos, colon - pos));
7631 # if GTEST_OS_WINDOWS
7632 // Recreates the pipe and event handles from the provided parameters,
7633 // signals the event, and returns a file descriptor wrapped around the pipe
7634 // handle. This function is called in the child process only.
7635 int GetStatusFileDescriptor(unsigned int parent_process_id,
7636 size_t write_handle_as_size_t,
7637 size_t event_handle_as_size_t) {
7638 AutoHandle parent_process_handle(::OpenProcess(PROCESS_DUP_HANDLE,
7639 FALSE, // Non-inheritable.
7640 parent_process_id));
7641 if (parent_process_handle.Get() == INVALID_HANDLE_VALUE) {
7642 DeathTestAbort("Unable to open parent process " +
7643 StreamableToString(parent_process_id));
7646 // TODO(vladl@google.com): Replace the following check with a
7647 // compile-time assertion when available.
7648 GTEST_CHECK_(sizeof(HANDLE) <= sizeof(size_t));
7650 const HANDLE write_handle =
7651 reinterpret_cast<HANDLE>(write_handle_as_size_t);
7652 HANDLE dup_write_handle;
7654 // The newly initialized handle is accessible only in in the parent
7655 // process. To obtain one accessible within the child, we need to use
7657 if (!::DuplicateHandle(parent_process_handle.Get(), write_handle,
7658 ::GetCurrentProcess(), &dup_write_handle,
7659 0x0, // Requested privileges ignored since
7660 // DUPLICATE_SAME_ACCESS is used.
7661 FALSE, // Request non-inheritable handler.
7662 DUPLICATE_SAME_ACCESS)) {
7663 DeathTestAbort("Unable to duplicate the pipe handle " +
7664 StreamableToString(write_handle_as_size_t) +
7665 " from the parent process " +
7666 StreamableToString(parent_process_id));
7669 const HANDLE event_handle = reinterpret_cast<HANDLE>(event_handle_as_size_t);
7670 HANDLE dup_event_handle;
7672 if (!::DuplicateHandle(parent_process_handle.Get(), event_handle,
7673 ::GetCurrentProcess(), &dup_event_handle,
7676 DUPLICATE_SAME_ACCESS)) {
7677 DeathTestAbort("Unable to duplicate the event handle " +
7678 StreamableToString(event_handle_as_size_t) +
7679 " from the parent process " +
7680 StreamableToString(parent_process_id));
7683 const int write_fd =
7684 ::_open_osfhandle(reinterpret_cast<intptr_t>(dup_write_handle), O_APPEND);
7685 if (write_fd == -1) {
7686 DeathTestAbort("Unable to convert pipe handle " +
7687 StreamableToString(write_handle_as_size_t) +
7688 " to a file descriptor");
7691 // Signals the parent that the write end of the pipe has been acquired
7692 // so the parent can release its own write end.
7693 ::SetEvent(dup_event_handle);
7697 # endif // GTEST_OS_WINDOWS
7699 // Returns a newly created InternalRunDeathTestFlag object with fields
7700 // initialized from the GTEST_FLAG(internal_run_death_test) flag if
7701 // the flag is specified; otherwise returns NULL.
7702 InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() {
7703 if (GTEST_FLAG(internal_run_death_test) == "") return NULL;
7705 // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we
7709 ::std::vector< ::std::string> fields;
7710 SplitString(GTEST_FLAG(internal_run_death_test).c_str(), '|', &fields);
7713 # if GTEST_OS_WINDOWS
7715 unsigned int parent_process_id = 0;
7716 size_t write_handle_as_size_t = 0;
7717 size_t event_handle_as_size_t = 0;
7719 if (fields.size() != 6
7720 || !ParseNaturalNumber(fields[1], &line)
7721 || !ParseNaturalNumber(fields[2], &index)
7722 || !ParseNaturalNumber(fields[3], &parent_process_id)
7723 || !ParseNaturalNumber(fields[4], &write_handle_as_size_t)
7724 || !ParseNaturalNumber(fields[5], &event_handle_as_size_t)) {
7725 DeathTestAbort("Bad --gtest_internal_run_death_test flag: " +
7726 GTEST_FLAG(internal_run_death_test));
7728 write_fd = GetStatusFileDescriptor(parent_process_id,
7729 write_handle_as_size_t,
7730 event_handle_as_size_t);
7733 if (fields.size() != 4
7734 || !ParseNaturalNumber(fields[1], &line)
7735 || !ParseNaturalNumber(fields[2], &index)
7736 || !ParseNaturalNumber(fields[3], &write_fd)) {
7737 DeathTestAbort("Bad --gtest_internal_run_death_test flag: "
7738 + GTEST_FLAG(internal_run_death_test));
7741 # endif // GTEST_OS_WINDOWS
7743 return new InternalRunDeathTestFlag(fields[0], line, index, write_fd);
7746 } // namespace internal
7748 #endif // GTEST_HAS_DEATH_TEST
7750 } // namespace testing
7751 // Copyright 2008, Google Inc.
7752 // All rights reserved.
7754 // Redistribution and use in source and binary forms, with or without
7755 // modification, are permitted provided that the following conditions are
7758 // * Redistributions of source code must retain the above copyright
7759 // notice, this list of conditions and the following disclaimer.
7760 // * Redistributions in binary form must reproduce the above
7761 // copyright notice, this list of conditions and the following disclaimer
7762 // in the documentation and/or other materials provided with the
7764 // * Neither the name of Google Inc. nor the names of its
7765 // contributors may be used to endorse or promote products derived from
7766 // this software without specific prior written permission.
7768 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
7769 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
7770 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
7771 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
7772 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
7773 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
7774 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
7775 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
7776 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
7777 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
7778 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
7780 // Authors: keith.ray@gmail.com (Keith Ray)
7785 #if GTEST_OS_WINDOWS_MOBILE
7786 # include <windows.h>
7787 #elif GTEST_OS_WINDOWS
7788 # include <direct.h>
7790 #elif GTEST_OS_SYMBIAN
7791 // Symbian OpenC has PATH_MAX in sys/syslimits.h
7792 # include <sys/syslimits.h>
7794 # include <limits.h>
7795 # include <climits> // Some Linux distributions define PATH_MAX here.
7796 #endif // GTEST_OS_WINDOWS_MOBILE
7798 #if GTEST_OS_WINDOWS
7799 # define GTEST_PATH_MAX_ _MAX_PATH
7800 #elif defined(PATH_MAX)
7801 # define GTEST_PATH_MAX_ PATH_MAX
7802 #elif defined(_XOPEN_PATH_MAX)
7803 # define GTEST_PATH_MAX_ _XOPEN_PATH_MAX
7805 # define GTEST_PATH_MAX_ _POSIX_PATH_MAX
7806 #endif // GTEST_OS_WINDOWS
7810 namespace internal {
7812 #if GTEST_OS_WINDOWS
7813 // On Windows, '\\' is the standard path separator, but many tools and the
7814 // Windows API also accept '/' as an alternate path separator. Unless otherwise
7815 // noted, a file path can contain either kind of path separators, or a mixture
7817 const char kPathSeparator = '\\';
7818 const char kAlternatePathSeparator = '/';
7819 const char kPathSeparatorString[] = "\\";
7820 const char kAlternatePathSeparatorString[] = "/";
7821 # if GTEST_OS_WINDOWS_MOBILE
7822 // Windows CE doesn't have a current directory. You should not use
7823 // the current directory in tests on Windows CE, but this at least
7824 // provides a reasonable fallback.
7825 const char kCurrentDirectoryString[] = "\\";
7826 // Windows CE doesn't define INVALID_FILE_ATTRIBUTES
7827 const DWORD kInvalidFileAttributes = 0xffffffff;
7829 const char kCurrentDirectoryString[] = ".\\";
7830 # endif // GTEST_OS_WINDOWS_MOBILE
7832 const char kPathSeparator = '/';
7833 const char kPathSeparatorString[] = "/";
7834 const char kCurrentDirectoryString[] = "./";
7835 #endif // GTEST_OS_WINDOWS
7837 // Returns whether the given character is a valid path separator.
7838 static bool IsPathSeparator(char c) {
7839 #if GTEST_HAS_ALT_PATH_SEP_
7840 return (c == kPathSeparator) || (c == kAlternatePathSeparator);
7842 return c == kPathSeparator;
7846 // Returns the current working directory, or "" if unsuccessful.
7847 FilePath FilePath::GetCurrentDir() {
7848 #if GTEST_OS_WINDOWS_MOBILE
7849 // Windows CE doesn't have a current directory, so we just return
7850 // something reasonable.
7851 return FilePath(kCurrentDirectoryString);
7852 #elif GTEST_OS_WINDOWS
7853 char cwd[GTEST_PATH_MAX_ + 1] = { '\0' };
7854 return FilePath(_getcwd(cwd, sizeof(cwd)) == NULL ? "" : cwd);
7856 char cwd[GTEST_PATH_MAX_ + 1] = { '\0' };
7857 return FilePath(getcwd(cwd, sizeof(cwd)) == NULL ? "" : cwd);
7858 #endif // GTEST_OS_WINDOWS_MOBILE
7861 // Returns a copy of the FilePath with the case-insensitive extension removed.
7862 // Example: FilePath("dir/file.exe").RemoveExtension("EXE") returns
7863 // FilePath("dir/file"). If a case-insensitive extension is not
7864 // found, returns a copy of the original FilePath.
7865 FilePath FilePath::RemoveExtension(const char* extension) const {
7866 const std::string dot_extension = std::string(".") + extension;
7867 if (String::EndsWithCaseInsensitive(pathname_, dot_extension)) {
7868 return FilePath(pathname_.substr(
7869 0, pathname_.length() - dot_extension.length()));
7874 // Returns a pointer to the last occurence of a valid path separator in
7875 // the FilePath. On Windows, for example, both '/' and '\' are valid path
7876 // separators. Returns NULL if no path separator was found.
7877 const char* FilePath::FindLastPathSeparator() const {
7878 const char* const last_sep = strrchr(c_str(), kPathSeparator);
7879 #if GTEST_HAS_ALT_PATH_SEP_
7880 const char* const last_alt_sep = strrchr(c_str(), kAlternatePathSeparator);
7881 // Comparing two pointers of which only one is NULL is undefined.
7882 if (last_alt_sep != NULL &&
7883 (last_sep == NULL || last_alt_sep > last_sep)) {
7884 return last_alt_sep;
7890 // Returns a copy of the FilePath with the directory part removed.
7891 // Example: FilePath("path/to/file").RemoveDirectoryName() returns
7892 // FilePath("file"). If there is no directory part ("just_a_file"), it returns
7893 // the FilePath unmodified. If there is no file part ("just_a_dir/") it
7894 // returns an empty FilePath ("").
7895 // On Windows platform, '\' is the path separator, otherwise it is '/'.
7896 FilePath FilePath::RemoveDirectoryName() const {
7897 const char* const last_sep = FindLastPathSeparator();
7898 return last_sep ? FilePath(last_sep + 1) : *this;
7901 // RemoveFileName returns the directory path with the filename removed.
7902 // Example: FilePath("path/to/file").RemoveFileName() returns "path/to/".
7903 // If the FilePath is "a_file" or "/a_file", RemoveFileName returns
7904 // FilePath("./") or, on Windows, FilePath(".\\"). If the filepath does
7905 // not have a file, like "just/a/dir/", it returns the FilePath unmodified.
7906 // On Windows platform, '\' is the path separator, otherwise it is '/'.
7907 FilePath FilePath::RemoveFileName() const {
7908 const char* const last_sep = FindLastPathSeparator();
7911 dir = std::string(c_str(), last_sep + 1 - c_str());
7913 dir = kCurrentDirectoryString;
7915 return FilePath(dir);
7918 // Helper functions for naming files in a directory for xml output.
7920 // Given directory = "dir", base_name = "test", number = 0,
7921 // extension = "xml", returns "dir/test.xml". If number is greater
7922 // than zero (e.g., 12), returns "dir/test_12.xml".
7923 // On Windows platform, uses \ as the separator rather than /.
7924 FilePath FilePath::MakeFileName(const FilePath& directory,
7925 const FilePath& base_name,
7927 const char* extension) {
7930 file = base_name.string() + "." + extension;
7932 file = base_name.string() + "_" + StreamableToString(number)
7935 return ConcatPaths(directory, FilePath(file));
7938 // Given directory = "dir", relative_path = "test.xml", returns "dir/test.xml".
7939 // On Windows, uses \ as the separator rather than /.
7940 FilePath FilePath::ConcatPaths(const FilePath& directory,
7941 const FilePath& relative_path) {
7942 if (directory.IsEmpty())
7943 return relative_path;
7944 const FilePath dir(directory.RemoveTrailingPathSeparator());
7945 return FilePath(dir.string() + kPathSeparator + relative_path.string());
7948 // Returns true if pathname describes something findable in the file-system,
7949 // either a file, directory, or whatever.
7950 bool FilePath::FileOrDirectoryExists() const {
7951 #if GTEST_OS_WINDOWS_MOBILE
7952 LPCWSTR unicode = String::AnsiToUtf16(pathname_.c_str());
7953 const DWORD attributes = GetFileAttributes(unicode);
7955 return attributes != kInvalidFileAttributes;
7957 posix::StatStruct file_stat;
7958 return posix::Stat(pathname_.c_str(), &file_stat) == 0;
7959 #endif // GTEST_OS_WINDOWS_MOBILE
7962 // Returns true if pathname describes a directory in the file-system
7964 bool FilePath::DirectoryExists() const {
7965 bool result = false;
7966 #if GTEST_OS_WINDOWS
7967 // Don't strip off trailing separator if path is a root directory on
7968 // Windows (like "C:\\").
7969 const FilePath& path(IsRootDirectory() ? *this :
7970 RemoveTrailingPathSeparator());
7972 const FilePath& path(*this);
7975 #if GTEST_OS_WINDOWS_MOBILE
7976 LPCWSTR unicode = String::AnsiToUtf16(path.c_str());
7977 const DWORD attributes = GetFileAttributes(unicode);
7979 if ((attributes != kInvalidFileAttributes) &&
7980 (attributes & FILE_ATTRIBUTE_DIRECTORY)) {
7984 posix::StatStruct file_stat;
7985 result = posix::Stat(path.c_str(), &file_stat) == 0 &&
7986 posix::IsDir(file_stat);
7987 #endif // GTEST_OS_WINDOWS_MOBILE
7992 // Returns true if pathname describes a root directory. (Windows has one
7993 // root directory per disk drive.)
7994 bool FilePath::IsRootDirectory() const {
7995 #if GTEST_OS_WINDOWS
7996 // TODO(wan@google.com): on Windows a network share like
7997 // \\server\share can be a root directory, although it cannot be the
7998 // current directory. Handle this properly.
7999 return pathname_.length() == 3 && IsAbsolutePath();
8001 return pathname_.length() == 1 && IsPathSeparator(pathname_.c_str()[0]);
8005 // Returns true if pathname describes an absolute path.
8006 bool FilePath::IsAbsolutePath() const {
8007 const char* const name = pathname_.c_str();
8008 #if GTEST_OS_WINDOWS
8009 return pathname_.length() >= 3 &&
8010 ((name[0] >= 'a' && name[0] <= 'z') ||
8011 (name[0] >= 'A' && name[0] <= 'Z')) &&
8013 IsPathSeparator(name[2]);
8015 return IsPathSeparator(name[0]);
8019 // Returns a pathname for a file that does not currently exist. The pathname
8020 // will be directory/base_name.extension or
8021 // directory/base_name_<number>.extension if directory/base_name.extension
8022 // already exists. The number will be incremented until a pathname is found
8023 // that does not already exist.
8024 // Examples: 'dir/foo_test.xml' or 'dir/foo_test_1.xml'.
8025 // There could be a race condition if two or more processes are calling this
8026 // function at the same time -- they could both pick the same filename.
8027 FilePath FilePath::GenerateUniqueFileName(const FilePath& directory,
8028 const FilePath& base_name,
8029 const char* extension) {
8030 FilePath full_pathname;
8033 full_pathname.Set(MakeFileName(directory, base_name, number++, extension));
8034 } while (full_pathname.FileOrDirectoryExists());
8035 return full_pathname;
8038 // Returns true if FilePath ends with a path separator, which indicates that
8039 // it is intended to represent a directory. Returns false otherwise.
8040 // This does NOT check that a directory (or file) actually exists.
8041 bool FilePath::IsDirectory() const {
8042 return !pathname_.empty() &&
8043 IsPathSeparator(pathname_.c_str()[pathname_.length() - 1]);
8046 // Create directories so that path exists. Returns true if successful or if
8047 // the directories already exist; returns false if unable to create directories
8049 bool FilePath::CreateDirectoriesRecursively() const {
8050 if (!this->IsDirectory()) {
8054 if (pathname_.length() == 0 || this->DirectoryExists()) {
8058 const FilePath parent(this->RemoveTrailingPathSeparator().RemoveFileName());
8059 return parent.CreateDirectoriesRecursively() && this->CreateFolder();
8062 // Create the directory so that path exists. Returns true if successful or
8063 // if the directory already exists; returns false if unable to create the
8064 // directory for any reason, including if the parent directory does not
8065 // exist. Not named "CreateDirectory" because that's a macro on Windows.
8066 bool FilePath::CreateFolder() const {
8067 #if GTEST_OS_WINDOWS_MOBILE
8068 FilePath removed_sep(this->RemoveTrailingPathSeparator());
8069 LPCWSTR unicode = String::AnsiToUtf16(removed_sep.c_str());
8070 int result = CreateDirectory(unicode, NULL) ? 0 : -1;
8072 #elif GTEST_OS_WINDOWS
8073 int result = _mkdir(pathname_.c_str());
8075 int result = mkdir(pathname_.c_str(), 0777);
8076 #endif // GTEST_OS_WINDOWS_MOBILE
8079 return this->DirectoryExists(); // An error is OK if the directory exists.
8081 return true; // No error.
8084 // If input name has a trailing separator character, remove it and return the
8085 // name, otherwise return the name string unmodified.
8086 // On Windows platform, uses \ as the separator, other platforms use /.
8087 FilePath FilePath::RemoveTrailingPathSeparator() const {
8088 return IsDirectory()
8089 ? FilePath(pathname_.substr(0, pathname_.length() - 1))
8093 // Removes any redundant separators that might be in the pathname.
8094 // For example, "bar///foo" becomes "bar/foo". Does not eliminate other
8095 // redundancies that might be in a pathname involving "." or "..".
8096 // TODO(wan@google.com): handle Windows network shares (e.g. \\server\share).
8097 void FilePath::Normalize() {
8098 if (pathname_.c_str() == NULL) {
8102 const char* src = pathname_.c_str();
8103 char* const dest = new char[pathname_.length() + 1];
8104 char* dest_ptr = dest;
8105 memset(dest_ptr, 0, pathname_.length() + 1);
8107 while (*src != '\0') {
8109 if (!IsPathSeparator(*src)) {
8112 #if GTEST_HAS_ALT_PATH_SEP_
8113 if (*dest_ptr == kAlternatePathSeparator) {
8114 *dest_ptr = kPathSeparator;
8117 while (IsPathSeparator(*src))
8127 } // namespace internal
8128 } // namespace testing
8129 // Copyright 2008, Google Inc.
8130 // All rights reserved.
8132 // Redistribution and use in source and binary forms, with or without
8133 // modification, are permitted provided that the following conditions are
8136 // * Redistributions of source code must retain the above copyright
8137 // notice, this list of conditions and the following disclaimer.
8138 // * Redistributions in binary form must reproduce the above
8139 // copyright notice, this list of conditions and the following disclaimer
8140 // in the documentation and/or other materials provided with the
8142 // * Neither the name of Google Inc. nor the names of its
8143 // contributors may be used to endorse or promote products derived from
8144 // this software without specific prior written permission.
8146 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
8147 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
8148 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
8149 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
8150 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
8151 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
8152 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
8153 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
8154 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
8155 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
8156 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
8158 // Author: wan@google.com (Zhanyong Wan)
8166 #if GTEST_OS_WINDOWS_MOBILE
8167 # include <windows.h> // For TerminateProcess()
8168 #elif GTEST_OS_WINDOWS
8170 # include <sys/stat.h>
8172 # include <unistd.h>
8173 #endif // GTEST_OS_WINDOWS_MOBILE
8176 # include <mach/mach_init.h>
8177 # include <mach/task.h>
8178 # include <mach/vm_map.h>
8179 #endif // GTEST_OS_MAC
8182 # include <devctl.h>
8183 # include <sys/procfs.h>
8184 #endif // GTEST_OS_QNX
8187 // Indicates that this translation unit is part of Google Test's
8188 // implementation. It must come before gtest-internal-inl.h is
8189 // included, or there will be a compiler error. This trick is to
8190 // prevent a user from accidentally including gtest-internal-inl.h in
8192 #define GTEST_IMPLEMENTATION_ 1
8193 #undef GTEST_IMPLEMENTATION_
8196 namespace internal {
8198 #if defined(_MSC_VER) || defined(__BORLANDC__)
8199 // MSVC and C++Builder do not provide a definition of STDERR_FILENO.
8200 const int kStdOutFileno = 1;
8201 const int kStdErrFileno = 2;
8203 const int kStdOutFileno = STDOUT_FILENO;
8204 const int kStdErrFileno = STDERR_FILENO;
8209 // Returns the number of threads running in the process, or 0 to indicate that
8210 // we cannot detect it.
8211 size_t GetThreadCount() {
8212 const task_t task = mach_task_self();
8213 mach_msg_type_number_t thread_count;
8214 thread_act_array_t thread_list;
8215 const kern_return_t status = task_threads(task, &thread_list, &thread_count);
8216 if (status == KERN_SUCCESS) {
8217 // task_threads allocates resources in thread_list and we need to free them
8220 reinterpret_cast<vm_address_t>(thread_list),
8221 sizeof(thread_t) * thread_count);
8222 return static_cast<size_t>(thread_count);
8230 // Returns the number of threads running in the process, or 0 to indicate that
8231 // we cannot detect it.
8232 size_t GetThreadCount() {
8233 const int fd = open("/proc/self/as", O_RDONLY);
8237 procfs_info process_info;
8239 devctl(fd, DCMD_PROC_INFO, &process_info, sizeof(process_info), NULL);
8241 if (status == EOK) {
8242 return static_cast<size_t>(process_info.num_threads);
8250 size_t GetThreadCount() {
8251 // There's no portable way to detect the number of threads, so we just
8252 // return 0 to indicate that we cannot detect it.
8256 #endif // GTEST_OS_MAC
8258 #if GTEST_USES_POSIX_RE
8260 // Implements RE. Currently only needed for death tests.
8264 // regfree'ing an invalid regex might crash because the content
8265 // of the regex is undefined. Since the regex's are essentially
8266 // the same, one cannot be valid (or invalid) without the other
8268 regfree(&partial_regex_);
8269 regfree(&full_regex_);
8271 free(const_cast<char*>(pattern_));
8274 // Returns true iff regular expression re matches the entire str.
8275 bool RE::FullMatch(const char* str, const RE& re) {
8276 if (!re.is_valid_) return false;
8279 return regexec(&re.full_regex_, str, 1, &match, 0) == 0;
8282 // Returns true iff regular expression re matches a substring of str
8283 // (including str itself).
8284 bool RE::PartialMatch(const char* str, const RE& re) {
8285 if (!re.is_valid_) return false;
8288 return regexec(&re.partial_regex_, str, 1, &match, 0) == 0;
8291 // Initializes an RE from its string representation.
8292 void RE::Init(const char* regex) {
8293 pattern_ = posix::StrDup(regex);
8295 // Reserves enough bytes to hold the regular expression used for a
8297 const size_t full_regex_len = strlen(regex) + 10;
8298 char* const full_pattern = new char[full_regex_len];
8300 snprintf(full_pattern, full_regex_len, "^(%s)$", regex);
8301 is_valid_ = regcomp(&full_regex_, full_pattern, REG_EXTENDED) == 0;
8302 // We want to call regcomp(&partial_regex_, ...) even if the
8303 // previous expression returns false. Otherwise partial_regex_ may
8304 // not be properly initialized can may cause trouble when it's
8307 // Some implementation of POSIX regex (e.g. on at least some
8308 // versions of Cygwin) doesn't accept the empty string as a valid
8309 // regex. We change it to an equivalent form "()" to be safe.
8311 const char* const partial_regex = (*regex == '\0') ? "()" : regex;
8312 is_valid_ = regcomp(&partial_regex_, partial_regex, REG_EXTENDED) == 0;
8314 EXPECT_TRUE(is_valid_)
8315 << "Regular expression \"" << regex
8316 << "\" is not a valid POSIX Extended regular expression.";
8318 delete[] full_pattern;
8321 #elif GTEST_USES_SIMPLE_RE
8323 // Returns true iff ch appears anywhere in str (excluding the
8324 // terminating '\0' character).
8325 bool IsInSet(char ch, const char* str) {
8326 return ch != '\0' && strchr(str, ch) != NULL;
8329 // Returns true iff ch belongs to the given classification. Unlike
8330 // similar functions in <ctype.h>, these aren't affected by the
8332 bool IsAsciiDigit(char ch) { return '0' <= ch && ch <= '9'; }
8333 bool IsAsciiPunct(char ch) {
8334 return IsInSet(ch, "^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~");
8336 bool IsRepeat(char ch) { return IsInSet(ch, "?*+"); }
8337 bool IsAsciiWhiteSpace(char ch) { return IsInSet(ch, " \f\n\r\t\v"); }
8338 bool IsAsciiWordChar(char ch) {
8339 return ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') ||
8340 ('0' <= ch && ch <= '9') || ch == '_';
8343 // Returns true iff "\\c" is a supported escape sequence.
8344 bool IsValidEscape(char c) {
8345 return (IsAsciiPunct(c) || IsInSet(c, "dDfnrsStvwW"));
8348 // Returns true iff the given atom (specified by escaped and pattern)
8349 // matches ch. The result is undefined if the atom is invalid.
8350 bool AtomMatchesChar(bool escaped, char pattern_char, char ch) {
8351 if (escaped) { // "\\p" where p is pattern_char.
8352 switch (pattern_char) {
8353 case 'd': return IsAsciiDigit(ch);
8354 case 'D': return !IsAsciiDigit(ch);
8355 case 'f': return ch == '\f';
8356 case 'n': return ch == '\n';
8357 case 'r': return ch == '\r';
8358 case 's': return IsAsciiWhiteSpace(ch);
8359 case 'S': return !IsAsciiWhiteSpace(ch);
8360 case 't': return ch == '\t';
8361 case 'v': return ch == '\v';
8362 case 'w': return IsAsciiWordChar(ch);
8363 case 'W': return !IsAsciiWordChar(ch);
8365 return IsAsciiPunct(pattern_char) && pattern_char == ch;
8368 return (pattern_char == '.' && ch != '\n') || pattern_char == ch;
8371 // Helper function used by ValidateRegex() to format error messages.
8372 std::string FormatRegexSyntaxError(const char* regex, int index) {
8373 return (Message() << "Syntax error at index " << index
8374 << " in simple regular expression \"" << regex << "\": ").GetString();
8377 // Generates non-fatal failures and returns false if regex is invalid;
8378 // otherwise returns true.
8379 bool ValidateRegex(const char* regex) {
8380 if (regex == NULL) {
8381 // TODO(wan@google.com): fix the source file location in the
8382 // assertion failures to match where the regex is used in user
8384 ADD_FAILURE() << "NULL is not a valid simple regular expression.";
8388 bool is_valid = true;
8390 // True iff ?, *, or + can follow the previous atom.
8391 bool prev_repeatable = false;
8392 for (int i = 0; regex[i]; i++) {
8393 if (regex[i] == '\\') { // An escape sequence
8395 if (regex[i] == '\0') {
8396 ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
8397 << "'\\' cannot appear at the end.";
8401 if (!IsValidEscape(regex[i])) {
8402 ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
8403 << "invalid escape sequence \"\\" << regex[i] << "\".";
8406 prev_repeatable = true;
8407 } else { // Not an escape sequence.
8408 const char ch = regex[i];
8410 if (ch == '^' && i > 0) {
8411 ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
8412 << "'^' can only appear at the beginning.";
8414 } else if (ch == '$' && regex[i + 1] != '\0') {
8415 ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
8416 << "'$' can only appear at the end.";
8418 } else if (IsInSet(ch, "()[]{}|")) {
8419 ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
8420 << "'" << ch << "' is unsupported.";
8422 } else if (IsRepeat(ch) && !prev_repeatable) {
8423 ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
8424 << "'" << ch << "' can only follow a repeatable token.";
8428 prev_repeatable = !IsInSet(ch, "^$?*+");
8435 // Matches a repeated regex atom followed by a valid simple regular
8436 // expression. The regex atom is defined as c if escaped is false,
8437 // or \c otherwise. repeat is the repetition meta character (?, *,
8438 // or +). The behavior is undefined if str contains too many
8439 // characters to be indexable by size_t, in which case the test will
8440 // probably time out anyway. We are fine with this limitation as
8441 // std::string has it too.
8442 bool MatchRepetitionAndRegexAtHead(
8443 bool escaped, char c, char repeat, const char* regex,
8445 const size_t min_count = (repeat == '+') ? 1 : 0;
8446 const size_t max_count = (repeat == '?') ? 1 :
8447 static_cast<size_t>(-1) - 1;
8448 // We cannot call numeric_limits::max() as it conflicts with the
8449 // max() macro on Windows.
8451 for (size_t i = 0; i <= max_count; ++i) {
8452 // We know that the atom matches each of the first i characters in str.
8453 if (i >= min_count && MatchRegexAtHead(regex, str + i)) {
8454 // We have enough matches at the head, and the tail matches too.
8455 // Since we only care about *whether* the pattern matches str
8456 // (as opposed to *how* it matches), there is no need to find a
8460 if (str[i] == '\0' || !AtomMatchesChar(escaped, c, str[i]))
8466 // Returns true iff regex matches a prefix of str. regex must be a
8467 // valid simple regular expression and not start with "^", or the
8468 // result is undefined.
8469 bool MatchRegexAtHead(const char* regex, const char* str) {
8470 if (*regex == '\0') // An empty regex matches a prefix of anything.
8473 // "$" only matches the end of a string. Note that regex being
8474 // valid guarantees that there's nothing after "$" in it.
8476 return *str == '\0';
8478 // Is the first thing in regex an escape sequence?
8479 const bool escaped = *regex == '\\';
8482 if (IsRepeat(regex[1])) {
8483 // MatchRepetitionAndRegexAtHead() calls MatchRegexAtHead(), so
8484 // here's an indirect recursion. It terminates as the regex gets
8485 // shorter in each recursion.
8486 return MatchRepetitionAndRegexAtHead(
8487 escaped, regex[0], regex[1], regex + 2, str);
8489 // regex isn't empty, isn't "$", and doesn't start with a
8490 // repetition. We match the first atom of regex with the first
8491 // character of str and recurse.
8492 return (*str != '\0') && AtomMatchesChar(escaped, *regex, *str) &&
8493 MatchRegexAtHead(regex + 1, str + 1);
8497 // Returns true iff regex matches any substring of str. regex must be
8498 // a valid simple regular expression, or the result is undefined.
8500 // The algorithm is recursive, but the recursion depth doesn't exceed
8501 // the regex length, so we won't need to worry about running out of
8502 // stack space normally. In rare cases the time complexity can be
8503 // exponential with respect to the regex length + the string length,
8504 // but usually it's must faster (often close to linear).
8505 bool MatchRegexAnywhere(const char* regex, const char* str) {
8506 if (regex == NULL || str == NULL)
8510 return MatchRegexAtHead(regex + 1, str);
8512 // A successful match can be anywhere in str.
8514 if (MatchRegexAtHead(regex, str))
8516 } while (*str++ != '\0');
8520 // Implements the RE class.
8523 free(const_cast<char*>(pattern_));
8524 free(const_cast<char*>(full_pattern_));
8527 // Returns true iff regular expression re matches the entire str.
8528 bool RE::FullMatch(const char* str, const RE& re) {
8529 return re.is_valid_ && MatchRegexAnywhere(re.full_pattern_, str);
8532 // Returns true iff regular expression re matches a substring of str
8533 // (including str itself).
8534 bool RE::PartialMatch(const char* str, const RE& re) {
8535 return re.is_valid_ && MatchRegexAnywhere(re.pattern_, str);
8538 // Initializes an RE from its string representation.
8539 void RE::Init(const char* regex) {
8540 pattern_ = full_pattern_ = NULL;
8541 if (regex != NULL) {
8542 pattern_ = posix::StrDup(regex);
8545 is_valid_ = ValidateRegex(regex);
8547 // No need to calculate the full pattern when the regex is invalid.
8551 const size_t len = strlen(regex);
8552 // Reserves enough bytes to hold the regular expression used for a
8553 // full match: we need space to prepend a '^', append a '$', and
8554 // terminate the string with '\0'.
8555 char* buffer = static_cast<char*>(malloc(len + 3));
8556 full_pattern_ = buffer;
8559 *buffer++ = '^'; // Makes sure full_pattern_ starts with '^'.
8561 // We don't use snprintf or strncpy, as they trigger a warning when
8562 // compiled with VC++ 8.0.
8563 memcpy(buffer, regex, len);
8566 if (len == 0 || regex[len - 1] != '$')
8567 *buffer++ = '$'; // Makes sure full_pattern_ ends with '$'.
8572 #endif // GTEST_USES_POSIX_RE
8574 const char kUnknownFile[] = "unknown file";
8576 // Formats a source file path and a line number as they would appear
8577 // in an error message from the compiler used to compile this code.
8578 GTEST_API_ ::std::string FormatFileLocation(const char* file, int line) {
8579 const std::string file_name(file == NULL ? kUnknownFile : file);
8582 return file_name + ":";
8585 return file_name + "(" + StreamableToString(line) + "):";
8587 return file_name + ":" + StreamableToString(line) + ":";
8591 // Formats a file location for compiler-independent XML output.
8592 // Although this function is not platform dependent, we put it next to
8593 // FormatFileLocation in order to contrast the two functions.
8594 // Note that FormatCompilerIndependentFileLocation() does NOT append colon
8595 // to the file location it produces, unlike FormatFileLocation().
8596 GTEST_API_ ::std::string FormatCompilerIndependentFileLocation(
8597 const char* file, int line) {
8598 const std::string file_name(file == NULL ? kUnknownFile : file);
8603 return file_name + ":" + StreamableToString(line);
8607 GTestLog::GTestLog(GTestLogSeverity severity, const char* file, int line)
8608 : severity_(severity) {
8609 const char* const marker =
8610 severity == GTEST_INFO ? "[ INFO ]" :
8611 severity == GTEST_WARNING ? "[WARNING]" :
8612 severity == GTEST_ERROR ? "[ ERROR ]" : "[ FATAL ]";
8613 GetStream() << ::std::endl << marker << " "
8614 << FormatFileLocation(file, line).c_str() << ": ";
8617 // Flushes the buffers and, if severity is GTEST_FATAL, aborts the program.
8618 GTestLog::~GTestLog() {
8619 GetStream() << ::std::endl;
8620 if (severity_ == GTEST_FATAL) {
8625 // Disable Microsoft deprecation warnings for POSIX functions called from
8626 // this class (creat, dup, dup2, and close)
8628 # pragma warning(push)
8629 # pragma warning(disable: 4996)
8632 #if GTEST_HAS_STREAM_REDIRECTION
8634 // Object that captures an output stream (stdout/stderr).
8635 class CapturedStream {
8637 // The ctor redirects the stream to a temporary file.
8638 explicit CapturedStream(int fd) : fd_(fd), uncaptured_fd_(dup(fd)) {
8639 # if GTEST_OS_WINDOWS
8640 char temp_dir_path[MAX_PATH + 1] = { '\0' }; // NOLINT
8641 char temp_file_path[MAX_PATH + 1] = { '\0' }; // NOLINT
8643 ::GetTempPathA(sizeof(temp_dir_path), temp_dir_path);
8644 const UINT success = ::GetTempFileNameA(temp_dir_path,
8646 0, // Generate unique file name.
8648 GTEST_CHECK_(success != 0)
8649 << "Unable to create a temporary file in " << temp_dir_path;
8650 const int captured_fd = creat(temp_file_path, _S_IREAD | _S_IWRITE);
8651 GTEST_CHECK_(captured_fd != -1) << "Unable to open temporary file "
8653 filename_ = temp_file_path;
8655 // There's no guarantee that a test has write access to the current
8656 // directory, so we create the temporary file in the /tmp directory
8657 // instead. We use /tmp on most systems, and /sdcard on Android.
8658 // That's because Android doesn't have /tmp.
8659 # if GTEST_OS_LINUX_ANDROID
8660 // Note: Android applications are expected to call the framework's
8661 // Context.getExternalStorageDirectory() method through JNI to get
8662 // the location of the world-writable SD Card directory. However,
8663 // this requires a Context handle, which cannot be retrieved
8664 // globally from native code. Doing so also precludes running the
8665 // code as part of a regular standalone executable, which doesn't
8666 // run in a Dalvik process (e.g. when running it through 'adb shell').
8668 // The location /sdcard is directly accessible from native code
8669 // and is the only location (unofficially) supported by the Android
8670 // team. It's generally a symlink to the real SD Card mount point
8671 // which can be /mnt/sdcard, /mnt/sdcard0, /system/media/sdcard, or
8672 // other OEM-customized locations. Never rely on these, and always
8674 char name_template[] = "/sdcard/gtest_captured_stream.XXXXXX";
8676 char name_template[] = "/tmp/captured_stream.XXXXXX";
8677 # endif // GTEST_OS_LINUX_ANDROID
8678 const int captured_fd = mkstemp(name_template);
8679 filename_ = name_template;
8680 # endif // GTEST_OS_WINDOWS
8682 dup2(captured_fd, fd_);
8687 remove(filename_.c_str());
8690 std::string GetCapturedString() {
8691 if (uncaptured_fd_ != -1) {
8692 // Restores the original stream.
8694 dup2(uncaptured_fd_, fd_);
8695 close(uncaptured_fd_);
8696 uncaptured_fd_ = -1;
8699 FILE* const file = posix::FOpen(filename_.c_str(), "r");
8700 const std::string content = ReadEntireFile(file);
8701 posix::FClose(file);
8706 // Reads the entire content of a file as an std::string.
8707 static std::string ReadEntireFile(FILE* file);
8709 // Returns the size (in bytes) of a file.
8710 static size_t GetFileSize(FILE* file);
8712 const int fd_; // A stream to capture.
8714 // Name of the temporary file holding the stderr output.
8715 ::std::string filename_;
8717 GTEST_DISALLOW_COPY_AND_ASSIGN_(CapturedStream);
8720 // Returns the size (in bytes) of a file.
8721 size_t CapturedStream::GetFileSize(FILE* file) {
8722 fseek(file, 0, SEEK_END);
8723 return static_cast<size_t>(ftell(file));
8726 // Reads the entire content of a file as a string.
8727 std::string CapturedStream::ReadEntireFile(FILE* file) {
8728 const size_t file_size = GetFileSize(file);
8729 char* const buffer = new char[file_size];
8731 size_t bytes_last_read = 0; // # of bytes read in the last fread()
8732 size_t bytes_read = 0; // # of bytes read so far
8734 fseek(file, 0, SEEK_SET);
8736 // Keeps reading the file until we cannot read further or the
8737 // pre-determined file size is reached.
8739 bytes_last_read = fread(buffer+bytes_read, 1, file_size-bytes_read, file);
8740 bytes_read += bytes_last_read;
8741 } while (bytes_last_read > 0 && bytes_read < file_size);
8743 const std::string content(buffer, bytes_read);
8750 # pragma warning(pop)
8753 static CapturedStream* g_captured_stderr = NULL;
8754 static CapturedStream* g_captured_stdout = NULL;
8756 // Starts capturing an output stream (stdout/stderr).
8757 static void CaptureStream(int fd, const char* stream_name, CapturedStream** stream) {
8758 if (*stream != NULL) {
8759 GTEST_LOG_(FATAL) << "Only one " << stream_name
8760 << " capturer can exist at a time.";
8762 *stream = new CapturedStream(fd);
8765 // Stops capturing the output stream and returns the captured string.
8766 static std::string GetCapturedStream(CapturedStream** captured_stream) {
8767 const std::string content = (*captured_stream)->GetCapturedString();
8769 delete *captured_stream;
8770 *captured_stream = NULL;
8775 // Starts capturing stdout.
8776 void CaptureStdout() {
8777 CaptureStream(kStdOutFileno, "stdout", &g_captured_stdout);
8780 // Starts capturing stderr.
8781 void CaptureStderr() {
8782 CaptureStream(kStdErrFileno, "stderr", &g_captured_stderr);
8785 // Stops capturing stdout and returns the captured string.
8786 std::string GetCapturedStdout() {
8787 return GetCapturedStream(&g_captured_stdout);
8790 // Stops capturing stderr and returns the captured string.
8791 std::string GetCapturedStderr() {
8792 return GetCapturedStream(&g_captured_stderr);
8795 #endif // GTEST_HAS_STREAM_REDIRECTION
8797 #if GTEST_HAS_DEATH_TEST
8799 // A copy of all command line arguments. Set by InitGoogleTest().
8800 ::std::vector<testing::internal::string> g_argvs;
8802 static const ::std::vector<testing::internal::string>* g_injected_test_argvs =
8805 void SetInjectableArgvs(const ::std::vector<testing::internal::string>* argvs) {
8806 if (g_injected_test_argvs != argvs)
8807 delete g_injected_test_argvs;
8808 g_injected_test_argvs = argvs;
8811 const ::std::vector<testing::internal::string>& GetInjectableArgvs() {
8812 if (g_injected_test_argvs != NULL) {
8813 return *g_injected_test_argvs;
8817 #endif // GTEST_HAS_DEATH_TEST
8819 #if GTEST_OS_WINDOWS_MOBILE
8823 TerminateProcess(GetCurrentProcess(), 1);
8825 } // namespace posix
8826 #endif // GTEST_OS_WINDOWS_MOBILE
8828 // Returns the name of the environment variable corresponding to the
8829 // given flag. For example, FlagToEnvVar("foo") will return
8830 // "GTEST_FOO" in the open-source version.
8831 static std::string FlagToEnvVar(const char* flag) {
8832 const std::string full_flag =
8833 (Message() << GTEST_FLAG_PREFIX_ << flag).GetString();
8836 for (size_t i = 0; i != full_flag.length(); i++) {
8837 env_var << ToUpper(full_flag.c_str()[i]);
8840 return env_var.GetString();
8843 // Parses 'str' for a 32-bit signed integer. If successful, writes
8844 // the result to *value and returns true; otherwise leaves *value
8845 // unchanged and returns false.
8846 bool ParseInt32(const Message& src_text, const char* str, Int32* value) {
8847 // Parses the environment variable as a decimal integer.
8849 const long long_value = strtol(str, &end, 10); // NOLINT
8851 // Has strtol() consumed all characters in the string?
8853 // No - an invalid character was encountered.
8855 msg << "WARNING: " << src_text
8856 << " is expected to be a 32-bit integer, but actually"
8857 << " has value \"" << str << "\".\n";
8858 printf("%s", msg.GetString().c_str());
8863 // Is the parsed value in the range of an Int32?
8864 const Int32 result = static_cast<Int32>(long_value);
8865 if (long_value == LONG_MAX || long_value == LONG_MIN ||
8866 // The parsed value overflows as a long. (strtol() returns
8867 // LONG_MAX or LONG_MIN when the input overflows.)
8868 result != long_value
8869 // The parsed value overflows as an Int32.
8872 msg << "WARNING: " << src_text
8873 << " is expected to be a 32-bit integer, but actually"
8874 << " has value " << str << ", which overflows.\n";
8875 printf("%s", msg.GetString().c_str());
8884 // Reads and returns the Boolean environment variable corresponding to
8885 // the given flag; if it's not set, returns default_value.
8887 // The value is considered true iff it's not "0".
8888 bool BoolFromGTestEnv(const char* flag, bool default_value) {
8889 const std::string env_var = FlagToEnvVar(flag);
8890 const char* const string_value = posix::GetEnv(env_var.c_str());
8891 return string_value == NULL ?
8892 default_value : strcmp(string_value, "0") != 0;
8895 // Reads and returns a 32-bit integer stored in the environment
8896 // variable corresponding to the given flag; if it isn't set or
8897 // doesn't represent a valid 32-bit integer, returns default_value.
8898 Int32 Int32FromGTestEnv(const char* flag, Int32 default_value) {
8899 const std::string env_var = FlagToEnvVar(flag);
8900 const char* const string_value = posix::GetEnv(env_var.c_str());
8901 if (string_value == NULL) {
8902 // The environment variable is not set.
8903 return default_value;
8906 Int32 result = default_value;
8907 if (!ParseInt32(Message() << "Environment variable " << env_var,
8908 string_value, &result)) {
8909 printf("The default value %s is used.\n",
8910 (Message() << default_value).GetString().c_str());
8912 return default_value;
8918 // Reads and returns the string environment variable corresponding to
8919 // the given flag; if it's not set, returns default_value.
8920 const char* StringFromGTestEnv(const char* flag, const char* default_value) {
8921 const std::string env_var = FlagToEnvVar(flag);
8922 const char* const value = posix::GetEnv(env_var.c_str());
8923 return value == NULL ? default_value : value;
8926 } // namespace internal
8927 } // namespace testing
8928 // Copyright 2007, Google Inc.
8929 // All rights reserved.
8931 // Redistribution and use in source and binary forms, with or without
8932 // modification, are permitted provided that the following conditions are
8935 // * Redistributions of source code must retain the above copyright
8936 // notice, this list of conditions and the following disclaimer.
8937 // * Redistributions in binary form must reproduce the above
8938 // copyright notice, this list of conditions and the following disclaimer
8939 // in the documentation and/or other materials provided with the
8941 // * Neither the name of Google Inc. nor the names of its
8942 // contributors may be used to endorse or promote products derived from
8943 // this software without specific prior written permission.
8945 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
8946 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
8947 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
8948 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
8949 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
8950 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
8951 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
8952 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
8953 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
8954 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
8955 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
8957 // Author: wan@google.com (Zhanyong Wan)
8959 // Google Test - The Google C++ Testing Framework
8961 // This file implements a universal value printer that can print a
8962 // value of any type T:
8964 // void ::testing::internal::UniversalPrinter<T>::Print(value, ostream_ptr);
8966 // It uses the << operator when possible, and prints the bytes in the
8967 // object otherwise. A user can override its behavior for a class
8968 // type Foo by defining either operator<<(::std::ostream&, const Foo&)
8969 // or void PrintTo(const Foo&, ::std::ostream*) in the namespace that
8974 #include <ostream> // NOLINT
8981 using ::std::ostream;
8983 // Prints a segment of bytes in the given object.
8984 void PrintByteSegmentInObjectTo(const unsigned char* obj_bytes, size_t start,
8985 size_t count, ostream* os) {
8987 for (size_t i = 0; i != count; i++) {
8988 const size_t j = start + i;
8990 // Organizes the bytes into groups of 2 for easy parsing by
8997 GTEST_SNPRINTF_(text, sizeof(text), "%02X", obj_bytes[j]);
9002 // Prints the bytes in the given value to the given ostream.
9003 void PrintBytesInObjectToImpl(const unsigned char* obj_bytes, size_t count,
9005 // Tells the user how big the object is.
9006 *os << count << "-byte object <";
9008 const size_t kThreshold = 132;
9009 const size_t kChunkSize = 64;
9010 // If the object size is bigger than kThreshold, we'll have to omit
9011 // some details by printing only the first and the last kChunkSize
9013 // TODO(wan): let the user control the threshold using a flag.
9014 if (count < kThreshold) {
9015 PrintByteSegmentInObjectTo(obj_bytes, 0, count, os);
9017 PrintByteSegmentInObjectTo(obj_bytes, 0, kChunkSize, os);
9019 // Rounds up to 2-byte boundary.
9020 const size_t resume_pos = (count - kChunkSize + 1)/2*2;
9021 PrintByteSegmentInObjectTo(obj_bytes, resume_pos, count - resume_pos, os);
9028 namespace internal2 {
9030 // Delegates to PrintBytesInObjectToImpl() to print the bytes in the
9031 // given object. The delegation simplifies the implementation, which
9032 // uses the << operator and thus is easier done outside of the
9033 // ::testing::internal namespace, which contains a << operator that
9034 // sometimes conflicts with the one in STL.
9035 void PrintBytesInObjectTo(const unsigned char* obj_bytes, size_t count,
9037 PrintBytesInObjectToImpl(obj_bytes, count, os);
9040 } // namespace internal2
9042 namespace internal {
9044 // Depending on the value of a char (or wchar_t), we print it in one
9045 // of three formats:
9046 // - as is if it's a printable ASCII (e.g. 'a', '2', ' '),
9047 // - as a hexidecimal escape sequence (e.g. '\x7F'), or
9048 // - as a special escape sequence (e.g. '\r', '\n').
9055 // Returns true if c is a printable ASCII character. We test the
9056 // value of c directly instead of calling isprint(), which is buggy on
9058 inline bool IsPrintableAscii(wchar_t c) {
9059 return 0x20 <= c && c <= 0x7E;
9062 // Prints a wide or narrow char c as a character literal without the
9063 // quotes, escaping it when necessary; returns how c was formatted.
9064 // The template argument UnsignedChar is the unsigned version of Char,
9065 // which is the type of c.
9066 template <typename UnsignedChar, typename Char>
9067 static CharFormat PrintAsCharLiteralTo(Char c, ostream* os) {
9068 switch (static_cast<wchar_t>(c)) {
9100 if (IsPrintableAscii(c)) {
9101 *os << static_cast<char>(c);
9104 *os << "\\x" + String::FormatHexInt(static_cast<UnsignedChar>(c));
9108 return kSpecialEscape;
9111 // Prints a wchar_t c as if it's part of a string literal, escaping it when
9112 // necessary; returns how c was formatted.
9113 static CharFormat PrintAsStringLiteralTo(wchar_t c, ostream* os) {
9120 return kSpecialEscape;
9122 return PrintAsCharLiteralTo<wchar_t>(c, os);
9126 // Prints a char c as if it's part of a string literal, escaping it when
9127 // necessary; returns how c was formatted.
9128 static CharFormat PrintAsStringLiteralTo(char c, ostream* os) {
9129 return PrintAsStringLiteralTo(
9130 static_cast<wchar_t>(static_cast<unsigned char>(c)), os);
9133 // Prints a wide or narrow character c and its code. '\0' is printed
9134 // as "'\\0'", other unprintable characters are also properly escaped
9135 // using the standard C++ escape sequence. The template argument
9136 // UnsignedChar is the unsigned version of Char, which is the type of c.
9137 template <typename UnsignedChar, typename Char>
9138 void PrintCharAndCodeTo(Char c, ostream* os) {
9139 // First, print c as a literal in the most readable form we can find.
9140 *os << ((sizeof(c) > 1) ? "L'" : "'");
9141 const CharFormat format = PrintAsCharLiteralTo<UnsignedChar>(c, os);
9144 // To aid user debugging, we also print c's code in decimal, unless
9145 // it's 0 (in which case c was printed as '\\0', making the code
9149 *os << " (" << static_cast<int>(c);
9151 // For more convenience, we print c's code again in hexidecimal,
9152 // unless c was already printed in the form '\x##' or the code is in
9154 if (format == kHexEscape || (1 <= c && c <= 9)) {
9157 *os << ", 0x" << String::FormatHexInt(static_cast<UnsignedChar>(c));
9162 void PrintTo(unsigned char c, ::std::ostream* os) {
9163 PrintCharAndCodeTo<unsigned char>(c, os);
9165 void PrintTo(signed char c, ::std::ostream* os) {
9166 PrintCharAndCodeTo<unsigned char>(c, os);
9169 // Prints a wchar_t as a symbol if it is printable or as its internal
9170 // code otherwise and also as its code. L'\0' is printed as "L'\\0'".
9171 void PrintTo(wchar_t wc, ostream* os) {
9172 PrintCharAndCodeTo<wchar_t>(wc, os);
9175 // Prints the given array of characters to the ostream. CharType must be either
9177 // The array starts at begin, the length is len, it may include '\0' characters
9178 // and may not be NUL-terminated.
9179 template <typename CharType>
9180 static void PrintCharsAsStringTo(
9181 const CharType* begin, size_t len, ostream* os) {
9182 const char* const kQuoteBegin = sizeof(CharType) == 1 ? "\"" : "L\"";
9184 bool is_previous_hex = false;
9185 for (size_t index = 0; index < len; ++index) {
9186 const CharType cur = begin[index];
9187 if (is_previous_hex && IsXDigit(cur)) {
9188 // Previous character is of '\x..' form and this character can be
9189 // interpreted as another hexadecimal digit in its number. Break string to
9191 *os << "\" " << kQuoteBegin;
9193 is_previous_hex = PrintAsStringLiteralTo(cur, os) == kHexEscape;
9198 // Prints a (const) char/wchar_t array of 'len' elements, starting at address
9199 // 'begin'. CharType must be either char or wchar_t.
9200 template <typename CharType>
9201 static void UniversalPrintCharArray(
9202 const CharType* begin, size_t len, ostream* os) {
9204 // const char kFoo[] = "foo";
9205 // generates an array of 4, not 3, elements, with the last one being '\0'.
9207 // Therefore when printing a char array, we don't print the last element if
9208 // it's '\0', such that the output matches the string literal as it's
9209 // written in the source code.
9210 if (len > 0 && begin[len - 1] == '\0') {
9211 PrintCharsAsStringTo(begin, len - 1, os);
9215 // If, however, the last element in the array is not '\0', e.g.
9216 // const char kFoo[] = { 'f', 'o', 'o' };
9217 // we must print the entire array. We also print a message to indicate
9218 // that the array is not NUL-terminated.
9219 PrintCharsAsStringTo(begin, len, os);
9220 *os << " (no terminating NUL)";
9223 // Prints a (const) char array of 'len' elements, starting at address 'begin'.
9224 void UniversalPrintArray(const char* begin, size_t len, ostream* os) {
9225 UniversalPrintCharArray(begin, len, os);
9228 // Prints a (const) wchar_t array of 'len' elements, starting at address
9230 void UniversalPrintArray(const wchar_t* begin, size_t len, ostream* os) {
9231 UniversalPrintCharArray(begin, len, os);
9234 // Prints the given C string to the ostream.
9235 void PrintTo(const char* s, ostream* os) {
9239 *os << ImplicitCast_<const void*>(s) << " pointing to ";
9240 PrintCharsAsStringTo(s, strlen(s), os);
9244 // MSVC compiler can be configured to define whar_t as a typedef
9245 // of unsigned short. Defining an overload for const wchar_t* in that case
9246 // would cause pointers to unsigned shorts be printed as wide strings,
9247 // possibly accessing more memory than intended and causing invalid
9248 // memory accesses. MSVC defines _NATIVE_WCHAR_T_DEFINED symbol when
9249 // wchar_t is implemented as a native type.
9250 #if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED)
9251 // Prints the given wide C string to the ostream.
9252 void PrintTo(const wchar_t* s, ostream* os) {
9256 *os << ImplicitCast_<const void*>(s) << " pointing to ";
9257 PrintCharsAsStringTo(s, wcslen(s), os);
9260 #endif // wchar_t is native
9262 // Prints a ::string object.
9263 #if GTEST_HAS_GLOBAL_STRING
9264 void PrintStringTo(const ::string& s, ostream* os) {
9265 PrintCharsAsStringTo(s.data(), s.size(), os);
9267 #endif // GTEST_HAS_GLOBAL_STRING
9269 void PrintStringTo(const ::std::string& s, ostream* os) {
9270 PrintCharsAsStringTo(s.data(), s.size(), os);
9273 // Prints a ::wstring object.
9274 #if GTEST_HAS_GLOBAL_WSTRING
9275 void PrintWideStringTo(const ::wstring& s, ostream* os) {
9276 PrintCharsAsStringTo(s.data(), s.size(), os);
9278 #endif // GTEST_HAS_GLOBAL_WSTRING
9280 #if GTEST_HAS_STD_WSTRING
9281 void PrintWideStringTo(const ::std::wstring& s, ostream* os) {
9282 PrintCharsAsStringTo(s.data(), s.size(), os);
9284 #endif // GTEST_HAS_STD_WSTRING
9286 } // namespace internal
9288 } // namespace testing
9289 // Copyright 2008, Google Inc.
9290 // All rights reserved.
9292 // Redistribution and use in source and binary forms, with or without
9293 // modification, are permitted provided that the following conditions are
9296 // * Redistributions of source code must retain the above copyright
9297 // notice, this list of conditions and the following disclaimer.
9298 // * Redistributions in binary form must reproduce the above
9299 // copyright notice, this list of conditions and the following disclaimer
9300 // in the documentation and/or other materials provided with the
9302 // * Neither the name of Google Inc. nor the names of its
9303 // contributors may be used to endorse or promote products derived from
9304 // this software without specific prior written permission.
9306 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
9307 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
9308 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
9309 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9310 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
9311 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9312 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
9313 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
9314 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
9315 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
9316 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
9318 // Author: mheule@google.com (Markus Heule)
9320 // The Google C++ Testing Framework (Google Test)
9323 // Indicates that this translation unit is part of Google Test's
9324 // implementation. It must come before gtest-internal-inl.h is
9325 // included, or there will be a compiler error. This trick is to
9326 // prevent a user from accidentally including gtest-internal-inl.h in
9328 #define GTEST_IMPLEMENTATION_ 1
9329 #undef GTEST_IMPLEMENTATION_
9333 using internal::GetUnitTestImpl;
9335 // Gets the summary of the failure message by omitting the stack trace
9337 std::string TestPartResult::ExtractSummary(const char* message) {
9338 const char* const stack_trace = strstr(message, internal::kStackTraceMarker);
9339 return stack_trace == NULL ? message :
9340 std::string(message, stack_trace);
9343 // Prints a TestPartResult object.
9344 std::ostream& operator<<(std::ostream& os, const TestPartResult& result) {
9346 << result.file_name() << ":" << result.line_number() << ": "
9347 << (result.type() == TestPartResult::kSuccess ? "Success" :
9348 result.type() == TestPartResult::kFatalFailure ? "Fatal failure" :
9349 "Non-fatal failure") << ":\n"
9350 << result.message() << std::endl;
9353 // Appends a TestPartResult to the array.
9354 void TestPartResultArray::Append(const TestPartResult& result) {
9355 array_.push_back(result);
9358 // Returns the TestPartResult at the given index (0-based).
9359 const TestPartResult& TestPartResultArray::GetTestPartResult(int index) const {
9360 if (index < 0 || index >= size()) {
9361 printf("\nInvalid index (%d) into TestPartResultArray.\n", index);
9362 internal::posix::Abort();
9365 return array_[index];
9368 // Returns the number of TestPartResult objects in the array.
9369 int TestPartResultArray::size() const {
9370 return static_cast<int>(array_.size());
9373 namespace internal {
9375 HasNewFatalFailureHelper::HasNewFatalFailureHelper()
9376 : has_new_fatal_failure_(false),
9377 original_reporter_(GetUnitTestImpl()->
9378 GetTestPartResultReporterForCurrentThread()) {
9379 GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(this);
9382 HasNewFatalFailureHelper::~HasNewFatalFailureHelper() {
9383 GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(
9384 original_reporter_);
9387 void HasNewFatalFailureHelper::ReportTestPartResult(
9388 const TestPartResult& result) {
9389 if (result.fatally_failed())
9390 has_new_fatal_failure_ = true;
9391 original_reporter_->ReportTestPartResult(result);
9394 } // namespace internal
9396 } // namespace testing
9397 // Copyright 2008 Google Inc.
9398 // All Rights Reserved.
9400 // Redistribution and use in source and binary forms, with or without
9401 // modification, are permitted provided that the following conditions are
9404 // * Redistributions of source code must retain the above copyright
9405 // notice, this list of conditions and the following disclaimer.
9406 // * Redistributions in binary form must reproduce the above
9407 // copyright notice, this list of conditions and the following disclaimer
9408 // in the documentation and/or other materials provided with the
9410 // * Neither the name of Google Inc. nor the names of its
9411 // contributors may be used to endorse or promote products derived from
9412 // this software without specific prior written permission.
9414 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
9415 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
9416 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
9417 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9418 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
9419 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9420 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
9421 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
9422 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
9423 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
9424 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
9426 // Author: wan@google.com (Zhanyong Wan)
9430 namespace internal {
9432 #if GTEST_HAS_TYPED_TEST_P
9434 // Skips to the first non-space char in str. Returns an empty string if str
9435 // contains only whitespace characters.
9436 static const char* SkipSpaces(const char* str) {
9437 while (IsSpace(*str))
9442 // Verifies that registered_tests match the test names in
9443 // defined_test_names_; returns registered_tests if successful, or
9444 // aborts the program otherwise.
9445 const char* TypedTestCasePState::VerifyRegisteredTestNames(
9446 const char* file, int line, const char* registered_tests) {
9447 typedef ::std::set<const char*>::const_iterator DefinedTestIter;
9450 // Skip initial whitespace in registered_tests since some
9451 // preprocessors prefix stringizied literals with whitespace.
9452 registered_tests = SkipSpaces(registered_tests);
9455 ::std::set<std::string> tests;
9456 for (const char* names = registered_tests; names != NULL;
9457 names = SkipComma(names)) {
9458 const std::string name = GetPrefixUntilComma(names);
9459 if (tests.count(name) != 0) {
9460 errors << "Test " << name << " is listed more than once.\n";
9465 for (DefinedTestIter it = defined_test_names_.begin();
9466 it != defined_test_names_.end();
9477 errors << "No test named " << name
9478 << " can be found in this test case.\n";
9482 for (DefinedTestIter it = defined_test_names_.begin();
9483 it != defined_test_names_.end();
9485 if (tests.count(*it) == 0) {
9486 errors << "You forgot to list test " << *it << ".\n";
9490 const std::string& errors_str = errors.GetString();
9491 if (errors_str != "") {
9492 fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(),
9493 errors_str.c_str());
9498 return registered_tests;
9501 #endif // GTEST_HAS_TYPED_TEST_P
9503 } // namespace internal
9504 } // namespace testing