gtest-all.cc revision 8b52a31e
1// Copyright 2008, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
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
13// distribution.
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.
17//
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.
29//
30// Author: mheule@google.com (Markus Heule)
31//
32// Google C++ Testing Framework (Google Test)
33//
34// Sometimes it's desirable to build Google Test by compiling a single file.
35// This file serves this purpose.
36
37// This line ensures that gtest.h can be compiled on its own, even
38// when it's fused.
39//
40//
41/*****
42 * NAME
43 *
44 *
45 * AUTHOR
46 *   google
47 *
48 * COPYRIGHT
49 *   Copyright (c) 2004-2011 by cisco Systems, Inc.
50 *   All rights reserved.
51 *
52 * DESCRIPTION
53 *
54 ****/
55
56#include <common/gtest.h>
57
58// The following lines pull in the real gtest *.cc files.
59// Copyright 2005, Google Inc.
60// All rights reserved.
61//
62// Redistribution and use in source and binary forms, with or without
63// modification, are permitted provided that the following conditions are
64// met:
65//
66//     * Redistributions of source code must retain the above copyright
67// notice, this list of conditions and the following disclaimer.
68//     * Redistributions in binary form must reproduce the above
69// copyright notice, this list of conditions and the following disclaimer
70// in the documentation and/or other materials provided with the
71// distribution.
72//     * Neither the name of Google Inc. nor the names of its
73// contributors may be used to endorse or promote products derived from
74// this software without specific prior written permission.
75//
76// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
77// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
78// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
79// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
80// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
81// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
82// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
83// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
84// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
85// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
86// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
87//
88// Author: wan@google.com (Zhanyong Wan)
89//
90// The Google C++ Testing Framework (Google Test)
91
92// Copyright 2007, Google Inc.
93// All rights reserved.
94//
95// Redistribution and use in source and binary forms, with or without
96// modification, are permitted provided that the following conditions are
97// met:
98//
99//     * Redistributions of source code must retain the above copyright
100// notice, this list of conditions and the following disclaimer.
101//     * Redistributions in binary form must reproduce the above
102// copyright notice, this list of conditions and the following disclaimer
103// in the documentation and/or other materials provided with the
104// distribution.
105//     * Neither the name of Google Inc. nor the names of its
106// contributors may be used to endorse or promote products derived from
107// this software without specific prior written permission.
108//
109// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
110// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
111// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
112// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
113// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
114// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
115// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
116// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
117// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
118// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
119// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
120//
121// Author: wan@google.com (Zhanyong Wan)
122//
123// Utilities for testing Google Test itself and code that uses Google Test
124// (e.g. frameworks built on top of Google Test).
125
126#ifndef GTEST_INCLUDE_GTEST_GTEST_SPI_H_
127#define GTEST_INCLUDE_GTEST_GTEST_SPI_H_
128
129
130namespace testing {
131
132// This helper class can be used to mock out Google Test failure reporting
133// so that we can test Google Test or code that builds on Google Test.
134//
135// An object of this class appends a TestPartResult object to the
136// TestPartResultArray object given in the constructor whenever a Google Test
137// failure is reported. It can either intercept only failures that are
138// generated in the same thread that created this object or it can intercept
139// all generated failures. The scope of this mock object can be controlled with
140// the second argument to the two arguments constructor.
141class GTEST_API_ ScopedFakeTestPartResultReporter
142    : public TestPartResultReporterInterface {
143 public:
144  // The two possible mocking modes of this object.
145  enum InterceptMode {
146    INTERCEPT_ONLY_CURRENT_THREAD,  // Intercepts only thread local failures.
147    INTERCEPT_ALL_THREADS           // Intercepts all failures.
148  };
149
150  // The c'tor sets this object as the test part result reporter used
151  // by Google Test.  The 'result' parameter specifies where to report the
152  // results. This reporter will only catch failures generated in the current
153  // thread. DEPRECATED
154  explicit ScopedFakeTestPartResultReporter(TestPartResultArray* result);
155
156  // Same as above, but you can choose the interception scope of this object.
157  ScopedFakeTestPartResultReporter(InterceptMode intercept_mode,
158                                   TestPartResultArray* result);
159
160  // The d'tor restores the previous test part result reporter.
161  virtual ~ScopedFakeTestPartResultReporter();
162
163  // Appends the TestPartResult object to the TestPartResultArray
164  // received in the constructor.
165  //
166  // This method is from the TestPartResultReporterInterface
167  // interface.
168  virtual void ReportTestPartResult(const TestPartResult& result);
169 private:
170  void Init();
171
172  const InterceptMode intercept_mode_;
173  TestPartResultReporterInterface* old_reporter_;
174  TestPartResultArray* const result_;
175
176  GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedFakeTestPartResultReporter);
177};
178
179namespace internal {
180
181// A helper class for implementing EXPECT_FATAL_FAILURE() and
182// EXPECT_NONFATAL_FAILURE().  Its destructor verifies that the given
183// TestPartResultArray contains exactly one failure that has the given
184// type and contains the given substring.  If that's not the case, a
185// non-fatal failure will be generated.
186class GTEST_API_ SingleFailureChecker {
187 public:
188  // The constructor remembers the arguments.
189  SingleFailureChecker(const TestPartResultArray* results,
190                       TestPartResult::Type type,
191                       const char* substr);
192  ~SingleFailureChecker();
193 private:
194  const TestPartResultArray* const results_;
195  const TestPartResult::Type type_;
196  const String substr_;
197
198  GTEST_DISALLOW_COPY_AND_ASSIGN_(SingleFailureChecker);
199};
200
201}  // namespace internal
202
203}  // namespace testing
204
205// A set of macros for testing Google Test assertions or code that's expected
206// to generate Google Test fatal failures.  It verifies that the given
207// statement will cause exactly one fatal Google Test failure with 'substr'
208// being part of the failure message.
209//
210// There are two different versions of this macro. EXPECT_FATAL_FAILURE only
211// affects and considers failures generated in the current thread and
212// EXPECT_FATAL_FAILURE_ON_ALL_THREADS does the same but for all threads.
213//
214// The verification of the assertion is done correctly even when the statement
215// throws an exception or aborts the current function.
216//
217// Known restrictions:
218//   - 'statement' cannot reference local non-static variables or
219//     non-static members of the current object.
220//   - 'statement' cannot return a value.
221//   - You cannot stream a failure message to this macro.
222//
223// Note that even though the implementations of the following two
224// macros are much alike, we cannot refactor them to use a common
225// helper macro, due to some peculiarity in how the preprocessor
226// works.  The AcceptsMacroThatExpandsToUnprotectedComma test in
227// gtest_unittest.cc will fail to compile if we do that.
228#define EXPECT_FATAL_FAILURE(statement, substr) \
229  do { \
230    class GTestExpectFatalFailureHelper {\
231     public:\
232      static void Execute() { statement; }\
233    };\
234    ::testing::TestPartResultArray gtest_failures;\
235    ::testing::internal::SingleFailureChecker gtest_checker(\
236        &gtest_failures, ::testing::TestPartResult::kFatalFailure, (substr));\
237    {\
238      ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
239          ::testing::ScopedFakeTestPartResultReporter:: \
240          INTERCEPT_ONLY_CURRENT_THREAD, &gtest_failures);\
241      GTestExpectFatalFailureHelper::Execute();\
242    }\
243  } while (::testing::internal::AlwaysFalse())
244
245#define EXPECT_FATAL_FAILURE_ON_ALL_THREADS(statement, substr) \
246  do { \
247    class GTestExpectFatalFailureHelper {\
248     public:\
249      static void Execute() { statement; }\
250    };\
251    ::testing::TestPartResultArray gtest_failures;\
252    ::testing::internal::SingleFailureChecker gtest_checker(\
253        &gtest_failures, ::testing::TestPartResult::kFatalFailure, (substr));\
254    {\
255      ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
256          ::testing::ScopedFakeTestPartResultReporter:: \
257          INTERCEPT_ALL_THREADS, &gtest_failures);\
258      GTestExpectFatalFailureHelper::Execute();\
259    }\
260  } while (::testing::internal::AlwaysFalse())
261
262// A macro for testing Google Test assertions or code that's expected to
263// generate Google Test non-fatal failures.  It asserts that the given
264// statement will cause exactly one non-fatal Google Test failure with 'substr'
265// being part of the failure message.
266//
267// There are two different versions of this macro. EXPECT_NONFATAL_FAILURE only
268// affects and considers failures generated in the current thread and
269// EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS does the same but for all threads.
270//
271// 'statement' is allowed to reference local variables and members of
272// the current object.
273//
274// The verification of the assertion is done correctly even when the statement
275// throws an exception or aborts the current function.
276//
277// Known restrictions:
278//   - You cannot stream a failure message to this macro.
279//
280// Note that even though the implementations of the following two
281// macros are much alike, we cannot refactor them to use a common
282// helper macro, due to some peculiarity in how the preprocessor
283// works.  If we do that, the code won't compile when the user gives
284// EXPECT_NONFATAL_FAILURE() a statement that contains a macro that
285// expands to code containing an unprotected comma.  The
286// AcceptsMacroThatExpandsToUnprotectedComma test in gtest_unittest.cc
287// catches that.
288//
289// For the same reason, we have to write
290//   if (::testing::internal::AlwaysTrue()) { statement; }
291// instead of
292//   GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement)
293// to avoid an MSVC warning on unreachable code.
294#define EXPECT_NONFATAL_FAILURE(statement, substr) \
295  do {\
296    ::testing::TestPartResultArray gtest_failures;\
297    ::testing::internal::SingleFailureChecker gtest_checker(\
298        &gtest_failures, ::testing::TestPartResult::kNonFatalFailure, \
299        (substr));\
300    {\
301      ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
302          ::testing::ScopedFakeTestPartResultReporter:: \
303          INTERCEPT_ONLY_CURRENT_THREAD, &gtest_failures);\
304      if (::testing::internal::AlwaysTrue()) { statement; }\
305    }\
306  } while (::testing::internal::AlwaysFalse())
307
308#define EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(statement, substr) \
309  do {\
310    ::testing::TestPartResultArray gtest_failures;\
311    ::testing::internal::SingleFailureChecker gtest_checker(\
312        &gtest_failures, ::testing::TestPartResult::kNonFatalFailure, \
313        (substr));\
314    {\
315      ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
316          ::testing::ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS,\
317          &gtest_failures);\
318      if (::testing::internal::AlwaysTrue()) { statement; }\
319    }\
320  } while (::testing::internal::AlwaysFalse())
321
322#endif  // GTEST_INCLUDE_GTEST_GTEST_SPI_H_
323
324#include <ctype.h>
325#include <math.h>
326#include <stdarg.h>
327#include <stdio.h>
328#include <stdlib.h>
329#include <wchar.h>
330#include <wctype.h>
331
332#include <algorithm>
333#include <ostream>
334#include <sstream>
335#include <vector>
336
337#if GTEST_OS_LINUX
338
339// TODO(kenton@google.com): Use autoconf to detect availability of
340// gettimeofday().
341#define GTEST_HAS_GETTIMEOFDAY_ 1
342
343#include <fcntl.h>
344#include <limits.h>
345#include <sched.h>
346// Declares vsnprintf().  This header is not available on Windows.
347#include <strings.h>
348#include <sys/mman.h>
349#include <sys/time.h>
350#include <unistd.h>
351#include <string>
352#include <vector>
353
354#elif GTEST_OS_SYMBIAN
355#define GTEST_HAS_GETTIMEOFDAY_ 1
356#include <sys/time.h>  // NOLINT
357
358#elif GTEST_OS_ZOS
359#define GTEST_HAS_GETTIMEOFDAY_ 1
360#include <sys/time.h>  // NOLINT
361
362// On z/OS we additionally need strings.h for strcasecmp.
363#include <strings.h>  // NOLINT
364
365#elif GTEST_OS_WINDOWS_MOBILE  // We are on Windows CE.
366
367#include <windows.h>  // NOLINT
368
369#elif GTEST_OS_WINDOWS  // We are on Windows proper.
370
371#include <io.h>  // NOLINT
372#include <sys/timeb.h>  // NOLINT
373#include <sys/types.h>  // NOLINT
374#include <sys/stat.h>  // NOLINT
375
376#if GTEST_OS_WINDOWS_MINGW
377// MinGW has gettimeofday() but not _ftime64().
378// TODO(kenton@google.com): Use autoconf to detect availability of
379//   gettimeofday().
380// TODO(kenton@google.com): There are other ways to get the time on
381//   Windows, like GetTickCount() or GetSystemTimeAsFileTime().  MinGW
382//   supports these.  consider using them instead.
383#define GTEST_HAS_GETTIMEOFDAY_ 1
384#include <sys/time.h>  // NOLINT
385#endif  // GTEST_OS_WINDOWS_MINGW
386
387// cpplint thinks that the header is already included, so we want to
388// silence it.
389#include <windows.h>  // NOLINT
390
391#else
392
393// Assume other platforms have gettimeofday().
394// TODO(kenton@google.com): Use autoconf to detect availability of
395//   gettimeofday().
396#define GTEST_HAS_GETTIMEOFDAY_ 1
397
398// cpplint thinks that the header is already included, so we want to
399// silence it.
400#include <sys/time.h>  // NOLINT
401#include <unistd.h>  // NOLINT
402
403#endif  // GTEST_OS_LINUX
404
405#if GTEST_HAS_EXCEPTIONS
406#include <stdexcept>
407#endif
408
409// Indicates that this translation unit is part of Google Test's
410// implementation.  It must come before gtest-internal-inl.h is
411// included, or there will be a compiler error.  This trick is to
412// prevent a user from accidentally including gtest-internal-inl.h in
413// his code.
414#define GTEST_IMPLEMENTATION_ 1
415// Copyright 2005, Google Inc.
416// All rights reserved.
417//
418// Redistribution and use in source and binary forms, with or without
419// modification, are permitted provided that the following conditions are
420// met:
421//
422//     * Redistributions of source code must retain the above copyright
423// notice, this list of conditions and the following disclaimer.
424//     * Redistributions in binary form must reproduce the above
425// copyright notice, this list of conditions and the following disclaimer
426// in the documentation and/or other materials provided with the
427// distribution.
428//     * Neither the name of Google Inc. nor the names of its
429// contributors may be used to endorse or promote products derived from
430// this software without specific prior written permission.
431//
432// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
433// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
434// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
435// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
436// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
437// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
438// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
439// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
440// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
441// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
442// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
443
444// Utility functions and classes used by the Google C++ testing framework.
445//
446// Author: wan@google.com (Zhanyong Wan)
447//
448// This file contains purely Google Test's internal implementation.  Please
449// DO NOT #INCLUDE IT IN A USER PROGRAM.
450
451#ifndef GTEST_SRC_GTEST_INTERNAL_INL_H_
452#define GTEST_SRC_GTEST_INTERNAL_INL_H_
453
454// GTEST_IMPLEMENTATION_ is defined to 1 iff the current translation unit is
455// part of Google Test's implementation; otherwise it's undefined.
456#if !GTEST_IMPLEMENTATION_
457// A user is trying to include this from his code - just say no.
458#error "gtest-internal-inl.h is part of Google Test's internal implementation."
459#error "It must not be included except by Google Test itself."
460#endif  // GTEST_IMPLEMENTATION_
461
462#ifndef _WIN32_WCE
463#include <errno.h>
464#endif  // !_WIN32_WCE
465#include <stddef.h>
466#include <stdlib.h>  // For strtoll/_strtoul64/malloc/free.
467#include <string.h>  // For memmove.
468
469#include <algorithm>
470#include <string>
471#include <vector>
472
473
474#if GTEST_OS_WINDOWS
475#include <windows.h>  // For DWORD.
476#endif  // GTEST_OS_WINDOWS
477
478
479namespace testing {
480
481// Declares the flags.
482//
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.
486GTEST_DECLARE_bool_(death_test_use_fork);
487
488namespace internal {
489
490// The value of GetTestTypeId() as seen from within the Google Test
491// library.  This is solely for testing GetTestTypeId().
492GTEST_API_ extern const TypeId kTestTypeIdInGoogleTest;
493
494// Names of the flags (needed for parsing Google Test flags).
495const char kAlsoRunDisabledTestsFlag[] = "also_run_disabled_tests";
496const char kBreakOnFailureFlag[] = "break_on_failure";
497const char kCatchExceptionsFlag[] = "catch_exceptions";
498const char kColorFlag[] = "color";
499const char kFilterFlag[] = "filter";
500const char kListTestsFlag[] = "list_tests";
501const char kOutputFlag[] = "output";
502const char kPrintTimeFlag[] = "print_time";
503const char kRandomSeedFlag[] = "random_seed";
504const char kRepeatFlag[] = "repeat";
505const char kShuffleFlag[] = "shuffle";
506const char kStackTraceDepthFlag[] = "stack_trace_depth";
507const char kThrowOnFailureFlag[] = "throw_on_failure";
508
509// A valid random seed must be in [1, kMaxRandomSeed].
510const int kMaxRandomSeed = 99999;
511
512// g_help_flag is true iff the --help flag or an equivalent form is
513// specified on the command line.
514GTEST_API_ extern bool g_help_flag;
515
516// Returns the current time in milliseconds.
517GTEST_API_ TimeInMillis GetTimeInMillis();
518
519// Returns true iff Google Test should use colors in the output.
520GTEST_API_ bool ShouldUseColor(bool stdout_is_tty);
521
522// Formats the given time in milliseconds as seconds.
523GTEST_API_ std::string FormatTimeInMillisAsSeconds(TimeInMillis ms);
524
525// Parses a string for an Int32 flag, in the form of "--flag=value".
526//
527// On success, stores the value of the flag in *value, and returns
528// true.  On failure, returns false without changing *value.
529GTEST_API_ bool ParseInt32Flag(
530    const char* str, const char* flag, Int32* value);
531
532// Returns a random seed in range [1, kMaxRandomSeed] based on the
533// given --gtest_random_seed flag value.
534inline int GetRandomSeedFromFlag(Int32 random_seed_flag) {
535  const unsigned int raw_seed = (random_seed_flag == 0) ?
536      static_cast<unsigned int>(GetTimeInMillis()) :
537      static_cast<unsigned int>(random_seed_flag);
538
539  // Normalizes the actual seed to range [1, kMaxRandomSeed] such that
540  // it's easy to type.
541  const int normalized_seed =
542      static_cast<int>((raw_seed - 1U) %
543                       static_cast<unsigned int>(kMaxRandomSeed)) + 1;
544  return normalized_seed;
545}
546
547// Returns the first valid random seed after 'seed'.  The behavior is
548// undefined if 'seed' is invalid.  The seed after kMaxRandomSeed is
549// considered to be 1.
550inline int GetNextRandomSeed(int seed) {
551  GTEST_CHECK_(1 <= seed && seed <= kMaxRandomSeed)
552      << "Invalid random seed " << seed << " - must be in [1, "
553      << kMaxRandomSeed << "].";
554  const int next_seed = seed + 1;
555  return (next_seed > kMaxRandomSeed) ? 1 : next_seed;
556}
557
558// This class saves the values of all Google Test flags in its c'tor, and
559// restores them in its d'tor.
560class GTestFlagSaver {
561 public:
562  // The c'tor.
563  GTestFlagSaver() {
564    also_run_disabled_tests_ = GTEST_FLAG(also_run_disabled_tests);
565    break_on_failure_ = GTEST_FLAG(break_on_failure);
566    catch_exceptions_ = GTEST_FLAG(catch_exceptions);
567    color_ = GTEST_FLAG(color);
568    death_test_style_ = GTEST_FLAG(death_test_style);
569    death_test_use_fork_ = GTEST_FLAG(death_test_use_fork);
570    filter_ = GTEST_FLAG(filter);
571    internal_run_death_test_ = GTEST_FLAG(internal_run_death_test);
572    list_tests_ = GTEST_FLAG(list_tests);
573    output_ = GTEST_FLAG(output);
574    print_time_ = GTEST_FLAG(print_time);
575    random_seed_ = GTEST_FLAG(random_seed);
576    repeat_ = GTEST_FLAG(repeat);
577    shuffle_ = GTEST_FLAG(shuffle);
578    stack_trace_depth_ = GTEST_FLAG(stack_trace_depth);
579    throw_on_failure_ = GTEST_FLAG(throw_on_failure);
580  }
581
582  // The d'tor is not virtual.  DO NOT INHERIT FROM THIS CLASS.
583  ~GTestFlagSaver() {
584    GTEST_FLAG(also_run_disabled_tests) = also_run_disabled_tests_;
585    GTEST_FLAG(break_on_failure) = break_on_failure_;
586    GTEST_FLAG(catch_exceptions) = catch_exceptions_;
587    GTEST_FLAG(color) = color_;
588    GTEST_FLAG(death_test_style) = death_test_style_;
589    GTEST_FLAG(death_test_use_fork) = death_test_use_fork_;
590    GTEST_FLAG(filter) = filter_;
591    GTEST_FLAG(internal_run_death_test) = internal_run_death_test_;
592    GTEST_FLAG(list_tests) = list_tests_;
593    GTEST_FLAG(output) = output_;
594    GTEST_FLAG(print_time) = print_time_;
595    GTEST_FLAG(random_seed) = random_seed_;
596    GTEST_FLAG(repeat) = repeat_;
597    GTEST_FLAG(shuffle) = shuffle_;
598    GTEST_FLAG(stack_trace_depth) = stack_trace_depth_;
599    GTEST_FLAG(throw_on_failure) = throw_on_failure_;
600  }
601 private:
602  // Fields for saving the original values of flags.
603  bool also_run_disabled_tests_;
604  bool break_on_failure_;
605  bool catch_exceptions_;
606  String color_;
607  String death_test_style_;
608  bool death_test_use_fork_;
609  String filter_;
610  String internal_run_death_test_;
611  bool list_tests_;
612  String output_;
613  bool print_time_;
614  bool pretty_;
615  internal::Int32 random_seed_;
616  internal::Int32 repeat_;
617  bool shuffle_;
618  internal::Int32 stack_trace_depth_;
619  bool throw_on_failure_;
620} GTEST_ATTRIBUTE_UNUSED_;
621
622// Converts a Unicode code point to a narrow string in UTF-8 encoding.
623// code_point parameter is of type UInt32 because wchar_t may not be
624// wide enough to contain a code point.
625// The output buffer str must containt at least 32 characters.
626// The function returns the address of the output buffer.
627// If the code_point is not a valid Unicode code point
628// (i.e. outside of Unicode range U+0 to U+10FFFF) it will be output
629// as '(Invalid Unicode 0xXXXXXXXX)'.
630GTEST_API_ char* CodePointToUtf8(UInt32 code_point, char* str);
631
632// Converts a wide string to a narrow string in UTF-8 encoding.
633// The wide string is assumed to have the following encoding:
634//   UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS)
635//   UTF-32 if sizeof(wchar_t) == 4 (on Linux)
636// Parameter str points to a null-terminated wide string.
637// Parameter num_chars may additionally limit the number
638// of wchar_t characters processed. -1 is used when the entire string
639// should be processed.
640// If the string contains code points that are not valid Unicode code points
641// (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
642// as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
643// and contains invalid UTF-16 surrogate pairs, values in those pairs
644// will be encoded as individual Unicode characters from Basic Normal Plane.
645GTEST_API_ String WideStringToUtf8(const wchar_t* str, int num_chars);
646
647// Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
648// if the variable is present. If a file already exists at this location, this
649// function will write over it. If the variable is present, but the file cannot
650// be created, prints an error and exits.
651void WriteToShardStatusFileIfNeeded();
652
653// Checks whether sharding is enabled by examining the relevant
654// environment variable values. If the variables are present,
655// but inconsistent (e.g., shard_index >= total_shards), prints
656// an error and exits. If in_subprocess_for_death_test, sharding is
657// disabled because it must only be applied to the original test
658// process. Otherwise, we could filter out death tests we intended to execute.
659GTEST_API_ bool ShouldShard(const char* total_shards_str,
660                            const char* shard_index_str,
661                            bool in_subprocess_for_death_test);
662
663// Parses the environment variable var as an Int32. If it is unset,
664// returns default_val. If it is not an Int32, prints an error and
665// and aborts.
666GTEST_API_ Int32 Int32FromEnvOrDie(const char* env_var, Int32 default_val);
667
668// Given the total number of shards, the shard index, and the test id,
669// returns true iff the test should be run on this shard. The test id is
670// some arbitrary but unique non-negative integer assigned to each test
671// method. Assumes that 0 <= shard_index < total_shards.
672GTEST_API_ bool ShouldRunTestOnShard(
673    int total_shards, int shard_index, int test_id);
674
675// STL container utilities.
676
677// Returns the number of elements in the given container that satisfy
678// the given predicate.
679template <class Container, typename Predicate>
680inline int CountIf(const Container& c, Predicate predicate) {
681  return static_cast<int>(std::count_if(c.begin(), c.end(), predicate));
682}
683
684// Applies a function/functor to each element in the container.
685template <class Container, typename Functor>
686void ForEach(const Container& c, Functor functor) {
687  std::for_each(c.begin(), c.end(), functor);
688}
689
690// Returns the i-th element of the vector, or default_value if i is not
691// in range [0, v.size()).
692template <typename E>
693inline E GetElementOr(const std::vector<E>& v, int i, E default_value) {
694  return (i < 0 || i >= static_cast<int>(v.size())) ? default_value : v[i];
695}
696
697// Performs an in-place shuffle of a range of the vector's elements.
698// 'begin' and 'end' are element indices as an STL-style range;
699// i.e. [begin, end) are shuffled, where 'end' == size() means to
700// shuffle to the end of the vector.
701template <typename E>
702void ShuffleRange(internal::Random* random, int begin, int end,
703                  std::vector<E>* v) {
704  const int size = static_cast<int>(v->size());
705  GTEST_CHECK_(0 <= begin && begin <= size)
706      << "Invalid shuffle range start " << begin << ": must be in range [0, "
707      << size << "].";
708  GTEST_CHECK_(begin <= end && end <= size)
709      << "Invalid shuffle range finish " << end << ": must be in range ["
710      << begin << ", " << size << "].";
711
712  // Fisher-Yates shuffle, from
713  // http://en.wikipedia.org/wiki/Fisher-Yates_shuffle
714  for (int range_width = end - begin; range_width >= 2; range_width--) {
715    const int last_in_range = begin + range_width - 1;
716    const int selected = begin + random->Generate(range_width);
717    std::swap((*v)[selected], (*v)[last_in_range]);
718  }
719}
720
721// Performs an in-place shuffle of the vector's elements.
722template <typename E>
723inline void Shuffle(internal::Random* random, std::vector<E>* v) {
724  ShuffleRange(random, 0, static_cast<int>(v->size()), v);
725}
726
727// A function for deleting an object.  Handy for being used as a
728// functor.
729template <typename T>
730static void Delete(T* x) {
731  delete x;
732}
733
734// A predicate that checks the key of a TestProperty against a known key.
735//
736// TestPropertyKeyIs is copyable.
737class TestPropertyKeyIs {
738 public:
739  // Constructor.
740  //
741  // TestPropertyKeyIs has NO default constructor.
742  explicit TestPropertyKeyIs(const char* key)
743      : key_(key) {}
744
745  // Returns true iff the test name of test property matches on key_.
746  bool operator()(const TestProperty& test_property) const {
747    return String(test_property.key()).Compare(key_) == 0;
748  }
749
750 private:
751  String key_;
752};
753
754class TestInfoImpl {
755 public:
756  TestInfoImpl(TestInfo* parent, const char* test_case_name,
757               const char* name, const char* test_case_comment,
758               const char* comment, TypeId fixture_class_id,
759               internal::TestFactoryBase* factory);
760  ~TestInfoImpl();
761
762  // Returns true if this test should run.
763  bool should_run() const { return should_run_; }
764
765  // Sets the should_run member.
766  void set_should_run(bool should) { should_run_ = should; }
767
768  // Returns true if this test is disabled. Disabled tests are not run.
769  bool is_disabled() const { return is_disabled_; }
770
771  // Sets the is_disabled member.
772  void set_is_disabled(bool is) { is_disabled_ = is; }
773
774  // Returns true if this test matches the filter specified by the user.
775  bool matches_filter() const { return matches_filter_; }
776
777  // Sets the matches_filter member.
778  void set_matches_filter(bool matches) { matches_filter_ = matches; }
779
780  // Returns the test case name.
781  const char* test_case_name() const { return test_case_name_.c_str(); }
782
783  // Returns the test name.
784  const char* name() const { return name_.c_str(); }
785
786  // Returns the test case comment.
787  const char* test_case_comment() const { return test_case_comment_.c_str(); }
788
789  // Returns the test comment.
790  const char* comment() const { return comment_.c_str(); }
791
792  // Returns the ID of the test fixture class.
793  TypeId fixture_class_id() const { return fixture_class_id_; }
794
795  // Returns the test result.
796  TestResult* result() { return &result_; }
797  const TestResult* result() const { return &result_; }
798
799  // Creates the test object, runs it, records its result, and then
800  // deletes it.
801  void Run();
802
803  // Clears the test result.
804  void ClearResult() { result_.Clear(); }
805
806  // Clears the test result in the given TestInfo object.
807  static void ClearTestResult(TestInfo * test_info) {
808    test_info->impl()->ClearResult();
809  }
810
811 private:
812  // These fields are immutable properties of the test.
813  TestInfo* const parent_;          // The owner of this object
814  const String test_case_name_;     // Test case name
815  const String name_;               // Test name
816  const String test_case_comment_;  // Test case comment
817  const String comment_;            // Test comment
818  const TypeId fixture_class_id_;   // ID of the test fixture class
819  bool should_run_;                 // True iff this test should run
820  bool is_disabled_;                // True iff this test is disabled
821  bool matches_filter_;             // True if this test matches the
822                                    // user-specified filter.
823  internal::TestFactoryBase* const factory_;  // The factory that creates
824                                              // the test object
825
826  // This field is mutable and needs to be reset before running the
827  // test for the second time.
828  TestResult result_;
829
830  GTEST_DISALLOW_COPY_AND_ASSIGN_(TestInfoImpl);
831};
832
833// Class UnitTestOptions.
834//
835// This class contains functions for processing options the user
836// specifies when running the tests.  It has only static members.
837//
838// In most cases, the user can specify an option using either an
839// environment variable or a command line flag.  E.g. you can set the
840// test filter using either GTEST_FILTER or --gtest_filter.  If both
841// the variable and the flag are present, the latter overrides the
842// former.
843class GTEST_API_ UnitTestOptions {
844 public:
845  // Functions for processing the gtest_output flag.
846
847  // Returns the output format, or "" for normal printed output.
848  static String GetOutputFormat();
849
850  // Returns the absolute path of the requested output file, or the
851  // default (test_detail.xml in the original working directory) if
852  // none was explicitly specified.
853  static String GetAbsolutePathToOutputFile();
854
855  // Functions for processing the gtest_filter flag.
856
857  // Returns true iff the wildcard pattern matches the string.  The
858  // first ':' or '\0' character in pattern marks the end of it.
859  //
860  // This recursive algorithm isn't very efficient, but is clear and
861  // works well enough for matching test names, which are short.
862  static bool PatternMatchesString(const char *pattern, const char *str);
863
864  // Returns true iff the user-specified filter matches the test case
865  // name and the test name.
866  static bool FilterMatchesTest(const String &test_case_name,
867                                const String &test_name);
868
869#if GTEST_OS_WINDOWS
870  // Function for supporting the gtest_catch_exception flag.
871
872  // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
873  // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
874  // This function is useful as an __except condition.
875  static int GTestShouldProcessSEH(DWORD exception_code);
876#endif  // GTEST_OS_WINDOWS
877
878  // Returns true if "name" matches the ':' separated list of glob-style
879  // filters in "filter".
880  static bool MatchesFilter(const String& name, const char* filter);
881};
882
883// Returns the current application's name, removing directory path if that
884// is present.  Used by UnitTestOptions::GetOutputFile.
885GTEST_API_ FilePath GetCurrentExecutableName();
886
887// The role interface for getting the OS stack trace as a string.
888class OsStackTraceGetterInterface {
889 public:
890  OsStackTraceGetterInterface() {}
891  virtual ~OsStackTraceGetterInterface() {}
892
893  // Returns the current OS stack trace as a String.  Parameters:
894  //
895  //   max_depth  - the maximum number of stack frames to be included
896  //                in the trace.
897  //   skip_count - the number of top frames to be skipped; doesn't count
898  //                against max_depth.
899  virtual String CurrentStackTrace(int max_depth, int skip_count) = 0;
900
901  // UponLeavingGTest() should be called immediately before Google Test calls
902  // user code. It saves some information about the current stack that
903  // CurrentStackTrace() will use to find and hide Google Test stack frames.
904  virtual void UponLeavingGTest() = 0;
905
906 private:
907  GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetterInterface);
908};
909
910// A working implementation of the OsStackTraceGetterInterface interface.
911class OsStackTraceGetter : public OsStackTraceGetterInterface {
912 public:
913  OsStackTraceGetter() : caller_frame_(NULL) {}
914  virtual String CurrentStackTrace(int max_depth, int skip_count);
915  virtual void UponLeavingGTest();
916
917  // This string is inserted in place of stack frames that are part of
918  // Google Test's implementation.
919  static const char* const kElidedFramesMarker;
920
921 private:
922  Mutex mutex_;  // protects all internal state
923
924  // We save the stack frame below the frame that calls user code.
925  // We do this because the address of the frame immediately below
926  // the user code changes between the call to UponLeavingGTest()
927  // and any calls to CurrentStackTrace() from within the user code.
928  void* caller_frame_;
929
930  GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetter);
931};
932
933// Information about a Google Test trace point.
934struct TraceInfo {
935  const char* file;
936  int line;
937  String message;
938};
939
940// This is the default global test part result reporter used in UnitTestImpl.
941// This class should only be used by UnitTestImpl.
942class DefaultGlobalTestPartResultReporter
943  : public TestPartResultReporterInterface {
944 public:
945  explicit DefaultGlobalTestPartResultReporter(UnitTestImpl* unit_test);
946  // Implements the TestPartResultReporterInterface. Reports the test part
947  // result in the current test.
948  virtual void ReportTestPartResult(const TestPartResult& result);
949
950 private:
951  UnitTestImpl* const unit_test_;
952
953  GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultGlobalTestPartResultReporter);
954};
955
956// This is the default per thread test part result reporter used in
957// UnitTestImpl. This class should only be used by UnitTestImpl.
958class DefaultPerThreadTestPartResultReporter
959    : public TestPartResultReporterInterface {
960 public:
961  explicit DefaultPerThreadTestPartResultReporter(UnitTestImpl* unit_test);
962  // Implements the TestPartResultReporterInterface. The implementation just
963  // delegates to the current global test part result reporter of *unit_test_.
964  virtual void ReportTestPartResult(const TestPartResult& result);
965
966 private:
967  UnitTestImpl* const unit_test_;
968
969  GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultPerThreadTestPartResultReporter);
970};
971
972// The private implementation of the UnitTest class.  We don't protect
973// the methods under a mutex, as this class is not accessible by a
974// user and the UnitTest class that delegates work to this class does
975// proper locking.
976class GTEST_API_ UnitTestImpl {
977 public:
978  explicit UnitTestImpl(UnitTest* parent);
979  virtual ~UnitTestImpl();
980
981  // There are two different ways to register your own TestPartResultReporter.
982  // You can register your own repoter to listen either only for test results
983  // from the current thread or for results from all threads.
984  // By default, each per-thread test result repoter just passes a new
985  // TestPartResult to the global test result reporter, which registers the
986  // test part result for the currently running test.
987
988  // Returns the global test part result reporter.
989  TestPartResultReporterInterface* GetGlobalTestPartResultReporter();
990
991  // Sets the global test part result reporter.
992  void SetGlobalTestPartResultReporter(
993      TestPartResultReporterInterface* reporter);
994
995  // Returns the test part result reporter for the current thread.
996  TestPartResultReporterInterface* GetTestPartResultReporterForCurrentThread();
997
998  // Sets the test part result reporter for the current thread.
999  void SetTestPartResultReporterForCurrentThread(
1000      TestPartResultReporterInterface* reporter);
1001
1002  // Gets the number of successful test cases.
1003  int successful_test_case_count() const;
1004
1005  // Gets the number of failed test cases.
1006  int failed_test_case_count() const;
1007
1008  // Gets the number of all test cases.
1009  int total_test_case_count() const;
1010
1011  // Gets the number of all test cases that contain at least one test
1012  // that should run.
1013  int test_case_to_run_count() const;
1014
1015  // Gets the number of successful tests.
1016  int successful_test_count() const;
1017
1018  // Gets the number of failed tests.
1019  int failed_test_count() const;
1020
1021  // Gets the number of disabled tests.
1022  int disabled_test_count() const;
1023
1024  // Gets the number of all tests.
1025  int total_test_count() const;
1026
1027  // Gets the number of tests that should run.
1028  int test_to_run_count() const;
1029
1030  // Gets the elapsed time, in milliseconds.
1031  TimeInMillis elapsed_time() const { return elapsed_time_; }
1032
1033  // Returns true iff the unit test passed (i.e. all test cases passed).
1034  bool Passed() const { return !Failed(); }
1035
1036  // Returns true iff the unit test failed (i.e. some test case failed
1037  // or something outside of all tests failed).
1038  bool Failed() const {
1039    return failed_test_case_count() > 0 || ad_hoc_test_result()->Failed();
1040  }
1041
1042  // Gets the i-th test case among all the test cases. i can range from 0 to
1043  // total_test_case_count() - 1. If i is not in that range, returns NULL.
1044  const TestCase* GetTestCase(int i) const {
1045    const int index = GetElementOr(test_case_indices_, i, -1);
1046    return index < 0 ? NULL : test_cases_[i];
1047  }
1048
1049  // Gets the i-th test case among all the test cases. i can range from 0 to
1050  // total_test_case_count() - 1. If i is not in that range, returns NULL.
1051  TestCase* GetMutableTestCase(int i) {
1052    const int index = GetElementOr(test_case_indices_, i, -1);
1053    return index < 0 ? NULL : test_cases_[index];
1054  }
1055
1056  // Provides access to the event listener list.
1057  TestEventListeners* listeners() { return &listeners_; }
1058
1059  // Returns the TestResult for the test that's currently running, or
1060  // the TestResult for the ad hoc test if no test is running.
1061  TestResult* current_test_result();
1062
1063  // Returns the TestResult for the ad hoc test.
1064  const TestResult* ad_hoc_test_result() const { return &ad_hoc_test_result_; }
1065
1066  // Sets the OS stack trace getter.
1067  //
1068  // Does nothing if the input and the current OS stack trace getter
1069  // are the same; otherwise, deletes the old getter and makes the
1070  // input the current getter.
1071  void set_os_stack_trace_getter(OsStackTraceGetterInterface* getter);
1072
1073  // Returns the current OS stack trace getter if it is not NULL;
1074  // otherwise, creates an OsStackTraceGetter, makes it the current
1075  // getter, and returns it.
1076  OsStackTraceGetterInterface* os_stack_trace_getter();
1077
1078  // Returns the current OS stack trace as a String.
1079  //
1080  // The maximum number of stack frames to be included is specified by
1081  // the gtest_stack_trace_depth flag.  The skip_count parameter
1082  // specifies the number of top frames to be skipped, which doesn't
1083  // count against the number of frames to be included.
1084  //
1085  // For example, if Foo() calls Bar(), which in turn calls
1086  // CurrentOsStackTraceExceptTop(1), Foo() will be included in the
1087  // trace but Bar() and CurrentOsStackTraceExceptTop() won't.
1088  String CurrentOsStackTraceExceptTop(int skip_count);
1089
1090  // Finds and returns a TestCase with the given name.  If one doesn't
1091  // exist, creates one and returns it.
1092  //
1093  // Arguments:
1094  //
1095  //   test_case_name: name of the test case
1096  //   set_up_tc:      pointer to the function that sets up the test case
1097  //   tear_down_tc:   pointer to the function that tears down the test case
1098  TestCase* GetTestCase(const char* test_case_name,
1099                        const char* comment,
1100                        Test::SetUpTestCaseFunc set_up_tc,
1101                        Test::TearDownTestCaseFunc tear_down_tc);
1102
1103  // Adds a TestInfo to the unit test.
1104  //
1105  // Arguments:
1106  //
1107  //   set_up_tc:    pointer to the function that sets up the test case
1108  //   tear_down_tc: pointer to the function that tears down the test case
1109  //   test_info:    the TestInfo object
1110  void AddTestInfo(Test::SetUpTestCaseFunc set_up_tc,
1111                   Test::TearDownTestCaseFunc tear_down_tc,
1112                   TestInfo * test_info) {
1113    // In order to support thread-safe death tests, we need to
1114    // remember the original working directory when the test program
1115    // was first invoked.  We cannot do this in RUN_ALL_TESTS(), as
1116    // the user may have changed the current directory before calling
1117    // RUN_ALL_TESTS().  Therefore we capture the current directory in
1118    // AddTestInfo(), which is called to register a TEST or TEST_F
1119    // before main() is reached.
1120    if (original_working_dir_.IsEmpty()) {
1121      original_working_dir_.Set(FilePath::GetCurrentDir());
1122      GTEST_CHECK_(!original_working_dir_.IsEmpty())
1123          << "Failed to get the current working directory.";
1124    }
1125
1126    GetTestCase(test_info->test_case_name(),
1127                test_info->test_case_comment(),
1128                set_up_tc,
1129                tear_down_tc)->AddTestInfo(test_info);
1130  }
1131
1132#if GTEST_HAS_PARAM_TEST
1133  // Returns ParameterizedTestCaseRegistry object used to keep track of
1134  // value-parameterized tests and instantiate and register them.
1135  internal::ParameterizedTestCaseRegistry& parameterized_test_registry() {
1136    return parameterized_test_registry_;
1137  }
1138#endif  // GTEST_HAS_PARAM_TEST
1139
1140  // Sets the TestCase object for the test that's currently running.
1141  void set_current_test_case(TestCase* a_current_test_case) {
1142    current_test_case_ = a_current_test_case;
1143  }
1144
1145  // Sets the TestInfo object for the test that's currently running.  If
1146  // current_test_info is NULL, the assertion results will be stored in
1147  // ad_hoc_test_result_.
1148  void set_current_test_info(TestInfo* a_current_test_info) {
1149    current_test_info_ = a_current_test_info;
1150  }
1151
1152  // Registers all parameterized tests defined using TEST_P and
1153  // INSTANTIATE_TEST_P, creating regular tests for each test/parameter
1154  // combination. This method can be called more then once; it has
1155  // guards protecting from registering the tests more then once.
1156  // If value-parameterized tests are disabled, RegisterParameterizedTests
1157  // is present but does nothing.
1158  void RegisterParameterizedTests();
1159
1160  // Runs all tests in this UnitTest object, prints the result, and
1161  // returns 0 if all tests are successful, or 1 otherwise.  If any
1162  // exception is thrown during a test on Windows, this test is
1163  // considered to be failed, but the rest of the tests will still be
1164  // run.  (We disable exceptions on Linux and Mac OS X, so the issue
1165  // doesn't apply there.)
1166  int RunAllTests();
1167
1168  // Clears the results of all tests, including the ad hoc test.
1169  void ClearResult() {
1170    ForEach(test_cases_, TestCase::ClearTestCaseResult);
1171    ad_hoc_test_result_.Clear();
1172  }
1173
1174  enum ReactionToSharding {
1175    HONOR_SHARDING_PROTOCOL,
1176    IGNORE_SHARDING_PROTOCOL
1177  };
1178
1179  // Matches the full name of each test against the user-specified
1180  // filter to decide whether the test should run, then records the
1181  // result in each TestCase and TestInfo object.
1182  // If shard_tests == HONOR_SHARDING_PROTOCOL, further filters tests
1183  // based on sharding variables in the environment.
1184  // Returns the number of tests that should run.
1185  int FilterTests(ReactionToSharding shard_tests);
1186
1187  // Prints the names of the tests matching the user-specified filter flag.
1188  void ListTestsMatchingFilter();
1189
1190  const TestCase* current_test_case() const { return current_test_case_; }
1191  TestInfo* current_test_info() { return current_test_info_; }
1192  const TestInfo* current_test_info() const { return current_test_info_; }
1193
1194  // Returns the vector of environments that need to be set-up/torn-down
1195  // before/after the tests are run.
1196  std::vector<Environment*>& environments() { return environments_; }
1197
1198  // Getters for the per-thread Google Test trace stack.
1199  std::vector<TraceInfo>& gtest_trace_stack() {
1200    return *(gtest_trace_stack_.pointer());
1201  }
1202  const std::vector<TraceInfo>& gtest_trace_stack() const {
1203    return gtest_trace_stack_.get();
1204  }
1205
1206#if GTEST_HAS_DEATH_TEST
1207  void InitDeathTestSubprocessControlInfo() {
1208    internal_run_death_test_flag_.reset(ParseInternalRunDeathTestFlag());
1209  }
1210  // Returns a pointer to the parsed --gtest_internal_run_death_test
1211  // flag, or NULL if that flag was not specified.
1212  // This information is useful only in a death test child process.
1213  // Must not be called before a call to InitGoogleTest.
1214  const InternalRunDeathTestFlag* internal_run_death_test_flag() const {
1215    return internal_run_death_test_flag_.get();
1216  }
1217
1218  // Returns a pointer to the current death test factory.
1219  internal::DeathTestFactory* death_test_factory() {
1220    return death_test_factory_.get();
1221  }
1222
1223  void SuppressTestEventsIfInSubprocess();
1224
1225  friend class ReplaceDeathTestFactory;
1226#endif  // GTEST_HAS_DEATH_TEST
1227
1228  // Initializes the event listener performing XML output as specified by
1229  // UnitTestOptions. Must not be called before InitGoogleTest.
1230  void ConfigureXmlOutput();
1231
1232  // Performs initialization dependent upon flag values obtained in
1233  // ParseGoogleTestFlagsOnly.  Is called from InitGoogleTest after the call to
1234  // ParseGoogleTestFlagsOnly.  In case a user neglects to call InitGoogleTest
1235  // this function is also called from RunAllTests.  Since this function can be
1236  // called more than once, it has to be idempotent.
1237  void PostFlagParsingInit();
1238
1239  // Gets the random seed used at the start of the current test iteration.
1240  int random_seed() const { return random_seed_; }
1241
1242  // Gets the random number generator.
1243  internal::Random* random() { return &random_; }
1244
1245  // Shuffles all test cases, and the tests within each test case,
1246  // making sure that death tests are still run first.
1247  void ShuffleTests();
1248
1249  // Restores the test cases and tests to their order before the first shuffle.
1250  void UnshuffleTests();
1251
1252 private:
1253  friend class ::testing::UnitTest;
1254
1255  // The UnitTest object that owns this implementation object.
1256  UnitTest* const parent_;
1257
1258  // The working directory when the first TEST() or TEST_F() was
1259  // executed.
1260  internal::FilePath original_working_dir_;
1261
1262  // The default test part result reporters.
1263  DefaultGlobalTestPartResultReporter default_global_test_part_result_reporter_;
1264  DefaultPerThreadTestPartResultReporter
1265      default_per_thread_test_part_result_reporter_;
1266
1267  // Points to (but doesn't own) the global test part result reporter.
1268  TestPartResultReporterInterface* global_test_part_result_repoter_;
1269
1270  // Protects read and write access to global_test_part_result_reporter_.
1271  internal::Mutex global_test_part_result_reporter_mutex_;
1272
1273  // Points to (but doesn't own) the per-thread test part result reporter.
1274  internal::ThreadLocal<TestPartResultReporterInterface*>
1275      per_thread_test_part_result_reporter_;
1276
1277  // The vector of environments that need to be set-up/torn-down
1278  // before/after the tests are run.
1279  std::vector<Environment*> environments_;
1280
1281  // The vector of TestCases in their original order.  It owns the
1282  // elements in the vector.
1283  std::vector<TestCase*> test_cases_;
1284
1285  // Provides a level of indirection for the test case list to allow
1286  // easy shuffling and restoring the test case order.  The i-th
1287  // element of this vector is the index of the i-th test case in the
1288  // shuffled order.
1289  std::vector<int> test_case_indices_;
1290
1291#if GTEST_HAS_PARAM_TEST
1292  // ParameterizedTestRegistry object used to register value-parameterized
1293  // tests.
1294  internal::ParameterizedTestCaseRegistry parameterized_test_registry_;
1295
1296  // Indicates whether RegisterParameterizedTests() has been called already.
1297  bool parameterized_tests_registered_;
1298#endif  // GTEST_HAS_PARAM_TEST
1299
1300  // Index of the last death test case registered.  Initially -1.
1301  int last_death_test_case_;
1302
1303  // This points to the TestCase for the currently running test.  It
1304  // changes as Google Test goes through one test case after another.
1305  // When no test is running, this is set to NULL and Google Test
1306  // stores assertion results in ad_hoc_test_result_.  Initially NULL.
1307  TestCase* current_test_case_;
1308
1309  // This points to the TestInfo for the currently running test.  It
1310  // changes as Google Test goes through one test after another.  When
1311  // no test is running, this is set to NULL and Google Test stores
1312  // assertion results in ad_hoc_test_result_.  Initially NULL.
1313  TestInfo* current_test_info_;
1314
1315  // Normally, a user only writes assertions inside a TEST or TEST_F,
1316  // or inside a function called by a TEST or TEST_F.  Since Google
1317  // Test keeps track of which test is current running, it can
1318  // associate such an assertion with the test it belongs to.
1319  //
1320  // If an assertion is encountered when no TEST or TEST_F is running,
1321  // Google Test attributes the assertion result to an imaginary "ad hoc"
1322  // test, and records the result in ad_hoc_test_result_.
1323  TestResult ad_hoc_test_result_;
1324
1325  // The list of event listeners that can be used to track events inside
1326  // Google Test.
1327  TestEventListeners listeners_;
1328
1329  // The OS stack trace getter.  Will be deleted when the UnitTest
1330  // object is destructed.  By default, an OsStackTraceGetter is used,
1331  // but the user can set this field to use a custom getter if that is
1332  // desired.
1333  OsStackTraceGetterInterface* os_stack_trace_getter_;
1334
1335  // True iff PostFlagParsingInit() has been called.
1336  bool post_flag_parse_init_performed_;
1337
1338  // The random number seed used at the beginning of the test run.
1339  int random_seed_;
1340
1341  // Our random number generator.
1342  internal::Random random_;
1343
1344  // How long the test took to run, in milliseconds.
1345  TimeInMillis elapsed_time_;
1346
1347#if GTEST_HAS_DEATH_TEST
1348  // The decomposed components of the gtest_internal_run_death_test flag,
1349  // parsed when RUN_ALL_TESTS is called.
1350  internal::scoped_ptr<InternalRunDeathTestFlag> internal_run_death_test_flag_;
1351  internal::scoped_ptr<internal::DeathTestFactory> death_test_factory_;
1352#endif  // GTEST_HAS_DEATH_TEST
1353
1354  // A per-thread stack of traces created by the SCOPED_TRACE() macro.
1355  internal::ThreadLocal<std::vector<TraceInfo> > gtest_trace_stack_;
1356
1357  GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTestImpl);
1358};  // class UnitTestImpl
1359
1360// Convenience function for accessing the global UnitTest
1361// implementation object.
1362inline UnitTestImpl* GetUnitTestImpl() {
1363  return UnitTest::GetInstance()->impl();
1364}
1365
1366// Internal helper functions for implementing the simple regular
1367// expression matcher.
1368GTEST_API_ bool IsInSet(char ch, const char* str);
1369GTEST_API_ bool IsDigit(char ch);
1370GTEST_API_ bool IsPunct(char ch);
1371GTEST_API_ bool IsRepeat(char ch);
1372GTEST_API_ bool IsWhiteSpace(char ch);
1373GTEST_API_ bool IsWordChar(char ch);
1374GTEST_API_ bool IsValidEscape(char ch);
1375GTEST_API_ bool AtomMatchesChar(bool escaped, char pattern, char ch);
1376GTEST_API_ bool ValidateRegex(const char* regex);
1377GTEST_API_ bool MatchRegexAtHead(const char* regex, const char* str);
1378GTEST_API_ bool MatchRepetitionAndRegexAtHead(
1379    bool escaped, char ch, char repeat, const char* regex, const char* str);
1380GTEST_API_ bool MatchRegexAnywhere(const char* regex, const char* str);
1381
1382// Parses the command line for Google Test flags, without initializing
1383// other parts of Google Test.
1384GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, char** argv);
1385GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv);
1386
1387#if GTEST_HAS_DEATH_TEST
1388
1389// Returns the message describing the last system error, regardless of the
1390// platform.
1391String GetLastErrnoDescription();
1392
1393#if GTEST_OS_WINDOWS
1394// Provides leak-safe Windows kernel handle ownership.
1395class AutoHandle {
1396 public:
1397  AutoHandle() : handle_(INVALID_HANDLE_VALUE) {}
1398  explicit AutoHandle(HANDLE handle) : handle_(handle) {}
1399
1400  ~AutoHandle() { Reset(); }
1401
1402  HANDLE Get() const { return handle_; }
1403  void Reset() { Reset(INVALID_HANDLE_VALUE); }
1404  void Reset(HANDLE handle) {
1405    if (handle != handle_) {
1406      if (handle_ != INVALID_HANDLE_VALUE)
1407        ::CloseHandle(handle_);
1408      handle_ = handle;
1409    }
1410  }
1411
1412 private:
1413  HANDLE handle_;
1414
1415  GTEST_DISALLOW_COPY_AND_ASSIGN_(AutoHandle);
1416};
1417#endif  // GTEST_OS_WINDOWS
1418
1419// Attempts to parse a string into a positive integer pointed to by the
1420// number parameter.  Returns true if that is possible.
1421// GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we can use
1422// it here.
1423template <typename Integer>
1424bool ParseNaturalNumber(const ::std::string& str, Integer* number) {
1425  // Fail fast if the given string does not begin with a digit;
1426  // this bypasses strtoXXX's "optional leading whitespace and plus
1427  // or minus sign" semantics, which are undesirable here.
1428  if (str.empty() || !isdigit(str[0])) {
1429    return false;
1430  }
1431  errno = 0;
1432
1433  char* end;
1434  // BiggestConvertible is the largest integer type that system-provided
1435  // string-to-number conversion routines can return.
1436#if GTEST_OS_WINDOWS && !defined(__GNUC__)
1437  // MSVC and C++ Builder define __int64 instead of the standard long long.
1438  typedef unsigned __int64 BiggestConvertible;
1439  const BiggestConvertible parsed = _strtoui64(str.c_str(), &end, 10);
1440#else
1441  typedef unsigned long long BiggestConvertible;  // NOLINT
1442  const BiggestConvertible parsed = strtoull(str.c_str(), &end, 10);
1443#endif  // GTEST_OS_WINDOWS && !defined(__GNUC__)
1444  const bool parse_success = *end == '\0' && errno == 0;
1445
1446  // TODO(vladl@google.com): Convert this to compile time assertion when it is
1447  // available.
1448  GTEST_CHECK_(sizeof(Integer) <= sizeof(parsed));
1449
1450  const Integer result = static_cast<Integer>(parsed);
1451  if (parse_success && static_cast<BiggestConvertible>(result) == parsed) {
1452    *number = result;
1453    return true;
1454  }
1455  return false;
1456}
1457#endif  // GTEST_HAS_DEATH_TEST
1458
1459// TestResult contains some private methods that should be hidden from
1460// Google Test user but are required for testing. This class allow our tests
1461// to access them.
1462//
1463// This class is supplied only for the purpose of testing Google Test's own
1464// constructs. Do not use it in user tests, either directly or indirectly.
1465class TestResultAccessor {
1466 public:
1467  static void RecordProperty(TestResult* test_result,
1468                             const TestProperty& property) {
1469    test_result->RecordProperty(property);
1470  }
1471
1472  static void ClearTestPartResults(TestResult* test_result) {
1473    test_result->ClearTestPartResults();
1474  }
1475
1476  static const std::vector<testing::TestPartResult>& test_part_results(
1477      const TestResult& test_result) {
1478    return test_result.test_part_results();
1479  }
1480};
1481
1482}  // namespace internal
1483}  // namespace testing
1484
1485#endif  // GTEST_SRC_GTEST_INTERNAL_INL_H_
1486#undef GTEST_IMPLEMENTATION_
1487
1488#if GTEST_OS_WINDOWS
1489#define vsnprintf _vsnprintf
1490#endif  // GTEST_OS_WINDOWS
1491
1492namespace testing {
1493
1494using internal::CountIf;
1495using internal::ForEach;
1496using internal::GetElementOr;
1497using internal::Shuffle;
1498
1499// Constants.
1500
1501// A test whose test case name or test name matches this filter is
1502// disabled and not run.
1503static const char kDisableTestFilter[] = "DISABLED_*:*/DISABLED_*";
1504
1505// A test case whose name matches this filter is considered a death
1506// test case and will be run before test cases whose name doesn't
1507// match this filter.
1508static const char kDeathTestCaseFilter[] = "*DeathTest:*DeathTest/*";
1509
1510// A test filter that matches everything.
1511static const char kUniversalFilter[] = "*";
1512
1513// The default output file for XML output.
1514static const char kDefaultOutputFile[] = "test_detail.xml";
1515
1516// The environment variable name for the test shard index.
1517static const char kTestShardIndex[] = "GTEST_SHARD_INDEX";
1518// The environment variable name for the total number of test shards.
1519static const char kTestTotalShards[] = "GTEST_TOTAL_SHARDS";
1520// The environment variable name for the test shard status file.
1521static const char kTestShardStatusFile[] = "GTEST_SHARD_STATUS_FILE";
1522
1523namespace internal {
1524
1525// The text used in failure messages to indicate the start of the
1526// stack trace.
1527const char kStackTraceMarker[] = "\nStack trace:\n";
1528
1529// g_help_flag is true iff the --help flag or an equivalent form is
1530// specified on the command line.
1531bool g_help_flag = false;
1532
1533}  // namespace internal
1534
1535GTEST_DEFINE_bool_(
1536    also_run_disabled_tests,
1537    internal::BoolFromGTestEnv("also_run_disabled_tests", false),
1538    "Run disabled tests too, in addition to the tests normally being run.");
1539
1540GTEST_DEFINE_bool_(
1541    break_on_failure,
1542    internal::BoolFromGTestEnv("break_on_failure", false),
1543    "True iff a failed assertion should be a debugger break-point.");
1544
1545GTEST_DEFINE_bool_(
1546    catch_exceptions,
1547    internal::BoolFromGTestEnv("catch_exceptions", false),
1548    "True iff " GTEST_NAME_
1549    " should catch exceptions and treat them as test failures.");
1550
1551GTEST_DEFINE_string_(
1552    color,
1553    internal::StringFromGTestEnv("color", "auto"),
1554    "Whether to use colors in the output.  Valid values: yes, no, "
1555    "and auto.  'auto' means to use colors if the output is "
1556    "being sent to a terminal and the TERM environment variable "
1557    "is set to xterm, xterm-color, xterm-256color, linux or cygwin.");
1558
1559GTEST_DEFINE_string_(
1560    filter,
1561    internal::StringFromGTestEnv("filter", kUniversalFilter),
1562    "A colon-separated list of glob (not regex) patterns "
1563    "for filtering the tests to run, optionally followed by a "
1564    "'-' and a : separated list of negative patterns (tests to "
1565    "exclude).  A test is run if it matches one of the positive "
1566    "patterns and does not match any of the negative patterns.");
1567
1568GTEST_DEFINE_bool_(list_tests, false,
1569                   "List all tests without running them.");
1570
1571GTEST_DEFINE_string_(
1572    output,
1573    internal::StringFromGTestEnv("output", ""),
1574    "A format (currently must be \"xml\"), optionally followed "
1575    "by a colon and an output file name or directory. A directory "
1576    "is indicated by a trailing pathname separator. "
1577    "Examples: \"xml:filename.xml\", \"xml::directoryname/\". "
1578    "If a directory is specified, output files will be created "
1579    "within that directory, with file-names based on the test "
1580    "executable's name and, if necessary, made unique by adding "
1581    "digits.");
1582
1583GTEST_DEFINE_bool_(
1584    print_time,
1585    internal::BoolFromGTestEnv("print_time", true),
1586    "True iff " GTEST_NAME_
1587    " should display elapsed time in text output.");
1588
1589GTEST_DEFINE_int32_(
1590    random_seed,
1591    internal::Int32FromGTestEnv("random_seed", 0),
1592    "Random number seed to use when shuffling test orders.  Must be in range "
1593    "[1, 99999], or 0 to use a seed based on the current time.");
1594
1595GTEST_DEFINE_int32_(
1596    repeat,
1597    internal::Int32FromGTestEnv("repeat", 1),
1598    "How many times to repeat each test.  Specify a negative number "
1599    "for repeating forever.  Useful for shaking out flaky tests.");
1600
1601GTEST_DEFINE_bool_(
1602    show_internal_stack_frames, false,
1603    "True iff " GTEST_NAME_ " should include internal stack frames when "
1604    "printing test failure stack traces.");
1605
1606GTEST_DEFINE_bool_(
1607    shuffle,
1608    internal::BoolFromGTestEnv("shuffle", false),
1609    "True iff " GTEST_NAME_
1610    " should randomize tests' order on every run.");
1611
1612GTEST_DEFINE_int32_(
1613    stack_trace_depth,
1614    internal::Int32FromGTestEnv("stack_trace_depth", kMaxStackTraceDepth),
1615    "The maximum number of stack frames to print when an "
1616    "assertion fails.  The valid range is 0 through 100, inclusive.");
1617
1618GTEST_DEFINE_bool_(
1619    throw_on_failure,
1620    internal::BoolFromGTestEnv("throw_on_failure", false),
1621    "When this flag is specified, a failed assertion will throw an exception "
1622    "if exceptions are enabled or exit the program with a non-zero code "
1623    "otherwise.");
1624
1625namespace internal {
1626
1627// Generates a random number from [0, range), using a Linear
1628// Congruential Generator (LCG).  Crashes if 'range' is 0 or greater
1629// than kMaxRange.
1630UInt32 Random::Generate(UInt32 range) {
1631  // These constants are the same as are used in glibc's rand(3).
1632  state_ = (1103515245U*state_ + 12345U) % kMaxRange;
1633
1634  GTEST_CHECK_(range > 0)
1635      << "Cannot generate a number in the range [0, 0).";
1636  GTEST_CHECK_(range <= kMaxRange)
1637      << "Generation of a number in [0, " << range << ") was requested, "
1638      << "but this can only generate numbers in [0, " << kMaxRange << ").";
1639
1640  // Converting via modulus introduces a bit of downward bias, but
1641  // it's simple, and a linear congruential generator isn't too good
1642  // to begin with.
1643  return state_ % range;
1644}
1645
1646// GTestIsInitialized() returns true iff the user has initialized
1647// Google Test.  Useful for catching the user mistake of not initializing
1648// Google Test before calling RUN_ALL_TESTS().
1649//
1650// A user must call testing::InitGoogleTest() to initialize Google
1651// Test.  g_init_gtest_count is set to the number of times
1652// InitGoogleTest() has been called.  We don't protect this variable
1653// under a mutex as it is only accessed in the main thread.
1654int g_init_gtest_count = 0;
1655static bool GTestIsInitialized() { return g_init_gtest_count != 0; }
1656
1657// Iterates over a vector of TestCases, keeping a running sum of the
1658// results of calling a given int-returning method on each.
1659// Returns the sum.
1660static int SumOverTestCaseList(const std::vector<TestCase*>& case_list,
1661                               int (TestCase::*method)() const) {
1662  int sum = 0;
1663  for (size_t i = 0; i < case_list.size(); i++) {
1664    sum += (case_list[i]->*method)();
1665  }
1666  return sum;
1667}
1668
1669// Returns true iff the test case passed.
1670static bool TestCasePassed(const TestCase* test_case) {
1671  return test_case->should_run() && test_case->Passed();
1672}
1673
1674// Returns true iff the test case failed.
1675static bool TestCaseFailed(const TestCase* test_case) {
1676  return test_case->should_run() && test_case->Failed();
1677}
1678
1679// Returns true iff test_case contains at least one test that should
1680// run.
1681static bool ShouldRunTestCase(const TestCase* test_case) {
1682  return test_case->should_run();
1683}
1684
1685// AssertHelper constructor.
1686AssertHelper::AssertHelper(TestPartResult::Type type,
1687                           const char* file,
1688                           int line,
1689                           const char* message)
1690    : data_(new AssertHelperData(type, file, line, message)) {
1691}
1692
1693AssertHelper::~AssertHelper() {
1694  delete data_;
1695}
1696
1697// Message assignment, for assertion streaming support.
1698void AssertHelper::operator=(const Message& message) const {
1699  UnitTest::GetInstance()->
1700    AddTestPartResult(data_->type, data_->file, data_->line,
1701                      AppendUserMessage(data_->message, message),
1702                      UnitTest::GetInstance()->impl()
1703                      ->CurrentOsStackTraceExceptTop(1)
1704                      // Skips the stack frame for this function itself.
1705                      );  // NOLINT
1706}
1707
1708// Mutex for linked pointers.
1709GTEST_DEFINE_STATIC_MUTEX_(g_linked_ptr_mutex);
1710
1711// Application pathname gotten in InitGoogleTest.
1712String g_executable_path;
1713
1714// Returns the current application's name, removing directory path if that
1715// is present.
1716FilePath GetCurrentExecutableName() {
1717  FilePath result;
1718
1719#if GTEST_OS_WINDOWS
1720  result.Set(FilePath(g_executable_path).RemoveExtension("exe"));
1721#else
1722  result.Set(FilePath(g_executable_path));
1723#endif  // GTEST_OS_WINDOWS
1724
1725  return result.RemoveDirectoryName();
1726}
1727
1728// Functions for processing the gtest_output flag.
1729
1730// Returns the output format, or "" for normal printed output.
1731String UnitTestOptions::GetOutputFormat() {
1732  const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
1733  if (gtest_output_flag == NULL) return String("");
1734
1735  const char* const colon = strchr(gtest_output_flag, ':');
1736  return (colon == NULL) ?
1737      String(gtest_output_flag) :
1738      String(gtest_output_flag, colon - gtest_output_flag);
1739}
1740
1741// Returns the name of the requested output file, or the default if none
1742// was explicitly specified.
1743String UnitTestOptions::GetAbsolutePathToOutputFile() {
1744  const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
1745  if (gtest_output_flag == NULL)
1746    return String("");
1747
1748  const char* const colon = strchr(gtest_output_flag, ':');
1749  if (colon == NULL)
1750    return String(internal::FilePath::ConcatPaths(
1751               internal::FilePath(
1752                   UnitTest::GetInstance()->original_working_dir()),
1753               internal::FilePath(kDefaultOutputFile)).ToString() );
1754
1755  internal::FilePath output_name(colon + 1);
1756  if (!output_name.IsAbsolutePath())
1757    // TODO(wan@google.com): on Windows \some\path is not an absolute
1758    // path (as its meaning depends on the current drive), yet the
1759    // following logic for turning it into an absolute path is wrong.
1760    // Fix it.
1761    output_name = internal::FilePath::ConcatPaths(
1762        internal::FilePath(UnitTest::GetInstance()->original_working_dir()),
1763        internal::FilePath(colon + 1));
1764
1765  if (!output_name.IsDirectory())
1766    return output_name.ToString();
1767
1768  internal::FilePath result(internal::FilePath::GenerateUniqueFileName(
1769      output_name, internal::GetCurrentExecutableName(),
1770      GetOutputFormat().c_str()));
1771  return result.ToString();
1772}
1773
1774// Returns true iff the wildcard pattern matches the string.  The
1775// first ':' or '\0' character in pattern marks the end of it.
1776//
1777// This recursive algorithm isn't very efficient, but is clear and
1778// works well enough for matching test names, which are short.
1779bool UnitTestOptions::PatternMatchesString(const char *pattern,
1780                                           const char *str) {
1781  switch (*pattern) {
1782    case '\0':
1783    case ':':  // Either ':' or '\0' marks the end of the pattern.
1784      return *str == '\0';
1785    case '?':  // Matches any single character.
1786      return *str != '\0' && PatternMatchesString(pattern + 1, str + 1);
1787    case '*':  // Matches any string (possibly empty) of characters.
1788      return (*str != '\0' && PatternMatchesString(pattern, str + 1)) ||
1789          PatternMatchesString(pattern + 1, str);
1790    default:  // Non-special character.  Matches itself.
1791      return *pattern == *str &&
1792          PatternMatchesString(pattern + 1, str + 1);
1793  }
1794}
1795
1796bool UnitTestOptions::MatchesFilter(const String& name, const char* filter) {
1797  const char *cur_pattern = filter;
1798  for (;;) {
1799    if (PatternMatchesString(cur_pattern, name.c_str())) {
1800      return true;
1801    }
1802
1803    // Finds the next pattern in the filter.
1804    cur_pattern = strchr(cur_pattern, ':');
1805
1806    // Returns if no more pattern can be found.
1807    if (cur_pattern == NULL) {
1808      return false;
1809    }
1810
1811    // Skips the pattern separater (the ':' character).
1812    cur_pattern++;
1813  }
1814}
1815
1816// TODO(keithray): move String function implementations to gtest-string.cc.
1817
1818// Returns true iff the user-specified filter matches the test case
1819// name and the test name.
1820bool UnitTestOptions::FilterMatchesTest(const String &test_case_name,
1821                                        const String &test_name) {
1822  const String& full_name = String::Format("%s.%s",
1823                                           test_case_name.c_str(),
1824                                           test_name.c_str());
1825
1826  // Split --gtest_filter at '-', if there is one, to separate into
1827  // positive filter and negative filter portions
1828  const char* const p = GTEST_FLAG(filter).c_str();
1829  const char* const dash = strchr(p, '-');
1830  String positive;
1831  String negative;
1832  if (dash == NULL) {
1833    positive = GTEST_FLAG(filter).c_str();  // Whole string is a positive filter
1834    negative = String("");
1835  } else {
1836    positive = String(p, dash - p);  // Everything up to the dash
1837    negative = String(dash+1);       // Everything after the dash
1838    if (positive.empty()) {
1839      // Treat '-test1' as the same as '*-test1'
1840      positive = kUniversalFilter;
1841    }
1842  }
1843
1844  // A filter is a colon-separated list of patterns.  It matches a
1845  // test if any pattern in it matches the test.
1846  return (MatchesFilter(full_name, positive.c_str()) &&
1847          !MatchesFilter(full_name, negative.c_str()));
1848}
1849
1850#if GTEST_OS_WINDOWS
1851// Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
1852// given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
1853// This function is useful as an __except condition.
1854int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) {
1855  // Google Test should handle an exception if:
1856  //   1. the user wants it to, AND
1857  //   2. this is not a breakpoint exception.
1858  return (GTEST_FLAG(catch_exceptions) &&
1859          exception_code != EXCEPTION_BREAKPOINT) ?
1860      EXCEPTION_EXECUTE_HANDLER :
1861      EXCEPTION_CONTINUE_SEARCH;
1862}
1863#endif  // GTEST_OS_WINDOWS
1864
1865}  // namespace internal
1866
1867// The c'tor sets this object as the test part result reporter used by
1868// Google Test.  The 'result' parameter specifies where to report the
1869// results. Intercepts only failures from the current thread.
1870ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
1871    TestPartResultArray* result)
1872    : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD),
1873      result_(result) {
1874  Init();
1875}
1876
1877// The c'tor sets this object as the test part result reporter used by
1878// Google Test.  The 'result' parameter specifies where to report the
1879// results.
1880ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
1881    InterceptMode intercept_mode, TestPartResultArray* result)
1882    : intercept_mode_(intercept_mode),
1883      result_(result) {
1884  Init();
1885}
1886
1887void ScopedFakeTestPartResultReporter::Init() {
1888  internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
1889  if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
1890    old_reporter_ = impl->GetGlobalTestPartResultReporter();
1891    impl->SetGlobalTestPartResultReporter(this);
1892  } else {
1893    old_reporter_ = impl->GetTestPartResultReporterForCurrentThread();
1894    impl->SetTestPartResultReporterForCurrentThread(this);
1895  }
1896}
1897
1898// The d'tor restores the test part result reporter used by Google Test
1899// before.
1900ScopedFakeTestPartResultReporter::~ScopedFakeTestPartResultReporter() {
1901  internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
1902  if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
1903    impl->SetGlobalTestPartResultReporter(old_reporter_);
1904  } else {
1905    impl->SetTestPartResultReporterForCurrentThread(old_reporter_);
1906  }
1907}
1908
1909// Increments the test part result count and remembers the result.
1910// This method is from the TestPartResultReporterInterface interface.
1911void ScopedFakeTestPartResultReporter::ReportTestPartResult(
1912    const TestPartResult& result) {
1913  result_->Append(result);
1914}
1915
1916namespace internal {
1917
1918// Returns the type ID of ::testing::Test.  We should always call this
1919// instead of GetTypeId< ::testing::Test>() to get the type ID of
1920// testing::Test.  This is to work around a suspected linker bug when
1921// using Google Test as a framework on Mac OS X.  The bug causes
1922// GetTypeId< ::testing::Test>() to return different values depending
1923// on whether the call is from the Google Test framework itself or
1924// from user test code.  GetTestTypeId() is guaranteed to always
1925// return the same value, as it always calls GetTypeId<>() from the
1926// gtest.cc, which is within the Google Test framework.
1927TypeId GetTestTypeId() {
1928  return GetTypeId<Test>();
1929}
1930
1931// The value of GetTestTypeId() as seen from within the Google Test
1932// library.  This is solely for testing GetTestTypeId().
1933extern const TypeId kTestTypeIdInGoogleTest = GetTestTypeId();
1934
1935// This predicate-formatter checks that 'results' contains a test part
1936// failure of the given type and that the failure message contains the
1937// given substring.
1938AssertionResult HasOneFailure(const char* /* results_expr */,
1939                              const char* /* type_expr */,
1940                              const char* /* substr_expr */,
1941                              const TestPartResultArray& results,
1942                              TestPartResult::Type type,
1943                              const char* substr) {
1944  const String expected(type == TestPartResult::kFatalFailure ?
1945                        "1 fatal failure" :
1946                        "1 non-fatal failure");
1947  Message msg;
1948  if (results.size() != 1) {
1949    msg << "Expected: " << expected << "\n"
1950        << "  Actual: " << results.size() << " failures";
1951    for (int i = 0; i < results.size(); i++) {
1952      msg << "\n" << results.GetTestPartResult(i);
1953    }
1954    return AssertionFailure(msg);
1955  }
1956
1957  const TestPartResult& r = results.GetTestPartResult(0);
1958  if (r.type() != type) {
1959    msg << "Expected: " << expected << "\n"
1960        << "  Actual:\n"
1961        << r;
1962    return AssertionFailure(msg);
1963  }
1964
1965  if (strstr(r.message(), substr) == NULL) {
1966    msg << "Expected: " << expected << " containing \""
1967        << substr << "\"\n"
1968        << "  Actual:\n"
1969        << r;
1970    return AssertionFailure(msg);
1971  }
1972
1973  return AssertionSuccess();
1974}
1975
1976// The constructor of SingleFailureChecker remembers where to look up
1977// test part results, what type of failure we expect, and what
1978// substring the failure message should contain.
1979SingleFailureChecker:: SingleFailureChecker(
1980    const TestPartResultArray* results,
1981    TestPartResult::Type type,
1982    const char* substr)
1983    : results_(results),
1984      type_(type),
1985      substr_(substr) {}
1986
1987// The destructor of SingleFailureChecker verifies that the given
1988// TestPartResultArray contains exactly one failure that has the given
1989// type and contains the given substring.  If that's not the case, a
1990// non-fatal failure will be generated.
1991SingleFailureChecker::~SingleFailureChecker() {
1992  EXPECT_PRED_FORMAT3(HasOneFailure, *results_, type_, substr_.c_str());
1993}
1994
1995DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter(
1996    UnitTestImpl* unit_test) : unit_test_(unit_test) {}
1997
1998void DefaultGlobalTestPartResultReporter::ReportTestPartResult(
1999    const TestPartResult& result) {
2000  unit_test_->current_test_result()->AddTestPartResult(result);
2001  unit_test_->listeners()->repeater()->OnTestPartResult(result);
2002}
2003
2004DefaultPerThreadTestPartResultReporter::DefaultPerThreadTestPartResultReporter(
2005    UnitTestImpl* unit_test) : unit_test_(unit_test) {}
2006
2007void DefaultPerThreadTestPartResultReporter::ReportTestPartResult(
2008    const TestPartResult& result) {
2009  unit_test_->GetGlobalTestPartResultReporter()->ReportTestPartResult(result);
2010}
2011
2012// Returns the global test part result reporter.
2013TestPartResultReporterInterface*
2014UnitTestImpl::GetGlobalTestPartResultReporter() {
2015  internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
2016  return global_test_part_result_repoter_;
2017}
2018
2019// Sets the global test part result reporter.
2020void UnitTestImpl::SetGlobalTestPartResultReporter(
2021    TestPartResultReporterInterface* reporter) {
2022  internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
2023  global_test_part_result_repoter_ = reporter;
2024}
2025
2026// Returns the test part result reporter for the current thread.
2027TestPartResultReporterInterface*
2028UnitTestImpl::GetTestPartResultReporterForCurrentThread() {
2029  return per_thread_test_part_result_reporter_.get();
2030}
2031
2032// Sets the test part result reporter for the current thread.
2033void UnitTestImpl::SetTestPartResultReporterForCurrentThread(
2034    TestPartResultReporterInterface* reporter) {
2035  per_thread_test_part_result_reporter_.set(reporter);
2036}
2037
2038// Gets the number of successful test cases.
2039int UnitTestImpl::successful_test_case_count() const {
2040  return CountIf(test_cases_, TestCasePassed);
2041}
2042
2043// Gets the number of failed test cases.
2044int UnitTestImpl::failed_test_case_count() const {
2045  return CountIf(test_cases_, TestCaseFailed);
2046}
2047
2048// Gets the number of all test cases.
2049int UnitTestImpl::total_test_case_count() const {
2050  return static_cast<int>(test_cases_.size());
2051}
2052
2053// Gets the number of all test cases that contain at least one test
2054// that should run.
2055int UnitTestImpl::test_case_to_run_count() const {
2056  return CountIf(test_cases_, ShouldRunTestCase);
2057}
2058
2059// Gets the number of successful tests.
2060int UnitTestImpl::successful_test_count() const {
2061  return SumOverTestCaseList(test_cases_, &TestCase::successful_test_count);
2062}
2063
2064// Gets the number of failed tests.
2065int UnitTestImpl::failed_test_count() const {
2066  return SumOverTestCaseList(test_cases_, &TestCase::failed_test_count);
2067}
2068
2069// Gets the number of disabled tests.
2070int UnitTestImpl::disabled_test_count() const {
2071  return SumOverTestCaseList(test_cases_, &TestCase::disabled_test_count);
2072}
2073
2074// Gets the number of all tests.
2075int UnitTestImpl::total_test_count() const {
2076  return SumOverTestCaseList(test_cases_, &TestCase::total_test_count);
2077}
2078
2079// Gets the number of tests that should run.
2080int UnitTestImpl::test_to_run_count() const {
2081  return SumOverTestCaseList(test_cases_, &TestCase::test_to_run_count);
2082}
2083
2084// Returns the current OS stack trace as a String.
2085//
2086// The maximum number of stack frames to be included is specified by
2087// the gtest_stack_trace_depth flag.  The skip_count parameter
2088// specifies the number of top frames to be skipped, which doesn't
2089// count against the number of frames to be included.
2090//
2091// For example, if Foo() calls Bar(), which in turn calls
2092// CurrentOsStackTraceExceptTop(1), Foo() will be included in the
2093// trace but Bar() and CurrentOsStackTraceExceptTop() won't.
2094String UnitTestImpl::CurrentOsStackTraceExceptTop(int skip_count) {
2095  (void)skip_count;
2096  return String("");
2097}
2098
2099// Returns the current time in milliseconds.
2100TimeInMillis GetTimeInMillis() {
2101#if GTEST_OS_WINDOWS_MOBILE || defined(__BORLANDC__)
2102  // Difference between 1970-01-01 and 1601-01-01 in milliseconds.
2103  // http://analogous.blogspot.com/2005/04/epoch.html
2104  const TimeInMillis kJavaEpochToWinFileTimeDelta =
2105    static_cast<TimeInMillis>(116444736UL) * 100000UL;
2106  const DWORD kTenthMicrosInMilliSecond = 10000;
2107
2108  SYSTEMTIME now_systime;
2109  FILETIME now_filetime;
2110  ULARGE_INTEGER now_int64;
2111  // TODO(kenton@google.com): Shouldn't this just use
2112  //   GetSystemTimeAsFileTime()?
2113  GetSystemTime(&now_systime);
2114  if (SystemTimeToFileTime(&now_systime, &now_filetime)) {
2115    now_int64.LowPart = now_filetime.dwLowDateTime;
2116    now_int64.HighPart = now_filetime.dwHighDateTime;
2117    now_int64.QuadPart = (now_int64.QuadPart / kTenthMicrosInMilliSecond) -
2118      kJavaEpochToWinFileTimeDelta;
2119    return now_int64.QuadPart;
2120  }
2121  return 0;
2122#elif GTEST_OS_WINDOWS && !GTEST_HAS_GETTIMEOFDAY_
2123  __timeb64 now;
2124#ifdef _MSC_VER
2125  // MSVC 8 deprecates _ftime64(), so we want to suppress warning 4996
2126  // (deprecated function) there.
2127  // TODO(kenton@google.com): Use GetTickCount()?  Or use
2128  //   SystemTimeToFileTime()
2129#pragma warning(push)          // Saves the current warning state.
2130#pragma warning(disable:4996)  // Temporarily disables warning 4996.
2131  _ftime64(&now);
2132#pragma warning(pop)           // Restores the warning state.
2133#else
2134  _ftime64(&now);
2135#endif  // _MSC_VER
2136  return static_cast<TimeInMillis>(now.time) * 1000 + now.millitm;
2137#elif GTEST_HAS_GETTIMEOFDAY_
2138  struct timeval now;
2139  gettimeofday(&now, NULL);
2140  return static_cast<TimeInMillis>(now.tv_sec) * 1000 + now.tv_usec / 1000;
2141#else
2142#error "Don't know how to get the current time on your system."
2143#endif
2144}
2145
2146// Utilities
2147
2148// class String
2149
2150// Returns the input enclosed in double quotes if it's not NULL;
2151// otherwise returns "(null)".  For example, "\"Hello\"" is returned
2152// for input "Hello".
2153//
2154// This is useful for printing a C string in the syntax of a literal.
2155//
2156// Known issue: escape sequences are not handled yet.
2157String String::ShowCStringQuoted(const char* c_str) {
2158  return c_str ? String::Format("\"%s\"", c_str) : String("(null)");
2159}
2160
2161// Copies at most length characters from str into a newly-allocated
2162// piece of memory of size length+1.  The memory is allocated with new[].
2163// A terminating null byte is written to the memory, and a pointer to it
2164// is returned.  If str is NULL, NULL is returned.
2165static char* CloneString(const char* str, size_t length) {
2166  if (str == NULL) {
2167    return NULL;
2168  } else {
2169    char* const clone = new char[length + 1];
2170    posix::StrNCpy(clone, str, length);
2171    clone[length] = '\0';
2172    return clone;
2173  }
2174}
2175
2176// Clones a 0-terminated C string, allocating memory using new.  The
2177// caller is responsible for deleting[] the return value.  Returns the
2178// cloned string, or NULL if the input is NULL.
2179const char * String::CloneCString(const char* c_str) {
2180  return (c_str == NULL) ?
2181                    NULL : CloneString(c_str, strlen(c_str));
2182}
2183
2184#if GTEST_OS_WINDOWS_MOBILE
2185// Creates a UTF-16 wide string from the given ANSI string, allocating
2186// memory using new. The caller is responsible for deleting the return
2187// value using delete[]. Returns the wide string, or NULL if the
2188// input is NULL.
2189LPCWSTR String::AnsiToUtf16(const char* ansi) {
2190  if (!ansi) return NULL;
2191  const int length = strlen(ansi);
2192  const int unicode_length =
2193      MultiByteToWideChar(CP_ACP, 0, ansi, length,
2194                          NULL, 0);
2195  WCHAR* unicode = new WCHAR[unicode_length + 1];
2196  MultiByteToWideChar(CP_ACP, 0, ansi, length,
2197                      unicode, unicode_length);
2198  unicode[unicode_length] = 0;
2199  return unicode;
2200}
2201
2202// Creates an ANSI string from the given wide string, allocating
2203// memory using new. The caller is responsible for deleting the return
2204// value using delete[]. Returns the ANSI string, or NULL if the
2205// input is NULL.
2206const char* String::Utf16ToAnsi(LPCWSTR utf16_str)  {
2207  if (!utf16_str) return NULL;
2208  const int ansi_length =
2209      WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
2210                          NULL, 0, NULL, NULL);
2211  char* ansi = new char[ansi_length + 1];
2212  WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
2213                      ansi, ansi_length, NULL, NULL);
2214  ansi[ansi_length] = 0;
2215  return ansi;
2216}
2217
2218#endif  // GTEST_OS_WINDOWS_MOBILE
2219
2220// Compares two C strings.  Returns true iff they have the same content.
2221//
2222// Unlike strcmp(), this function can handle NULL argument(s).  A NULL
2223// C string is considered different to any non-NULL C string,
2224// including the empty string.
2225bool String::CStringEquals(const char * lhs, const char * rhs) {
2226  if ( lhs == NULL ) return rhs == NULL;
2227
2228  if ( rhs == NULL ) return false;
2229
2230  return strcmp(lhs, rhs) == 0;
2231}
2232
2233#if GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
2234
2235// Converts an array of wide chars to a narrow string using the UTF-8
2236// encoding, and streams the result to the given Message object.
2237static void StreamWideCharsToMessage(const wchar_t* wstr, size_t length,
2238                                     Message* msg) {
2239  // TODO(wan): consider allowing a testing::String object to
2240  // contain '\0'.  This will make it behave more like std::string,
2241  // and will allow ToUtf8String() to return the correct encoding
2242  // for '\0' s.t. we can get rid of the conditional here (and in
2243  // several other places).
2244  for (size_t i = 0; i != length; ) {  // NOLINT
2245    if (wstr[i] != L'\0') {
2246      *msg << WideStringToUtf8(wstr + i, static_cast<int>(length - i));
2247      while (i != length && wstr[i] != L'\0')
2248        i++;
2249    } else {
2250      *msg << '\0';
2251      i++;
2252    }
2253  }
2254}
2255
2256#endif  // GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
2257
2258}  // namespace internal
2259
2260#if GTEST_HAS_STD_WSTRING
2261// Converts the given wide string to a narrow string using the UTF-8
2262// encoding, and streams the result to this Message object.
2263Message& Message::operator <<(const ::std::wstring& wstr) {
2264  internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
2265  return *this;
2266}
2267#endif  // GTEST_HAS_STD_WSTRING
2268
2269#if GTEST_HAS_GLOBAL_WSTRING
2270// Converts the given wide string to a narrow string using the UTF-8
2271// encoding, and streams the result to this Message object.
2272Message& Message::operator <<(const ::wstring& wstr) {
2273  internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
2274  return *this;
2275}
2276#endif  // GTEST_HAS_GLOBAL_WSTRING
2277
2278namespace internal {
2279
2280// Formats a value to be used in a failure message.
2281
2282// For a char value, we print it as a C++ char literal and as an
2283// unsigned integer (both in decimal and in hexadecimal).
2284String FormatForFailureMessage(char ch) {
2285  const unsigned int ch_as_uint = ch;
2286  // A String object cannot contain '\0', so we print "\\0" when ch is
2287  // '\0'.
2288  return String::Format("'%s' (%u, 0x%X)",
2289                        ch ? String::Format("%c", ch).c_str() : "\\0",
2290                        ch_as_uint, ch_as_uint);
2291}
2292
2293// For a wchar_t value, we print it as a C++ wchar_t literal and as an
2294// unsigned integer (both in decimal and in hexidecimal).
2295String FormatForFailureMessage(wchar_t wchar) {
2296  // The C++ standard doesn't specify the exact size of the wchar_t
2297  // type.  It just says that it shall have the same size as another
2298  // integral type, called its underlying type.
2299  //
2300  // Therefore, in order to print a wchar_t value in the numeric form,
2301  // we first convert it to the largest integral type (UInt64) and
2302  // then print the converted value.
2303  //
2304  // We use streaming to print the value as "%llu" doesn't work
2305  // correctly with MSVC 7.1.
2306  const UInt64 wchar_as_uint64 = wchar;
2307  Message msg;
2308  // A String object cannot contain '\0', so we print "\\0" when wchar is
2309  // L'\0'.
2310  char buffer[32];  // CodePointToUtf8 requires a buffer that big.
2311  msg << "L'"
2312      << (wchar ? CodePointToUtf8(static_cast<UInt32>(wchar), buffer) : "\\0")
2313      << "' (" << wchar_as_uint64 << ", 0x" << ::std::setbase(16)
2314      << wchar_as_uint64 << ")";
2315  return msg.GetString();
2316}
2317
2318}  // namespace internal
2319
2320// AssertionResult constructors.
2321// Used in EXPECT_TRUE/FALSE(assertion_result).
2322AssertionResult::AssertionResult(const AssertionResult& other)
2323    : success_(other.success_),
2324      message_(other.message_.get() != NULL ?
2325               new internal::String(*other.message_) :
2326               static_cast<internal::String*>(NULL)) {
2327}
2328
2329// Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE.
2330AssertionResult AssertionResult::operator!() const {
2331  AssertionResult negation(!success_);
2332  if (message_.get() != NULL)
2333    negation << *message_;
2334  return negation;
2335}
2336
2337// Makes a successful assertion result.
2338AssertionResult AssertionSuccess() {
2339  return AssertionResult(true);
2340}
2341
2342// Makes a failed assertion result.
2343AssertionResult AssertionFailure() {
2344  return AssertionResult(false);
2345}
2346
2347// Makes a failed assertion result with the given failure message.
2348// Deprecated; use AssertionFailure() << message.
2349AssertionResult AssertionFailure(const Message& message) {
2350  return AssertionFailure() << message;
2351}
2352
2353namespace internal {
2354
2355// Constructs and returns the message for an equality assertion
2356// (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure.
2357//
2358// The first four parameters are the expressions used in the assertion
2359// and their values, as strings.  For example, for ASSERT_EQ(foo, bar)
2360// where foo is 5 and bar is 6, we have:
2361//
2362//   expected_expression: "foo"
2363//   actual_expression:   "bar"
2364//   expected_value:      "5"
2365//   actual_value:        "6"
2366//
2367// The ignoring_case parameter is true iff the assertion is a
2368// *_STRCASEEQ*.  When it's true, the string " (ignoring case)" will
2369// be inserted into the message.
2370AssertionResult EqFailure(const char* expected_expression,
2371                          const char* actual_expression,
2372                          const String& expected_value,
2373                          const String& actual_value,
2374                          bool ignoring_case) {
2375  Message msg;
2376  msg << "Value of: " << actual_expression;
2377  if (actual_value != actual_expression) {
2378    msg << "\n  Actual: " << actual_value;
2379  }
2380
2381  msg << "\nExpected: " << expected_expression;
2382  if (ignoring_case) {
2383    msg << " (ignoring case)";
2384  }
2385  if (expected_value != expected_expression) {
2386    msg << "\nWhich is: " << expected_value;
2387  }
2388
2389  return AssertionFailure(msg);
2390}
2391
2392// Constructs a failure message for Boolean assertions such as EXPECT_TRUE.
2393String GetBoolAssertionFailureMessage(const AssertionResult& assertion_result,
2394                                      const char* expression_text,
2395                                      const char* actual_predicate_value,
2396                                      const char* expected_predicate_value) {
2397  const char* actual_message = assertion_result.message();
2398  Message msg;
2399  msg << "Value of: " << expression_text
2400      << "\n  Actual: " << actual_predicate_value;
2401  if (actual_message[0] != '\0')
2402    msg << " (" << actual_message << ")";
2403  msg << "\nExpected: " << expected_predicate_value;
2404  return msg.GetString();
2405}
2406
2407// Helper function for implementing ASSERT_NEAR.
2408AssertionResult DoubleNearPredFormat(const char* expr1,
2409                                     const char* expr2,
2410                                     const char* abs_error_expr,
2411                                     double val1,
2412                                     double val2,
2413                                     double abs_error) {
2414  const double diff = fabs(val1 - val2);
2415  if (diff <= abs_error) return AssertionSuccess();
2416
2417  // TODO(wan): do not print the value of an expression if it's
2418  // already a literal.
2419  Message msg;
2420  msg << "The difference between " << expr1 << " and " << expr2
2421      << " is " << diff << ", which exceeds " << abs_error_expr << ", where\n"
2422      << expr1 << " evaluates to " << val1 << ",\n"
2423      << expr2 << " evaluates to " << val2 << ", and\n"
2424      << abs_error_expr << " evaluates to " << abs_error << ".";
2425  return AssertionFailure(msg);
2426}
2427
2428
2429// Helper template for implementing FloatLE() and DoubleLE().
2430template <typename RawType>
2431AssertionResult FloatingPointLE(const char* expr1,
2432                                const char* expr2,
2433                                RawType val1,
2434                                RawType val2) {
2435  // Returns success if val1 is less than val2,
2436  if (val1 < val2) {
2437    return AssertionSuccess();
2438  }
2439
2440  // or if val1 is almost equal to val2.
2441  const FloatingPoint<RawType> lhs(val1), rhs(val2);
2442  if (lhs.AlmostEquals(rhs)) {
2443    return AssertionSuccess();
2444  }
2445
2446  // Note that the above two checks will both fail if either val1 or
2447  // val2 is NaN, as the IEEE floating-point standard requires that
2448  // any predicate involving a NaN must return false.
2449
2450  StrStream val1_ss;
2451  val1_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
2452          << val1;
2453
2454  StrStream val2_ss;
2455  val2_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
2456          << val2;
2457
2458  Message msg;
2459  msg << "Expected: (" << expr1 << ") <= (" << expr2 << ")\n"
2460      << "  Actual: " << StrStreamToString(&val1_ss) << " vs "
2461      << StrStreamToString(&val2_ss);
2462
2463  return AssertionFailure(msg);
2464}
2465
2466}  // namespace internal
2467
2468// Asserts that val1 is less than, or almost equal to, val2.  Fails
2469// otherwise.  In particular, it fails if either val1 or val2 is NaN.
2470AssertionResult FloatLE(const char* expr1, const char* expr2,
2471                        float val1, float val2) {
2472  return internal::FloatingPointLE<float>(expr1, expr2, val1, val2);
2473}
2474
2475// Asserts that val1 is less than, or almost equal to, val2.  Fails
2476// otherwise.  In particular, it fails if either val1 or val2 is NaN.
2477AssertionResult DoubleLE(const char* expr1, const char* expr2,
2478                         double val1, double val2) {
2479  return internal::FloatingPointLE<double>(expr1, expr2, val1, val2);
2480}
2481
2482namespace internal {
2483
2484// The helper function for {ASSERT|EXPECT}_EQ with int or enum
2485// arguments.
2486AssertionResult CmpHelperEQ(const char* expected_expression,
2487                            const char* actual_expression,
2488                            BiggestInt expected,
2489                            BiggestInt actual) {
2490  if (expected == actual) {
2491    return AssertionSuccess();
2492  }
2493
2494  return EqFailure(expected_expression,
2495                   actual_expression,
2496                   FormatForComparisonFailureMessage(expected, actual),
2497                   FormatForComparisonFailureMessage(actual, expected),
2498                   false);
2499}
2500
2501// A macro for implementing the helper functions needed to implement
2502// ASSERT_?? and EXPECT_?? with integer or enum arguments.  It is here
2503// just to avoid copy-and-paste of similar code.
2504#define GTEST_IMPL_CMP_HELPER_(op_name, op)\
2505AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \
2506                                   BiggestInt val1, BiggestInt val2) {\
2507  if (val1 op val2) {\
2508    return AssertionSuccess();\
2509  } else {\
2510    Message msg;\
2511    msg << "Expected: (" << expr1 << ") " #op " (" << expr2\
2512        << "), actual: " << FormatForComparisonFailureMessage(val1, val2)\
2513        << " vs " << FormatForComparisonFailureMessage(val2, val1);\
2514    return AssertionFailure(msg);\
2515  }\
2516}
2517
2518// Implements the helper function for {ASSERT|EXPECT}_NE with int or
2519// enum arguments.
2520GTEST_IMPL_CMP_HELPER_(NE, !=)
2521// Implements the helper function for {ASSERT|EXPECT}_LE with int or
2522// enum arguments.
2523GTEST_IMPL_CMP_HELPER_(LE, <=)
2524// Implements the helper function for {ASSERT|EXPECT}_LT with int or
2525// enum arguments.
2526GTEST_IMPL_CMP_HELPER_(LT, < )
2527// Implements the helper function for {ASSERT|EXPECT}_GE with int or
2528// enum arguments.
2529GTEST_IMPL_CMP_HELPER_(GE, >=)
2530// Implements the helper function for {ASSERT|EXPECT}_GT with int or
2531// enum arguments.
2532GTEST_IMPL_CMP_HELPER_(GT, > )
2533
2534#undef GTEST_IMPL_CMP_HELPER_
2535
2536// The helper function for {ASSERT|EXPECT}_STREQ.
2537AssertionResult CmpHelperSTREQ(const char* expected_expression,
2538                               const char* actual_expression,
2539                               const char* expected,
2540                               const char* actual) {
2541  if (String::CStringEquals(expected, actual)) {
2542    return AssertionSuccess();
2543  }
2544
2545  return EqFailure(expected_expression,
2546                   actual_expression,
2547                   String::ShowCStringQuoted(expected),
2548                   String::ShowCStringQuoted(actual),
2549                   false);
2550}
2551
2552// The helper function for {ASSERT|EXPECT}_STRCASEEQ.
2553AssertionResult CmpHelperSTRCASEEQ(const char* expected_expression,
2554                                   const char* actual_expression,
2555                                   const char* expected,
2556                                   const char* actual) {
2557  if (String::CaseInsensitiveCStringEquals(expected, actual)) {
2558    return AssertionSuccess();
2559  }
2560
2561  return EqFailure(expected_expression,
2562                   actual_expression,
2563                   String::ShowCStringQuoted(expected),
2564                   String::ShowCStringQuoted(actual),
2565                   true);
2566}
2567
2568// The helper function for {ASSERT|EXPECT}_STRNE.
2569AssertionResult CmpHelperSTRNE(const char* s1_expression,
2570                               const char* s2_expression,
2571                               const char* s1,
2572                               const char* s2) {
2573  if (!String::CStringEquals(s1, s2)) {
2574    return AssertionSuccess();
2575  } else {
2576    Message msg;
2577    msg << "Expected: (" << s1_expression << ") != ("
2578        << s2_expression << "), actual: \""
2579        << s1 << "\" vs \"" << s2 << "\"";
2580    return AssertionFailure(msg);
2581  }
2582}
2583
2584// The helper function for {ASSERT|EXPECT}_STRCASENE.
2585AssertionResult CmpHelperSTRCASENE(const char* s1_expression,
2586                                   const char* s2_expression,
2587                                   const char* s1,
2588                                   const char* s2) {
2589  if (!String::CaseInsensitiveCStringEquals(s1, s2)) {
2590    return AssertionSuccess();
2591  } else {
2592    Message msg;
2593    msg << "Expected: (" << s1_expression << ") != ("
2594        << s2_expression << ") (ignoring case), actual: \""
2595        << s1 << "\" vs \"" << s2 << "\"";
2596    return AssertionFailure(msg);
2597  }
2598}
2599
2600}  // namespace internal
2601
2602namespace {
2603
2604// Helper functions for implementing IsSubString() and IsNotSubstring().
2605
2606// This group of overloaded functions return true iff needle is a
2607// substring of haystack.  NULL is considered a substring of itself
2608// only.
2609
2610bool IsSubstringPred(const char* needle, const char* haystack) {
2611  if (needle == NULL || haystack == NULL)
2612    return needle == haystack;
2613
2614  return strstr(haystack, needle) != NULL;
2615}
2616
2617bool IsSubstringPred(const wchar_t* needle, const wchar_t* haystack) {
2618  if (needle == NULL || haystack == NULL)
2619    return needle == haystack;
2620
2621  return wcsstr(haystack, needle) != NULL;
2622}
2623
2624// StringType here can be either ::std::string or ::std::wstring.
2625template <typename StringType>
2626bool IsSubstringPred(const StringType& needle,
2627                     const StringType& haystack) {
2628  return haystack.find(needle) != StringType::npos;
2629}
2630
2631// This function implements either IsSubstring() or IsNotSubstring(),
2632// depending on the value of the expected_to_be_substring parameter.
2633// StringType here can be const char*, const wchar_t*, ::std::string,
2634// or ::std::wstring.
2635template <typename StringType>
2636AssertionResult IsSubstringImpl(
2637    bool expected_to_be_substring,
2638    const char* needle_expr, const char* haystack_expr,
2639    const StringType& needle, const StringType& haystack) {
2640  if (IsSubstringPred(needle, haystack) == expected_to_be_substring)
2641    return AssertionSuccess();
2642
2643  const bool is_wide_string = sizeof(needle[0]) > 1;
2644  const char* const begin_string_quote = is_wide_string ? "L\"" : "\"";
2645  return AssertionFailure(
2646      Message()
2647      << "Value of: " << needle_expr << "\n"
2648      << "  Actual: " << begin_string_quote << needle << "\"\n"
2649      << "Expected: " << (expected_to_be_substring ? "" : "not ")
2650      << "a substring of " << haystack_expr << "\n"
2651      << "Which is: " << begin_string_quote << haystack << "\"");
2652}
2653
2654}  // namespace
2655
2656// IsSubstring() and IsNotSubstring() check whether needle is a
2657// substring of haystack (NULL is considered a substring of itself
2658// only), and return an appropriate error message when they fail.
2659
2660AssertionResult IsSubstring(
2661    const char* needle_expr, const char* haystack_expr,
2662    const char* needle, const char* haystack) {
2663  return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
2664}
2665
2666AssertionResult IsSubstring(
2667    const char* needle_expr, const char* haystack_expr,
2668    const wchar_t* needle, const wchar_t* haystack) {
2669  return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
2670}
2671
2672AssertionResult IsNotSubstring(
2673    const char* needle_expr, const char* haystack_expr,
2674    const char* needle, const char* haystack) {
2675  return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
2676}
2677
2678AssertionResult IsNotSubstring(
2679    const char* needle_expr, const char* haystack_expr,
2680    const wchar_t* needle, const wchar_t* haystack) {
2681  return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
2682}
2683
2684AssertionResult IsSubstring(
2685    const char* needle_expr, const char* haystack_expr,
2686    const ::std::string& needle, const ::std::string& haystack) {
2687  return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
2688}
2689
2690AssertionResult IsNotSubstring(
2691    const char* needle_expr, const char* haystack_expr,
2692    const ::std::string& needle, const ::std::string& haystack) {
2693  return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
2694}
2695
2696#if GTEST_HAS_STD_WSTRING
2697AssertionResult IsSubstring(
2698    const char* needle_expr, const char* haystack_expr,
2699    const ::std::wstring& needle, const ::std::wstring& haystack) {
2700  return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
2701}
2702
2703AssertionResult IsNotSubstring(
2704    const char* needle_expr, const char* haystack_expr,
2705    const ::std::wstring& needle, const ::std::wstring& haystack) {
2706  return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
2707}
2708#endif  // GTEST_HAS_STD_WSTRING
2709
2710namespace internal {
2711
2712#if GTEST_OS_WINDOWS
2713
2714namespace {
2715
2716// Helper function for IsHRESULT{SuccessFailure} predicates
2717AssertionResult HRESULTFailureHelper(const char* expr,
2718                                     const char* expected,
2719                                     long hr) {  // NOLINT
2720#if GTEST_OS_WINDOWS_MOBILE
2721  // Windows CE doesn't support FormatMessage.
2722  const char error_text[] = "";
2723#else
2724  // Looks up the human-readable system message for the HRESULT code
2725  // and since we're not passing any params to FormatMessage, we don't
2726  // want inserts expanded.
2727  const DWORD kFlags = FORMAT_MESSAGE_FROM_SYSTEM |
2728                       FORMAT_MESSAGE_IGNORE_INSERTS;
2729  const DWORD kBufSize = 4096;  // String::Format can't exceed this length.
2730  // Gets the system's human readable message string for this HRESULT.
2731  char error_text[kBufSize] = { '\0' };
2732  DWORD message_length = ::FormatMessageA(kFlags,
2733                                          0,  // no source, we're asking system
2734                                          hr,  // the error
2735                                          0,  // no line width restrictions
2736                                          error_text,  // output buffer
2737                                          kBufSize,  // buf size
2738                                          NULL);  // no arguments for inserts
2739  // Trims tailing white space (FormatMessage leaves a trailing cr-lf)
2740  for (; message_length && isspace(error_text[message_length - 1]);
2741          --message_length) {
2742    error_text[message_length - 1] = '\0';
2743  }
2744#endif  // GTEST_OS_WINDOWS_MOBILE
2745
2746  const String error_hex(String::Format("0x%08X ", hr));
2747  Message msg;
2748  msg << "Expected: " << expr << " " << expected << ".\n"
2749      << "  Actual: " << error_hex << error_text << "\n";
2750
2751  return ::testing::AssertionFailure(msg);
2752}
2753
2754}  // namespace
2755
2756AssertionResult IsHRESULTSuccess(const char* expr, long hr) {  // NOLINT
2757  if (SUCCEEDED(hr)) {
2758    return AssertionSuccess();
2759  }
2760  return HRESULTFailureHelper(expr, "succeeds", hr);
2761}
2762
2763AssertionResult IsHRESULTFailure(const char* expr, long hr) {  // NOLINT
2764  if (FAILED(hr)) {
2765    return AssertionSuccess();
2766  }
2767  return HRESULTFailureHelper(expr, "fails", hr);
2768}
2769
2770#endif  // GTEST_OS_WINDOWS
2771
2772// Utility functions for encoding Unicode text (wide strings) in
2773// UTF-8.
2774
2775// A Unicode code-point can have upto 21 bits, and is encoded in UTF-8
2776// like this:
2777//
2778// Code-point length   Encoding
2779//   0 -  7 bits       0xxxxxxx
2780//   8 - 11 bits       110xxxxx 10xxxxxx
2781//  12 - 16 bits       1110xxxx 10xxxxxx 10xxxxxx
2782//  17 - 21 bits       11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
2783
2784// The maximum code-point a one-byte UTF-8 sequence can represent.
2785const UInt32 kMaxCodePoint1 = (static_cast<UInt32>(1) <<  7) - 1;
2786
2787// The maximum code-point a two-byte UTF-8 sequence can represent.
2788const UInt32 kMaxCodePoint2 = (static_cast<UInt32>(1) << (5 + 6)) - 1;
2789
2790// The maximum code-point a three-byte UTF-8 sequence can represent.
2791const UInt32 kMaxCodePoint3 = (static_cast<UInt32>(1) << (4 + 2*6)) - 1;
2792
2793// The maximum code-point a four-byte UTF-8 sequence can represent.
2794const UInt32 kMaxCodePoint4 = (static_cast<UInt32>(1) << (3 + 3*6)) - 1;
2795
2796// Chops off the n lowest bits from a bit pattern.  Returns the n
2797// lowest bits.  As a side effect, the original bit pattern will be
2798// shifted to the right by n bits.
2799inline UInt32 ChopLowBits(UInt32* bits, int n) {
2800  const UInt32 low_bits = *bits & ((static_cast<UInt32>(1) << n) - 1);
2801  *bits >>= n;
2802  return low_bits;
2803}
2804
2805// Converts a Unicode code point to a narrow string in UTF-8 encoding.
2806// code_point parameter is of type UInt32 because wchar_t may not be
2807// wide enough to contain a code point.
2808// The output buffer str must containt at least 32 characters.
2809// The function returns the address of the output buffer.
2810// If the code_point is not a valid Unicode code point
2811// (i.e. outside of Unicode range U+0 to U+10FFFF) it will be output
2812// as '(Invalid Unicode 0xXXXXXXXX)'.
2813char* CodePointToUtf8(UInt32 code_point, char* str) {
2814  if (code_point <= kMaxCodePoint1) {
2815    str[1] = '\0';
2816    str[0] = static_cast<char>(code_point);                          // 0xxxxxxx
2817  } else if (code_point <= kMaxCodePoint2) {
2818    str[2] = '\0';
2819    str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx
2820    str[0] = static_cast<char>(0xC0 | code_point);                   // 110xxxxx
2821  } else if (code_point <= kMaxCodePoint3) {
2822    str[3] = '\0';
2823    str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx
2824    str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx
2825    str[0] = static_cast<char>(0xE0 | code_point);                   // 1110xxxx
2826  } else if (code_point <= kMaxCodePoint4) {
2827    str[4] = '\0';
2828    str[3] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx
2829    str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx
2830    str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx
2831    str[0] = static_cast<char>(0xF0 | code_point);                   // 11110xxx
2832  } else {
2833    // The longest string String::Format can produce when invoked
2834    // with these parameters is 28 character long (not including
2835    // the terminating nul character). We are asking for 32 character
2836    // buffer just in case. This is also enough for strncpy to
2837    // null-terminate the destination string.
2838    posix::StrNCpy(
2839        str, String::Format("(Invalid Unicode 0x%X)", code_point).c_str(), 32);
2840    str[31] = '\0';  // Makes sure no change in the format to strncpy leaves
2841                     // the result unterminated.
2842  }
2843  return str;
2844}
2845
2846// The following two functions only make sense if the the system
2847// uses UTF-16 for wide string encoding. All supported systems
2848// with 16 bit wchar_t (Windows, Cygwin, Symbian OS) do use UTF-16.
2849
2850// Determines if the arguments constitute UTF-16 surrogate pair
2851// and thus should be combined into a single Unicode code point
2852// using CreateCodePointFromUtf16SurrogatePair.
2853inline bool IsUtf16SurrogatePair(wchar_t first, wchar_t second) {
2854  return sizeof(wchar_t) == 2 &&
2855      (first & 0xFC00) == 0xD800 && (second & 0xFC00) == 0xDC00;
2856}
2857
2858// Creates a Unicode code point from UTF16 surrogate pair.
2859inline UInt32 CreateCodePointFromUtf16SurrogatePair(wchar_t first,
2860                                                    wchar_t second) {
2861  const UInt32 mask = (1 << 10) - 1;
2862  return (sizeof(wchar_t) == 2) ?
2863      (((first & mask) << 10) | (second & mask)) + 0x10000 :
2864      // This function should not be called when the condition is
2865      // false, but we provide a sensible default in case it is.
2866      static_cast<UInt32>(first);
2867}
2868
2869// Converts a wide string to a narrow string in UTF-8 encoding.
2870// The wide string is assumed to have the following encoding:
2871//   UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS)
2872//   UTF-32 if sizeof(wchar_t) == 4 (on Linux)
2873// Parameter str points to a null-terminated wide string.
2874// Parameter num_chars may additionally limit the number
2875// of wchar_t characters processed. -1 is used when the entire string
2876// should be processed.
2877// If the string contains code points that are not valid Unicode code points
2878// (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
2879// as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
2880// and contains invalid UTF-16 surrogate pairs, values in those pairs
2881// will be encoded as individual Unicode characters from Basic Normal Plane.
2882String WideStringToUtf8(const wchar_t* str, int num_chars) {
2883  if (num_chars == -1)
2884    num_chars = static_cast<int>(wcslen(str));
2885
2886  StrStream stream;
2887  for (int i = 0; i < num_chars; ++i) {
2888    UInt32 unicode_code_point;
2889
2890    if (str[i] == L'\0') {
2891      break;
2892    } else if (i + 1 < num_chars && IsUtf16SurrogatePair(str[i], str[i + 1])) {
2893      unicode_code_point = CreateCodePointFromUtf16SurrogatePair(str[i],
2894                                                                 str[i + 1]);
2895      i++;
2896    } else {
2897      unicode_code_point = static_cast<UInt32>(str[i]);
2898    }
2899
2900    char buffer[32];  // CodePointToUtf8 requires a buffer this big.
2901    stream << CodePointToUtf8(unicode_code_point, buffer);
2902  }
2903  return StrStreamToString(&stream);
2904}
2905
2906// Converts a wide C string to a String using the UTF-8 encoding.
2907// NULL will be converted to "(null)".
2908String String::ShowWideCString(const wchar_t * wide_c_str) {
2909  if (wide_c_str == NULL) return String("(null)");
2910
2911  return String(internal::WideStringToUtf8(wide_c_str, -1).c_str());
2912}
2913
2914// Similar to ShowWideCString(), except that this function encloses
2915// the converted string in double quotes.
2916String String::ShowWideCStringQuoted(const wchar_t* wide_c_str) {
2917  if (wide_c_str == NULL) return String("(null)");
2918
2919  return String::Format("L\"%s\"",
2920                        String::ShowWideCString(wide_c_str).c_str());
2921}
2922
2923// Compares two wide C strings.  Returns true iff they have the same
2924// content.
2925//
2926// Unlike wcscmp(), this function can handle NULL argument(s).  A NULL
2927// C string is considered different to any non-NULL C string,
2928// including the empty string.
2929bool String::WideCStringEquals(const wchar_t * lhs, const wchar_t * rhs) {
2930  if (lhs == NULL) return rhs == NULL;
2931
2932  if (rhs == NULL) return false;
2933
2934  return wcscmp(lhs, rhs) == 0;
2935}
2936
2937// Helper function for *_STREQ on wide strings.
2938AssertionResult CmpHelperSTREQ(const char* expected_expression,
2939                               const char* actual_expression,
2940                               const wchar_t* expected,
2941                               const wchar_t* actual) {
2942  if (String::WideCStringEquals(expected, actual)) {
2943    return AssertionSuccess();
2944  }
2945
2946  return EqFailure(expected_expression,
2947                   actual_expression,
2948                   String::ShowWideCStringQuoted(expected),
2949                   String::ShowWideCStringQuoted(actual),
2950                   false);
2951}
2952
2953// Helper function for *_STRNE on wide strings.
2954AssertionResult CmpHelperSTRNE(const char* s1_expression,
2955                               const char* s2_expression,
2956                               const wchar_t* s1,
2957                               const wchar_t* s2) {
2958  if (!String::WideCStringEquals(s1, s2)) {
2959    return AssertionSuccess();
2960  }
2961
2962  Message msg;
2963  msg << "Expected: (" << s1_expression << ") != ("
2964      << s2_expression << "), actual: "
2965      << String::ShowWideCStringQuoted(s1)
2966      << " vs " << String::ShowWideCStringQuoted(s2);
2967  return AssertionFailure(msg);
2968}
2969
2970// Compares two C strings, ignoring case.  Returns true iff they have
2971// the same content.
2972//
2973// Unlike strcasecmp(), this function can handle NULL argument(s).  A
2974// NULL C string is considered different to any non-NULL C string,
2975// including the empty string.
2976bool String::CaseInsensitiveCStringEquals(const char * lhs, const char * rhs) {
2977  if (lhs == NULL)
2978    return rhs == NULL;
2979  if (rhs == NULL)
2980    return false;
2981  return posix::StrCaseCmp(lhs, rhs) == 0;
2982}
2983
2984  // Compares two wide C strings, ignoring case.  Returns true iff they
2985  // have the same content.
2986  //
2987  // Unlike wcscasecmp(), this function can handle NULL argument(s).
2988  // A NULL C string is considered different to any non-NULL wide C string,
2989  // including the empty string.
2990  // NB: The implementations on different platforms slightly differ.
2991  // On windows, this method uses _wcsicmp which compares according to LC_CTYPE
2992  // environment variable. On GNU platform this method uses wcscasecmp
2993  // which compares according to LC_CTYPE category of the current locale.
2994  // On MacOS X, it uses towlower, which also uses LC_CTYPE category of the
2995  // current locale.
2996bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs,
2997                                              const wchar_t* rhs) {
2998  if ( lhs == NULL ) return rhs == NULL;
2999
3000  if ( rhs == NULL ) return false;
3001
3002#if GTEST_OS_WINDOWS
3003  return _wcsicmp(lhs, rhs) == 0;
3004#elif GTEST_OS_LINUX
3005  return wcscasecmp(lhs, rhs) == 0;
3006#else
3007  // Mac OS X and Cygwin don't define wcscasecmp.  Other unknown OSes
3008  // may not define it either.
3009  wint_t left, right;
3010  do {
3011    left = towlower(*lhs++);
3012    right = towlower(*rhs++);
3013  } while (left && left == right);
3014  return left == right;
3015#endif  // OS selector
3016}
3017
3018// Compares this with another String.
3019// Returns < 0 if this is less than rhs, 0 if this is equal to rhs, or > 0
3020// if this is greater than rhs.
3021int String::Compare(const String & rhs) const {
3022  const char* const lhs_c_str = c_str();
3023  const char* const rhs_c_str = rhs.c_str();
3024
3025  if (lhs_c_str == NULL) {
3026    return rhs_c_str == NULL ? 0 : -1;  // NULL < anything except NULL
3027  } else if (rhs_c_str == NULL) {
3028    return 1;
3029  }
3030
3031  const size_t shorter_str_len =
3032      length() <= rhs.length() ? length() : rhs.length();
3033  for (size_t i = 0; i != shorter_str_len; i++) {
3034    if (lhs_c_str[i] < rhs_c_str[i]) {
3035      return -1;
3036    } else if (lhs_c_str[i] > rhs_c_str[i]) {
3037      return 1;
3038    }
3039  }
3040  return (length() < rhs.length()) ? -1 :
3041      (length() > rhs.length()) ? 1 : 0;
3042}
3043
3044// Returns true iff this String ends with the given suffix.  *Any*
3045// String is considered to end with a NULL or empty suffix.
3046bool String::EndsWith(const char* suffix) const {
3047  if (suffix == NULL || CStringEquals(suffix, "")) return true;
3048
3049  if (c_str() == NULL) return false;
3050
3051  const size_t this_len = strlen(c_str());
3052  const size_t suffix_len = strlen(suffix);
3053  return (this_len >= suffix_len) &&
3054         CStringEquals(c_str() + this_len - suffix_len, suffix);
3055}
3056
3057// Returns true iff this String ends with the given suffix, ignoring case.
3058// Any String is considered to end with a NULL or empty suffix.
3059bool String::EndsWithCaseInsensitive(const char* suffix) const {
3060  if (suffix == NULL || CStringEquals(suffix, "")) return true;
3061
3062  if (c_str() == NULL) return false;
3063
3064  const size_t this_len = strlen(c_str());
3065  const size_t suffix_len = strlen(suffix);
3066  return (this_len >= suffix_len) &&
3067         CaseInsensitiveCStringEquals(c_str() + this_len - suffix_len, suffix);
3068}
3069
3070// Formats a list of arguments to a String, using the same format
3071// spec string as for printf.
3072//
3073// We do not use the StringPrintf class as it is not universally
3074// available.
3075//
3076// The result is limited to 4096 characters (including the tailing 0).
3077// If 4096 characters are not enough to format the input, or if
3078// there's an error, "<formatting error or buffer exceeded>" is
3079// returned.
3080String String::Format(const char * format, ...) {
3081  va_list args;
3082  va_start(args, format);
3083
3084  char buffer[4096];
3085  const int kBufferSize = sizeof(buffer)/sizeof(buffer[0]);
3086
3087  // MSVC 8 deprecates vsnprintf(), so we want to suppress warning
3088  // 4996 (deprecated function) there.
3089#ifdef _MSC_VER  // We are using MSVC.
3090#pragma warning(push)          // Saves the current warning state.
3091#pragma warning(disable:4996)  // Temporarily disables warning 4996.
3092  const int size = vsnprintf(buffer, kBufferSize, format, args);
3093#pragma warning(pop)           // Restores the warning state.
3094#else  // We are not using MSVC.
3095  const int size = vsnprintf(buffer, kBufferSize, format, args);
3096#endif  // _MSC_VER
3097  va_end(args);
3098
3099  // vsnprintf()'s behavior is not portable.  When the buffer is not
3100  // big enough, it returns a negative value in MSVC, and returns the
3101  // needed buffer size on Linux.  When there is an output error, it
3102  // always returns a negative value.  For simplicity, we lump the two
3103  // error cases together.
3104  if (size < 0 || size >= kBufferSize) {
3105    return String("<formatting error or buffer exceeded>");
3106  } else {
3107    return String(buffer, size);
3108  }
3109}
3110
3111// Converts the buffer in a StrStream to a String, converting NUL
3112// bytes to "\\0" along the way.
3113String StrStreamToString(StrStream* ss) {
3114  const ::std::string& str = ss->str();
3115  const char* const start = str.c_str();
3116  const char* const end = start + str.length();
3117
3118  // We need to use a helper StrStream to do this transformation
3119  // because String doesn't support push_back().
3120  StrStream helper;
3121  for (const char* ch = start; ch != end; ++ch) {
3122    if (*ch == '\0') {
3123      helper << "\\0";  // Replaces NUL with "\\0";
3124    } else {
3125      helper.put(*ch);
3126    }
3127  }
3128
3129  return String(helper.str().c_str());
3130}
3131
3132// Appends the user-supplied message to the Google-Test-generated message.
3133String AppendUserMessage(const String& gtest_msg,
3134                         const Message& user_msg) {
3135  // Appends the user message if it's non-empty.
3136  const String user_msg_string = user_msg.GetString();
3137  if (user_msg_string.empty()) {
3138    return gtest_msg;
3139  }
3140
3141  Message msg;
3142  msg << gtest_msg << "\n" << user_msg_string;
3143
3144  return msg.GetString();
3145}
3146
3147}  // namespace internal
3148
3149// class TestResult
3150
3151// Creates an empty TestResult.
3152TestResult::TestResult()
3153    : death_test_count_(0),
3154      elapsed_time_(0) {
3155}
3156
3157// D'tor.
3158TestResult::~TestResult() {
3159}
3160
3161// Returns the i-th test part result among all the results. i can
3162// range from 0 to total_part_count() - 1. If i is not in that range,
3163// aborts the program.
3164const TestPartResult& TestResult::GetTestPartResult(int i) const {
3165  if (i < 0 || i >= total_part_count())
3166    internal::posix::Abort();
3167  return test_part_results_.at(i);
3168}
3169
3170// Returns the i-th test property. i can range from 0 to
3171// test_property_count() - 1. If i is not in that range, aborts the
3172// program.
3173const TestProperty& TestResult::GetTestProperty(int i) const {
3174  if (i < 0 || i >= test_property_count())
3175    internal::posix::Abort();
3176  return test_properties_.at(i);
3177}
3178
3179// Clears the test part results.
3180void TestResult::ClearTestPartResults() {
3181  test_part_results_.clear();
3182}
3183
3184// Adds a test part result to the list.
3185void TestResult::AddTestPartResult(const TestPartResult& test_part_result) {
3186  test_part_results_.push_back(test_part_result);
3187}
3188
3189// Adds a test property to the list. If a property with the same key as the
3190// supplied property is already represented, the value of this test_property
3191// replaces the old value for that key.
3192void TestResult::RecordProperty(const TestProperty& test_property) {
3193  if (!ValidateTestProperty(test_property)) {
3194    return;
3195  }
3196  internal::MutexLock lock(&test_properites_mutex_);
3197  const std::vector<TestProperty>::iterator property_with_matching_key =
3198      std::find_if(test_properties_.begin(), test_properties_.end(),
3199                   internal::TestPropertyKeyIs(test_property.key()));
3200  if (property_with_matching_key == test_properties_.end()) {
3201    test_properties_.push_back(test_property);
3202    return;
3203  }
3204  property_with_matching_key->SetValue(test_property.value());
3205}
3206
3207// Adds a failure if the key is a reserved attribute of Google Test
3208// testcase tags.  Returns true if the property is valid.
3209bool TestResult::ValidateTestProperty(const TestProperty& test_property) {
3210  internal::String key(test_property.key());
3211  if (key == "name" || key == "status" || key == "time" || key == "classname") {
3212    ADD_FAILURE()
3213        << "Reserved key used in RecordProperty(): "
3214        << key
3215        << " ('name', 'status', 'time', and 'classname' are reserved by "
3216        << GTEST_NAME_ << ")";
3217    return false;
3218  }
3219  return true;
3220}
3221
3222// Clears the object.
3223void TestResult::Clear() {
3224  test_part_results_.clear();
3225  test_properties_.clear();
3226  death_test_count_ = 0;
3227  elapsed_time_ = 0;
3228}
3229
3230// Returns true iff the test failed.
3231bool TestResult::Failed() const {
3232  for (int i = 0; i < total_part_count(); ++i) {
3233    if (GetTestPartResult(i).failed())
3234      return true;
3235  }
3236  return false;
3237}
3238
3239// Returns true iff the test part fatally failed.
3240static bool TestPartFatallyFailed(const TestPartResult& result) {
3241  return result.fatally_failed();
3242}
3243
3244// Returns true iff the test fatally failed.
3245bool TestResult::HasFatalFailure() const {
3246  return CountIf(test_part_results_, TestPartFatallyFailed) > 0;
3247}
3248
3249// Returns true iff the test part non-fatally failed.
3250static bool TestPartNonfatallyFailed(const TestPartResult& result) {
3251  return result.nonfatally_failed();
3252}
3253
3254// Returns true iff the test has a non-fatal failure.
3255bool TestResult::HasNonfatalFailure() const {
3256  return CountIf(test_part_results_, TestPartNonfatallyFailed) > 0;
3257}
3258
3259// Gets the number of all test parts.  This is the sum of the number
3260// of successful test parts and the number of failed test parts.
3261int TestResult::total_part_count() const {
3262  return static_cast<int>(test_part_results_.size());
3263}
3264
3265// Returns the number of the test properties.
3266int TestResult::test_property_count() const {
3267  return static_cast<int>(test_properties_.size());
3268}
3269
3270// class Test
3271
3272// Creates a Test object.
3273
3274// The c'tor saves the values of all Google Test flags.
3275Test::Test()
3276    : gtest_flag_saver_(new internal::GTestFlagSaver) {
3277}
3278
3279// The d'tor restores the values of all Google Test flags.
3280Test::~Test() {
3281  delete gtest_flag_saver_;
3282}
3283
3284// Sets up the test fixture.
3285//
3286// A sub-class may override this.
3287void Test::SetUp() {
3288}
3289
3290// Tears down the test fixture.
3291//
3292// A sub-class may override this.
3293void Test::TearDown() {
3294}
3295
3296// Allows user supplied key value pairs to be recorded for later output.
3297void Test::RecordProperty(const char* key, const char* value) {
3298  UnitTest::GetInstance()->RecordPropertyForCurrentTest(key, value);
3299}
3300
3301// Allows user supplied key value pairs to be recorded for later output.
3302void Test::RecordProperty(const char* key, int value) {
3303  Message value_message;
3304  value_message << value;
3305  RecordProperty(key, value_message.GetString().c_str());
3306}
3307
3308namespace internal {
3309
3310void ReportFailureInUnknownLocation(TestPartResult::Type result_type,
3311                                    const String& message) {
3312  // This function is a friend of UnitTest and as such has access to
3313  // AddTestPartResult.
3314  UnitTest::GetInstance()->AddTestPartResult(
3315      result_type,
3316      NULL,  // No info about the source file where the exception occurred.
3317      -1,    // We have no info on which line caused the exception.
3318      message,
3319      String());  // No stack trace, either.
3320}
3321
3322}  // namespace internal
3323
3324#if GTEST_OS_WINDOWS
3325// We are on Windows.
3326
3327// Adds an "exception thrown" fatal failure to the current test.
3328static void AddExceptionThrownFailure(DWORD exception_code,
3329                                      const char* location) {
3330  Message message;
3331  message << "Exception thrown with code 0x" << std::setbase(16) <<
3332    exception_code << std::setbase(10) << " in " << location << ".";
3333
3334  internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure,
3335                                           message.GetString());
3336}
3337
3338#endif  // GTEST_OS_WINDOWS
3339
3340// Google Test requires all tests in the same test case to use the same test
3341// fixture class.  This function checks if the current test has the
3342// same fixture class as the first test in the current test case.  If
3343// yes, it returns true; otherwise it generates a Google Test failure and
3344// returns false.
3345bool Test::HasSameFixtureClass() {
3346  internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
3347  const TestCase* const test_case = impl->current_test_case();
3348
3349  // Info about the first test in the current test case.
3350  const internal::TestInfoImpl* const first_test_info =
3351      test_case->test_info_list()[0]->impl();
3352  const internal::TypeId first_fixture_id = first_test_info->fixture_class_id();
3353  const char* const first_test_name = first_test_info->name();
3354
3355  // Info about the current test.
3356  const internal::TestInfoImpl* const this_test_info =
3357      impl->current_test_info()->impl();
3358  const internal::TypeId this_fixture_id = this_test_info->fixture_class_id();
3359  const char* const this_test_name = this_test_info->name();
3360
3361  if (this_fixture_id != first_fixture_id) {
3362    // Is the first test defined using TEST?
3363    const bool first_is_TEST = first_fixture_id == internal::GetTestTypeId();
3364    // Is this test defined using TEST?
3365    const bool this_is_TEST = this_fixture_id == internal::GetTestTypeId();
3366
3367    if (first_is_TEST || this_is_TEST) {
3368      // The user mixed TEST and TEST_F in this test case - we'll tell
3369      // him/her how to fix it.
3370
3371      // Gets the name of the TEST and the name of the TEST_F.  Note
3372      // that first_is_TEST and this_is_TEST cannot both be true, as
3373      // the fixture IDs are different for the two tests.
3374      const char* const TEST_name =
3375          first_is_TEST ? first_test_name : this_test_name;
3376      const char* const TEST_F_name =
3377          first_is_TEST ? this_test_name : first_test_name;
3378
3379      ADD_FAILURE()
3380          << "All tests in the same test case must use the same test fixture\n"
3381          << "class, so mixing TEST_F and TEST in the same test case is\n"
3382          << "illegal.  In test case " << this_test_info->test_case_name()
3383          << ",\n"
3384          << "test " << TEST_F_name << " is defined using TEST_F but\n"
3385          << "test " << TEST_name << " is defined using TEST.  You probably\n"
3386          << "want to change the TEST to TEST_F or move it to another test\n"
3387          << "case.";
3388    } else {
3389      // The user defined two fixture classes with the same name in
3390      // two namespaces - we'll tell him/her how to fix it.
3391      ADD_FAILURE()
3392          << "All tests in the same test case must use the same test fixture\n"
3393          << "class.  However, in test case "
3394          << this_test_info->test_case_name() << ",\n"
3395          << "you defined test " << first_test_name
3396          << " and test " << this_test_name << "\n"
3397          << "using two different test fixture classes.  This can happen if\n"
3398          << "the two classes are from different namespaces or translation\n"
3399          << "units and have the same name.  You should probably rename one\n"
3400          << "of the classes to put the tests into different test cases.";
3401    }
3402    return false;
3403  }
3404
3405  return true;
3406}
3407
3408// Runs the test and updates the test result.
3409void Test::Run() {
3410  if (!HasSameFixtureClass()) return;
3411
3412  internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
3413#if GTEST_HAS_SEH
3414  // Catch SEH-style exceptions.
3415  impl->os_stack_trace_getter()->UponLeavingGTest();
3416  __try {
3417    SetUp();
3418  } __except(internal::UnitTestOptions::GTestShouldProcessSEH(
3419      GetExceptionCode())) {
3420    AddExceptionThrownFailure(GetExceptionCode(), "SetUp()");
3421  }
3422
3423  // We will run the test only if SetUp() had no fatal failure.
3424  if (!HasFatalFailure()) {
3425    impl->os_stack_trace_getter()->UponLeavingGTest();
3426    __try {
3427      TestBody();
3428    } __except(internal::UnitTestOptions::GTestShouldProcessSEH(
3429        GetExceptionCode())) {
3430      AddExceptionThrownFailure(GetExceptionCode(), "the test body");
3431    }
3432  }
3433
3434  // However, we want to clean up as much as possible.  Hence we will
3435  // always call TearDown(), even if SetUp() or the test body has
3436  // failed.
3437  impl->os_stack_trace_getter()->UponLeavingGTest();
3438  __try {
3439    TearDown();
3440  } __except(internal::UnitTestOptions::GTestShouldProcessSEH(
3441      GetExceptionCode())) {
3442    AddExceptionThrownFailure(GetExceptionCode(), "TearDown()");
3443  }
3444
3445#else  // We are on a compiler or platform that doesn't support SEH.
3446  impl->os_stack_trace_getter()->UponLeavingGTest();
3447  SetUp();
3448
3449  // We will run the test only if SetUp() was successful.
3450  if (!HasFatalFailure()) {
3451    impl->os_stack_trace_getter()->UponLeavingGTest();
3452    TestBody();
3453  }
3454
3455  // However, we want to clean up as much as possible.  Hence we will
3456  // always call TearDown(), even if SetUp() or the test body has
3457  // failed.
3458  impl->os_stack_trace_getter()->UponLeavingGTest();
3459  TearDown();
3460#endif  // GTEST_HAS_SEH
3461}
3462
3463
3464// Returns true iff the current test has a fatal failure.
3465bool Test::HasFatalFailure() {
3466  return internal::GetUnitTestImpl()->current_test_result()->HasFatalFailure();
3467}
3468
3469// Returns true iff the current test has a non-fatal failure.
3470bool Test::HasNonfatalFailure() {
3471  return internal::GetUnitTestImpl()->current_test_result()->
3472      HasNonfatalFailure();
3473}
3474
3475// class TestInfo
3476
3477// Constructs a TestInfo object. It assumes ownership of the test factory
3478// object via impl_.
3479TestInfo::TestInfo(const char* a_test_case_name,
3480                   const char* a_name,
3481                   const char* a_test_case_comment,
3482                   const char* a_comment,
3483                   internal::TypeId fixture_class_id,
3484                   internal::TestFactoryBase* factory) {
3485  impl_ = new internal::TestInfoImpl(this, a_test_case_name, a_name,
3486                                     a_test_case_comment, a_comment,
3487                                     fixture_class_id, factory);
3488}
3489
3490// Destructs a TestInfo object.
3491TestInfo::~TestInfo() {
3492  delete impl_;
3493}
3494
3495namespace internal {
3496
3497// Creates a new TestInfo object and registers it with Google Test;
3498// returns the created object.
3499//
3500// Arguments:
3501//
3502//   test_case_name:   name of the test case
3503//   name:             name of the test
3504//   test_case_comment: a comment on the test case that will be included in
3505//                      the test output
3506//   comment:          a comment on the test that will be included in the
3507//                     test output
3508//   fixture_class_id: ID of the test fixture class
3509//   set_up_tc:        pointer to the function that sets up the test case
3510//   tear_down_tc:     pointer to the function that tears down the test case
3511//   factory:          pointer to the factory that creates a test object.
3512//                     The newly created TestInfo instance will assume
3513//                     ownership of the factory object.
3514TestInfo* MakeAndRegisterTestInfo(
3515    const char* test_case_name, const char* name,
3516    const char* test_case_comment, const char* comment,
3517    TypeId fixture_class_id,
3518    SetUpTestCaseFunc set_up_tc,
3519    TearDownTestCaseFunc tear_down_tc,
3520    TestFactoryBase* factory) {
3521  TestInfo* const test_info =
3522      new TestInfo(test_case_name, name, test_case_comment, comment,
3523                   fixture_class_id, factory);
3524  GetUnitTestImpl()->AddTestInfo(set_up_tc, tear_down_tc, test_info);
3525  return test_info;
3526}
3527
3528#if GTEST_HAS_PARAM_TEST
3529void ReportInvalidTestCaseType(const char* test_case_name,
3530                               const char* file, int line) {
3531  Message errors;
3532  errors
3533      << "Attempted redefinition of test case " << test_case_name << ".\n"
3534      << "All tests in the same test case must use the same test fixture\n"
3535      << "class.  However, in test case " << test_case_name << ", you tried\n"
3536      << "to define a test using a fixture class different from the one\n"
3537      << "used earlier. This can happen if the two fixture classes are\n"
3538      << "from different namespaces and have the same name. You should\n"
3539      << "probably rename one of the classes to put the tests into different\n"
3540      << "test cases.";
3541
3542  fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(),
3543          errors.GetString().c_str());
3544}
3545#endif  // GTEST_HAS_PARAM_TEST
3546
3547}  // namespace internal
3548
3549// Returns the test case name.
3550const char* TestInfo::test_case_name() const {
3551  return impl_->test_case_name();
3552}
3553
3554// Returns the test name.
3555const char* TestInfo::name() const {
3556  return impl_->name();
3557}
3558
3559// Returns the test case comment.
3560const char* TestInfo::test_case_comment() const {
3561  return impl_->test_case_comment();
3562}
3563
3564// Returns the test comment.
3565const char* TestInfo::comment() const {
3566  return impl_->comment();
3567}
3568
3569// Returns true if this test should run.
3570bool TestInfo::should_run() const { return impl_->should_run(); }
3571
3572// Returns true if this test matches the user-specified filter.
3573bool TestInfo::matches_filter() const { return impl_->matches_filter(); }
3574
3575// Returns the result of the test.
3576const TestResult* TestInfo::result() const { return impl_->result(); }
3577
3578// Increments the number of death tests encountered in this test so
3579// far.
3580int TestInfo::increment_death_test_count() {
3581  return impl_->result()->increment_death_test_count();
3582}
3583
3584namespace {
3585
3586// A predicate that checks the test name of a TestInfo against a known
3587// value.
3588//
3589// This is used for implementation of the TestCase class only.  We put
3590// it in the anonymous namespace to prevent polluting the outer
3591// namespace.
3592//
3593// TestNameIs is copyable.
3594class TestNameIs {
3595 public:
3596  // Constructor.
3597  //
3598  // TestNameIs has NO default constructor.
3599  explicit TestNameIs(const char* name)
3600      : name_(name) {}
3601
3602  // Returns true iff the test name of test_info matches name_.
3603  bool operator()(const TestInfo * test_info) const {
3604    return test_info && internal::String(test_info->name()).Compare(name_) == 0;
3605  }
3606
3607 private:
3608  internal::String name_;
3609};
3610
3611}  // namespace
3612
3613namespace internal {
3614
3615// This method expands all parameterized tests registered with macros TEST_P
3616// and INSTANTIATE_TEST_CASE_P into regular tests and registers those.
3617// This will be done just once during the program runtime.
3618void UnitTestImpl::RegisterParameterizedTests() {
3619#if GTEST_HAS_PARAM_TEST
3620  if (!parameterized_tests_registered_) {
3621    parameterized_test_registry_.RegisterTests();
3622    parameterized_tests_registered_ = true;
3623  }
3624#endif
3625}
3626
3627// Creates the test object, runs it, records its result, and then
3628// deletes it.
3629void TestInfoImpl::Run() {
3630  if (!should_run_) return;
3631
3632  // Tells UnitTest where to store test result.
3633  UnitTestImpl* const impl = internal::GetUnitTestImpl();
3634  impl->set_current_test_info(parent_);
3635
3636  TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
3637
3638  // Notifies the unit test event listeners that a test is about to start.
3639  repeater->OnTestStart(*parent_);
3640
3641  const TimeInMillis start = GetTimeInMillis();
3642
3643  impl->os_stack_trace_getter()->UponLeavingGTest();
3644#if GTEST_HAS_SEH
3645  // Catch SEH-style exceptions.
3646  Test* test = NULL;
3647
3648  __try {
3649    // Creates the test object.
3650    test = factory_->CreateTest();
3651  } __except(internal::UnitTestOptions::GTestShouldProcessSEH(
3652      GetExceptionCode())) {
3653    AddExceptionThrownFailure(GetExceptionCode(),
3654                              "the test fixture's constructor");
3655    return;
3656  }
3657#else  // We are on a compiler or platform that doesn't support SEH.
3658
3659  // TODO(wan): If test->Run() throws, test won't be deleted.  This is
3660  // not a problem now as we don't use exceptions.  If we were to
3661  // enable exceptions, we should revise the following to be
3662  // exception-safe.
3663
3664  // Creates the test object.
3665  Test* test = factory_->CreateTest();
3666#endif  // GTEST_HAS_SEH
3667
3668  // Runs the test only if the constructor of the test fixture didn't
3669  // generate a fatal failure.
3670  if (!Test::HasFatalFailure()) {
3671    test->Run();
3672  }
3673
3674  // Deletes the test object.
3675  impl->os_stack_trace_getter()->UponLeavingGTest();
3676  delete test;
3677  test = NULL;
3678
3679  result_.set_elapsed_time(GetTimeInMillis() - start);
3680
3681  // Notifies the unit test event listener that a test has just finished.
3682  repeater->OnTestEnd(*parent_);
3683
3684  // Tells UnitTest to stop associating assertion results to this
3685  // test.
3686  impl->set_current_test_info(NULL);
3687}
3688
3689}  // namespace internal
3690
3691// class TestCase
3692
3693// Gets the number of successful tests in this test case.
3694int TestCase::successful_test_count() const {
3695  return CountIf(test_info_list_, TestPassed);
3696}
3697
3698// Gets the number of failed tests in this test case.
3699int TestCase::failed_test_count() const {
3700  return CountIf(test_info_list_, TestFailed);
3701}
3702
3703int TestCase::disabled_test_count() const {
3704  return CountIf(test_info_list_, TestDisabled);
3705}
3706
3707// Get the number of tests in this test case that should run.
3708int TestCase::test_to_run_count() const {
3709  return CountIf(test_info_list_, ShouldRunTest);
3710}
3711
3712// Gets the number of all tests.
3713int TestCase::total_test_count() const {
3714  return static_cast<int>(test_info_list_.size());
3715}
3716
3717// Creates a TestCase with the given name.
3718//
3719// Arguments:
3720//
3721//   name:         name of the test case
3722//   set_up_tc:    pointer to the function that sets up the test case
3723//   tear_down_tc: pointer to the function that tears down the test case
3724TestCase::TestCase(const char* a_name, const char* a_comment,
3725                   Test::SetUpTestCaseFunc set_up_tc,
3726                   Test::TearDownTestCaseFunc tear_down_tc)
3727    : name_(a_name),
3728      comment_(a_comment),
3729      set_up_tc_(set_up_tc),
3730      tear_down_tc_(tear_down_tc),
3731      should_run_(false),
3732      elapsed_time_(0) {
3733}
3734
3735// Destructor of TestCase.
3736TestCase::~TestCase() {
3737  // Deletes every Test in the collection.
3738  ForEach(test_info_list_, internal::Delete<TestInfo>);
3739}
3740
3741// Returns the i-th test among all the tests. i can range from 0 to
3742// total_test_count() - 1. If i is not in that range, returns NULL.
3743const TestInfo* TestCase::GetTestInfo(int i) const {
3744  const int index = GetElementOr(test_indices_, i, -1);
3745  return index < 0 ? NULL : test_info_list_[index];
3746}
3747
3748// Returns the i-th test among all the tests. i can range from 0 to
3749// total_test_count() - 1. If i is not in that range, returns NULL.
3750TestInfo* TestCase::GetMutableTestInfo(int i) {
3751  const int index = GetElementOr(test_indices_, i, -1);
3752  return index < 0 ? NULL : test_info_list_[index];
3753}
3754
3755// Adds a test to this test case.  Will delete the test upon
3756// destruction of the TestCase object.
3757void TestCase::AddTestInfo(TestInfo * test_info) {
3758  test_info_list_.push_back(test_info);
3759  test_indices_.push_back(static_cast<int>(test_indices_.size()));
3760}
3761
3762// Runs every test in this TestCase.
3763void TestCase::Run() {
3764  if (!should_run_) return;
3765
3766  internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
3767  impl->set_current_test_case(this);
3768
3769  TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
3770
3771  repeater->OnTestCaseStart(*this);
3772  impl->os_stack_trace_getter()->UponLeavingGTest();
3773  set_up_tc_();
3774
3775  const internal::TimeInMillis start = internal::GetTimeInMillis();
3776  for (int i = 0; i < total_test_count(); i++) {
3777    GetMutableTestInfo(i)->impl()->Run();
3778  }
3779  elapsed_time_ = internal::GetTimeInMillis() - start;
3780
3781  impl->os_stack_trace_getter()->UponLeavingGTest();
3782  tear_down_tc_();
3783  repeater->OnTestCaseEnd(*this);
3784  impl->set_current_test_case(NULL);
3785}
3786
3787// Clears the results of all tests in this test case.
3788void TestCase::ClearResult() {
3789  ForEach(test_info_list_, internal::TestInfoImpl::ClearTestResult);
3790}
3791
3792// Returns true iff test passed.
3793bool TestCase::TestPassed(const TestInfo * test_info) {
3794  const internal::TestInfoImpl* const impl = test_info->impl();
3795  return impl->should_run() && impl->result()->Passed();
3796}
3797
3798// Returns true iff test failed.
3799bool TestCase::TestFailed(const TestInfo * test_info) {
3800  const internal::TestInfoImpl* const impl = test_info->impl();
3801  return impl->should_run() && impl->result()->Failed();
3802}
3803
3804// Returns true iff test is disabled.
3805bool TestCase::TestDisabled(const TestInfo * test_info) {
3806  return test_info->impl()->is_disabled();
3807}
3808
3809// Returns true if the given test should run.
3810bool TestCase::ShouldRunTest(const TestInfo *test_info) {
3811  return test_info->impl()->should_run();
3812}
3813
3814// Shuffles the tests in this test case.
3815void TestCase::ShuffleTests(internal::Random* random) {
3816  Shuffle(random, &test_indices_);
3817}
3818
3819// Restores the test order to before the first shuffle.
3820void TestCase::UnshuffleTests() {
3821  for (size_t i = 0; i < test_indices_.size(); i++) {
3822    test_indices_[i] = static_cast<int>(i);
3823  }
3824}
3825
3826// Formats a countable noun.  Depending on its quantity, either the
3827// singular form or the plural form is used. e.g.
3828//
3829// FormatCountableNoun(1, "formula", "formuli") returns "1 formula".
3830// FormatCountableNoun(5, "book", "books") returns "5 books".
3831static internal::String FormatCountableNoun(int count,
3832                                            const char * singular_form,
3833                                            const char * plural_form) {
3834  return internal::String::Format("%d %s", count,
3835                                  count == 1 ? singular_form : plural_form);
3836}
3837
3838// Formats the count of tests.
3839static internal::String FormatTestCount(int test_count) {
3840  return FormatCountableNoun(test_count, "test", "tests");
3841}
3842
3843// Formats the count of test cases.
3844static internal::String FormatTestCaseCount(int test_case_count) {
3845  return FormatCountableNoun(test_case_count, "test case", "test cases");
3846}
3847
3848// Converts a TestPartResult::Type enum to human-friendly string
3849// representation.  Both kNonFatalFailure and kFatalFailure are translated
3850// to "Failure", as the user usually doesn't care about the difference
3851// between the two when viewing the test result.
3852static const char * TestPartResultTypeToString(TestPartResult::Type type) {
3853  switch (type) {
3854    case TestPartResult::kSuccess:
3855      return "Success";
3856
3857    case TestPartResult::kNonFatalFailure:
3858    case TestPartResult::kFatalFailure:
3859#ifdef _MSC_VER
3860      return "error: ";
3861#else
3862      return "Failure\n";
3863#endif
3864  }
3865
3866  return "Unknown result type";
3867}
3868
3869// Prints a TestPartResult to a String.
3870static internal::String PrintTestPartResultToString(
3871    const TestPartResult& test_part_result) {
3872  return (Message()
3873          << internal::FormatFileLocation(test_part_result.file_name(),
3874                                          test_part_result.line_number())
3875          << " " << TestPartResultTypeToString(test_part_result.type())
3876          << test_part_result.message()).GetString();
3877}
3878
3879// Prints a TestPartResult.
3880static void PrintTestPartResult(const TestPartResult& test_part_result) {
3881  const internal::String& result =
3882      PrintTestPartResultToString(test_part_result);
3883  printf("%s\n", result.c_str());
3884  fflush(stdout);
3885  // If the test program runs in Visual Studio or a debugger, the
3886  // following statements add the test part result message to the Output
3887  // window such that the user can double-click on it to jump to the
3888  // corresponding source code location; otherwise they do nothing.
3889#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
3890  // We don't call OutputDebugString*() on Windows Mobile, as printing
3891  // to stdout is done by OutputDebugString() there already - we don't
3892  // want the same message printed twice.
3893  ::OutputDebugStringA(result.c_str());
3894  ::OutputDebugStringA("\n");
3895#endif
3896}
3897
3898// class PrettyUnitTestResultPrinter
3899
3900namespace internal {
3901
3902enum GTestColor {
3903  COLOR_DEFAULT,
3904  COLOR_RED,
3905  COLOR_GREEN,
3906  COLOR_YELLOW
3907};
3908
3909#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
3910
3911// Returns the character attribute for the given color.
3912WORD GetColorAttribute(GTestColor color) {
3913  switch (color) {
3914    case COLOR_RED:    return FOREGROUND_RED;
3915    case COLOR_GREEN:  return FOREGROUND_GREEN;
3916    case COLOR_YELLOW: return FOREGROUND_RED | FOREGROUND_GREEN;
3917    default:           return 0;
3918  }
3919}
3920
3921#else
3922
3923// Returns the ANSI color code for the given color.  COLOR_DEFAULT is
3924// an invalid input.
3925const char* GetAnsiColorCode(GTestColor color) {
3926  switch (color) {
3927    case COLOR_RED:     return "1";
3928    case COLOR_GREEN:   return "2";
3929    case COLOR_YELLOW:  return "3";
3930    default:            return NULL;
3931  };
3932}
3933
3934#endif  // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
3935
3936// Returns true iff Google Test should use colors in the output.
3937bool ShouldUseColor(bool stdout_is_tty) {
3938  const char* const gtest_color = GTEST_FLAG(color).c_str();
3939
3940  if (String::CaseInsensitiveCStringEquals(gtest_color, "auto")) {
3941#if GTEST_OS_WINDOWS
3942    // On Windows the TERM variable is usually not set, but the
3943    // console there does support colors.
3944    return stdout_is_tty;
3945#else
3946    // On non-Windows platforms, we rely on the TERM variable.
3947    const char* const term = posix::GetEnv("TERM");
3948    const bool term_supports_color =
3949        String::CStringEquals(term, "xterm") ||
3950        String::CStringEquals(term, "xterm-color") ||
3951        String::CStringEquals(term, "xterm-256color") ||
3952        String::CStringEquals(term, "linux") ||
3953        String::CStringEquals(term, "cygwin");
3954    return stdout_is_tty && term_supports_color;
3955#endif  // GTEST_OS_WINDOWS
3956  }
3957
3958  return String::CaseInsensitiveCStringEquals(gtest_color, "yes") ||
3959      String::CaseInsensitiveCStringEquals(gtest_color, "true") ||
3960      String::CaseInsensitiveCStringEquals(gtest_color, "t") ||
3961      String::CStringEquals(gtest_color, "1");
3962  // We take "yes", "true", "t", and "1" as meaning "yes".  If the
3963  // value is neither one of these nor "auto", we treat it as "no" to
3964  // be conservative.
3965}
3966
3967// Helpers for printing colored strings to stdout. Note that on Windows, we
3968// cannot simply emit special characters and have the terminal change colors.
3969// This routine must actually emit the characters rather than return a string
3970// that would be colored when printed, as can be done on Linux.
3971void ColoredPrintf(GTestColor color, const char* fmt, ...) {
3972  va_list args;
3973  va_start(args, fmt);
3974
3975#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS
3976  const bool use_color = false;
3977#else
3978  static const bool in_color_mode =
3979      ShouldUseColor(posix::IsATTY(posix::FileNo(stdout)) != 0);
3980  const bool use_color = in_color_mode && (color != COLOR_DEFAULT);
3981#endif  // GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS
3982  // The '!= 0' comparison is necessary to satisfy MSVC 7.1.
3983
3984  if (!use_color) {
3985    vprintf(fmt, args);
3986    va_end(args);
3987    return;
3988  }
3989
3990#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
3991  const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
3992
3993  // Gets the current text color.
3994  CONSOLE_SCREEN_BUFFER_INFO buffer_info;
3995  GetConsoleScreenBufferInfo(stdout_handle, &buffer_info);
3996  const WORD old_color_attrs = buffer_info.wAttributes;
3997
3998  // We need to flush the stream buffers into the console before each
3999  // SetConsoleTextAttribute call lest it affect the text that is already
4000  // printed but has not yet reached the console.
4001  fflush(stdout);
4002  SetConsoleTextAttribute(stdout_handle,
4003                          GetColorAttribute(color) | FOREGROUND_INTENSITY);
4004  vprintf(fmt, args);
4005
4006  fflush(stdout);
4007  // Restores the text color.
4008  SetConsoleTextAttribute(stdout_handle, old_color_attrs);
4009#else
4010  printf("\033[0;3%sm", GetAnsiColorCode(color));
4011  vprintf(fmt, args);
4012  printf("\033[m");  // Resets the terminal to default.
4013#endif  // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
4014  va_end(args);
4015}
4016
4017// This class implements the TestEventListener interface.
4018//
4019// Class PrettyUnitTestResultPrinter is copyable.
4020class PrettyUnitTestResultPrinter : public TestEventListener {
4021 public:
4022  PrettyUnitTestResultPrinter() {}
4023  static void PrintTestName(const char * test_case, const char * test) {
4024    printf("%s.%s", test_case, test);
4025  }
4026
4027  // The following methods override what's in the TestEventListener class.
4028  virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {}
4029  virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration);
4030  virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test);
4031  virtual void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) {}
4032  virtual void OnTestCaseStart(const TestCase& test_case);
4033  virtual void OnTestStart(const TestInfo& test_info);
4034  virtual void OnTestPartResult(const TestPartResult& result);
4035  virtual void OnTestEnd(const TestInfo& test_info);
4036  virtual void OnTestCaseEnd(const TestCase& test_case);
4037  virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test);
4038  virtual void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) {}
4039  virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
4040  virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) {}
4041
4042 private:
4043  static void PrintFailedTests(const UnitTest& unit_test);
4044
4045  internal::String test_case_name_;
4046};
4047
4048  // Fired before each iteration of tests starts.
4049void PrettyUnitTestResultPrinter::OnTestIterationStart(
4050    const UnitTest& unit_test, int iteration) {
4051  if (GTEST_FLAG(repeat) != 1)
4052    printf("\nRepeating all tests (iteration %d) . . .\n\n", iteration + 1);
4053
4054  const char* const filter = GTEST_FLAG(filter).c_str();
4055
4056  // Prints the filter if it's not *.  This reminds the user that some
4057  // tests may be skipped.
4058  if (!internal::String::CStringEquals(filter, kUniversalFilter)) {
4059    ColoredPrintf(COLOR_YELLOW,
4060                  "Note: %s filter = %s\n", GTEST_NAME_, filter);
4061  }
4062
4063  if (internal::ShouldShard(kTestTotalShards, kTestShardIndex, false)) {
4064    ColoredPrintf(COLOR_YELLOW,
4065                  "Note: This is test shard %s of %s.\n",
4066                  internal::posix::GetEnv(kTestShardIndex),
4067                  internal::posix::GetEnv(kTestTotalShards));
4068  }
4069
4070  if (GTEST_FLAG(shuffle)) {
4071    ColoredPrintf(COLOR_YELLOW,
4072                  "Note: Randomizing tests' orders with a seed of %d .\n",
4073                  unit_test.random_seed());
4074  }
4075
4076  ColoredPrintf(COLOR_GREEN,  "[==========] ");
4077  printf("Running %s from %s.\n",
4078         FormatTestCount(unit_test.test_to_run_count()).c_str(),
4079         FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str());
4080  fflush(stdout);
4081}
4082
4083void PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart(
4084    const UnitTest& /*unit_test*/) {
4085  ColoredPrintf(COLOR_GREEN,  "[----------] ");
4086  printf("Global test environment set-up.\n");
4087  fflush(stdout);
4088}
4089
4090void PrettyUnitTestResultPrinter::OnTestCaseStart(const TestCase& test_case) {
4091  test_case_name_ = test_case.name();
4092  const internal::String counts =
4093      FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
4094  ColoredPrintf(COLOR_GREEN, "[----------] ");
4095  printf("%s from %s", counts.c_str(), test_case_name_.c_str());
4096  if (test_case.comment()[0] == '\0') {
4097    printf("\n");
4098  } else {
4099    printf(", where %s\n", test_case.comment());
4100  }
4101  fflush(stdout);
4102}
4103
4104void PrettyUnitTestResultPrinter::OnTestStart(const TestInfo& test_info) {
4105  ColoredPrintf(COLOR_GREEN,  "[ RUN      ] ");
4106  PrintTestName(test_case_name_.c_str(), test_info.name());
4107  if (test_info.comment()[0] == '\0') {
4108    printf("\n");
4109  } else {
4110    printf(", where %s\n", test_info.comment());
4111  }
4112  fflush(stdout);
4113}
4114
4115// Called after an assertion failure.
4116void PrettyUnitTestResultPrinter::OnTestPartResult(
4117    const TestPartResult& result) {
4118  // If the test part succeeded, we don't need to do anything.
4119  if (result.type() == TestPartResult::kSuccess)
4120    return;
4121
4122  // Print failure message from the assertion (e.g. expected this and got that).
4123  PrintTestPartResult(result);
4124  fflush(stdout);
4125}
4126
4127void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) {
4128  if (test_info.result()->Passed()) {
4129    ColoredPrintf(COLOR_GREEN, "[       OK ] ");
4130  } else {
4131    ColoredPrintf(COLOR_RED, "[  FAILED  ] ");
4132  }
4133  PrintTestName(test_case_name_.c_str(), test_info.name());
4134  if (GTEST_FLAG(print_time)) {
4135    printf(" (%s ms)\n", internal::StreamableToString(
4136           test_info.result()->elapsed_time()).c_str());
4137  } else {
4138    printf("\n");
4139  }
4140  fflush(stdout);
4141}
4142
4143void PrettyUnitTestResultPrinter::OnTestCaseEnd(const TestCase& test_case) {
4144  if (!GTEST_FLAG(print_time)) return;
4145
4146  test_case_name_ = test_case.name();
4147  const internal::String counts =
4148      FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
4149  ColoredPrintf(COLOR_GREEN, "[----------] ");
4150  printf("%s from %s (%s ms total)\n\n",
4151         counts.c_str(), test_case_name_.c_str(),
4152         internal::StreamableToString(test_case.elapsed_time()).c_str());
4153  fflush(stdout);
4154}
4155
4156void PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart(
4157    const UnitTest& /*unit_test*/) {
4158  ColoredPrintf(COLOR_GREEN,  "[----------] ");
4159  printf("Global test environment tear-down\n");
4160  fflush(stdout);
4161}
4162
4163// Internal helper for printing the list of failed tests.
4164void PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest& unit_test) {
4165  const int failed_test_count = unit_test.failed_test_count();
4166  if (failed_test_count == 0) {
4167    return;
4168  }
4169
4170  for (int i = 0; i < unit_test.total_test_case_count(); ++i) {
4171    const TestCase& test_case = *unit_test.GetTestCase(i);
4172    if (!test_case.should_run() || (test_case.failed_test_count() == 0)) {
4173      continue;
4174    }
4175    for (int j = 0; j < test_case.total_test_count(); ++j) {
4176      const TestInfo& test_info = *test_case.GetTestInfo(j);
4177      if (!test_info.should_run() || test_info.result()->Passed()) {
4178        continue;
4179      }
4180      ColoredPrintf(COLOR_RED, "[  FAILED  ] ");
4181      printf("%s.%s", test_case.name(), test_info.name());
4182      if (test_case.comment()[0] != '\0' ||
4183          test_info.comment()[0] != '\0') {
4184        printf(", where %s", test_case.comment());
4185        if (test_case.comment()[0] != '\0' &&
4186            test_info.comment()[0] != '\0') {
4187          printf(" and ");
4188        }
4189      }
4190      printf("%s\n", test_info.comment());
4191    }
4192  }
4193}
4194
4195 void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
4196                                                      int /*iteration*/) {
4197  ColoredPrintf(COLOR_GREEN,  "[==========] ");
4198  printf("%s from %s ran.",
4199         FormatTestCount(unit_test.test_to_run_count()).c_str(),
4200         FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str());
4201  if (GTEST_FLAG(print_time)) {
4202    printf(" (%s ms total)",
4203           internal::StreamableToString(unit_test.elapsed_time()).c_str());
4204  }
4205  printf("\n");
4206  ColoredPrintf(COLOR_GREEN,  "[  PASSED  ] ");
4207  printf("%s.\n", FormatTestCount(unit_test.successful_test_count()).c_str());
4208
4209  int num_failures = unit_test.failed_test_count();
4210  if (!unit_test.Passed()) {
4211    const int failed_test_count = unit_test.failed_test_count();
4212    ColoredPrintf(COLOR_RED,  "[  FAILED  ] ");
4213    printf("%s, listed below:\n", FormatTestCount(failed_test_count).c_str());
4214    PrintFailedTests(unit_test);
4215    printf("\n%2d FAILED %s\n", num_failures,
4216                        num_failures == 1 ? "TEST" : "TESTS");
4217  }
4218
4219  int num_disabled = unit_test.disabled_test_count();
4220  if (num_disabled && !GTEST_FLAG(also_run_disabled_tests)) {
4221    if (!num_failures) {
4222      printf("\n");  // Add a spacer if no FAILURE banner is displayed.
4223    }
4224    ColoredPrintf(COLOR_YELLOW,
4225                  "  YOU HAVE %d DISABLED %s\n\n",
4226                  num_disabled,
4227                  num_disabled == 1 ? "TEST" : "TESTS");
4228  }
4229  // Ensure that Google Test output is printed before, e.g., heapchecker output.
4230  fflush(stdout);
4231}
4232
4233// End PrettyUnitTestResultPrinter
4234
4235// class TestEventRepeater
4236//
4237// This class forwards events to other event listeners.
4238class TestEventRepeater : public TestEventListener {
4239 public:
4240  TestEventRepeater() : forwarding_enabled_(true) {}
4241  virtual ~TestEventRepeater();
4242  void Append(TestEventListener *listener);
4243  TestEventListener* Release(TestEventListener* listener);
4244
4245  // Controls whether events will be forwarded to listeners_. Set to false
4246  // in death test child processes.
4247  bool forwarding_enabled() const { return forwarding_enabled_; }
4248  void set_forwarding_enabled(bool enable) { forwarding_enabled_ = enable; }
4249
4250  virtual void OnTestProgramStart(const UnitTest& unit_test);
4251  virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration);
4252  virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test);
4253  virtual void OnEnvironmentsSetUpEnd(const UnitTest& unit_test);
4254  virtual void OnTestCaseStart(const TestCase& test_case);
4255  virtual void OnTestStart(const TestInfo& test_info);
4256  virtual void OnTestPartResult(const TestPartResult& result);
4257  virtual void OnTestEnd(const TestInfo& test_info);
4258  virtual void OnTestCaseEnd(const TestCase& test_case);
4259  virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test);
4260  virtual void OnEnvironmentsTearDownEnd(const UnitTest& unit_test);
4261  virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
4262  virtual void OnTestProgramEnd(const UnitTest& unit_test);
4263
4264 private:
4265  // Controls whether events will be forwarded to listeners_. Set to false
4266  // in death test child processes.
4267  bool forwarding_enabled_;
4268  // The list of listeners that receive events.
4269  std::vector<TestEventListener*> listeners_;
4270
4271  GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventRepeater);
4272};
4273
4274TestEventRepeater::~TestEventRepeater() {
4275  ForEach(listeners_, Delete<TestEventListener>);
4276}
4277
4278void TestEventRepeater::Append(TestEventListener *listener) {
4279  listeners_.push_back(listener);
4280}
4281
4282// TODO(vladl@google.com): Factor the search functionality into Vector::Find.
4283TestEventListener* TestEventRepeater::Release(TestEventListener *listener) {
4284  for (size_t i = 0; i < listeners_.size(); ++i) {
4285    if (listeners_[i] == listener) {
4286      listeners_.erase(listeners_.begin() + i);
4287      return listener;
4288    }
4289  }
4290
4291  return NULL;
4292}
4293
4294// Since most methods are very similar, use macros to reduce boilerplate.
4295// This defines a member that forwards the call to all listeners.
4296#define GTEST_REPEATER_METHOD_(Name, Type) \
4297void TestEventRepeater::Name(const Type& parameter) { \
4298  if (forwarding_enabled_) { \
4299    for (size_t i = 0; i < listeners_.size(); i++) { \
4300      listeners_[i]->Name(parameter); \
4301    } \
4302  } \
4303}
4304// This defines a member that forwards the call to all listeners in reverse
4305// order.
4306#define GTEST_REVERSE_REPEATER_METHOD_(Name, Type) \
4307void TestEventRepeater::Name(const Type& parameter) { \
4308  if (forwarding_enabled_) { \
4309    for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) { \
4310      listeners_[i]->Name(parameter); \
4311    } \
4312  } \
4313}
4314
4315GTEST_REPEATER_METHOD_(OnTestProgramStart, UnitTest)
4316GTEST_REPEATER_METHOD_(OnEnvironmentsSetUpStart, UnitTest)
4317GTEST_REPEATER_METHOD_(OnTestCaseStart, TestCase)
4318GTEST_REPEATER_METHOD_(OnTestStart, TestInfo)
4319GTEST_REPEATER_METHOD_(OnTestPartResult, TestPartResult)
4320GTEST_REPEATER_METHOD_(OnEnvironmentsTearDownStart, UnitTest)
4321GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsSetUpEnd, UnitTest)
4322GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsTearDownEnd, UnitTest)
4323GTEST_REVERSE_REPEATER_METHOD_(OnTestEnd, TestInfo)
4324GTEST_REVERSE_REPEATER_METHOD_(OnTestCaseEnd, TestCase)
4325GTEST_REVERSE_REPEATER_METHOD_(OnTestProgramEnd, UnitTest)
4326
4327#undef GTEST_REPEATER_METHOD_
4328#undef GTEST_REVERSE_REPEATER_METHOD_
4329
4330void TestEventRepeater::OnTestIterationStart(const UnitTest& unit_test,
4331                                             int iteration) {
4332  if (forwarding_enabled_) {
4333    for (size_t i = 0; i < listeners_.size(); i++) {
4334      listeners_[i]->OnTestIterationStart(unit_test, iteration);
4335    }
4336  }
4337}
4338
4339void TestEventRepeater::OnTestIterationEnd(const UnitTest& unit_test,
4340                                           int iteration) {
4341  if (forwarding_enabled_) {
4342    for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) {
4343      listeners_[i]->OnTestIterationEnd(unit_test, iteration);
4344    }
4345  }
4346}
4347
4348// End TestEventRepeater
4349
4350// This class generates an XML output file.
4351class XmlUnitTestResultPrinter : public EmptyTestEventListener {
4352 public:
4353  explicit XmlUnitTestResultPrinter(const char* output_file);
4354
4355  virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
4356
4357 private:
4358  // Is c a whitespace character that is normalized to a space character
4359  // when it appears in an XML attribute value?
4360  static bool IsNormalizableWhitespace(char c) {
4361    return c == 0x9 || c == 0xA || c == 0xD;
4362  }
4363
4364  // May c appear in a well-formed XML document?
4365  static bool IsValidXmlCharacter(char c) {
4366    return IsNormalizableWhitespace(c) || c >= 0x20;
4367  }
4368
4369  // Returns an XML-escaped copy of the input string str.  If
4370  // is_attribute is true, the text is meant to appear as an attribute
4371  // value, and normalizable whitespace is preserved by replacing it
4372  // with character references.
4373  static String EscapeXml(const char* str, bool is_attribute);
4374
4375  // Returns the given string with all characters invalid in XML removed.
4376  static String RemoveInvalidXmlCharacters(const char* str);
4377
4378  // Convenience wrapper around EscapeXml when str is an attribute value.
4379  static String EscapeXmlAttribute(const char* str) {
4380    return EscapeXml(str, true);
4381  }
4382
4383  // Convenience wrapper around EscapeXml when str is not an attribute value.
4384  static String EscapeXmlText(const char* str) { return EscapeXml(str, false); }
4385
4386  // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
4387  static void OutputXmlCDataSection(::std::ostream* stream, const char* data);
4388
4389  // Streams an XML representation of a TestInfo object.
4390  static void OutputXmlTestInfo(::std::ostream* stream,
4391                                const char* test_case_name,
4392                                const TestInfo& test_info);
4393
4394  // Prints an XML representation of a TestCase object
4395  static void PrintXmlTestCase(FILE* out, const TestCase& test_case);
4396
4397  // Prints an XML summary of unit_test to output stream out.
4398  static void PrintXmlUnitTest(FILE* out, const UnitTest& unit_test);
4399
4400  // Produces a string representing the test properties in a result as space
4401  // delimited XML attributes based on the property key="value" pairs.
4402  // When the String is not empty, it includes a space at the beginning,
4403  // to delimit this attribute from prior attributes.
4404  static String TestPropertiesAsXmlAttributes(const TestResult& result);
4405
4406  // The output file.
4407  const String output_file_;
4408
4409  GTEST_DISALLOW_COPY_AND_ASSIGN_(XmlUnitTestResultPrinter);
4410};
4411
4412// Creates a new XmlUnitTestResultPrinter.
4413XmlUnitTestResultPrinter::XmlUnitTestResultPrinter(const char* output_file)
4414    : output_file_(output_file) {
4415  if (output_file_.c_str() == NULL || output_file_.empty()) {
4416    fprintf(stderr, "XML output file may not be null\n");
4417    fflush(stderr);
4418    exit(EXIT_FAILURE);
4419  }
4420}
4421
4422// Called after the unit test ends.
4423void XmlUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
4424                                                  int /*iteration*/) {
4425  FILE* xmlout = NULL;
4426  FilePath output_file(output_file_);
4427  FilePath output_dir(output_file.RemoveFileName());
4428
4429  if (output_dir.CreateDirectoriesRecursively()) {
4430    xmlout = posix::FOpen(output_file_.c_str(), "w");
4431  }
4432  if (xmlout == NULL) {
4433    // TODO(wan): report the reason of the failure.
4434    //
4435    // We don't do it for now as:
4436    //
4437    //   1. There is no urgent need for it.
4438    //   2. It's a bit involved to make the errno variable thread-safe on
4439    //      all three operating systems (Linux, Windows, and Mac OS).
4440    //   3. To interpret the meaning of errno in a thread-safe way,
4441    //      we need the strerror_r() function, which is not available on
4442    //      Windows.
4443    fprintf(stderr,
4444            "Unable to open file \"%s\"\n",
4445            output_file_.c_str());
4446    fflush(stderr);
4447    exit(EXIT_FAILURE);
4448  }
4449  PrintXmlUnitTest(xmlout, unit_test);
4450  fclose(xmlout);
4451}
4452
4453// Returns an XML-escaped copy of the input string str.  If is_attribute
4454// is true, the text is meant to appear as an attribute value, and
4455// normalizable whitespace is preserved by replacing it with character
4456// references.
4457//
4458// Invalid XML characters in str, if any, are stripped from the output.
4459// It is expected that most, if not all, of the text processed by this
4460// module will consist of ordinary English text.
4461// If this module is ever modified to produce version 1.1 XML output,
4462// most invalid characters can be retained using character references.
4463// TODO(wan): It might be nice to have a minimally invasive, human-readable
4464// escaping scheme for invalid characters, rather than dropping them.
4465String XmlUnitTestResultPrinter::EscapeXml(const char* str, bool is_attribute) {
4466  Message m;
4467
4468  if (str != NULL) {
4469    for (const char* src = str; *src; ++src) {
4470      switch (*src) {
4471        case '<':
4472          m << "&lt;";
4473          break;
4474        case '>':
4475          m << "&gt;";
4476          break;
4477        case '&':
4478          m << "&amp;";
4479          break;
4480        case '\'':
4481          if (is_attribute)
4482            m << "&apos;";
4483          else
4484            m << '\'';
4485          break;
4486        case '"':
4487          if (is_attribute)
4488            m << "&quot;";
4489          else
4490            m << '"';
4491          break;
4492        default:
4493          if (IsValidXmlCharacter(*src)) {
4494            if (is_attribute && IsNormalizableWhitespace(*src))
4495              m << String::Format("&#x%02X;", unsigned(*src));
4496            else
4497              m << *src;
4498          }
4499          break;
4500      }
4501    }
4502  }
4503
4504  return m.GetString();
4505}
4506
4507// Returns the given string with all characters invalid in XML removed.
4508// Currently invalid characters are dropped from the string. An
4509// alternative is to replace them with certain characters such as . or ?.
4510String XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters(const char* str) {
4511  char* const output = new char[strlen(str) + 1];
4512  char* appender = output;
4513  for (char ch = *str; ch != '\0'; ch = *++str)
4514    if (IsValidXmlCharacter(ch))
4515      *appender++ = ch;
4516  *appender = '\0';
4517
4518  String ret_value(output);
4519  delete[] output;
4520  return ret_value;
4521}
4522
4523// The following routines generate an XML representation of a UnitTest
4524// object.
4525//
4526// This is how Google Test concepts map to the DTD:
4527//
4528// <testsuites name="AllTests">        <-- corresponds to a UnitTest object
4529//   <testsuite name="testcase-name">  <-- corresponds to a TestCase object
4530//     <testcase name="test-name">     <-- corresponds to a TestInfo object
4531//       <failure message="...">...</failure>
4532//       <failure message="...">...</failure>
4533//       <failure message="...">...</failure>
4534//                                     <-- individual assertion failures
4535//     </testcase>
4536//   </testsuite>
4537// </testsuites>
4538
4539// Formats the given time in milliseconds as seconds.
4540std::string FormatTimeInMillisAsSeconds(TimeInMillis ms) {
4541  ::std::stringstream ss;
4542  ss << ms/1000.0;
4543  return ss.str();
4544}
4545
4546// Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
4547void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream,
4548                                                     const char* data) {
4549  const char* segment = data;
4550  *stream << "<![CDATA[";
4551  for (;;) {
4552    const char* const next_segment = strstr(segment, "]]>");
4553    if (next_segment != NULL) {
4554      stream->write(
4555          segment, static_cast<std::streamsize>(next_segment - segment));
4556      *stream << "]]>]]&gt;<![CDATA[";
4557      segment = next_segment + strlen("]]>");
4558    } else {
4559      *stream << segment;
4560      break;
4561    }
4562  }
4563  *stream << "]]>";
4564}
4565
4566// Prints an XML representation of a TestInfo object.
4567// TODO(wan): There is also value in printing properties with the plain printer.
4568void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream,
4569                                                 const char* test_case_name,
4570                                                 const TestInfo& test_info) {
4571  const TestResult& result = *test_info.result();
4572  *stream << "    <testcase name=\""
4573          << EscapeXmlAttribute(test_info.name()).c_str()
4574          << "\" status=\""
4575          << (test_info.should_run() ? "run" : "notrun")
4576          << "\" time=\""
4577          << FormatTimeInMillisAsSeconds(result.elapsed_time())
4578          << "\" classname=\""<< GTEST_FLAG(output).c_str()<<"." << EscapeXmlAttribute(test_case_name).c_str()
4579          << "\"" << TestPropertiesAsXmlAttributes(result).c_str();
4580
4581  int failures = 0;
4582  for (int i = 0; i < result.total_part_count(); ++i) {
4583    const TestPartResult& part = result.GetTestPartResult(i);
4584    if (part.failed()) {
4585      if (++failures == 1)
4586        *stream << ">\n";
4587      *stream << "      <failure message=\""
4588              << EscapeXmlAttribute(part.summary()).c_str()
4589              << "\" type=\"\">";
4590      const String message = RemoveInvalidXmlCharacters(String::Format(
4591          "%s:%d\n%s",
4592          part.file_name(), part.line_number(),
4593          part.message()).c_str());
4594      OutputXmlCDataSection(stream, message.c_str());
4595      *stream << "</failure>\n";
4596    }
4597  }
4598
4599  if (failures == 0)
4600    *stream << " />\n";
4601  else
4602    *stream << "    </testcase>\n";
4603}
4604
4605// Prints an XML representation of a TestCase object
4606void XmlUnitTestResultPrinter::PrintXmlTestCase(FILE* out,
4607                                                const TestCase& test_case) {
4608  fprintf(out,
4609          "  <testsuite name=\"%s\" tests=\"%d\" failures=\"%d\" "
4610          "disabled=\"%d\" ",
4611          EscapeXmlAttribute(test_case.name()).c_str(),
4612          test_case.total_test_count(),
4613          test_case.failed_test_count(),
4614          test_case.disabled_test_count());
4615  fprintf(out,
4616          "errors=\"0\" time=\"%s\">\n",
4617          FormatTimeInMillisAsSeconds(test_case.elapsed_time()).c_str());
4618  for (int i = 0; i < test_case.total_test_count(); ++i) {
4619    StrStream stream;
4620    OutputXmlTestInfo(&stream, test_case.name(), *test_case.GetTestInfo(i));
4621    fprintf(out, "%s", StrStreamToString(&stream).c_str());
4622  }
4623  fprintf(out, "  </testsuite>\n");
4624}
4625
4626// Prints an XML summary of unit_test to output stream out.
4627void XmlUnitTestResultPrinter::PrintXmlUnitTest(FILE* out,
4628                                                const UnitTest& unit_test) {
4629  fprintf(out, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
4630  fprintf(out,
4631          "<testsuites tests=\"%d\" failures=\"%d\" disabled=\"%d\" "
4632          "errors=\"0\" time=\"%s\" ",
4633          unit_test.total_test_count(),
4634          unit_test.failed_test_count(),
4635          unit_test.disabled_test_count(),
4636          FormatTimeInMillisAsSeconds(unit_test.elapsed_time()).c_str());
4637  if (GTEST_FLAG(shuffle)) {
4638    fprintf(out, "random_seed=\"%d\" ", unit_test.random_seed());
4639  }
4640  fprintf(out, "name=\"%s\">\n",GTEST_FLAG(output).c_str());
4641  for (int i = 0; i < unit_test.total_test_case_count(); ++i)
4642    PrintXmlTestCase(out, *unit_test.GetTestCase(i));
4643  fprintf(out, "</testsuites>\n");
4644}
4645
4646// Produces a string representing the test properties in a result as space
4647// delimited XML attributes based on the property key="value" pairs.
4648String XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes(
4649    const TestResult& result) {
4650  Message attributes;
4651  for (int i = 0; i < result.test_property_count(); ++i) {
4652    const TestProperty& property = result.GetTestProperty(i);
4653    attributes << " " << property.key() << "="
4654        << "\"" << EscapeXmlAttribute(property.value()) << "\"";
4655  }
4656  return attributes.GetString();
4657}
4658
4659// End XmlUnitTestResultPrinter
4660
4661// Class ScopedTrace
4662
4663// Pushes the given source file location and message onto a per-thread
4664// trace stack maintained by Google Test.
4665// L < UnitTest::mutex_
4666ScopedTrace::ScopedTrace(const char* file, int line, const Message& message) {
4667  TraceInfo trace;
4668  trace.file = file;
4669  trace.line = line;
4670  trace.message = message.GetString();
4671
4672  UnitTest::GetInstance()->PushGTestTrace(trace);
4673}
4674
4675// Pops the info pushed by the c'tor.
4676// L < UnitTest::mutex_
4677ScopedTrace::~ScopedTrace() {
4678  UnitTest::GetInstance()->PopGTestTrace();
4679}
4680
4681
4682// class OsStackTraceGetter
4683
4684// Returns the current OS stack trace as a String.  Parameters:
4685//
4686//   max_depth  - the maximum number of stack frames to be included
4687//                in the trace.
4688//   skip_count - the number of top frames to be skipped; doesn't count
4689//                against max_depth.
4690//
4691// L < mutex_
4692// We use "L < mutex_" to denote that the function may acquire mutex_.
4693String OsStackTraceGetter::CurrentStackTrace(int, int) {
4694  return String("");
4695}
4696
4697// L < mutex_
4698void OsStackTraceGetter::UponLeavingGTest() {
4699}
4700
4701const char* const
4702OsStackTraceGetter::kElidedFramesMarker =
4703    "... " GTEST_NAME_ " internal frames ...";
4704
4705}  // namespace internal
4706
4707// class TestEventListeners
4708
4709TestEventListeners::TestEventListeners()
4710    : repeater_(new internal::TestEventRepeater()),
4711      default_result_printer_(NULL),
4712      default_xml_generator_(NULL) {
4713}
4714
4715TestEventListeners::~TestEventListeners() { delete repeater_; }
4716
4717// Returns the standard listener responsible for the default console
4718// output.  Can be removed from the listeners list to shut down default
4719// console output.  Note that removing this object from the listener list
4720// with Release transfers its ownership to the user.
4721void TestEventListeners::Append(TestEventListener* listener) {
4722  repeater_->Append(listener);
4723}
4724
4725// Removes the given event listener from the list and returns it.  It then
4726// becomes the caller's responsibility to delete the listener. Returns
4727// NULL if the listener is not found in the list.
4728TestEventListener* TestEventListeners::Release(TestEventListener* listener) {
4729  if (listener == default_result_printer_)
4730    default_result_printer_ = NULL;
4731  else if (listener == default_xml_generator_)
4732    default_xml_generator_ = NULL;
4733  return repeater_->Release(listener);
4734}
4735
4736// Returns repeater that broadcasts the TestEventListener events to all
4737// subscribers.
4738TestEventListener* TestEventListeners::repeater() { return repeater_; }
4739
4740// Sets the default_result_printer attribute to the provided listener.
4741// The listener is also added to the listener list and previous
4742// default_result_printer is removed from it and deleted. The listener can
4743// also be NULL in which case it will not be added to the list. Does
4744// nothing if the previous and the current listener objects are the same.
4745void TestEventListeners::SetDefaultResultPrinter(TestEventListener* listener) {
4746  if (default_result_printer_ != listener) {
4747    // It is an error to pass this method a listener that is already in the
4748    // list.
4749    delete Release(default_result_printer_);
4750    default_result_printer_ = listener;
4751    if (listener != NULL)
4752      Append(listener);
4753  }
4754}
4755
4756// Sets the default_xml_generator attribute to the provided listener.  The
4757// listener is also added to the listener list and previous
4758// default_xml_generator is removed from it and deleted. The listener can
4759// also be NULL in which case it will not be added to the list. Does
4760// nothing if the previous and the current listener objects are the same.
4761void TestEventListeners::SetDefaultXmlGenerator(TestEventListener* listener) {
4762  if (default_xml_generator_ != listener) {
4763    // It is an error to pass this method a listener that is already in the
4764    // list.
4765    delete Release(default_xml_generator_);
4766    default_xml_generator_ = listener;
4767    if (listener != NULL)
4768      Append(listener);
4769  }
4770}
4771
4772// Controls whether events will be forwarded by the repeater to the
4773// listeners in the list.
4774bool TestEventListeners::EventForwardingEnabled() const {
4775  return repeater_->forwarding_enabled();
4776}
4777
4778void TestEventListeners::SuppressEventForwarding() {
4779  repeater_->set_forwarding_enabled(false);
4780}
4781
4782// class UnitTest
4783
4784// Gets the singleton UnitTest object.  The first time this method is
4785// called, a UnitTest object is constructed and returned.  Consecutive
4786// calls will return the same object.
4787//
4788// We don't protect this under mutex_ as a user is not supposed to
4789// call this before main() starts, from which point on the return
4790// value will never change.
4791UnitTest * UnitTest::GetInstance() {
4792  // When compiled with MSVC 7.1 in optimized mode, destroying the
4793  // UnitTest object upon exiting the program messes up the exit code,
4794  // causing successful tests to appear failed.  We have to use a
4795  // different implementation in this case to bypass the compiler bug.
4796  // This implementation makes the compiler happy, at the cost of
4797  // leaking the UnitTest object.
4798
4799  // CodeGear C++Builder insists on a public destructor for the
4800  // default implementation.  Use this implementation to keep good OO
4801  // design with private destructor.
4802
4803#if (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)
4804  static UnitTest* const instance = new UnitTest;
4805  return instance;
4806#else
4807  static UnitTest instance;
4808  return &instance;
4809#endif  // (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)
4810}
4811
4812// Gets the number of successful test cases.
4813int UnitTest::successful_test_case_count() const {
4814  return impl()->successful_test_case_count();
4815}
4816
4817// Gets the number of failed test cases.
4818int UnitTest::failed_test_case_count() const {
4819  return impl()->failed_test_case_count();
4820}
4821
4822// Gets the number of all test cases.
4823int UnitTest::total_test_case_count() const {
4824  return impl()->total_test_case_count();
4825}
4826
4827// Gets the number of all test cases that contain at least one test
4828// that should run.
4829int UnitTest::test_case_to_run_count() const {
4830  return impl()->test_case_to_run_count();
4831}
4832
4833// Gets the number of successful tests.
4834int UnitTest::successful_test_count() const {
4835  return impl()->successful_test_count();
4836}
4837
4838// Gets the number of failed tests.
4839int UnitTest::failed_test_count() const { return impl()->failed_test_count(); }
4840
4841// Gets the number of disabled tests.
4842int UnitTest::disabled_test_count() const {
4843  return impl()->disabled_test_count();
4844}
4845
4846// Gets the number of all tests.
4847int UnitTest::total_test_count() const { return impl()->total_test_count(); }
4848
4849// Gets the number of tests that should run.
4850int UnitTest::test_to_run_count() const { return impl()->test_to_run_count(); }
4851
4852// Gets the elapsed time, in milliseconds.
4853internal::TimeInMillis UnitTest::elapsed_time() const {
4854  return impl()->elapsed_time();
4855}
4856
4857// Returns true iff the unit test passed (i.e. all test cases passed).
4858bool UnitTest::Passed() const { return impl()->Passed(); }
4859
4860// Returns true iff the unit test failed (i.e. some test case failed
4861// or something outside of all tests failed).
4862bool UnitTest::Failed() const { return impl()->Failed(); }
4863
4864// Gets the i-th test case among all the test cases. i can range from 0 to
4865// total_test_case_count() - 1. If i is not in that range, returns NULL.
4866const TestCase* UnitTest::GetTestCase(int i) const {
4867  return impl()->GetTestCase(i);
4868}
4869
4870// Gets the i-th test case among all the test cases. i can range from 0 to
4871// total_test_case_count() - 1. If i is not in that range, returns NULL.
4872TestCase* UnitTest::GetMutableTestCase(int i) {
4873  return impl()->GetMutableTestCase(i);
4874}
4875
4876// Returns the list of event listeners that can be used to track events
4877// inside Google Test.
4878TestEventListeners& UnitTest::listeners() {
4879  return *impl()->listeners();
4880}
4881
4882// Registers and returns a global test environment.  When a test
4883// program is run, all global test environments will be set-up in the
4884// order they were registered.  After all tests in the program have
4885// finished, all global test environments will be torn-down in the
4886// *reverse* order they were registered.
4887//
4888// The UnitTest object takes ownership of the given environment.
4889//
4890// We don't protect this under mutex_, as we only support calling it
4891// from the main thread.
4892Environment* UnitTest::AddEnvironment(Environment* env) {
4893  if (env == NULL) {
4894    return NULL;
4895  }
4896
4897  impl_->environments().push_back(env);
4898  return env;
4899}
4900
4901#if GTEST_HAS_EXCEPTIONS
4902// A failed Google Test assertion will throw an exception of this type
4903// when exceptions are enabled.  We derive it from std::runtime_error,
4904// which is for errors presumably detectable only at run time.  Since
4905// std::runtime_error inherits from std::exception, many testing
4906// frameworks know how to extract and print the message inside it.
4907class GoogleTestFailureException : public ::std::runtime_error {
4908 public:
4909  explicit GoogleTestFailureException(const TestPartResult& failure)
4910      : ::std::runtime_error(PrintTestPartResultToString(failure).c_str()) {}
4911};
4912#endif
4913
4914// Adds a TestPartResult to the current TestResult object.  All Google Test
4915// assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) eventually call
4916// this to report their results.  The user code should use the
4917// assertion macros instead of calling this directly.
4918// L < mutex_
4919void UnitTest::AddTestPartResult(TestPartResult::Type result_type,
4920                                 const char* file_name,
4921                                 int line_number,
4922                                 const internal::String& message,
4923                                 const internal::String& os_stack_trace) {
4924  Message msg;
4925  msg << message;
4926
4927  internal::MutexLock lock(&mutex_);
4928  if (impl_->gtest_trace_stack().size() > 0) {
4929    msg << "\n" << GTEST_NAME_ << " trace:";
4930
4931    for (int i = static_cast<int>(impl_->gtest_trace_stack().size());
4932         i > 0; --i) {
4933      const internal::TraceInfo& trace = impl_->gtest_trace_stack()[i - 1];
4934      msg << "\n" << internal::FormatFileLocation(trace.file, trace.line)
4935          << " " << trace.message;
4936    }
4937  }
4938
4939  if (os_stack_trace.c_str() != NULL && !os_stack_trace.empty()) {
4940    msg << internal::kStackTraceMarker << os_stack_trace;
4941  }
4942
4943  const TestPartResult result =
4944    TestPartResult(result_type, file_name, line_number,
4945                   msg.GetString().c_str());
4946  impl_->GetTestPartResultReporterForCurrentThread()->
4947      ReportTestPartResult(result);
4948
4949  if (result_type != TestPartResult::kSuccess) {
4950    // gtest_break_on_failure takes precedence over
4951    // gtest_throw_on_failure.  This allows a user to set the latter
4952    // in the code (perhaps in order to use Google Test assertions
4953    // with another testing framework) and specify the former on the
4954    // command line for debugging.
4955    if (GTEST_FLAG(break_on_failure)) {
4956#if GTEST_OS_WINDOWS
4957      // Using DebugBreak on Windows allows gtest to still break into a debugger
4958      // when a failure happens and both the --gtest_break_on_failure and
4959      // the --gtest_catch_exceptions flags are specified.
4960      DebugBreak();
4961#else
4962      *static_cast<int*>(NULL) = 1;
4963#endif  // GTEST_OS_WINDOWS
4964    } else if (GTEST_FLAG(throw_on_failure)) {
4965#if GTEST_HAS_EXCEPTIONS
4966      throw GoogleTestFailureException(result);
4967#else
4968      // We cannot call abort() as it generates a pop-up in debug mode
4969      // that cannot be suppressed in VC 7.1 or below.
4970      exit(1);
4971#endif
4972    }
4973  }
4974}
4975
4976// Creates and adds a property to the current TestResult. If a property matching
4977// the supplied value already exists, updates its value instead.
4978void UnitTest::RecordPropertyForCurrentTest(const char* key,
4979                                            const char* value) {
4980  const TestProperty test_property(key, value);
4981  impl_->current_test_result()->RecordProperty(test_property);
4982}
4983
4984// Runs all tests in this UnitTest object and prints the result.
4985// Returns 0 if successful, or 1 otherwise.
4986//
4987// We don't protect this under mutex_, as we only support calling it
4988// from the main thread.
4989int UnitTest::Run() {
4990#if GTEST_HAS_SEH
4991  // Catch SEH-style exceptions.
4992
4993  const bool in_death_test_child_process =
4994      internal::GTEST_FLAG(internal_run_death_test).length() > 0;
4995
4996  // Either the user wants Google Test to catch exceptions thrown by the
4997  // tests or this is executing in the context of death test child
4998  // process. In either case the user does not want to see pop-up dialogs
4999  // about crashes - they are expected..
5000  if (GTEST_FLAG(catch_exceptions) || in_death_test_child_process) {
5001#if !GTEST_OS_WINDOWS_MOBILE
5002    // SetErrorMode doesn't exist on CE.
5003    SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT |
5004                 SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);
5005#endif  // !GTEST_OS_WINDOWS_MOBILE
5006
5007#if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE
5008    // Death test children can be terminated with _abort().  On Windows,
5009    // _abort() can show a dialog with a warning message.  This forces the
5010    // abort message to go to stderr instead.
5011    _set_error_mode(_OUT_TO_STDERR);
5012#endif
5013
5014#if _MSC_VER >= 1400 && !GTEST_OS_WINDOWS_MOBILE
5015    // In the debug version, Visual Studio pops up a separate dialog
5016    // offering a choice to debug the aborted program. We need to suppress
5017    // this dialog or it will pop up for every EXPECT/ASSERT_DEATH statement
5018    // executed. Google Test will notify the user of any unexpected
5019    // failure via stderr.
5020    //
5021    // VC++ doesn't define _set_abort_behavior() prior to the version 8.0.
5022    // Users of prior VC versions shall suffer the agony and pain of
5023    // clicking through the countless debug dialogs.
5024    // TODO(vladl@google.com): find a way to suppress the abort dialog() in the
5025    // debug mode when compiled with VC 7.1 or lower.
5026    if (!GTEST_FLAG(break_on_failure))
5027      _set_abort_behavior(
5028          0x0,                                    // Clear the following flags:
5029          _WRITE_ABORT_MSG | _CALL_REPORTFAULT);  // pop-up window, core dump.
5030#endif
5031  }
5032
5033  __try {
5034    return impl_->RunAllTests();
5035  } __except(internal::UnitTestOptions::GTestShouldProcessSEH(
5036      GetExceptionCode())) {
5037    printf("Exception thrown with code 0x%x.\nFAIL\n", GetExceptionCode());
5038    fflush(stdout);
5039    return 1;
5040  }
5041
5042#else  // We are on a compiler or platform that doesn't support SEH.
5043
5044  return impl_->RunAllTests();
5045#endif  // GTEST_HAS_SEH
5046}
5047
5048// Returns the working directory when the first TEST() or TEST_F() was
5049// executed.
5050const char* UnitTest::original_working_dir() const {
5051  return impl_->original_working_dir_.c_str();
5052}
5053
5054// Returns the TestCase object for the test that's currently running,
5055// or NULL if no test is running.
5056// L < mutex_
5057const TestCase* UnitTest::current_test_case() const {
5058  internal::MutexLock lock(&mutex_);
5059  return impl_->current_test_case();
5060}
5061
5062// Returns the TestInfo object for the test that's currently running,
5063// or NULL if no test is running.
5064// L < mutex_
5065const TestInfo* UnitTest::current_test_info() const {
5066  internal::MutexLock lock(&mutex_);
5067  return impl_->current_test_info();
5068}
5069
5070// Returns the random seed used at the start of the current test run.
5071int UnitTest::random_seed() const { return impl_->random_seed(); }
5072
5073#if GTEST_HAS_PARAM_TEST
5074// Returns ParameterizedTestCaseRegistry object used to keep track of
5075// value-parameterized tests and instantiate and register them.
5076// L < mutex_
5077internal::ParameterizedTestCaseRegistry&
5078    UnitTest::parameterized_test_registry() {
5079  return impl_->parameterized_test_registry();
5080}
5081#endif  // GTEST_HAS_PARAM_TEST
5082
5083// Creates an empty UnitTest.
5084UnitTest::UnitTest() {
5085  impl_ = new internal::UnitTestImpl(this);
5086}
5087
5088// Destructor of UnitTest.
5089UnitTest::~UnitTest() {
5090  delete impl_;
5091}
5092
5093// Pushes a trace defined by SCOPED_TRACE() on to the per-thread
5094// Google Test trace stack.
5095// L < mutex_
5096void UnitTest::PushGTestTrace(const internal::TraceInfo& trace) {
5097  internal::MutexLock lock(&mutex_);
5098  impl_->gtest_trace_stack().push_back(trace);
5099}
5100
5101// Pops a trace from the per-thread Google Test trace stack.
5102// L < mutex_
5103void UnitTest::PopGTestTrace() {
5104  internal::MutexLock lock(&mutex_);
5105  impl_->gtest_trace_stack().pop_back();
5106}
5107
5108namespace internal {
5109
5110UnitTestImpl::UnitTestImpl(UnitTest* parent)
5111    : parent_(parent),
5112#ifdef _MSC_VER
5113#pragma warning(push)                    // Saves the current warning state.
5114#pragma warning(disable:4355)            // Temporarily disables warning 4355
5115                                         // (using this in initializer).
5116      default_global_test_part_result_reporter_(this),
5117      default_per_thread_test_part_result_reporter_(this),
5118#pragma warning(pop)                     // Restores the warning state again.
5119#else
5120      default_global_test_part_result_reporter_(this),
5121      default_per_thread_test_part_result_reporter_(this),
5122#endif  // _MSC_VER
5123      global_test_part_result_repoter_(
5124          &default_global_test_part_result_reporter_),
5125      per_thread_test_part_result_reporter_(
5126          &default_per_thread_test_part_result_reporter_),
5127#if GTEST_HAS_PARAM_TEST
5128      parameterized_test_registry_(),
5129      parameterized_tests_registered_(false),
5130#endif  // GTEST_HAS_PARAM_TEST
5131      last_death_test_case_(-1),
5132      current_test_case_(NULL),
5133      current_test_info_(NULL),
5134      ad_hoc_test_result_(),
5135      os_stack_trace_getter_(NULL),
5136      post_flag_parse_init_performed_(false),
5137      random_seed_(0),  // Will be overridden by the flag before first use.
5138      random_(0),  // Will be reseeded before first use.
5139#if GTEST_HAS_DEATH_TEST
5140      elapsed_time_(0),
5141      internal_run_death_test_flag_(NULL),
5142      death_test_factory_(new DefaultDeathTestFactory) {
5143#else
5144      elapsed_time_(0) {
5145#endif  // GTEST_HAS_DEATH_TEST
5146  listeners()->SetDefaultResultPrinter(new PrettyUnitTestResultPrinter);
5147}
5148
5149UnitTestImpl::~UnitTestImpl() {
5150  // Deletes every TestCase.
5151  ForEach(test_cases_, internal::Delete<TestCase>);
5152
5153  // Deletes every Environment.
5154  ForEach(environments_, internal::Delete<Environment>);
5155
5156  delete os_stack_trace_getter_;
5157}
5158
5159#if GTEST_HAS_DEATH_TEST
5160// Disables event forwarding if the control is currently in a death test
5161// subprocess. Must not be called before InitGoogleTest.
5162void UnitTestImpl::SuppressTestEventsIfInSubprocess() {
5163  if (internal_run_death_test_flag_.get() != NULL)
5164    listeners()->SuppressEventForwarding();
5165}
5166#endif  // GTEST_HAS_DEATH_TEST
5167
5168// Initializes event listeners performing XML output as specified by
5169// UnitTestOptions. Must not be called before InitGoogleTest.
5170void UnitTestImpl::ConfigureXmlOutput() {
5171  const String& output_format = UnitTestOptions::GetOutputFormat();
5172  if (output_format == "xml") {
5173    listeners()->SetDefaultXmlGenerator(new XmlUnitTestResultPrinter(
5174        UnitTestOptions::GetAbsolutePathToOutputFile().c_str()));
5175  } else if (output_format != "") {
5176    printf("WARNING: unrecognized output format \"%s\" ignored.\n",
5177           output_format.c_str());
5178    fflush(stdout);
5179  }
5180}
5181
5182// Performs initialization dependent upon flag values obtained in
5183// ParseGoogleTestFlagsOnly.  Is called from InitGoogleTest after the call to
5184// ParseGoogleTestFlagsOnly.  In case a user neglects to call InitGoogleTest
5185// this function is also called from RunAllTests.  Since this function can be
5186// called more than once, it has to be idempotent.
5187void UnitTestImpl::PostFlagParsingInit() {
5188  // Ensures that this function does not execute more than once.
5189  if (!post_flag_parse_init_performed_) {
5190    post_flag_parse_init_performed_ = true;
5191
5192#if GTEST_HAS_DEATH_TEST
5193    InitDeathTestSubprocessControlInfo();
5194    SuppressTestEventsIfInSubprocess();
5195#endif  // GTEST_HAS_DEATH_TEST
5196
5197    // Registers parameterized tests. This makes parameterized tests
5198    // available to the UnitTest reflection API without running
5199    // RUN_ALL_TESTS.
5200    RegisterParameterizedTests();
5201
5202    // Configures listeners for XML output. This makes it possible for users
5203    // to shut down the default XML output before invoking RUN_ALL_TESTS.
5204    ConfigureXmlOutput();
5205  }
5206}
5207
5208// A predicate that checks the name of a TestCase against a known
5209// value.
5210//
5211// This is used for implementation of the UnitTest class only.  We put
5212// it in the anonymous namespace to prevent polluting the outer
5213// namespace.
5214//
5215// TestCaseNameIs is copyable.
5216class TestCaseNameIs {
5217 public:
5218  // Constructor.
5219  explicit TestCaseNameIs(const String& name)
5220      : name_(name) {}
5221
5222  // Returns true iff the name of test_case matches name_.
5223  bool operator()(const TestCase* test_case) const {
5224    return test_case != NULL && strcmp(test_case->name(), name_.c_str()) == 0;
5225  }
5226
5227 private:
5228  String name_;
5229};
5230
5231// Finds and returns a TestCase with the given name.  If one doesn't
5232// exist, creates one and returns it.  It's the CALLER'S
5233// RESPONSIBILITY to ensure that this function is only called WHEN THE
5234// TESTS ARE NOT SHUFFLED.
5235//
5236// Arguments:
5237//
5238//   test_case_name: name of the test case
5239//   set_up_tc:      pointer to the function that sets up the test case
5240//   tear_down_tc:   pointer to the function that tears down the test case
5241TestCase* UnitTestImpl::GetTestCase(const char* test_case_name,
5242                                    const char* comment,
5243                                    Test::SetUpTestCaseFunc set_up_tc,
5244                                    Test::TearDownTestCaseFunc tear_down_tc) {
5245  // Can we find a TestCase with the given name?
5246  const std::vector<TestCase*>::const_iterator test_case =
5247      std::find_if(test_cases_.begin(), test_cases_.end(),
5248                   TestCaseNameIs(test_case_name));
5249
5250  if (test_case != test_cases_.end())
5251    return *test_case;
5252
5253  // No.  Let's create one.
5254  TestCase* const new_test_case =
5255      new TestCase(test_case_name, comment, set_up_tc, tear_down_tc);
5256
5257  // Is this a death test case?
5258  if (internal::UnitTestOptions::MatchesFilter(String(test_case_name),
5259                                               kDeathTestCaseFilter)) {
5260    // Yes.  Inserts the test case after the last death test case
5261    // defined so far.  This only works when the test cases haven't
5262    // been shuffled.  Otherwise we may end up running a death test
5263    // after a non-death test.
5264    ++last_death_test_case_;
5265    test_cases_.insert(test_cases_.begin() + last_death_test_case_,
5266                       new_test_case);
5267  } else {
5268    // No.  Appends to the end of the list.
5269    test_cases_.push_back(new_test_case);
5270  }
5271
5272  test_case_indices_.push_back(static_cast<int>(test_case_indices_.size()));
5273  return new_test_case;
5274}
5275
5276// Helpers for setting up / tearing down the given environment.  They
5277// are for use in the ForEach() function.
5278static void SetUpEnvironment(Environment* env) { env->SetUp(); }
5279static void TearDownEnvironment(Environment* env) { env->TearDown(); }
5280
5281// Runs all tests in this UnitTest object, prints the result, and
5282// returns 0 if all tests are successful, or 1 otherwise.  If any
5283// exception is thrown during a test on Windows, this test is
5284// considered to be failed, but the rest of the tests will still be
5285// run.  (We disable exceptions on Linux and Mac OS X, so the issue
5286// doesn't apply there.)
5287// When parameterized tests are enabled, it expands and registers
5288// parameterized tests first in RegisterParameterizedTests().
5289// All other functions called from RunAllTests() may safely assume that
5290// parameterized tests are ready to be counted and run.
5291int UnitTestImpl::RunAllTests() {
5292  // Makes sure InitGoogleTest() was called.
5293  if (!GTestIsInitialized()) {
5294    printf("%s",
5295           "\nThis test program did NOT call ::testing::InitGoogleTest "
5296           "before calling RUN_ALL_TESTS().  Please fix it.\n");
5297    return 1;
5298  }
5299
5300  // Do not run any test if the --help flag was specified.
5301  if (g_help_flag)
5302    return 0;
5303
5304  // Repeats the call to the post-flag parsing initialization in case the
5305  // user didn't call InitGoogleTest.
5306  PostFlagParsingInit();
5307
5308  // Even if sharding is not on, test runners may want to use the
5309  // GTEST_SHARD_STATUS_FILE to query whether the test supports the sharding
5310  // protocol.
5311  internal::WriteToShardStatusFileIfNeeded();
5312
5313  // True iff we are in a subprocess for running a thread-safe-style
5314  // death test.
5315  bool in_subprocess_for_death_test = false;
5316
5317#if GTEST_HAS_DEATH_TEST
5318  in_subprocess_for_death_test = (internal_run_death_test_flag_.get() != NULL);
5319#endif  // GTEST_HAS_DEATH_TEST
5320
5321  const bool should_shard = ShouldShard(kTestTotalShards, kTestShardIndex,
5322                                        in_subprocess_for_death_test);
5323
5324  // Compares the full test names with the filter to decide which
5325  // tests to run.
5326  const bool has_tests_to_run = FilterTests(should_shard
5327                                              ? HONOR_SHARDING_PROTOCOL
5328                                              : IGNORE_SHARDING_PROTOCOL) > 0;
5329
5330  // Lists the tests and exits if the --gtest_list_tests flag was specified.
5331  if (GTEST_FLAG(list_tests)) {
5332    // This must be called *after* FilterTests() has been called.
5333    ListTestsMatchingFilter();
5334    return 0;
5335  }
5336
5337  random_seed_ = GTEST_FLAG(shuffle) ?
5338      GetRandomSeedFromFlag(GTEST_FLAG(random_seed)) : 0;
5339
5340  // True iff at least one test has failed.
5341  bool failed = false;
5342
5343  TestEventListener* repeater = listeners()->repeater();
5344
5345  repeater->OnTestProgramStart(*parent_);
5346
5347  // How many times to repeat the tests?  We don't want to repeat them
5348  // when we are inside the subprocess of a death test.
5349  const int repeat = in_subprocess_for_death_test ? 1 : GTEST_FLAG(repeat);
5350  // Repeats forever if the repeat count is negative.
5351  const bool forever = repeat < 0;
5352  for (int i = 0; forever || i != repeat; i++) {
5353    ClearResult();
5354
5355    const TimeInMillis start = GetTimeInMillis();
5356
5357    // Shuffles test cases and tests if requested.
5358    if (has_tests_to_run && GTEST_FLAG(shuffle)) {
5359      random()->Reseed(random_seed_);
5360      // This should be done before calling OnTestIterationStart(),
5361      // such that a test event listener can see the actual test order
5362      // in the event.
5363      ShuffleTests();
5364    }
5365
5366    // Tells the unit test event listeners that the tests are about to start.
5367    repeater->OnTestIterationStart(*parent_, i);
5368
5369    // Runs each test case if there is at least one test to run.
5370    if (has_tests_to_run) {
5371      // Sets up all environments beforehand.
5372      repeater->OnEnvironmentsSetUpStart(*parent_);
5373      ForEach(environments_, SetUpEnvironment);
5374      repeater->OnEnvironmentsSetUpEnd(*parent_);
5375
5376      // Runs the tests only if there was no fatal failure during global
5377      // set-up.
5378      if (!Test::HasFatalFailure()) {
5379        for (int test_index = 0; test_index < total_test_case_count();
5380             test_index++) {
5381          GetMutableTestCase(test_index)->Run();
5382        }
5383      }
5384
5385      // Tears down all environments in reverse order afterwards.
5386      repeater->OnEnvironmentsTearDownStart(*parent_);
5387      std::for_each(environments_.rbegin(), environments_.rend(),
5388                    TearDownEnvironment);
5389      repeater->OnEnvironmentsTearDownEnd(*parent_);
5390    }
5391
5392    elapsed_time_ = GetTimeInMillis() - start;
5393
5394    // Tells the unit test event listener that the tests have just finished.
5395    repeater->OnTestIterationEnd(*parent_, i);
5396
5397    // Gets the result and clears it.
5398    if (!Passed()) {
5399      failed = true;
5400    }
5401
5402    // Restores the original test order after the iteration.  This
5403    // allows the user to quickly repro a failure that happens in the
5404    // N-th iteration without repeating the first (N - 1) iterations.
5405    // This is not enclosed in "if (GTEST_FLAG(shuffle)) { ... }", in
5406    // case the user somehow changes the value of the flag somewhere
5407    // (it's always safe to unshuffle the tests).
5408    UnshuffleTests();
5409
5410    if (GTEST_FLAG(shuffle)) {
5411      // Picks a new random seed for each iteration.
5412      random_seed_ = GetNextRandomSeed(random_seed_);
5413    }
5414  }
5415
5416  repeater->OnTestProgramEnd(*parent_);
5417
5418  // Returns 0 if all tests passed, or 1 other wise.
5419  return failed ? 1 : 0;
5420}
5421
5422// Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
5423// if the variable is present. If a file already exists at this location, this
5424// function will write over it. If the variable is present, but the file cannot
5425// be created, prints an error and exits.
5426void WriteToShardStatusFileIfNeeded() {
5427  const char* const test_shard_file = posix::GetEnv(kTestShardStatusFile);
5428  if (test_shard_file != NULL) {
5429    FILE* const file = posix::FOpen(test_shard_file, "w");
5430    if (file == NULL) {
5431      ColoredPrintf(COLOR_RED,
5432                    "Could not write to the test shard status file \"%s\" "
5433                    "specified by the %s environment variable.\n",
5434                    test_shard_file, kTestShardStatusFile);
5435      fflush(stdout);
5436      exit(EXIT_FAILURE);
5437    }
5438    fclose(file);
5439  }
5440}
5441
5442// Checks whether sharding is enabled by examining the relevant
5443// environment variable values. If the variables are present,
5444// but inconsistent (i.e., shard_index >= total_shards), prints
5445// an error and exits. If in_subprocess_for_death_test, sharding is
5446// disabled because it must only be applied to the original test
5447// process. Otherwise, we could filter out death tests we intended to execute.
5448bool ShouldShard(const char* total_shards_env,
5449                 const char* shard_index_env,
5450                 bool in_subprocess_for_death_test) {
5451  if (in_subprocess_for_death_test) {
5452    return false;
5453  }
5454
5455  const Int32 total_shards = Int32FromEnvOrDie(total_shards_env, -1);
5456  const Int32 shard_index = Int32FromEnvOrDie(shard_index_env, -1);
5457
5458  if (total_shards == -1 && shard_index == -1) {
5459    return false;
5460  } else if (total_shards == -1 && shard_index != -1) {
5461    const Message msg = Message()
5462      << "Invalid environment variables: you have "
5463      << kTestShardIndex << " = " << shard_index
5464      << ", but have left " << kTestTotalShards << " unset.\n";
5465    ColoredPrintf(COLOR_RED, msg.GetString().c_str());
5466    fflush(stdout);
5467    exit(EXIT_FAILURE);
5468  } else if (total_shards != -1 && shard_index == -1) {
5469    const Message msg = Message()
5470      << "Invalid environment variables: you have "
5471      << kTestTotalShards << " = " << total_shards
5472      << ", but have left " << kTestShardIndex << " unset.\n";
5473    ColoredPrintf(COLOR_RED, msg.GetString().c_str());
5474    fflush(stdout);
5475    exit(EXIT_FAILURE);
5476  } else if (shard_index < 0 || shard_index >= total_shards) {
5477    const Message msg = Message()
5478      << "Invalid environment variables: we require 0 <= "
5479      << kTestShardIndex << " < " << kTestTotalShards
5480      << ", but you have " << kTestShardIndex << "=" << shard_index
5481      << ", " << kTestTotalShards << "=" << total_shards << ".\n";
5482    ColoredPrintf(COLOR_RED, msg.GetString().c_str());
5483    fflush(stdout);
5484    exit(EXIT_FAILURE);
5485  }
5486
5487  return total_shards > 1;
5488}
5489
5490// Parses the environment variable var as an Int32. If it is unset,
5491// returns default_val. If it is not an Int32, prints an error
5492// and aborts.
5493Int32 Int32FromEnvOrDie(const char* const var, Int32 default_val) {
5494  const char* str_val = posix::GetEnv(var);
5495  if (str_val == NULL) {
5496    return default_val;
5497  }
5498
5499  Int32 result;
5500  if (!ParseInt32(Message() << "The value of environment variable " << var,
5501                  str_val, &result)) {
5502    exit(EXIT_FAILURE);
5503  }
5504  return result;
5505}
5506
5507// Given the total number of shards, the shard index, and the test id,
5508// returns true iff the test should be run on this shard. The test id is
5509// some arbitrary but unique non-negative integer assigned to each test
5510// method. Assumes that 0 <= shard_index < total_shards.
5511bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) {
5512  return (test_id % total_shards) == shard_index;
5513}
5514
5515// Compares the name of each test with the user-specified filter to
5516// decide whether the test should be run, then records the result in
5517// each TestCase and TestInfo object.
5518// If shard_tests == true, further filters tests based on sharding
5519// variables in the environment - see
5520// http://code.google.com/p/googletest/wiki/GoogleTestAdvancedGuide.
5521// Returns the number of tests that should run.
5522int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) {
5523  const Int32 total_shards = shard_tests == HONOR_SHARDING_PROTOCOL ?
5524      Int32FromEnvOrDie(kTestTotalShards, -1) : -1;
5525  const Int32 shard_index = shard_tests == HONOR_SHARDING_PROTOCOL ?
5526      Int32FromEnvOrDie(kTestShardIndex, -1) : -1;
5527
5528  // num_runnable_tests are the number of tests that will
5529  // run across all shards (i.e., match filter and are not disabled).
5530  // num_selected_tests are the number of tests to be run on
5531  // this shard.
5532  int num_runnable_tests = 0;
5533  int num_selected_tests = 0;
5534  for (size_t i = 0; i < test_cases_.size(); i++) {
5535    TestCase* const test_case = test_cases_[i];
5536    const String &test_case_name = test_case->name();
5537    test_case->set_should_run(false);
5538
5539    for (size_t j = 0; j < test_case->test_info_list().size(); j++) {
5540      TestInfo* const test_info = test_case->test_info_list()[j];
5541      const String test_name(test_info->name());
5542      // A test is disabled if test case name or test name matches
5543      // kDisableTestFilter.
5544      const bool is_disabled =
5545          internal::UnitTestOptions::MatchesFilter(test_case_name,
5546                                                   kDisableTestFilter) ||
5547          internal::UnitTestOptions::MatchesFilter(test_name,
5548                                                   kDisableTestFilter);
5549      test_info->impl()->set_is_disabled(is_disabled);
5550
5551      const bool matches_filter =
5552          internal::UnitTestOptions::FilterMatchesTest(test_case_name,
5553                                                       test_name);
5554      test_info->impl()->set_matches_filter(matches_filter);
5555
5556      const bool is_runnable =
5557          (GTEST_FLAG(also_run_disabled_tests) || !is_disabled) &&
5558          matches_filter;
5559
5560      const bool is_selected = is_runnable &&
5561          (shard_tests == IGNORE_SHARDING_PROTOCOL ||
5562           ShouldRunTestOnShard(total_shards, shard_index,
5563                                num_runnable_tests));
5564
5565      num_runnable_tests += is_runnable;
5566      num_selected_tests += is_selected;
5567
5568      test_info->impl()->set_should_run(is_selected);
5569      test_case->set_should_run(test_case->should_run() || is_selected);
5570    }
5571  }
5572  return num_selected_tests;
5573}
5574
5575// Prints the names of the tests matching the user-specified filter flag.
5576void UnitTestImpl::ListTestsMatchingFilter() {
5577  for (size_t i = 0; i < test_cases_.size(); i++) {
5578    const TestCase* const test_case = test_cases_[i];
5579    bool printed_test_case_name = false;
5580
5581    for (size_t j = 0; j < test_case->test_info_list().size(); j++) {
5582      const TestInfo* const test_info =
5583          test_case->test_info_list()[j];
5584      if (test_info->matches_filter()) {
5585        if (!printed_test_case_name) {
5586          printed_test_case_name = true;
5587          printf("%s.\n", test_case->name());
5588        }
5589        printf("  %s\n", test_info->name());
5590      }
5591    }
5592  }
5593  fflush(stdout);
5594}
5595
5596// Sets the OS stack trace getter.
5597//
5598// Does nothing if the input and the current OS stack trace getter are
5599// the same; otherwise, deletes the old getter and makes the input the
5600// current getter.
5601void UnitTestImpl::set_os_stack_trace_getter(
5602    OsStackTraceGetterInterface* getter) {
5603  if (os_stack_trace_getter_ != getter) {
5604    delete os_stack_trace_getter_;
5605    os_stack_trace_getter_ = getter;
5606  }
5607}
5608
5609// Returns the current OS stack trace getter if it is not NULL;
5610// otherwise, creates an OsStackTraceGetter, makes it the current
5611// getter, and returns it.
5612OsStackTraceGetterInterface* UnitTestImpl::os_stack_trace_getter() {
5613  if (os_stack_trace_getter_ == NULL) {
5614    os_stack_trace_getter_ = new OsStackTraceGetter;
5615  }
5616
5617  return os_stack_trace_getter_;
5618}
5619
5620// Returns the TestResult for the test that's currently running, or
5621// the TestResult for the ad hoc test if no test is running.
5622TestResult* UnitTestImpl::current_test_result() {
5623  return current_test_info_ ?
5624    current_test_info_->impl()->result() : &ad_hoc_test_result_;
5625}
5626
5627// Shuffles all test cases, and the tests within each test case,
5628// making sure that death tests are still run first.
5629void UnitTestImpl::ShuffleTests() {
5630  // Shuffles the death test cases.
5631  ShuffleRange(random(), 0, last_death_test_case_ + 1, &test_case_indices_);
5632
5633  // Shuffles the non-death test cases.
5634  ShuffleRange(random(), last_death_test_case_ + 1,
5635               static_cast<int>(test_cases_.size()), &test_case_indices_);
5636
5637  // Shuffles the tests inside each test case.
5638  for (size_t i = 0; i < test_cases_.size(); i++) {
5639    test_cases_[i]->ShuffleTests(random());
5640  }
5641}
5642
5643// Restores the test cases and tests to their order before the first shuffle.
5644void UnitTestImpl::UnshuffleTests() {
5645  for (size_t i = 0; i < test_cases_.size(); i++) {
5646    // Unshuffles the tests in each test case.
5647    test_cases_[i]->UnshuffleTests();
5648    // Resets the index of each test case.
5649    test_case_indices_[i] = static_cast<int>(i);
5650  }
5651}
5652
5653// TestInfoImpl constructor. The new instance assumes ownership of the test
5654// factory object.
5655TestInfoImpl::TestInfoImpl(TestInfo* parent,
5656                           const char* a_test_case_name,
5657                           const char* a_name,
5658                           const char* a_test_case_comment,
5659                           const char* a_comment,
5660                           TypeId a_fixture_class_id,
5661                           internal::TestFactoryBase* factory) :
5662    parent_(parent),
5663    test_case_name_(String(a_test_case_name)),
5664    name_(String(a_name)),
5665    test_case_comment_(String(a_test_case_comment)),
5666    comment_(String(a_comment)),
5667    fixture_class_id_(a_fixture_class_id),
5668    should_run_(false),
5669    is_disabled_(false),
5670    matches_filter_(false),
5671    factory_(factory) {
5672}
5673
5674// TestInfoImpl destructor.
5675TestInfoImpl::~TestInfoImpl() {
5676  delete factory_;
5677}
5678
5679// Returns the current OS stack trace as a String.
5680//
5681// The maximum number of stack frames to be included is specified by
5682// the gtest_stack_trace_depth flag.  The skip_count parameter
5683// specifies the number of top frames to be skipped, which doesn't
5684// count against the number of frames to be included.
5685//
5686// For example, if Foo() calls Bar(), which in turn calls
5687// GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in
5688// the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.
5689String GetCurrentOsStackTraceExceptTop(UnitTest* /*unit_test*/,
5690                                       int skip_count) {
5691  // We pass skip_count + 1 to skip this wrapper function in addition
5692  // to what the user really wants to skip.
5693  return GetUnitTestImpl()->CurrentOsStackTraceExceptTop(skip_count + 1);
5694}
5695
5696// Used by the GTEST_HIDE_UNREACHABLE_CODE_ macro to suppress unreachable
5697// code warnings.
5698namespace {
5699class ClassUniqueToAlwaysTrue {};
5700}
5701
5702bool IsTrue(bool condition) { return condition; }
5703
5704bool AlwaysTrue() {
5705#if GTEST_HAS_EXCEPTIONS
5706  // This condition is always false so AlwaysTrue() never actually throws,
5707  // but it makes the compiler think that it may throw.
5708  if (IsTrue(false))
5709    throw ClassUniqueToAlwaysTrue();
5710#endif  // GTEST_HAS_EXCEPTIONS
5711  return true;
5712}
5713
5714// If *pstr starts with the given prefix, modifies *pstr to be right
5715// past the prefix and returns true; otherwise leaves *pstr unchanged
5716// and returns false.  None of pstr, *pstr, and prefix can be NULL.
5717bool SkipPrefix(const char* prefix, const char** pstr) {
5718  const size_t prefix_len = strlen(prefix);
5719  if (strncmp(*pstr, prefix, prefix_len) == 0) {
5720    *pstr += prefix_len;
5721    return true;
5722  }
5723  return false;
5724}
5725
5726// Parses a string as a command line flag.  The string should have
5727// the format "--flag=value".  When def_optional is true, the "=value"
5728// part can be omitted.
5729//
5730// Returns the value of the flag, or NULL if the parsing failed.
5731const char* ParseFlagValue(const char* str,
5732                           const char* flag,
5733                           bool def_optional) {
5734  // str and flag must not be NULL.
5735  if (str == NULL || flag == NULL) return NULL;
5736
5737  // The flag must start with "--" followed by GTEST_FLAG_PREFIX_.
5738  const String flag_str = String::Format("--%s%s", GTEST_FLAG_PREFIX_, flag);
5739  const size_t flag_len = flag_str.length();
5740  if (strncmp(str, flag_str.c_str(), flag_len) != 0) return NULL;
5741
5742  // Skips the flag name.
5743  const char* flag_end = str + flag_len;
5744
5745  // When def_optional is true, it's OK to not have a "=value" part.
5746  if (def_optional && (flag_end[0] == '\0')) {
5747    return flag_end;
5748  }
5749
5750  // If def_optional is true and there are more characters after the
5751  // flag name, or if def_optional is false, there must be a '=' after
5752  // the flag name.
5753  if (flag_end[0] != '=') return NULL;
5754
5755  // Returns the string after "=".
5756  return flag_end + 1;
5757}
5758
5759// Parses a string for a bool flag, in the form of either
5760// "--flag=value" or "--flag".
5761//
5762// In the former case, the value is taken as true as long as it does
5763// not start with '0', 'f', or 'F'.
5764//
5765// In the latter case, the value is taken as true.
5766//
5767// On success, stores the value of the flag in *value, and returns
5768// true.  On failure, returns false without changing *value.
5769bool ParseBoolFlag(const char* str, const char* flag, bool* value) {
5770  // Gets the value of the flag as a string.
5771  const char* const value_str = ParseFlagValue(str, flag, true);
5772
5773  // Aborts if the parsing failed.
5774  if (value_str == NULL) return false;
5775
5776  // Converts the string value to a bool.
5777  *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F');
5778  return true;
5779}
5780
5781// Parses a string for an Int32 flag, in the form of
5782// "--flag=value".
5783//
5784// On success, stores the value of the flag in *value, and returns
5785// true.  On failure, returns false without changing *value.
5786bool ParseInt32Flag(const char* str, const char* flag, Int32* value) {
5787  // Gets the value of the flag as a string.
5788  const char* const value_str = ParseFlagValue(str, flag, false);
5789
5790  // Aborts if the parsing failed.
5791  if (value_str == NULL) return false;
5792
5793  // Sets *value to the value of the flag.
5794  return ParseInt32(Message() << "The value of flag --" << flag,
5795                    value_str, value);
5796}
5797
5798// Parses a string for a string flag, in the form of
5799// "--flag=value".
5800//
5801// On success, stores the value of the flag in *value, and returns
5802// true.  On failure, returns false without changing *value.
5803bool ParseStringFlag(const char* str, const char* flag, String* value) {
5804  // Gets the value of the flag as a string.
5805  const char* const value_str = ParseFlagValue(str, flag, false);
5806
5807  // Aborts if the parsing failed.
5808  if (value_str == NULL) return false;
5809
5810  // Sets *value to the value of the flag.
5811  *value = value_str;
5812  return true;
5813}
5814
5815// Determines whether a string has a prefix that Google Test uses for its
5816// flags, i.e., starts with GTEST_FLAG_PREFIX_ or GTEST_FLAG_PREFIX_DASH_.
5817// If Google Test detects that a command line flag has its prefix but is not
5818// recognized, it will print its help message. Flags starting with
5819// GTEST_INTERNAL_PREFIX_ followed by "internal_" are considered Google Test
5820// internal flags and do not trigger the help message.
5821static bool HasGoogleTestFlagPrefix(const char* str) {
5822  return (SkipPrefix("--", &str) ||
5823          SkipPrefix("-", &str) ||
5824          SkipPrefix("/", &str)) &&
5825         !SkipPrefix(GTEST_FLAG_PREFIX_ "internal_", &str) &&
5826         (SkipPrefix(GTEST_FLAG_PREFIX_, &str) ||
5827          SkipPrefix(GTEST_FLAG_PREFIX_DASH_, &str));
5828}
5829
5830// Prints a string containing code-encoded text.  The following escape
5831// sequences can be used in the string to control the text color:
5832//
5833//   @@    prints a single '@' character.
5834//   @R    changes the color to red.
5835//   @G    changes the color to green.
5836//   @Y    changes the color to yellow.
5837//   @D    changes to the default terminal text color.
5838//
5839// TODO(wan@google.com): Write tests for this once we add stdout
5840// capturing to Google Test.
5841static void PrintColorEncoded(const char* str) {
5842  GTestColor color = COLOR_DEFAULT;  // The current color.
5843
5844  // Conceptually, we split the string into segments divided by escape
5845  // sequences.  Then we print one segment at a time.  At the end of
5846  // each iteration, the str pointer advances to the beginning of the
5847  // next segment.
5848  for (;;) {
5849    const char* p = strchr(str, '@');
5850    if (p == NULL) {
5851      ColoredPrintf(color, "%s", str);
5852      return;
5853    }
5854
5855    ColoredPrintf(color, "%s", String(str, p - str).c_str());
5856
5857    const char ch = p[1];
5858    str = p + 2;
5859    if (ch == '@') {
5860      ColoredPrintf(color, "@");
5861    } else if (ch == 'D') {
5862      color = COLOR_DEFAULT;
5863    } else if (ch == 'R') {
5864      color = COLOR_RED;
5865    } else if (ch == 'G') {
5866      color = COLOR_GREEN;
5867    } else if (ch == 'Y') {
5868      color = COLOR_YELLOW;
5869    } else {
5870      --str;
5871    }
5872  }
5873}
5874
5875static const char kColorEncodedHelpMessage[] =
5876"This program contains tests written using " GTEST_NAME_ ". You can use the\n"
5877"following command line flags to control its behavior:\n"
5878"\n"
5879"Test Selection:\n"
5880"  @G--" GTEST_FLAG_PREFIX_ "list_tests@D\n"
5881"      List the names of all tests instead of running them. The name of\n"
5882"      TEST(Foo, Bar) is \"Foo.Bar\".\n"
5883"  @G--" GTEST_FLAG_PREFIX_ "filter=@YPOSTIVE_PATTERNS"
5884    "[@G-@YNEGATIVE_PATTERNS]@D\n"
5885"      Run only the tests whose name matches one of the positive patterns but\n"
5886"      none of the negative patterns. '?' matches any single character; '*'\n"
5887"      matches any substring; ':' separates two patterns.\n"
5888"  @G--" GTEST_FLAG_PREFIX_ "also_run_disabled_tests@D\n"
5889"      Run all disabled tests too.\n"
5890"\n"
5891"Test Execution:\n"
5892"  @G--" GTEST_FLAG_PREFIX_ "repeat=@Y[COUNT]@D\n"
5893"      Run the tests repeatedly; use a negative count to repeat forever.\n"
5894"  @G--" GTEST_FLAG_PREFIX_ "shuffle@D\n"
5895"      Randomize tests' orders on every iteration.\n"
5896"  @G--" GTEST_FLAG_PREFIX_ "random_seed=@Y[NUMBER]@D\n"
5897"      Random number seed to use for shuffling test orders (between 1 and\n"
5898"      99999, or 0 to use a seed based on the current time).\n"
5899"\n"
5900"Test Output:\n"
5901"  @G--" GTEST_FLAG_PREFIX_ "color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\n"
5902"      Enable/disable colored output. The default is @Gauto@D.\n"
5903"  -@G-" GTEST_FLAG_PREFIX_ "print_time=0@D\n"
5904"      Don't print the elapsed time of each test.\n"
5905"  @G--" GTEST_FLAG_PREFIX_ "output=xml@Y[@G:@YDIRECTORY_PATH@G"
5906    GTEST_PATH_SEP_ "@Y|@G:@YFILE_PATH]@D\n"
5907"      Generate an XML report in the given directory or with the given file\n"
5908"      name. @YFILE_PATH@D defaults to @Gtest_details.xml@D.\n"
5909"\n"
5910"Assertion Behavior:\n"
5911#if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
5912"  @G--" GTEST_FLAG_PREFIX_ "death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n"
5913"      Set the default death test style.\n"
5914#endif  // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
5915"  @G--" GTEST_FLAG_PREFIX_ "break_on_failure@D\n"
5916"      Turn assertion failures into debugger break-points.\n"
5917"  @G--" GTEST_FLAG_PREFIX_ "throw_on_failure@D\n"
5918"      Turn assertion failures into C++ exceptions.\n"
5919#if GTEST_OS_WINDOWS
5920"  @G--" GTEST_FLAG_PREFIX_ "catch_exceptions@D\n"
5921"      Suppress pop-ups caused by exceptions.\n"
5922#endif  // GTEST_OS_WINDOWS
5923"\n"
5924"Except for @G--" GTEST_FLAG_PREFIX_ "list_tests@D, you can alternatively set "
5925    "the corresponding\n"
5926"environment variable of a flag (all letters in upper-case). For example, to\n"
5927"disable colored text output, you can either specify @G--" GTEST_FLAG_PREFIX_
5928    "color=no@D or set\n"
5929"the @G" GTEST_FLAG_PREFIX_UPPER_ "COLOR@D environment variable to @Gno@D.\n"
5930"\n"
5931"For more information, please read the " GTEST_NAME_ " documentation at\n"
5932"@G" GTEST_PROJECT_URL_ "@D. If you find a bug in " GTEST_NAME_ "\n"
5933"(not one in your own code or tests), please report it to\n"
5934"@G<" GTEST_DEV_EMAIL_ ">@D.\n";
5935
5936// Parses the command line for Google Test flags, without initializing
5937// other parts of Google Test.  The type parameter CharType can be
5938// instantiated to either char or wchar_t.
5939template <typename CharType>
5940void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) {
5941  for (int i = 1; i < *argc; i++) {
5942    const String arg_string = StreamableToString(argv[i]);
5943    const char* const arg = arg_string.c_str();
5944
5945    using internal::ParseBoolFlag;
5946    using internal::ParseInt32Flag;
5947    using internal::ParseStringFlag;
5948
5949    // Do we see a Google Test flag?
5950    if (ParseBoolFlag(arg, kAlsoRunDisabledTestsFlag,
5951                      &GTEST_FLAG(also_run_disabled_tests)) ||
5952        ParseBoolFlag(arg, kBreakOnFailureFlag,
5953                      &GTEST_FLAG(break_on_failure)) ||
5954        ParseBoolFlag(arg, kCatchExceptionsFlag,
5955                      &GTEST_FLAG(catch_exceptions)) ||
5956        ParseStringFlag(arg, kColorFlag, &GTEST_FLAG(color)) ||
5957        ParseStringFlag(arg, kDeathTestStyleFlag,
5958                        &GTEST_FLAG(death_test_style)) ||
5959        ParseBoolFlag(arg, kDeathTestUseFork,
5960                      &GTEST_FLAG(death_test_use_fork)) ||
5961        ParseStringFlag(arg, kFilterFlag, &GTEST_FLAG(filter)) ||
5962        ParseStringFlag(arg, kInternalRunDeathTestFlag,
5963                        &GTEST_FLAG(internal_run_death_test)) ||
5964        ParseBoolFlag(arg, kListTestsFlag, &GTEST_FLAG(list_tests)) ||
5965        ParseStringFlag(arg, kOutputFlag, &GTEST_FLAG(output)) ||
5966        ParseBoolFlag(arg, kPrintTimeFlag, &GTEST_FLAG(print_time)) ||
5967        ParseInt32Flag(arg, kRandomSeedFlag, &GTEST_FLAG(random_seed)) ||
5968        ParseInt32Flag(arg, kRepeatFlag, &GTEST_FLAG(repeat)) ||
5969        ParseBoolFlag(arg, kShuffleFlag, &GTEST_FLAG(shuffle)) ||
5970        ParseInt32Flag(arg, kStackTraceDepthFlag,
5971                       &GTEST_FLAG(stack_trace_depth)) ||
5972        ParseBoolFlag(arg, kThrowOnFailureFlag, &GTEST_FLAG(throw_on_failure))
5973        ) {
5974      // Yes.  Shift the remainder of the argv list left by one.  Note
5975      // that argv has (*argc + 1) elements, the last one always being
5976      // NULL.  The following loop moves the trailing NULL element as
5977      // well.
5978      for (int j = i; j != *argc; j++) {
5979        argv[j] = argv[j + 1];
5980      }
5981
5982      // Decrements the argument count.
5983      (*argc)--;
5984
5985      // We also need to decrement the iterator as we just removed
5986      // an element.
5987      i--;
5988    } else if (arg_string == "--help" || arg_string == "-h" ||
5989               arg_string == "-?" || arg_string == "/?" ||
5990               HasGoogleTestFlagPrefix(arg)) {
5991      // Both help flag and unrecognized Google Test flags (excluding
5992      // internal ones) trigger help display.
5993      g_help_flag = true;
5994    }
5995  }
5996
5997  if (g_help_flag) {
5998    // We print the help here instead of in RUN_ALL_TESTS(), as the
5999    // latter may not be called at all if the user is using Google
6000    // Test with another testing framework.
6001    PrintColorEncoded(kColorEncodedHelpMessage);
6002  }
6003}
6004
6005// Parses the command line for Google Test flags, without initializing
6006// other parts of Google Test.
6007void ParseGoogleTestFlagsOnly(int* argc, char** argv) {
6008  ParseGoogleTestFlagsOnlyImpl(argc, argv);
6009}
6010void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv) {
6011  ParseGoogleTestFlagsOnlyImpl(argc, argv);
6012}
6013
6014// The internal implementation of InitGoogleTest().
6015//
6016// The type parameter CharType can be instantiated to either char or
6017// wchar_t.
6018template <typename CharType>
6019void InitGoogleTestImpl(int* argc, CharType** argv) {
6020  g_init_gtest_count++;
6021
6022  // We don't want to run the initialization code twice.
6023  if (g_init_gtest_count != 1) return;
6024
6025  if (*argc <= 0) return;
6026
6027  internal::g_executable_path = internal::StreamableToString(argv[0]);
6028
6029#if GTEST_HAS_DEATH_TEST
6030  g_argvs.clear();
6031  for (int i = 0; i != *argc; i++) {
6032    g_argvs.push_back(StreamableToString(argv[i]));
6033  }
6034#endif  // GTEST_HAS_DEATH_TEST
6035
6036  ParseGoogleTestFlagsOnly(argc, argv);
6037  GetUnitTestImpl()->PostFlagParsingInit();
6038}
6039
6040}  // namespace internal
6041
6042// Initializes Google Test.  This must be called before calling
6043// RUN_ALL_TESTS().  In particular, it parses a command line for the
6044// flags that Google Test recognizes.  Whenever a Google Test flag is
6045// seen, it is removed from argv, and *argc is decremented.
6046//
6047// No value is returned.  Instead, the Google Test flag variables are
6048// updated.
6049//
6050// Calling the function for the second time has no user-visible effect.
6051void InitGoogleTest(int* argc, char** argv) {
6052  internal::InitGoogleTestImpl(argc, argv);
6053}
6054
6055// This overloaded version can be used in Windows programs compiled in
6056// UNICODE mode.
6057void InitGoogleTest(int* argc, wchar_t** argv) {
6058  internal::InitGoogleTestImpl(argc, argv);
6059}
6060
6061}  // namespace testing
6062// Copyright 2005, Google Inc.
6063// All rights reserved.
6064//
6065// Redistribution and use in source and binary forms, with or without
6066// modification, are permitted provided that the following conditions are
6067// met:
6068//
6069//     * Redistributions of source code must retain the above copyright
6070// notice, this list of conditions and the following disclaimer.
6071//     * Redistributions in binary form must reproduce the above
6072// copyright notice, this list of conditions and the following disclaimer
6073// in the documentation and/or other materials provided with the
6074// distribution.
6075//     * Neither the name of Google Inc. nor the names of its
6076// contributors may be used to endorse or promote products derived from
6077// this software without specific prior written permission.
6078//
6079// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
6080// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
6081// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
6082// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
6083// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
6084// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
6085// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
6086// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
6087// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
6088// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
6089// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
6090//
6091// Author: wan@google.com (Zhanyong Wan), vladl@google.com (Vlad Losev)
6092//
6093// This file implements death tests.
6094
6095
6096#if GTEST_HAS_DEATH_TEST
6097
6098#if GTEST_OS_MAC
6099#include <crt_externs.h>
6100#endif  // GTEST_OS_MAC
6101
6102#include <errno.h>
6103#include <fcntl.h>
6104#include <limits.h>
6105#include <stdarg.h>
6106
6107#if GTEST_OS_WINDOWS
6108#include <windows.h>
6109#else
6110#include <sys/mman.h>
6111#include <sys/wait.h>
6112#endif  // GTEST_OS_WINDOWS
6113
6114#endif  // GTEST_HAS_DEATH_TEST
6115
6116
6117// Indicates that this translation unit is part of Google Test's
6118// implementation.  It must come before gtest-internal-inl.h is
6119// included, or there will be a compiler error.  This trick is to
6120// prevent a user from accidentally including gtest-internal-inl.h in
6121// his code.
6122#define GTEST_IMPLEMENTATION_ 1
6123#undef GTEST_IMPLEMENTATION_
6124
6125namespace testing {
6126
6127// Constants.
6128
6129// The default death test style.
6130static const char kDefaultDeathTestStyle[] = "fast";
6131
6132GTEST_DEFINE_string_(
6133    death_test_style,
6134    internal::StringFromGTestEnv("death_test_style", kDefaultDeathTestStyle),
6135    "Indicates how to run a death test in a forked child process: "
6136    "\"threadsafe\" (child process re-executes the test binary "
6137    "from the beginning, running only the specific death test) or "
6138    "\"fast\" (child process runs the death test immediately "
6139    "after forking).");
6140
6141GTEST_DEFINE_bool_(
6142    death_test_use_fork,
6143    internal::BoolFromGTestEnv("death_test_use_fork", false),
6144    "Instructs to use fork()/_exit() instead of clone() in death tests. "
6145    "Ignored and always uses fork() on POSIX systems where clone() is not "
6146    "implemented. Useful when running under valgrind or similar tools if "
6147    "those do not support clone(). Valgrind 3.3.1 will just fail if "
6148    "it sees an unsupported combination of clone() flags. "
6149    "It is not recommended to use this flag w/o valgrind though it will "
6150    "work in 99% of the cases. Once valgrind is fixed, this flag will "
6151    "most likely be removed.");
6152
6153namespace internal {
6154GTEST_DEFINE_string_(
6155    internal_run_death_test, "",
6156    "Indicates the file, line number, temporal index of "
6157    "the single death test to run, and a file descriptor to "
6158    "which a success code may be sent, all separated by "
6159    "colons.  This flag is specified if and only if the current "
6160    "process is a sub-process launched for running a thread-safe "
6161    "death test.  FOR INTERNAL USE ONLY.");
6162}  // namespace internal
6163
6164#if GTEST_HAS_DEATH_TEST
6165
6166// ExitedWithCode constructor.
6167ExitedWithCode::ExitedWithCode(int exit_code) : exit_code_(exit_code) {
6168}
6169
6170// ExitedWithCode function-call operator.
6171bool ExitedWithCode::operator()(int exit_status) const {
6172#if GTEST_OS_WINDOWS
6173  return exit_status == exit_code_;
6174#else
6175  return WIFEXITED(exit_status) && WEXITSTATUS(exit_status) == exit_code_;
6176#endif  // GTEST_OS_WINDOWS
6177}
6178
6179#if !GTEST_OS_WINDOWS
6180// KilledBySignal constructor.
6181KilledBySignal::KilledBySignal(int signum) : signum_(signum) {
6182}
6183
6184// KilledBySignal function-call operator.
6185bool KilledBySignal::operator()(int exit_status) const {
6186  return WIFSIGNALED(exit_status) && WTERMSIG(exit_status) == signum_;
6187}
6188#endif  // !GTEST_OS_WINDOWS
6189
6190namespace internal {
6191
6192// Utilities needed for death tests.
6193
6194// Generates a textual description of a given exit code, in the format
6195// specified by wait(2).
6196static String ExitSummary(int exit_code) {
6197  Message m;
6198#if GTEST_OS_WINDOWS
6199  m << "Exited with exit status " << exit_code;
6200#else
6201  if (WIFEXITED(exit_code)) {
6202    m << "Exited with exit status " << WEXITSTATUS(exit_code);
6203  } else if (WIFSIGNALED(exit_code)) {
6204    m << "Terminated by signal " << WTERMSIG(exit_code);
6205  }
6206#ifdef WCOREDUMP
6207  if (WCOREDUMP(exit_code)) {
6208    m << " (core dumped)";
6209  }
6210#endif
6211#endif  // GTEST_OS_WINDOWS
6212  return m.GetString();
6213}
6214
6215// Returns true if exit_status describes a process that was terminated
6216// by a signal, or exited normally with a nonzero exit code.
6217bool ExitedUnsuccessfully(int exit_status) {
6218  return !ExitedWithCode(0)(exit_status);
6219}
6220
6221#if !GTEST_OS_WINDOWS
6222// Generates a textual failure message when a death test finds more than
6223// one thread running, or cannot determine the number of threads, prior
6224// to executing the given statement.  It is the responsibility of the
6225// caller not to pass a thread_count of 1.
6226static String DeathTestThreadWarning(size_t thread_count) {
6227  Message msg;
6228  msg << "Death tests use fork(), which is unsafe particularly"
6229      << " in a threaded context. For this test, " << GTEST_NAME_ << " ";
6230  if (thread_count == 0)
6231    msg << "couldn't detect the number of threads.";
6232  else
6233    msg << "detected " << thread_count << " threads.";
6234  return msg.GetString();
6235}
6236#endif  // !GTEST_OS_WINDOWS
6237
6238// Flag characters for reporting a death test that did not die.
6239static const char kDeathTestLived = 'L';
6240static const char kDeathTestReturned = 'R';
6241static const char kDeathTestInternalError = 'I';
6242
6243// An enumeration describing all of the possible ways that a death test
6244// can conclude.  DIED means that the process died while executing the
6245// test code; LIVED means that process lived beyond the end of the test
6246// code; and RETURNED means that the test statement attempted a "return,"
6247// which is not allowed.  IN_PROGRESS means the test has not yet
6248// concluded.
6249enum DeathTestOutcome { IN_PROGRESS, DIED, LIVED, RETURNED };
6250
6251// Routine for aborting the program which is safe to call from an
6252// exec-style death test child process, in which case the error
6253// message is propagated back to the parent process.  Otherwise, the
6254// message is simply printed to stderr.  In either case, the program
6255// then exits with status 1.
6256void DeathTestAbort(const String& message) {
6257  // On a POSIX system, this function may be called from a threadsafe-style
6258  // death test child process, which operates on a very small stack.  Use
6259  // the heap for any additional non-minuscule memory requirements.
6260  const InternalRunDeathTestFlag* const flag =
6261      GetUnitTestImpl()->internal_run_death_test_flag();
6262  if (flag != NULL) {
6263    FILE* parent = posix::FDOpen(flag->write_fd(), "w");
6264    fputc(kDeathTestInternalError, parent);
6265    fprintf(parent, "%s", message.c_str());
6266    fflush(parent);
6267    _exit(1);
6268  } else {
6269    fprintf(stderr, "%s", message.c_str());
6270    fflush(stderr);
6271    abort();
6272  }
6273}
6274
6275// A replacement for CHECK that calls DeathTestAbort if the assertion
6276// fails.
6277#define GTEST_DEATH_TEST_CHECK_(expression) \
6278  do { \
6279    if (!::testing::internal::IsTrue(expression)) { \
6280      DeathTestAbort(::testing::internal::String::Format( \
6281          "CHECK failed: File %s, line %d: %s", \
6282          __FILE__, __LINE__, #expression)); \
6283    } \
6284  } while (::testing::internal::AlwaysFalse())
6285
6286// This macro is similar to GTEST_DEATH_TEST_CHECK_, but it is meant for
6287// evaluating any system call that fulfills two conditions: it must return
6288// -1 on failure, and set errno to EINTR when it is interrupted and
6289// should be tried again.  The macro expands to a loop that repeatedly
6290// evaluates the expression as long as it evaluates to -1 and sets
6291// errno to EINTR.  If the expression evaluates to -1 but errno is
6292// something other than EINTR, DeathTestAbort is called.
6293#define GTEST_DEATH_TEST_CHECK_SYSCALL_(expression) \
6294  do { \
6295    int gtest_retval; \
6296    do { \
6297      gtest_retval = (expression); \
6298    } while (gtest_retval == -1 && errno == EINTR); \
6299    if (gtest_retval == -1) { \
6300      DeathTestAbort(::testing::internal::String::Format( \
6301          "CHECK failed: File %s, line %d: %s != -1", \
6302          __FILE__, __LINE__, #expression)); \
6303    } \
6304  } while (::testing::internal::AlwaysFalse())
6305
6306// Returns the message describing the last system error in errno.
6307String GetLastErrnoDescription() {
6308    return String(errno == 0 ? "" : posix::StrError(errno));
6309}
6310
6311// This is called from a death test parent process to read a failure
6312// message from the death test child process and log it with the FATAL
6313// severity. On Windows, the message is read from a pipe handle. On other
6314// platforms, it is read from a file descriptor.
6315static void FailFromInternalError(int fd) {
6316  Message error;
6317  char buffer[256];
6318  int num_read;
6319
6320  do {
6321    while ((num_read = posix::Read(fd, buffer, 255)) > 0) {
6322      buffer[num_read] = '\0';
6323      error << buffer;
6324    }
6325  } while (num_read == -1 && errno == EINTR);
6326
6327  if (num_read == 0) {
6328    GTEST_LOG_(FATAL) << error.GetString();
6329  } else {
6330    const int last_error = errno;
6331    GTEST_LOG_(FATAL) << "Error while reading death test internal: "
6332                      << GetLastErrnoDescription() << " [" << last_error << "]";
6333  }
6334}
6335
6336// Death test constructor.  Increments the running death test count
6337// for the current test.
6338DeathTest::DeathTest() {
6339  TestInfo* const info = GetUnitTestImpl()->current_test_info();
6340  if (info == NULL) {
6341    DeathTestAbort("Cannot run a death test outside of a TEST or "
6342                   "TEST_F construct");
6343  }
6344}
6345
6346// Creates and returns a death test by dispatching to the current
6347// death test factory.
6348bool DeathTest::Create(const char* statement, const RE* regex,
6349                       const char* file, int line, DeathTest** test) {
6350  return GetUnitTestImpl()->death_test_factory()->Create(
6351      statement, regex, file, line, test);
6352}
6353
6354const char* DeathTest::LastMessage() {
6355  return last_death_test_message_.c_str();
6356}
6357
6358void DeathTest::set_last_death_test_message(const String& message) {
6359  last_death_test_message_ = message;
6360}
6361
6362String DeathTest::last_death_test_message_;
6363
6364// Provides cross platform implementation for some death functionality.
6365class DeathTestImpl : public DeathTest {
6366 protected:
6367  DeathTestImpl(const char* a_statement, const RE* a_regex)
6368      : statement_(a_statement),
6369        regex_(a_regex),
6370        spawned_(false),
6371        status_(-1),
6372        outcome_(IN_PROGRESS),
6373        read_fd_(-1),
6374        write_fd_(-1) {}
6375
6376  // read_fd_ is expected to be closed and cleared by a derived class.
6377  ~DeathTestImpl() { GTEST_DEATH_TEST_CHECK_(read_fd_ == -1); }
6378
6379  void Abort(AbortReason reason);
6380  virtual bool Passed(bool status_ok);
6381
6382  const char* statement() const { return statement_; }
6383  const RE* regex() const { return regex_; }
6384  bool spawned() const { return spawned_; }
6385  void set_spawned(bool is_spawned) { spawned_ = is_spawned; }
6386  int status() const { return status_; }
6387  void set_status(int a_status) { status_ = a_status; }
6388  DeathTestOutcome outcome() const { return outcome_; }
6389  void set_outcome(DeathTestOutcome an_outcome) { outcome_ = an_outcome; }
6390  int read_fd() const { return read_fd_; }
6391  void set_read_fd(int fd) { read_fd_ = fd; }
6392  int write_fd() const { return write_fd_; }
6393  void set_write_fd(int fd) { write_fd_ = fd; }
6394
6395  // Called in the parent process only. Reads the result code of the death
6396  // test child process via a pipe, interprets it to set the outcome_
6397  // member, and closes read_fd_.  Outputs diagnostics and terminates in
6398  // case of unexpected codes.
6399  void ReadAndInterpretStatusByte();
6400
6401 private:
6402  // The textual content of the code this object is testing.  This class
6403  // doesn't own this string and should not attempt to delete it.
6404  const char* const statement_;
6405  // The regular expression which test output must match.  DeathTestImpl
6406  // doesn't own this object and should not attempt to delete it.
6407  const RE* const regex_;
6408  // True if the death test child process has been successfully spawned.
6409  bool spawned_;
6410  // The exit status of the child process.
6411  int status_;
6412  // How the death test concluded.
6413  DeathTestOutcome outcome_;
6414  // Descriptor to the read end of the pipe to the child process.  It is
6415  // always -1 in the child process.  The child keeps its write end of the
6416  // pipe in write_fd_.
6417  int read_fd_;
6418  // Descriptor to the child's write end of the pipe to the parent process.
6419  // It is always -1 in the parent process.  The parent keeps its end of the
6420  // pipe in read_fd_.
6421  int write_fd_;
6422};
6423
6424// Called in the parent process only. Reads the result code of the death
6425// test child process via a pipe, interprets it to set the outcome_
6426// member, and closes read_fd_.  Outputs diagnostics and terminates in
6427// case of unexpected codes.
6428void DeathTestImpl::ReadAndInterpretStatusByte() {
6429  char flag;
6430  int bytes_read;
6431
6432  // The read() here blocks until data is available (signifying the
6433  // failure of the death test) or until the pipe is closed (signifying
6434  // its success), so it's okay to call this in the parent before
6435  // the child process has exited.
6436  do {
6437    bytes_read = posix::Read(read_fd(), &flag, 1);
6438  } while (bytes_read == -1 && errno == EINTR);
6439
6440  if (bytes_read == 0) {
6441    set_outcome(DIED);
6442  } else if (bytes_read == 1) {
6443    switch (flag) {
6444      case kDeathTestReturned:
6445        set_outcome(RETURNED);
6446        break;
6447      case kDeathTestLived:
6448        set_outcome(LIVED);
6449        break;
6450      case kDeathTestInternalError:
6451        FailFromInternalError(read_fd());  // Does not return.
6452        break;
6453      default:
6454        GTEST_LOG_(FATAL) << "Death test child process reported "
6455                          << "unexpected status byte ("
6456                          << static_cast<unsigned int>(flag) << ")";
6457    }
6458  } else {
6459    GTEST_LOG_(FATAL) << "Read from death test child process failed: "
6460                      << GetLastErrnoDescription();
6461  }
6462  GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Close(read_fd()));
6463  set_read_fd(-1);
6464}
6465
6466// Signals that the death test code which should have exited, didn't.
6467// Should be called only in a death test child process.
6468// Writes a status byte to the child's status file descriptor, then
6469// calls _exit(1).
6470void DeathTestImpl::Abort(AbortReason reason) {
6471  // The parent process considers the death test to be a failure if
6472  // it finds any data in our pipe.  So, here we write a single flag byte
6473  // to the pipe, then exit.
6474  const char status_ch =
6475      reason == TEST_DID_NOT_DIE ? kDeathTestLived : kDeathTestReturned;
6476  GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Write(write_fd(), &status_ch, 1));
6477  GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Close(write_fd()));
6478  _exit(1);  // Exits w/o any normal exit hooks (we were supposed to crash)
6479}
6480
6481// Assesses the success or failure of a death test, using both private
6482// members which have previously been set, and one argument:
6483//
6484// Private data members:
6485//   outcome:  An enumeration describing how the death test
6486//             concluded: DIED, LIVED, or RETURNED.  The death test fails
6487//             in the latter two cases.
6488//   status:   The exit status of the child process. On *nix, it is in the
6489//             in the format specified by wait(2). On Windows, this is the
6490//             value supplied to the ExitProcess() API or a numeric code
6491//             of the exception that terminated the program.
6492//   regex:    A regular expression object to be applied to
6493//             the test's captured standard error output; the death test
6494//             fails if it does not match.
6495//
6496// Argument:
6497//   status_ok: true if exit_status is acceptable in the context of
6498//              this particular death test, which fails if it is false
6499//
6500// Returns true iff all of the above conditions are met.  Otherwise, the
6501// first failing condition, in the order given above, is the one that is
6502// reported. Also sets the last death test message string.
6503bool DeathTestImpl::Passed(bool status_ok) {
6504  if (!spawned())
6505    return false;
6506
6507  const String error_message = GetCapturedStderr();
6508
6509  bool success = false;
6510  Message buffer;
6511
6512  buffer << "Death test: " << statement() << "\n";
6513  switch (outcome()) {
6514    case LIVED:
6515      buffer << "    Result: failed to die.\n"
6516             << " Error msg: " << error_message;
6517      break;
6518    case RETURNED:
6519      buffer << "    Result: illegal return in test statement.\n"
6520             << " Error msg: " << error_message;
6521      break;
6522    case DIED:
6523      if (status_ok) {
6524        const bool matched = RE::PartialMatch(error_message.c_str(), *regex());
6525        if (matched) {
6526          success = true;
6527        } else {
6528          buffer << "    Result: died but not with expected error.\n"
6529                 << "  Expected: " << regex()->pattern() << "\n"
6530                 << "Actual msg: " << error_message;
6531        }
6532      } else {
6533        buffer << "    Result: died but not with expected exit code:\n"
6534               << "            " << ExitSummary(status()) << "\n";
6535      }
6536      break;
6537    case IN_PROGRESS:
6538    default:
6539      GTEST_LOG_(FATAL)
6540          << "DeathTest::Passed somehow called before conclusion of test";
6541  }
6542
6543  DeathTest::set_last_death_test_message(buffer.GetString());
6544  return success;
6545}
6546
6547#if GTEST_OS_WINDOWS
6548// WindowsDeathTest implements death tests on Windows. Due to the
6549// specifics of starting new processes on Windows, death tests there are
6550// always threadsafe, and Google Test considers the
6551// --gtest_death_test_style=fast setting to be equivalent to
6552// --gtest_death_test_style=threadsafe there.
6553//
6554// A few implementation notes:  Like the Linux version, the Windows
6555// implementation uses pipes for child-to-parent communication. But due to
6556// the specifics of pipes on Windows, some extra steps are required:
6557//
6558// 1. The parent creates a communication pipe and stores handles to both
6559//    ends of it.
6560// 2. The parent starts the child and provides it with the information
6561//    necessary to acquire the handle to the write end of the pipe.
6562// 3. The child acquires the write end of the pipe and signals the parent
6563//    using a Windows event.
6564// 4. Now the parent can release the write end of the pipe on its side. If
6565//    this is done before step 3, the object's reference count goes down to
6566//    0 and it is destroyed, preventing the child from acquiring it. The
6567//    parent now has to release it, or read operations on the read end of
6568//    the pipe will not return when the child terminates.
6569// 5. The parent reads child's output through the pipe (outcome code and
6570//    any possible error messages) from the pipe, and its stderr and then
6571//    determines whether to fail the test.
6572//
6573// Note: to distinguish Win32 API calls from the local method and function
6574// calls, the former are explicitly resolved in the global namespace.
6575//
6576class WindowsDeathTest : public DeathTestImpl {
6577 public:
6578  WindowsDeathTest(const char* statement,
6579                   const RE* regex,
6580                   const char* file,
6581                   int line)
6582      : DeathTestImpl(statement, regex), file_(file), line_(line) {}
6583
6584  // All of these virtual functions are inherited from DeathTest.
6585  virtual int Wait();
6586  virtual TestRole AssumeRole();
6587
6588 private:
6589  // The name of the file in which the death test is located.
6590  const char* const file_;
6591  // The line number on which the death test is located.
6592  const int line_;
6593  // Handle to the write end of the pipe to the child process.
6594  AutoHandle write_handle_;
6595  // Child process handle.
6596  AutoHandle child_handle_;
6597  // Event the child process uses to signal the parent that it has
6598  // acquired the handle to the write end of the pipe. After seeing this
6599  // event the parent can release its own handles to make sure its
6600  // ReadFile() calls return when the child terminates.
6601  AutoHandle event_handle_;
6602};
6603
6604// Waits for the child in a death test to exit, returning its exit
6605// status, or 0 if no child process exists.  As a side effect, sets the
6606// outcome data member.
6607int WindowsDeathTest::Wait() {
6608  if (!spawned())
6609    return 0;
6610
6611  // Wait until the child either signals that it has acquired the write end
6612  // of the pipe or it dies.
6613  const HANDLE wait_handles[2] = { child_handle_.Get(), event_handle_.Get() };
6614  switch (::WaitForMultipleObjects(2,
6615                                   wait_handles,
6616                                   FALSE,  // Waits for any of the handles.
6617                                   INFINITE)) {
6618    case WAIT_OBJECT_0:
6619    case WAIT_OBJECT_0 + 1:
6620      break;
6621    default:
6622      GTEST_DEATH_TEST_CHECK_(false);  // Should not get here.
6623  }
6624
6625  // The child has acquired the write end of the pipe or exited.
6626  // We release the handle on our side and continue.
6627  write_handle_.Reset();
6628  event_handle_.Reset();
6629
6630  ReadAndInterpretStatusByte();
6631
6632  // Waits for the child process to exit if it haven't already. This
6633  // returns immediately if the child has already exited, regardless of
6634  // whether previous calls to WaitForMultipleObjects synchronized on this
6635  // handle or not.
6636  GTEST_DEATH_TEST_CHECK_(
6637      WAIT_OBJECT_0 == ::WaitForSingleObject(child_handle_.Get(),
6638                                             INFINITE));
6639  DWORD status;
6640  GTEST_DEATH_TEST_CHECK_(::GetExitCodeProcess(child_handle_.Get(), &status)
6641                          != FALSE);
6642  child_handle_.Reset();
6643  set_status(static_cast<int>(status));
6644  return this->status();
6645}
6646
6647// The AssumeRole process for a Windows death test.  It creates a child
6648// process with the same executable as the current process to run the
6649// death test.  The child process is given the --gtest_filter and
6650// --gtest_internal_run_death_test flags such that it knows to run the
6651// current death test only.
6652DeathTest::TestRole WindowsDeathTest::AssumeRole() {
6653  const UnitTestImpl* const impl = GetUnitTestImpl();
6654  const InternalRunDeathTestFlag* const flag =
6655      impl->internal_run_death_test_flag();
6656  const TestInfo* const info = impl->current_test_info();
6657  const int death_test_index = info->result()->death_test_count();
6658
6659  if (flag != NULL) {
6660    // ParseInternalRunDeathTestFlag() has performed all the necessary
6661    // processing.
6662    set_write_fd(flag->write_fd());
6663    return EXECUTE_TEST;
6664  }
6665
6666  // WindowsDeathTest uses an anonymous pipe to communicate results of
6667  // a death test.
6668  SECURITY_ATTRIBUTES handles_are_inheritable = {
6669    sizeof(SECURITY_ATTRIBUTES), NULL, TRUE };
6670  HANDLE read_handle, write_handle;
6671  GTEST_DEATH_TEST_CHECK_(
6672      ::CreatePipe(&read_handle, &write_handle, &handles_are_inheritable,
6673                   0)  // Default buffer size.
6674      != FALSE);
6675  set_read_fd(::_open_osfhandle(reinterpret_cast<intptr_t>(read_handle),
6676                                O_RDONLY));
6677  write_handle_.Reset(write_handle);
6678  event_handle_.Reset(::CreateEvent(
6679      &handles_are_inheritable,
6680      TRUE,    // The event will automatically reset to non-signaled state.
6681      FALSE,   // The initial state is non-signalled.
6682      NULL));  // The even is unnamed.
6683  GTEST_DEATH_TEST_CHECK_(event_handle_.Get() != NULL);
6684  const String filter_flag = String::Format("--%s%s=%s.%s",
6685                                            GTEST_FLAG_PREFIX_, kFilterFlag,
6686                                            info->test_case_name(),
6687                                            info->name());
6688  const String internal_flag = String::Format(
6689    "--%s%s=%s|%d|%d|%u|%Iu|%Iu",
6690      GTEST_FLAG_PREFIX_,
6691      kInternalRunDeathTestFlag,
6692      file_, line_,
6693      death_test_index,
6694      static_cast<unsigned int>(::GetCurrentProcessId()),
6695      // size_t has the same with as pointers on both 32-bit and 64-bit
6696      // Windows platforms.
6697      // See http://msdn.microsoft.com/en-us/library/tcxf1dw6.aspx.
6698      reinterpret_cast<size_t>(write_handle),
6699      reinterpret_cast<size_t>(event_handle_.Get()));
6700
6701  char executable_path[_MAX_PATH + 1];  // NOLINT
6702  GTEST_DEATH_TEST_CHECK_(
6703      _MAX_PATH + 1 != ::GetMo