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 #include "gtest.h"
40 
41 // The following lines pull in the real gtest *.cc files.
42 // Copyright 2005, Google Inc.
43 // All rights reserved.
44 //
45 // Redistribution and use in source and binary forms, with or without
46 // modification, are permitted provided that the following conditions are
47 // met:
48 //
49 //     * Redistributions of source code must retain the above copyright
50 // notice, this list of conditions and the following disclaimer.
51 //     * Redistributions in binary form must reproduce the above
52 // copyright notice, this list of conditions and the following disclaimer
53 // in the documentation and/or other materials provided with the
54 // distribution.
55 //     * Neither the name of Google Inc. nor the names of its
56 // contributors may be used to endorse or promote products derived from
57 // this software without specific prior written permission.
58 //
59 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
60 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
61 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
62 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
63 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
64 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
65 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
66 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
67 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
68 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
69 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
70 //
71 // Author: wan@google.com (Zhanyong Wan)
72 //
73 // The Google C++ Testing Framework (Google Test)
74 
75 // Copyright 2007, Google Inc.
76 // All rights reserved.
77 //
78 // Redistribution and use in source and binary forms, with or without
79 // modification, are permitted provided that the following conditions are
80 // met:
81 //
82 //     * Redistributions of source code must retain the above copyright
83 // notice, this list of conditions and the following disclaimer.
84 //     * Redistributions in binary form must reproduce the above
85 // copyright notice, this list of conditions and the following disclaimer
86 // in the documentation and/or other materials provided with the
87 // distribution.
88 //     * Neither the name of Google Inc. nor the names of its
89 // contributors may be used to endorse or promote products derived from
90 // this software without specific prior written permission.
91 //
92 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
93 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
94 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
95 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
96 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
97 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
98 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
99 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
100 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
101 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
102 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
103 //
104 // Author: wan@google.com (Zhanyong Wan)
105 //
106 // Utilities for testing Google Test itself and code that uses Google Test
107 // (e.g. frameworks built on top of Google Test).
108 
109 #ifndef GTEST_INCLUDE_GTEST_GTEST_SPI_H_
110 #  define GTEST_INCLUDE_GTEST_GTEST_SPI_H_
111 
112 namespace testing {
113 
114 // This helper class can be used to mock out Google Test failure reporting
115 // so that we can test Google Test or code that builds on Google Test.
116 //
117 // An object of this class appends a TestPartResult object to the
118 // TestPartResultArray object given in the constructor whenever a Google Test
119 // failure is reported. It can either intercept only failures that are
120 // generated in the same thread that created this object or it can intercept
121 // all generated failures. The scope of this mock object can be controlled with
122 // the second argument to the two arguments constructor.
123 class GTEST_API_ ScopedFakeTestPartResultReporter
124     : public TestPartResultReporterInterface {
125  public:
126   // The two possible mocking modes of this object.
127   enum InterceptMode {
128     INTERCEPT_ONLY_CURRENT_THREAD,  // Intercepts only thread local failures.
129     INTERCEPT_ALL_THREADS           // Intercepts all failures.
130   };
131 
132   // The c'tor sets this object as the test part result reporter used
133   // by Google Test.  The 'result' parameter specifies where to report the
134   // results. This reporter will only catch failures generated in the current
135   // thread. DEPRECATED
136   explicit ScopedFakeTestPartResultReporter(TestPartResultArray* result);
137 
138   // Same as above, but you can choose the interception scope of this object.
139   ScopedFakeTestPartResultReporter(InterceptMode intercept_mode,
140                                    TestPartResultArray* result);
141 
142   // The d'tor restores the previous test part result reporter.
143   virtual ~ScopedFakeTestPartResultReporter();
144 
145   // Appends the TestPartResult object to the TestPartResultArray
146   // received in the constructor.
147   //
148   // This method is from the TestPartResultReporterInterface
149   // interface.
150   virtual void ReportTestPartResult(const TestPartResult& result);
151 
152  private:
153   void Init();
154 
155   const InterceptMode intercept_mode_;
156   TestPartResultReporterInterface* old_reporter_;
157   TestPartResultArray* const result_;
158 
159   GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedFakeTestPartResultReporter);
160 };
161 
162 namespace internal {
163 
164 // A helper class for implementing EXPECT_FATAL_FAILURE() and
165 // EXPECT_NONFATAL_FAILURE().  Its destructor verifies that the given
166 // TestPartResultArray contains exactly one failure that has the given
167 // type and contains the given substring.  If that's not the case, a
168 // non-fatal failure will be generated.
169 class GTEST_API_ SingleFailureChecker {
170  public:
171   // The constructor remembers the arguments.
172   SingleFailureChecker(const TestPartResultArray* results,
173                        TestPartResult::Type type, const string& substr);
174   ~SingleFailureChecker();
175 
176  private:
177   const TestPartResultArray* const results_;
178   const TestPartResult::Type type_;
179   const string substr_;
180 
181   GTEST_DISALLOW_COPY_AND_ASSIGN_(SingleFailureChecker);
182 };
183 
184 }  // namespace internal
185 
186 }  // namespace testing
187 
188 // A set of macros for testing Google Test assertions or code that's expected
189 // to generate Google Test fatal failures.  It verifies that the given
190 // statement will cause exactly one fatal Google Test failure with 'substr'
191 // being part of the failure message.
192 //
193 // There are two different versions of this macro. EXPECT_FATAL_FAILURE only
194 // affects and considers failures generated in the current thread and
195 // EXPECT_FATAL_FAILURE_ON_ALL_THREADS does the same but for all threads.
196 //
197 // The verification of the assertion is done correctly even when the statement
198 // throws an exception or aborts the current function.
199 //
200 // Known restrictions:
201 //   - 'statement' cannot reference local non-static variables or
202 //     non-static members of the current object.
203 //   - 'statement' cannot return a value.
204 //   - You cannot stream a failure message to this macro.
205 //
206 // Note that even though the implementations of the following two
207 // macros are much alike, we cannot refactor them to use a common
208 // helper macro, due to some peculiarity in how the preprocessor
209 // works.  The AcceptsMacroThatExpandsToUnprotectedComma test in
210 // gtest_unittest.cc will fail to compile if we do that.
211 #  define EXPECT_FATAL_FAILURE(statement, substr)                    \
212     do {                                                             \
213       class GTestExpectFatalFailureHelper {                          \
214        public:                                                       \
215         static void Execute() { statement; }                         \
216       };                                                             \
217       ::testing::TestPartResultArray gtest_failures;                 \
218       ::testing::internal::SingleFailureChecker gtest_checker(       \
219           &gtest_failures, ::testing::TestPartResult::kFatalFailure, \
220           (substr));                                                 \
221       {                                                              \
222         ::testing::ScopedFakeTestPartResultReporter gtest_reporter(  \
223             ::testing::ScopedFakeTestPartResultReporter::            \
224                 INTERCEPT_ONLY_CURRENT_THREAD,                       \
225             &gtest_failures);                                        \
226         GTestExpectFatalFailureHelper::Execute();                    \
227       }                                                              \
228     } while (::testing::internal::AlwaysFalse())
229 
230 #  define EXPECT_FATAL_FAILURE_ON_ALL_THREADS(statement, substr)     \
231     do {                                                             \
232       class GTestExpectFatalFailureHelper {                          \
233        public:                                                       \
234         static void Execute() { statement; }                         \
235       };                                                             \
236       ::testing::TestPartResultArray gtest_failures;                 \
237       ::testing::internal::SingleFailureChecker gtest_checker(       \
238           &gtest_failures, ::testing::TestPartResult::kFatalFailure, \
239           (substr));                                                 \
240       {                                                              \
241         ::testing::ScopedFakeTestPartResultReporter gtest_reporter(  \
242             ::testing::ScopedFakeTestPartResultReporter::            \
243                 INTERCEPT_ALL_THREADS,                               \
244             &gtest_failures);                                        \
245         GTestExpectFatalFailureHelper::Execute();                    \
246       }                                                              \
247     } while (::testing::internal::AlwaysFalse())
248 
249 // A macro for testing Google Test assertions or code that's expected to
250 // generate Google Test non-fatal failures.  It asserts that the given
251 // statement will cause exactly one non-fatal Google Test failure with 'substr'
252 // being part of the failure message.
253 //
254 // There are two different versions of this macro. EXPECT_NONFATAL_FAILURE only
255 // affects and considers failures generated in the current thread and
256 // EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS does the same but for all threads.
257 //
258 // 'statement' is allowed to reference local variables and members of
259 // the current object.
260 //
261 // The verification of the assertion is done correctly even when the statement
262 // throws an exception or aborts the current function.
263 //
264 // Known restrictions:
265 //   - You cannot stream a failure message to this macro.
266 //
267 // Note that even though the implementations of the following two
268 // macros are much alike, we cannot refactor them to use a common
269 // helper macro, due to some peculiarity in how the preprocessor
270 // works.  If we do that, the code won't compile when the user gives
271 // EXPECT_NONFATAL_FAILURE() a statement that contains a macro that
272 // expands to code containing an unprotected comma.  The
273 // AcceptsMacroThatExpandsToUnprotectedComma test in gtest_unittest.cc
274 // catches that.
275 //
276 // For the same reason, we have to write
277 //   if (::testing::internal::AlwaysTrue()) { statement; }
278 // instead of
279 //   GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement)
280 // to avoid an MSVC warning on unreachable code.
281 #  define EXPECT_NONFATAL_FAILURE(statement, substr)                    \
282     do {                                                                \
283       ::testing::TestPartResultArray gtest_failures;                    \
284       ::testing::internal::SingleFailureChecker gtest_checker(          \
285           &gtest_failures, ::testing::TestPartResult::kNonFatalFailure, \
286           (substr));                                                    \
287       {                                                                 \
288         ::testing::ScopedFakeTestPartResultReporter gtest_reporter(     \
289             ::testing::ScopedFakeTestPartResultReporter::               \
290                 INTERCEPT_ONLY_CURRENT_THREAD,                          \
291             &gtest_failures);                                           \
292         if (::testing::internal::AlwaysTrue()) {                        \
293           statement;                                                    \
294         }                                                               \
295       }                                                                 \
296     } while (::testing::internal::AlwaysFalse())
297 
298 #  define EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(statement, substr)     \
299     do {                                                                \
300       ::testing::TestPartResultArray gtest_failures;                    \
301       ::testing::internal::SingleFailureChecker gtest_checker(          \
302           &gtest_failures, ::testing::TestPartResult::kNonFatalFailure, \
303           (substr));                                                    \
304       {                                                                 \
305         ::testing::ScopedFakeTestPartResultReporter gtest_reporter(     \
306             ::testing::ScopedFakeTestPartResultReporter::               \
307                 INTERCEPT_ALL_THREADS,                                  \
308             &gtest_failures);                                           \
309         if (::testing::internal::AlwaysTrue()) {                        \
310           statement;                                                    \
311         }                                                               \
312       }                                                                 \
313     } while (::testing::internal::AlwaysFalse())
314 
315 #endif  // GTEST_INCLUDE_GTEST_GTEST_SPI_H_
316 
317 #include <ctype.h>
318 #include <math.h>
319 #include <stdarg.h>
320 #include <stdio.h>
321 #include <stdlib.h>
322 #include <time.h>
323 #include <wchar.h>
324 #include <wctype.h>
325 
326 #include <algorithm>
327 #include <iomanip>
328 #include <limits>
329 #include <ostream>  // NOLINT
330 #include <sstream>
331 #include <vector>
332 
333 #if GTEST_OS_LINUX
334 
335 // TODO(kenton@google.com): Use autoconf to detect availability of
336 // gettimeofday().
337 #  define GTEST_HAS_GETTIMEOFDAY_ 1
338 
339 #  include <fcntl.h>   // NOLINT
340 #  include <limits.h>  // NOLINT
341 #  include <sched.h>   // NOLINT
342 // Declares vsnprintf().  This header is not available on Windows.
343 #  include <strings.h>   // NOLINT
344 #  include <sys/mman.h>  // NOLINT
345 #  include <sys/time.h>  // NOLINT
346 #  include <unistd.h>    // NOLINT
347 #  include <string>
348 
349 #elif GTEST_OS_SYMBIAN
350 #  define GTEST_HAS_GETTIMEOFDAY_ 1
351 #  include <sys/time.h>  // NOLINT
352 
353 #elif GTEST_OS_ZOS
354 #  define GTEST_HAS_GETTIMEOFDAY_ 1
355 #  include <sys/time.h>  // NOLINT
356 
357 // On z/OS we additionally need strings.h for strcasecmp.
358 #  include <strings.h>   // NOLINT
359 
360 #elif GTEST_OS_WINDOWS_MOBILE  // We are on Windows CE.
361 
362 #  include <windows.h>  // NOLINT
363 
364 #elif GTEST_OS_WINDOWS  // We are on Windows proper.
365 
366 #  include <io.h>         // NOLINT
367 #  include <sys/stat.h>   // NOLINT
368 #  include <sys/timeb.h>  // NOLINT
369 #  include <sys/types.h>  // NOLINT
370 
371 #  if GTEST_OS_WINDOWS_MINGW
372 // MinGW has gettimeofday() but not _ftime64().
373 // TODO(kenton@google.com): Use autoconf to detect availability of
374 //   gettimeofday().
375 // TODO(kenton@google.com): There are other ways to get the time on
376 //   Windows, like GetTickCount() or GetSystemTimeAsFileTime().  MinGW
377 //   supports these.  consider using them instead.
378 #    define GTEST_HAS_GETTIMEOFDAY_ 1
379 #    include <sys/time.h>  // NOLINT
380 #  endif                   // GTEST_OS_WINDOWS_MINGW
381 
382 // cpplint thinks that the header is already included, so we want to
383 // silence it.
384 #  include <windows.h>     // NOLINT
385 
386 #else
387 
388 // Assume other platforms have gettimeofday().
389 // TODO(kenton@google.com): Use autoconf to detect availability of
390 //   gettimeofday().
391 #  define GTEST_HAS_GETTIMEOFDAY_ 1
392 
393 // cpplint thinks that the header is already included, so we want to
394 // silence it.
395 #  include <sys/time.h>  // NOLINT
396 #  include <unistd.h>    // NOLINT
397 
398 #endif  // GTEST_OS_LINUX
399 
400 #if GTEST_HAS_EXCEPTIONS
401 #  include <stdexcept>
402 #endif
403 
404 #if GTEST_CAN_STREAM_RESULTS_
405 #  include <arpa/inet.h>  // NOLINT
406 #  include <netdb.h>      // NOLINT
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 \
459         "gtest-internal-inl.h is part of Google Test's internal implementation."
460 #    error "It must not be included except by Google Test itself."
461 #  endif  // GTEST_IMPLEMENTATION_
462 
463 #  ifndef _WIN32_WCE
464 #    include <errno.h>
465 #  endif  // !_WIN32_WCE
466 #  include <stddef.h>
467 #  include <stdlib.h>  // For strtoll/_strtoul64/malloc/free.
468 #  include <string.h>  // For memmove.
469 
470 #  include <algorithm>
471 #  include <string>
472 #  include <vector>
473 
474 #  if GTEST_CAN_STREAM_RESULTS_
475 #    include <arpa/inet.h>  // NOLINT
476 #    include <netdb.h>      // NOLINT
477 #  endif
478 
479 #  if GTEST_OS_WINDOWS
480 #    include <windows.h>  // NOLINT
481 #  endif                  // GTEST_OS_WINDOWS
482 
483 namespace testing {
484 
485 // Declares the flags.
486 //
487 // We don't want the users to modify this flag in the code, but want
488 // Google Test's own unit tests to be able to access it. Therefore we
489 // declare it here as opposed to in gtest.h.
490 GTEST_DECLARE_bool_(death_test_use_fork);
491 
492 namespace internal {
493 
494 // The value of GetTestTypeId() as seen from within the Google Test
495 // library.  This is solely for testing GetTestTypeId().
496 GTEST_API_ extern const TypeId kTestTypeIdInGoogleTest;
497 
498 // Names of the flags (needed for parsing Google Test flags).
499 const char kAlsoRunDisabledTestsFlag[] = "also_run_disabled_tests";
500 const char kBreakOnFailureFlag[] = "break_on_failure";
501 const char kCatchExceptionsFlag[] = "catch_exceptions";
502 const char kColorFlag[] = "color";
503 const char kFilterFlag[] = "filter";
504 const char kListTestsFlag[] = "list_tests";
505 const char kOutputFlag[] = "output";
506 const char kPrintTimeFlag[] = "print_time";
507 const char kRandomSeedFlag[] = "random_seed";
508 const char kRepeatFlag[] = "repeat";
509 const char kShuffleFlag[] = "shuffle";
510 const char kStackTraceDepthFlag[] = "stack_trace_depth";
511 const char kStreamResultToFlag[] = "stream_result_to";
512 const char kThrowOnFailureFlag[] = "throw_on_failure";
513 
514 // A valid random seed must be in [1, kMaxRandomSeed].
515 const int kMaxRandomSeed = 99999;
516 
517 // g_help_flag is true iff the --help flag or an equivalent form is
518 // specified on the command line.
519 GTEST_API_ extern bool g_help_flag;
520 
521 // Returns the current time in milliseconds.
522 GTEST_API_ TimeInMillis GetTimeInMillis();
523 
524 // Returns true iff Google Test should use colors in the output.
525 GTEST_API_ bool ShouldUseColor(bool stdout_is_tty);
526 
527 // Formats the given time in milliseconds as seconds.
528 GTEST_API_ std::string FormatTimeInMillisAsSeconds(TimeInMillis ms);
529 
530 // Converts the given time in milliseconds to a date string in the ISO 8601
531 // format, without the timezone information.  N.B.: due to the use the
532 // non-reentrant localtime() function, this function is not thread safe.  Do
533 // not use it in any code that can be called from multiple threads.
534 GTEST_API_ std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms);
535 
536 // Parses a string for an Int32 flag, in the form of "--flag=value".
537 //
538 // On success, stores the value of the flag in *value, and returns
539 // true.  On failure, returns false without changing *value.
540 GTEST_API_ bool ParseInt32Flag(const char* str, const char* flag, Int32* value);
541 
542 // Returns a random seed in range [1, kMaxRandomSeed] based on the
543 // given --gtest_random_seed flag value.
GetRandomSeedFromFlag(Int32 random_seed_flag)544 inline int GetRandomSeedFromFlag(Int32 random_seed_flag) {
545   const unsigned int raw_seed =
546       (random_seed_flag == 0) ? static_cast<unsigned int>(GetTimeInMillis())
547                               : static_cast<unsigned int>(random_seed_flag);
548 
549   // Normalizes the actual seed to range [1, kMaxRandomSeed] such that
550   // it's easy to type.
551   const int normalized_seed =
552       static_cast<int>((raw_seed - 1U) %
553                        static_cast<unsigned int>(kMaxRandomSeed)) +
554       1;
555   return normalized_seed;
556 }
557 
558 // Returns the first valid random seed after 'seed'.  The behavior is
559 // undefined if 'seed' is invalid.  The seed after kMaxRandomSeed is
560 // considered to be 1.
GetNextRandomSeed(int seed)561 inline int GetNextRandomSeed(int seed) {
562   GTEST_CHECK_(1 <= seed && seed <= kMaxRandomSeed)
563       << "Invalid random seed " << seed << " - must be in [1, "
564       << kMaxRandomSeed << "].";
565   const int next_seed = seed + 1;
566   return (next_seed > kMaxRandomSeed) ? 1 : next_seed;
567 }
568 
569 // This class saves the values of all Google Test flags in its c'tor, and
570 // restores them in its d'tor.
571 class GTestFlagSaver {
572  public:
573   // The c'tor.
GTestFlagSaver()574   GTestFlagSaver() {
575     also_run_disabled_tests_ = GTEST_FLAG(also_run_disabled_tests);
576     break_on_failure_ = GTEST_FLAG(break_on_failure);
577     catch_exceptions_ = GTEST_FLAG(catch_exceptions);
578     color_ = GTEST_FLAG(color);
579     death_test_style_ = GTEST_FLAG(death_test_style);
580     death_test_use_fork_ = GTEST_FLAG(death_test_use_fork);
581     filter_ = GTEST_FLAG(filter);
582     internal_run_death_test_ = GTEST_FLAG(internal_run_death_test);
583     list_tests_ = GTEST_FLAG(list_tests);
584     output_ = GTEST_FLAG(output);
585     print_time_ = GTEST_FLAG(print_time);
586     random_seed_ = GTEST_FLAG(random_seed);
587     repeat_ = GTEST_FLAG(repeat);
588     shuffle_ = GTEST_FLAG(shuffle);
589     stack_trace_depth_ = GTEST_FLAG(stack_trace_depth);
590     stream_result_to_ = GTEST_FLAG(stream_result_to);
591     throw_on_failure_ = GTEST_FLAG(throw_on_failure);
592   }
593 
594   // The d'tor is not virtual.  DO NOT INHERIT FROM THIS CLASS.
~GTestFlagSaver()595   ~GTestFlagSaver() {
596     GTEST_FLAG(also_run_disabled_tests) = also_run_disabled_tests_;
597     GTEST_FLAG(break_on_failure) = break_on_failure_;
598     GTEST_FLAG(catch_exceptions) = catch_exceptions_;
599     GTEST_FLAG(color) = color_;
600     GTEST_FLAG(death_test_style) = death_test_style_;
601     GTEST_FLAG(death_test_use_fork) = death_test_use_fork_;
602     GTEST_FLAG(filter) = filter_;
603     GTEST_FLAG(internal_run_death_test) = internal_run_death_test_;
604     GTEST_FLAG(list_tests) = list_tests_;
605     GTEST_FLAG(output) = output_;
606     GTEST_FLAG(print_time) = print_time_;
607     GTEST_FLAG(random_seed) = random_seed_;
608     GTEST_FLAG(repeat) = repeat_;
609     GTEST_FLAG(shuffle) = shuffle_;
610     GTEST_FLAG(stack_trace_depth) = stack_trace_depth_;
611     GTEST_FLAG(stream_result_to) = stream_result_to_;
612     GTEST_FLAG(throw_on_failure) = throw_on_failure_;
613   }
614 
615  private:
616   // Fields for saving the original values of flags.
617   bool also_run_disabled_tests_;
618   bool break_on_failure_;
619   bool catch_exceptions_;
620   std::string color_;
621   std::string death_test_style_;
622   bool death_test_use_fork_;
623   std::string filter_;
624   std::string internal_run_death_test_;
625   bool list_tests_;
626   std::string output_;
627   bool print_time_;
628   internal::Int32 random_seed_;
629   internal::Int32 repeat_;
630   bool shuffle_;
631   internal::Int32 stack_trace_depth_;
632   std::string stream_result_to_;
633   bool throw_on_failure_;
634 } GTEST_ATTRIBUTE_UNUSED_;
635 
636 // Converts a Unicode code point to a narrow string in UTF-8 encoding.
637 // code_point parameter is of type UInt32 because wchar_t may not be
638 // wide enough to contain a code point.
639 // If the code_point is not a valid Unicode code point
640 // (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted
641 // to "(Invalid Unicode 0xXXXXXXXX)".
642 GTEST_API_ std::string CodePointToUtf8(UInt32 code_point);
643 
644 // Converts a wide string to a narrow string in UTF-8 encoding.
645 // The wide string is assumed to have the following encoding:
646 //   UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS)
647 //   UTF-32 if sizeof(wchar_t) == 4 (on Linux)
648 // Parameter str points to a null-terminated wide string.
649 // Parameter num_chars may additionally limit the number
650 // of wchar_t characters processed. -1 is used when the entire string
651 // should be processed.
652 // If the string contains code points that are not valid Unicode code points
653 // (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
654 // as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
655 // and contains invalid UTF-16 surrogate pairs, values in those pairs
656 // will be encoded as individual Unicode characters from Basic Normal Plane.
657 GTEST_API_ std::string WideStringToUtf8(const wchar_t* str, int num_chars);
658 
659 // Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
660 // if the variable is present. If a file already exists at this location, this
661 // function will write over it. If the variable is present, but the file cannot
662 // be created, prints an error and exits.
663 void WriteToShardStatusFileIfNeeded();
664 
665 // Checks whether sharding is enabled by examining the relevant
666 // environment variable values. If the variables are present,
667 // but inconsistent (e.g., shard_index >= total_shards), prints
668 // an error and exits. If in_subprocess_for_death_test, sharding is
669 // disabled because it must only be applied to the original test
670 // process. Otherwise, we could filter out death tests we intended to execute.
671 GTEST_API_ bool ShouldShard(const char* total_shards_str,
672                             const char* shard_index_str,
673                             bool in_subprocess_for_death_test);
674 
675 // Parses the environment variable var as an Int32. If it is unset,
676 // returns default_val. If it is not an Int32, prints an error and
677 // and aborts.
678 GTEST_API_ Int32 Int32FromEnvOrDie(const char* env_var, Int32 default_val);
679 
680 // Given the total number of shards, the shard index, and the test id,
681 // returns true iff the test should be run on this shard. The test id is
682 // some arbitrary but unique non-negative integer assigned to each test
683 // method. Assumes that 0 <= shard_index < total_shards.
684 GTEST_API_ bool ShouldRunTestOnShard(int total_shards, int shard_index,
685                                      int test_id);
686 
687 // STL container utilities.
688 
689 // Returns the number of elements in the given container that satisfy
690 // the given predicate.
691 template <class Container, typename Predicate>
CountIf(const Container & c,Predicate predicate)692 inline int CountIf(const Container& c, Predicate predicate) {
693   // Implemented as an explicit loop since std::count_if() in libCstd on
694   // Solaris has a non-standard signature.
695   int count = 0;
696   for (typename Container::const_iterator it = c.begin(); it != c.end(); ++it) {
697     if (predicate(*it)) ++count;
698   }
699   return count;
700 }
701 
702 // Applies a function/functor to each element in the container.
703 template <class Container, typename Functor>
ForEach(const Container & c,Functor functor)704 void ForEach(const Container& c, Functor functor) {
705   std::for_each(c.begin(), c.end(), functor);
706 }
707 
708 // Returns the i-th element of the vector, or default_value if i is not
709 // in range [0, v.size()).
710 template <typename E>
GetElementOr(const std::vector<E> & v,int i,E default_value)711 inline E GetElementOr(const std::vector<E>& v, int i, E default_value) {
712   return (i < 0 || i >= static_cast<int>(v.size())) ? default_value : v[i];
713 }
714 
715 // Performs an in-place shuffle of a range of the vector's elements.
716 // 'begin' and 'end' are element indices as an STL-style range;
717 // i.e. [begin, end) are shuffled, where 'end' == size() means to
718 // shuffle to the end of the vector.
719 template <typename E>
ShuffleRange(internal::Random * random,int begin,int end,std::vector<E> * v)720 void ShuffleRange(internal::Random* random, int begin, int end,
721                   std::vector<E>* v) {
722   const int size = static_cast<int>(v->size());
723   GTEST_CHECK_(0 <= begin && begin <= size)
724       << "Invalid shuffle range start " << begin << ": must be in range [0, "
725       << size << "].";
726   GTEST_CHECK_(begin <= end && end <= size)
727       << "Invalid shuffle range finish " << end << ": must be in range ["
728       << begin << ", " << size << "].";
729 
730   // Fisher-Yates shuffle, from
731   // http://en.wikipedia.org/wiki/Fisher-Yates_shuffle
732   for (int range_width = end - begin; range_width >= 2; range_width--) {
733     const int last_in_range = begin + range_width - 1;
734     const int selected = begin + random->Generate(range_width);
735     std::swap((*v)[selected], (*v)[last_in_range]);
736   }
737 }
738 
739 // Performs an in-place shuffle of the vector's elements.
740 template <typename E>
Shuffle(internal::Random * random,std::vector<E> * v)741 inline void Shuffle(internal::Random* random, std::vector<E>* v) {
742   ShuffleRange(random, 0, static_cast<int>(v->size()), v);
743 }
744 
745 // A function for deleting an object.  Handy for being used as a
746 // functor.
Delete(T * x)747 template <typename T> static void Delete(T* x) { delete x; }
748 
749 // A predicate that checks the key of a TestProperty against a known key.
750 //
751 // TestPropertyKeyIs is copyable.
752 class TestPropertyKeyIs {
753  public:
754   // Constructor.
755   //
756   // TestPropertyKeyIs has NO default constructor.
TestPropertyKeyIs(const std::string & key)757   explicit TestPropertyKeyIs(const std::string& key) : key_(key) {}
758 
759   // Returns true iff the test name of test property matches on key_.
operator ()(const TestProperty & test_property) const760   bool operator()(const TestProperty& test_property) const {
761     return test_property.key() == key_;
762   }
763 
764  private:
765   std::string key_;
766 };
767 
768 // Class UnitTestOptions.
769 //
770 // This class contains functions for processing options the user
771 // specifies when running the tests.  It has only static members.
772 //
773 // In most cases, the user can specify an option using either an
774 // environment variable or a command line flag.  E.g. you can set the
775 // test filter using either GTEST_FILTER or --gtest_filter.  If both
776 // the variable and the flag are present, the latter overrides the
777 // former.
778 class GTEST_API_ UnitTestOptions {
779  public:
780   // Functions for processing the gtest_output flag.
781 
782   // Returns the output format, or "" for normal printed output.
783   static std::string GetOutputFormat();
784 
785   // Returns the absolute path of the requested output file, or the
786   // default (test_detail.xml in the original working directory) if
787   // none was explicitly specified.
788   static std::string GetAbsolutePathToOutputFile();
789 
790   // Functions for processing the gtest_filter flag.
791 
792   // Returns true iff the wildcard pattern matches the string.  The
793   // first ':' or '\0' character in pattern marks the end of it.
794   //
795   // This recursive algorithm isn't very efficient, but is clear and
796   // works well enough for matching test names, which are short.
797   static bool PatternMatchesString(const char* pattern, const char* str);
798 
799   // Returns true iff the user-specified filter matches the test case
800   // name and the test name.
801   static bool FilterMatchesTest(const std::string& test_case_name,
802                                 const std::string& test_name);
803 
804 #  if GTEST_OS_WINDOWS
805   // Function for supporting the gtest_catch_exception flag.
806 
807   // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
808   // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
809   // This function is useful as an __except condition.
810   static int GTestShouldProcessSEH(DWORD exception_code);
811 #  endif  // GTEST_OS_WINDOWS
812 
813   // Returns true if "name" matches the ':' separated list of glob-style
814   // filters in "filter".
815   static bool MatchesFilter(const std::string& name, const char* filter);
816 };
817 
818 // Returns the current application's name, removing directory path if that
819 // is present.  Used by UnitTestOptions::GetOutputFile.
820 GTEST_API_ FilePath GetCurrentExecutableName();
821 
822 // The role interface for getting the OS stack trace as a string.
823 class OsStackTraceGetterInterface {
824  public:
OsStackTraceGetterInterface()825   OsStackTraceGetterInterface() {}
~OsStackTraceGetterInterface()826   virtual ~OsStackTraceGetterInterface() {}
827 
828   // Returns the current OS stack trace as an std::string.  Parameters:
829   //
830   //   max_depth  - the maximum number of stack frames to be included
831   //                in the trace.
832   //   skip_count - the number of top frames to be skipped; doesn't count
833   //                against max_depth.
834   virtual string CurrentStackTrace(int max_depth, int skip_count) = 0;
835 
836   // UponLeavingGTest() should be called immediately before Google Test calls
837   // user code. It saves some information about the current stack that
838   // CurrentStackTrace() will use to find and hide Google Test stack frames.
839   virtual void UponLeavingGTest() = 0;
840 
841  private:
842   GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetterInterface);
843 };
844 
845 // A working implementation of the OsStackTraceGetterInterface interface.
846 class OsStackTraceGetter : public OsStackTraceGetterInterface {
847  public:
OsStackTraceGetter()848   OsStackTraceGetter() : caller_frame_(NULL) {}
849 
850   virtual string CurrentStackTrace(int max_depth, int skip_count)
851       GTEST_LOCK_EXCLUDED_(mutex_);
852 
853   virtual void UponLeavingGTest() GTEST_LOCK_EXCLUDED_(mutex_);
854 
855   // This string is inserted in place of stack frames that are part of
856   // Google Test's implementation.
857   static const char* const kElidedFramesMarker;
858 
859  private:
860   Mutex mutex_;  // protects all internal state
861 
862   // We save the stack frame below the frame that calls user code.
863   // We do this because the address of the frame immediately below
864   // the user code changes between the call to UponLeavingGTest()
865   // and any calls to CurrentStackTrace() from within the user code.
866   void* caller_frame_;
867 
868   GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetter);
869 };
870 
871 // Information about a Google Test trace point.
872 struct TraceInfo {
873   const char* file;
874   int line;
875   std::string message;
876 };
877 
878 // This is the default global test part result reporter used in UnitTestImpl.
879 // This class should only be used by UnitTestImpl.
880 class DefaultGlobalTestPartResultReporter
881     : public TestPartResultReporterInterface {
882  public:
883   explicit DefaultGlobalTestPartResultReporter(UnitTestImpl* unit_test);
884   // Implements the TestPartResultReporterInterface. Reports the test part
885   // result in the current test.
886   virtual void ReportTestPartResult(const TestPartResult& result);
887 
888  private:
889   UnitTestImpl* const unit_test_;
890 
891   GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultGlobalTestPartResultReporter);
892 };
893 
894 // This is the default per thread test part result reporter used in
895 // UnitTestImpl. This class should only be used by UnitTestImpl.
896 class DefaultPerThreadTestPartResultReporter
897     : public TestPartResultReporterInterface {
898  public:
899   explicit DefaultPerThreadTestPartResultReporter(UnitTestImpl* unit_test);
900   // Implements the TestPartResultReporterInterface. The implementation just
901   // delegates to the current global test part result reporter of *unit_test_.
902   virtual void ReportTestPartResult(const TestPartResult& result);
903 
904  private:
905   UnitTestImpl* const unit_test_;
906 
907   GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultPerThreadTestPartResultReporter);
908 };
909 
910 // The private implementation of the UnitTest class.  We don't protect
911 // the methods under a mutex, as this class is not accessible by a
912 // user and the UnitTest class that delegates work to this class does
913 // proper locking.
914 class GTEST_API_ UnitTestImpl {
915  public:
916   explicit UnitTestImpl(UnitTest* parent);
917   virtual ~UnitTestImpl();
918 
919   // There are two different ways to register your own TestPartResultReporter.
920   // You can register your own repoter to listen either only for test results
921   // from the current thread or for results from all threads.
922   // By default, each per-thread test result repoter just passes a new
923   // TestPartResult to the global test result reporter, which registers the
924   // test part result for the currently running test.
925 
926   // Returns the global test part result reporter.
927   TestPartResultReporterInterface* GetGlobalTestPartResultReporter();
928 
929   // Sets the global test part result reporter.
930   void SetGlobalTestPartResultReporter(
931       TestPartResultReporterInterface* reporter);
932 
933   // Returns the test part result reporter for the current thread.
934   TestPartResultReporterInterface* GetTestPartResultReporterForCurrentThread();
935 
936   // Sets the test part result reporter for the current thread.
937   void SetTestPartResultReporterForCurrentThread(
938       TestPartResultReporterInterface* reporter);
939 
940   // Gets the number of successful test cases.
941   int successful_test_case_count() const;
942 
943   // Gets the number of failed test cases.
944   int failed_test_case_count() const;
945 
946   // Gets the number of all test cases.
947   int total_test_case_count() const;
948 
949   // Gets the number of all test cases that contain at least one test
950   // that should run.
951   int test_case_to_run_count() const;
952 
953   // Gets the number of successful tests.
954   int successful_test_count() const;
955 
956   // Gets the number of failed tests.
957   int failed_test_count() const;
958 
959   // Gets the number of disabled tests that will be reported in the XML report.
960   int reportable_disabled_test_count() const;
961 
962   // Gets the number of disabled tests.
963   int disabled_test_count() const;
964 
965   // Gets the number of tests to be printed in the XML report.
966   int reportable_test_count() const;
967 
968   // Gets the number of all tests.
969   int total_test_count() const;
970 
971   // Gets the number of tests that should run.
972   int test_to_run_count() const;
973 
974   // Gets the time of the test program start, in ms from the start of the
975   // UNIX epoch.
start_timestamp() const976   TimeInMillis start_timestamp() const { return start_timestamp_; }
977 
978   // Gets the elapsed time, in milliseconds.
elapsed_time() const979   TimeInMillis elapsed_time() const { return elapsed_time_; }
980 
981   // Returns true iff the unit test passed (i.e. all test cases passed).
Passed() const982   bool Passed() const { return !Failed(); }
983 
984   // Returns true iff the unit test failed (i.e. some test case failed
985   // or something outside of all tests failed).
Failed() const986   bool Failed() const {
987     return failed_test_case_count() > 0 || ad_hoc_test_result()->Failed();
988   }
989 
990   // Gets the i-th test case among all the test cases. i can range from 0 to
991   // total_test_case_count() - 1. If i is not in that range, returns NULL.
GetTestCase(int i) const992   const TestCase* GetTestCase(int i) const {
993     const int index = GetElementOr(test_case_indices_, i, -1);
994     return index < 0 ? NULL : test_cases_[i];
995   }
996 
997   // Gets the i-th test case among all the test cases. i can range from 0 to
998   // total_test_case_count() - 1. If i is not in that range, returns NULL.
GetMutableTestCase(int i)999   TestCase* GetMutableTestCase(int i) {
1000     const int index = GetElementOr(test_case_indices_, i, -1);
1001     return index < 0 ? NULL : test_cases_[index];
1002   }
1003 
1004   // Provides access to the event listener list.
listeners()1005   TestEventListeners* listeners() { return &listeners_; }
1006 
1007   // Returns the TestResult for the test that's currently running, or
1008   // the TestResult for the ad hoc test if no test is running.
1009   TestResult* current_test_result();
1010 
1011   // Returns the TestResult for the ad hoc test.
ad_hoc_test_result() const1012   const TestResult* ad_hoc_test_result() const { return &ad_hoc_test_result_; }
1013 
1014   // Sets the OS stack trace getter.
1015   //
1016   // Does nothing if the input and the current OS stack trace getter
1017   // are the same; otherwise, deletes the old getter and makes the
1018   // input the current getter.
1019   void set_os_stack_trace_getter(OsStackTraceGetterInterface* getter);
1020 
1021   // Returns the current OS stack trace getter if it is not NULL;
1022   // otherwise, creates an OsStackTraceGetter, makes it the current
1023   // getter, and returns it.
1024   OsStackTraceGetterInterface* os_stack_trace_getter();
1025 
1026   // Returns the current OS stack trace as an std::string.
1027   //
1028   // The maximum number of stack frames to be included is specified by
1029   // the gtest_stack_trace_depth flag.  The skip_count parameter
1030   // specifies the number of top frames to be skipped, which doesn't
1031   // count against the number of frames to be included.
1032   //
1033   // For example, if Foo() calls Bar(), which in turn calls
1034   // CurrentOsStackTraceExceptTop(1), Foo() will be included in the
1035   // trace but Bar() and CurrentOsStackTraceExceptTop() won't.
1036   std::string CurrentOsStackTraceExceptTop(int skip_count) GTEST_NO_INLINE_;
1037 
1038   // Finds and returns a TestCase with the given name.  If one doesn't
1039   // exist, creates one and returns it.
1040   //
1041   // Arguments:
1042   //
1043   //   test_case_name: name of the test case
1044   //   type_param:     the name of the test's type parameter, or NULL if
1045   //                   this is not a typed or a type-parameterized test.
1046   //   set_up_tc:      pointer to the function that sets up the test case
1047   //   tear_down_tc:   pointer to the function that tears down the test case
1048   TestCase* GetTestCase(const char* test_case_name, const char* type_param,
1049                         Test::SetUpTestCaseFunc set_up_tc,
1050                         Test::TearDownTestCaseFunc tear_down_tc);
1051 
1052   // Adds a TestInfo to the unit test.
1053   //
1054   // Arguments:
1055   //
1056   //   set_up_tc:    pointer to the function that sets up the test case
1057   //   tear_down_tc: pointer to the function that tears down the test case
1058   //   test_info:    the TestInfo object
AddTestInfo(Test::SetUpTestCaseFunc set_up_tc,Test::TearDownTestCaseFunc tear_down_tc,TestInfo * test_info)1059   void AddTestInfo(Test::SetUpTestCaseFunc set_up_tc,
1060                    Test::TearDownTestCaseFunc tear_down_tc,
1061                    TestInfo* test_info) {
1062     // In order to support thread-safe death tests, we need to
1063     // remember the original working directory when the test program
1064     // was first invoked.  We cannot do this in RUN_ALL_TESTS(), as
1065     // the user may have changed the current directory before calling
1066     // RUN_ALL_TESTS().  Therefore we capture the current directory in
1067     // AddTestInfo(), which is called to register a TEST or TEST_F
1068     // before main() is reached.
1069     if (original_working_dir_.IsEmpty()) {
1070       original_working_dir_.Set(FilePath::GetCurrentDir());
1071       GTEST_CHECK_(!original_working_dir_.IsEmpty())
1072           << "Failed to get the current working directory.";
1073     }
1074 
1075     GetTestCase(test_info->test_case_name(), test_info->type_param(), set_up_tc,
1076                 tear_down_tc)
1077         ->AddTestInfo(test_info);
1078   }
1079 
1080 #  if GTEST_HAS_PARAM_TEST
1081   // Returns ParameterizedTestCaseRegistry object used to keep track of
1082   // value-parameterized tests and instantiate and register them.
parameterized_test_registry()1083   internal::ParameterizedTestCaseRegistry& parameterized_test_registry() {
1084     return parameterized_test_registry_;
1085   }
1086 #  endif  // GTEST_HAS_PARAM_TEST
1087 
1088   // Sets the TestCase object for the test that's currently running.
set_current_test_case(TestCase * a_current_test_case)1089   void set_current_test_case(TestCase* a_current_test_case) {
1090     current_test_case_ = a_current_test_case;
1091   }
1092 
1093   // Sets the TestInfo object for the test that's currently running.  If
1094   // current_test_info is NULL, the assertion results will be stored in
1095   // ad_hoc_test_result_.
set_current_test_info(TestInfo * a_current_test_info)1096   void set_current_test_info(TestInfo* a_current_test_info) {
1097     current_test_info_ = a_current_test_info;
1098   }
1099 
1100   // Registers all parameterized tests defined using TEST_P and
1101   // INSTANTIATE_TEST_CASE_P, creating regular tests for each test/parameter
1102   // combination. This method can be called more then once; it has guards
1103   // protecting from registering the tests more then once.  If
1104   // value-parameterized tests are disabled, RegisterParameterizedTests is
1105   // present but does nothing.
1106   void RegisterParameterizedTests();
1107 
1108   // Runs all tests in this UnitTest object, prints the result, and
1109   // returns true if all tests are successful.  If any exception is
1110   // thrown during a test, this test is considered to be failed, but
1111   // the rest of the tests will still be run.
1112   bool RunAllTests();
1113 
1114   // Clears the results of all tests, except the ad hoc tests.
ClearNonAdHocTestResult()1115   void ClearNonAdHocTestResult() {
1116     ForEach(test_cases_, TestCase::ClearTestCaseResult);
1117   }
1118 
1119   // Clears the results of ad-hoc test assertions.
ClearAdHocTestResult()1120   void ClearAdHocTestResult() { ad_hoc_test_result_.Clear(); }
1121 
1122   // Adds a TestProperty to the current TestResult object when invoked in a
1123   // context of a test or a test case, or to the global property set. If the
1124   // result already contains a property with the same key, the value will be
1125   // updated.
1126   void RecordProperty(const TestProperty& test_property);
1127 
1128   enum ReactionToSharding { HONOR_SHARDING_PROTOCOL, IGNORE_SHARDING_PROTOCOL };
1129 
1130   // Matches the full name of each test against the user-specified
1131   // filter to decide whether the test should run, then records the
1132   // result in each TestCase and TestInfo object.
1133   // If shard_tests == HONOR_SHARDING_PROTOCOL, further filters tests
1134   // based on sharding variables in the environment.
1135   // Returns the number of tests that should run.
1136   int FilterTests(ReactionToSharding shard_tests);
1137 
1138   // Prints the names of the tests matching the user-specified filter flag.
1139   void ListTestsMatchingFilter();
1140 
current_test_case() const1141   const TestCase* current_test_case() const { return current_test_case_; }
current_test_info()1142   TestInfo* current_test_info() { return current_test_info_; }
current_test_info() const1143   const TestInfo* current_test_info() const { return current_test_info_; }
1144 
1145   // Returns the vector of environments that need to be set-up/torn-down
1146   // before/after the tests are run.
environments()1147   std::vector<Environment*>& environments() { return environments_; }
1148 
1149   // Getters for the per-thread Google Test trace stack.
gtest_trace_stack()1150   std::vector<TraceInfo>& gtest_trace_stack() {
1151     return *(gtest_trace_stack_.pointer());
1152   }
gtest_trace_stack() const1153   const std::vector<TraceInfo>& gtest_trace_stack() const {
1154     return gtest_trace_stack_.get();
1155   }
1156 
1157 #  if GTEST_HAS_DEATH_TEST
InitDeathTestSubprocessControlInfo()1158   void InitDeathTestSubprocessControlInfo() {
1159     internal_run_death_test_flag_.reset(ParseInternalRunDeathTestFlag());
1160   }
1161   // Returns a pointer to the parsed --gtest_internal_run_death_test
1162   // flag, or NULL if that flag was not specified.
1163   // This information is useful only in a death test child process.
1164   // Must not be called before a call to InitGoogleTest.
internal_run_death_test_flag() const1165   const InternalRunDeathTestFlag* internal_run_death_test_flag() const {
1166     return internal_run_death_test_flag_.get();
1167   }
1168 
1169   // Returns a pointer to the current death test factory.
death_test_factory()1170   internal::DeathTestFactory* death_test_factory() {
1171     return death_test_factory_.get();
1172   }
1173 
1174   void SuppressTestEventsIfInSubprocess();
1175 
1176   friend class ReplaceDeathTestFactory;
1177 #  endif  // GTEST_HAS_DEATH_TEST
1178 
1179   // Initializes the event listener performing XML output as specified by
1180   // UnitTestOptions. Must not be called before InitGoogleTest.
1181   void ConfigureXmlOutput();
1182 
1183 #  if GTEST_CAN_STREAM_RESULTS_
1184   // Initializes the event listener for streaming test results to a socket.
1185   // Must not be called before InitGoogleTest.
1186   void ConfigureStreamingOutput();
1187 #  endif
1188 
1189   // Performs initialization dependent upon flag values obtained in
1190   // ParseGoogleTestFlagsOnly.  Is called from InitGoogleTest after the call to
1191   // ParseGoogleTestFlagsOnly.  In case a user neglects to call InitGoogleTest
1192   // this function is also called from RunAllTests.  Since this function can be
1193   // called more than once, it has to be idempotent.
1194   void PostFlagParsingInit();
1195 
1196   // Gets the random seed used at the start of the current test iteration.
random_seed() const1197   int random_seed() const { return random_seed_; }
1198 
1199   // Gets the random number generator.
random()1200   internal::Random* random() { return &random_; }
1201 
1202   // Shuffles all test cases, and the tests within each test case,
1203   // making sure that death tests are still run first.
1204   void ShuffleTests();
1205 
1206   // Restores the test cases and tests to their order before the first shuffle.
1207   void UnshuffleTests();
1208 
1209   // Returns the value of GTEST_FLAG(catch_exceptions) at the moment
1210   // UnitTest::Run() starts.
catch_exceptions() const1211   bool catch_exceptions() const { return catch_exceptions_; }
1212 
1213  private:
1214   friend class ::testing::UnitTest;
1215 
1216   // Used by UnitTest::Run() to capture the state of
1217   // GTEST_FLAG(catch_exceptions) at the moment it starts.
set_catch_exceptions(bool value)1218   void set_catch_exceptions(bool value) { catch_exceptions_ = value; }
1219 
1220   // The UnitTest object that owns this implementation object.
1221   UnitTest* const parent_;
1222 
1223   // The working directory when the first TEST() or TEST_F() was
1224   // executed.
1225   internal::FilePath original_working_dir_;
1226 
1227   // The default test part result reporters.
1228   DefaultGlobalTestPartResultReporter default_global_test_part_result_reporter_;
1229   DefaultPerThreadTestPartResultReporter
1230       default_per_thread_test_part_result_reporter_;
1231 
1232   // Points to (but doesn't own) the global test part result reporter.
1233   TestPartResultReporterInterface* global_test_part_result_repoter_;
1234 
1235   // Protects read and write access to global_test_part_result_reporter_.
1236   internal::Mutex global_test_part_result_reporter_mutex_;
1237 
1238   // Points to (but doesn't own) the per-thread test part result reporter.
1239   internal::ThreadLocal<TestPartResultReporterInterface*>
1240       per_thread_test_part_result_reporter_;
1241 
1242   // The vector of environments that need to be set-up/torn-down
1243   // before/after the tests are run.
1244   std::vector<Environment*> environments_;
1245 
1246   // The vector of TestCases in their original order.  It owns the
1247   // elements in the vector.
1248   std::vector<TestCase*> test_cases_;
1249 
1250   // Provides a level of indirection for the test case list to allow
1251   // easy shuffling and restoring the test case order.  The i-th
1252   // element of this vector is the index of the i-th test case in the
1253   // shuffled order.
1254   std::vector<int> test_case_indices_;
1255 
1256 #  if GTEST_HAS_PARAM_TEST
1257   // ParameterizedTestRegistry object used to register value-parameterized
1258   // tests.
1259   internal::ParameterizedTestCaseRegistry parameterized_test_registry_;
1260 
1261   // Indicates whether RegisterParameterizedTests() has been called already.
1262   bool parameterized_tests_registered_;
1263 #  endif  // GTEST_HAS_PARAM_TEST
1264 
1265   // Index of the last death test case registered.  Initially -1.
1266   int last_death_test_case_;
1267 
1268   // This points to the TestCase for the currently running test.  It
1269   // changes as Google Test goes through one test case after another.
1270   // When no test is running, this is set to NULL and Google Test
1271   // stores assertion results in ad_hoc_test_result_.  Initially NULL.
1272   TestCase* current_test_case_;
1273 
1274   // This points to the TestInfo for the currently running test.  It
1275   // changes as Google Test goes through one test after another.  When
1276   // no test is running, this is set to NULL and Google Test stores
1277   // assertion results in ad_hoc_test_result_.  Initially NULL.
1278   TestInfo* current_test_info_;
1279 
1280   // Normally, a user only writes assertions inside a TEST or TEST_F,
1281   // or inside a function called by a TEST or TEST_F.  Since Google
1282   // Test keeps track of which test is current running, it can
1283   // associate such an assertion with the test it belongs to.
1284   //
1285   // If an assertion is encountered when no TEST or TEST_F is running,
1286   // Google Test attributes the assertion result to an imaginary "ad hoc"
1287   // test, and records the result in ad_hoc_test_result_.
1288   TestResult ad_hoc_test_result_;
1289 
1290   // The list of event listeners that can be used to track events inside
1291   // Google Test.
1292   TestEventListeners listeners_;
1293 
1294   // The OS stack trace getter.  Will be deleted when the UnitTest
1295   // object is destructed.  By default, an OsStackTraceGetter is used,
1296   // but the user can set this field to use a custom getter if that is
1297   // desired.
1298   OsStackTraceGetterInterface* os_stack_trace_getter_;
1299 
1300   // True iff PostFlagParsingInit() has been called.
1301   bool post_flag_parse_init_performed_;
1302 
1303   // The random number seed used at the beginning of the test run.
1304   int random_seed_;
1305 
1306   // Our random number generator.
1307   internal::Random random_;
1308 
1309   // The time of the test program start, in ms from the start of the
1310   // UNIX epoch.
1311   TimeInMillis start_timestamp_;
1312 
1313   // How long the test took to run, in milliseconds.
1314   TimeInMillis elapsed_time_;
1315 
1316 #  if GTEST_HAS_DEATH_TEST
1317   // The decomposed components of the gtest_internal_run_death_test flag,
1318   // parsed when RUN_ALL_TESTS is called.
1319   internal::scoped_ptr<InternalRunDeathTestFlag> internal_run_death_test_flag_;
1320   internal::scoped_ptr<internal::DeathTestFactory> death_test_factory_;
1321 #  endif  // GTEST_HAS_DEATH_TEST
1322 
1323   // A per-thread stack of traces created by the SCOPED_TRACE() macro.
1324   internal::ThreadLocal<std::vector<TraceInfo> > gtest_trace_stack_;
1325 
1326   // The value of GTEST_FLAG(catch_exceptions) at the moment RunAllTests()
1327   // starts.
1328   bool catch_exceptions_;
1329 
1330   GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTestImpl);
1331 };  // class UnitTestImpl
1332 
1333 // Convenience function for accessing the global UnitTest
1334 // implementation object.
GetUnitTestImpl()1335 inline UnitTestImpl* GetUnitTestImpl() {
1336   return UnitTest::GetInstance()->impl();
1337 }
1338 
1339 #  if GTEST_USES_SIMPLE_RE
1340 
1341 // Internal helper functions for implementing the simple regular
1342 // expression matcher.
1343 GTEST_API_ bool IsInSet(char ch, const char* str);
1344 GTEST_API_ bool IsAsciiDigit(char ch);
1345 GTEST_API_ bool IsAsciiPunct(char ch);
1346 GTEST_API_ bool IsRepeat(char ch);
1347 GTEST_API_ bool IsAsciiWhiteSpace(char ch);
1348 GTEST_API_ bool IsAsciiWordChar(char ch);
1349 GTEST_API_ bool IsValidEscape(char ch);
1350 GTEST_API_ bool AtomMatchesChar(bool escaped, char pattern, char ch);
1351 GTEST_API_ bool ValidateRegex(const char* regex);
1352 GTEST_API_ bool MatchRegexAtHead(const char* regex, const char* str);
1353 GTEST_API_ bool MatchRepetitionAndRegexAtHead(bool escaped, char ch,
1354                                               char repeat, const char* regex,
1355                                               const char* str);
1356 GTEST_API_ bool MatchRegexAnywhere(const char* regex, const char* str);
1357 
1358 #  endif  // GTEST_USES_SIMPLE_RE
1359 
1360 // Parses the command line for Google Test flags, without initializing
1361 // other parts of Google Test.
1362 GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, char** argv);
1363 GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv);
1364 
1365 #  if GTEST_HAS_DEATH_TEST
1366 
1367 // Returns the message describing the last system error, regardless of the
1368 // platform.
1369 GTEST_API_ std::string GetLastErrnoDescription();
1370 
1371 #    if GTEST_OS_WINDOWS
1372 // Provides leak-safe Windows kernel handle ownership.
1373 class AutoHandle {
1374  public:
AutoHandle()1375   AutoHandle() : handle_(INVALID_HANDLE_VALUE) {}
AutoHandle(HANDLE handle)1376   explicit AutoHandle(HANDLE handle) : handle_(handle) {}
1377 
~AutoHandle()1378   ~AutoHandle() { Reset(); }
1379 
Get() const1380   HANDLE Get() const { return handle_; }
Reset()1381   void Reset() { Reset(INVALID_HANDLE_VALUE); }
Reset(HANDLE handle)1382   void Reset(HANDLE handle) {
1383     if (handle != handle_) {
1384       if (handle_ != INVALID_HANDLE_VALUE) ::CloseHandle(handle_);
1385       handle_ = handle;
1386     }
1387   }
1388 
1389  private:
1390   HANDLE handle_;
1391 
1392   GTEST_DISALLOW_COPY_AND_ASSIGN_(AutoHandle);
1393 };
1394 #    endif  // GTEST_OS_WINDOWS
1395 
1396 // Attempts to parse a string into a positive integer pointed to by the
1397 // number parameter.  Returns true if that is possible.
1398 // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we can use
1399 // it here.
1400 template <typename Integer>
ParseNaturalNumber(const::std::string & str,Integer * number)1401 bool ParseNaturalNumber(const ::std::string& str, Integer* number) {
1402   // Fail fast if the given string does not begin with a digit;
1403   // this bypasses strtoXXX's "optional leading whitespace and plus
1404   // or minus sign" semantics, which are undesirable here.
1405   if (str.empty() || !IsDigit(str[0])) {
1406     return false;
1407   }
1408   errno = 0;
1409 
1410   char* end;
1411   // BiggestConvertible is the largest integer type that system-provided
1412   // string-to-number conversion routines can return.
1413 
1414 #    if GTEST_OS_WINDOWS && !defined(__GNUC__)
1415 
1416   // MSVC and C++ Builder define __int64 instead of the standard long long.
1417   typedef unsigned __int64 BiggestConvertible;
1418   const BiggestConvertible parsed = _strtoui64(str.c_str(), &end, 10);
1419 
1420 #    else
1421 
1422   typedef unsigned long long BiggestConvertible;  // NOLINT
1423   const BiggestConvertible parsed = strtoull(str.c_str(), &end, 10);
1424 
1425 #    endif  // GTEST_OS_WINDOWS && !defined(__GNUC__)
1426 
1427   const bool parse_success = *end == '\0' && errno == 0;
1428 
1429   // TODO(vladl@google.com): Convert this to compile time assertion when it is
1430   // available.
1431   GTEST_CHECK_(sizeof(Integer) <= sizeof(parsed));
1432 
1433   const Integer result = static_cast<Integer>(parsed);
1434   if (parse_success && static_cast<BiggestConvertible>(result) == parsed) {
1435     *number = result;
1436     return true;
1437   }
1438   return false;
1439 }
1440 #  endif  // GTEST_HAS_DEATH_TEST
1441 
1442 // TestResult contains some private methods that should be hidden from
1443 // Google Test user but are required for testing. This class allow our tests
1444 // to access them.
1445 //
1446 // This class is supplied only for the purpose of testing Google Test's own
1447 // constructs. Do not use it in user tests, either directly or indirectly.
1448 class TestResultAccessor {
1449  public:
RecordProperty(TestResult * test_result,const std::string & xml_element,const TestProperty & property)1450   static void RecordProperty(TestResult* test_result,
1451                              const std::string& xml_element,
1452                              const TestProperty& property) {
1453     test_result->RecordProperty(xml_element, property);
1454   }
1455 
ClearTestPartResults(TestResult * test_result)1456   static void ClearTestPartResults(TestResult* test_result) {
1457     test_result->ClearTestPartResults();
1458   }
1459 
test_part_results(const TestResult & test_result)1460   static const std::vector<testing::TestPartResult>& test_part_results(
1461       const TestResult& test_result) {
1462     return test_result.test_part_results();
1463   }
1464 };
1465 
1466 #  if GTEST_CAN_STREAM_RESULTS_
1467 
1468 // Streams test results to the given port on the given host machine.
1469 class StreamingListener : public EmptyTestEventListener {
1470  public:
1471   // Abstract base class for writing strings to a socket.
1472   class AbstractSocketWriter {
1473    public:
~AbstractSocketWriter()1474     virtual ~AbstractSocketWriter() {}
1475 
1476     // Sends a string to the socket.
1477     virtual void Send(const string& message) = 0;
1478 
1479     // Closes the socket.
CloseConnection()1480     virtual void CloseConnection() {}
1481 
1482     // Sends a string and a newline to the socket.
SendLn(const string & message)1483     void SendLn(const string& message) { Send(message + "\n"); }
1484   };
1485 
1486   // Concrete class for actually writing strings to a socket.
1487   class SocketWriter : public AbstractSocketWriter {
1488    public:
SocketWriter(const string & host,const string & port)1489     SocketWriter(const string& host, const string& port)
1490         : sockfd_(-1), host_name_(host), port_num_(port) {
1491       MakeConnection();
1492     }
1493 
~SocketWriter()1494     virtual ~SocketWriter() {
1495       if (sockfd_ != -1) CloseConnection();
1496     }
1497 
1498     // Sends a string to the socket.
Send(const string & message)1499     virtual void Send(const string& message) {
1500       GTEST_CHECK_(sockfd_ != -1)
1501           << "Send() can be called only when there is a connection.";
1502 
1503       const int len = static_cast<int>(message.length());
1504       if (write(sockfd_, message.c_str(), len) != len) {
1505         GTEST_LOG_(WARNING) << "stream_result_to: failed to stream to "
1506                             << host_name_ << ":" << port_num_;
1507       }
1508     }
1509 
1510    private:
1511     // Creates a client socket and connects to the server.
1512     void MakeConnection();
1513 
1514     // Closes the socket.
CloseConnection()1515     void CloseConnection() {
1516       GTEST_CHECK_(sockfd_ != -1)
1517           << "CloseConnection() can be called only when there is a connection.";
1518 
1519       close(sockfd_);
1520       sockfd_ = -1;
1521     }
1522 
1523     int sockfd_;  // socket file descriptor
1524     const string host_name_;
1525     const string port_num_;
1526 
1527     GTEST_DISALLOW_COPY_AND_ASSIGN_(SocketWriter);
1528   };  // class SocketWriter
1529 
1530   // Escapes '=', '&', '%', and '\n' characters in str as "%xx".
1531   static string UrlEncode(const char* str);
1532 
StreamingListener(const string & host,const string & port)1533   StreamingListener(const string& host, const string& port)
1534       : socket_writer_(new SocketWriter(host, port)) {
1535     Start();
1536   }
1537 
StreamingListener(AbstractSocketWriter * socket_writer)1538   explicit StreamingListener(AbstractSocketWriter* socket_writer)
1539       : socket_writer_(socket_writer) {
1540     Start();
1541   }
1542 
OnTestProgramStart(const UnitTest &)1543   void OnTestProgramStart(const UnitTest& /* unit_test */) {
1544     SendLn("event=TestProgramStart");
1545   }
1546 
OnTestProgramEnd(const UnitTest & unit_test)1547   void OnTestProgramEnd(const UnitTest& unit_test) {
1548     // Note that Google Test current only report elapsed time for each
1549     // test iteration, not for the entire test program.
1550     SendLn("event=TestProgramEnd&passed=" + FormatBool(unit_test.Passed()));
1551 
1552     // Notify the streaming server to stop.
1553     socket_writer_->CloseConnection();
1554   }
1555 
OnTestIterationStart(const UnitTest &,int iteration)1556   void OnTestIterationStart(const UnitTest& /* unit_test */, int iteration) {
1557     SendLn("event=TestIterationStart&iteration=" +
1558            StreamableToString(iteration));
1559   }
1560 
OnTestIterationEnd(const UnitTest & unit_test,int)1561   void OnTestIterationEnd(const UnitTest& unit_test, int /* iteration */) {
1562     SendLn("event=TestIterationEnd&passed=" + FormatBool(unit_test.Passed()) +
1563            "&elapsed_time=" + StreamableToString(unit_test.elapsed_time()) +
1564            "ms");
1565   }
1566 
OnTestCaseStart(const TestCase & test_case)1567   void OnTestCaseStart(const TestCase& test_case) {
1568     SendLn(std::string("event=TestCaseStart&name=") + test_case.name());
1569   }
1570 
OnTestCaseEnd(const TestCase & test_case)1571   void OnTestCaseEnd(const TestCase& test_case) {
1572     SendLn("event=TestCaseEnd&passed=" + FormatBool(test_case.Passed()) +
1573            "&elapsed_time=" + StreamableToString(test_case.elapsed_time()) +
1574            "ms");
1575   }
1576 
OnTestStart(const TestInfo & test_info)1577   void OnTestStart(const TestInfo& test_info) {
1578     SendLn(std::string("event=TestStart&name=") + test_info.name());
1579   }
1580 
OnTestEnd(const TestInfo & test_info)1581   void OnTestEnd(const TestInfo& test_info) {
1582     SendLn("event=TestEnd&passed=" +
1583            FormatBool((test_info.result())->Passed()) + "&elapsed_time=" +
1584            StreamableToString((test_info.result())->elapsed_time()) + "ms");
1585   }
1586 
OnTestPartResult(const TestPartResult & test_part_result)1587   void OnTestPartResult(const TestPartResult& test_part_result) {
1588     const char* file_name = test_part_result.file_name();
1589     if (file_name == NULL) file_name = "";
1590     SendLn("event=TestPartResult&file=" + UrlEncode(file_name) +
1591            "&line=" + StreamableToString(test_part_result.line_number()) +
1592            "&message=" + UrlEncode(test_part_result.message()));
1593   }
1594 
1595  private:
1596   // Sends the given message and a newline to the socket.
SendLn(const string & message)1597   void SendLn(const string& message) { socket_writer_->SendLn(message); }
1598 
1599   // Called at the start of streaming to notify the receiver what
1600   // protocol we are using.
Start()1601   void Start() { SendLn("gtest_streaming_protocol_version=1.0"); }
1602 
FormatBool(bool value)1603   string FormatBool(bool value) { return value ? "1" : "0"; }
1604 
1605   const scoped_ptr<AbstractSocketWriter> socket_writer_;
1606 
1607   GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamingListener);
1608 };  // class StreamingListener
1609 
1610 #  endif  // GTEST_CAN_STREAM_RESULTS_
1611 
1612 }  // namespace internal
1613 }  // namespace testing
1614 
1615 #endif  // GTEST_SRC_GTEST_INTERNAL_INL_H_
1616 #undef GTEST_IMPLEMENTATION_
1617 
1618 #if GTEST_OS_WINDOWS
1619 #  define vsnprintf _vsnprintf
1620 #endif  // GTEST_OS_WINDOWS
1621 
1622 namespace testing {
1623 
1624 using internal::CountIf;
1625 using internal::ForEach;
1626 using internal::GetElementOr;
1627 using internal::Shuffle;
1628 
1629 // Constants.
1630 
1631 // A test whose test case name or test name matches this filter is
1632 // disabled and not run.
1633 static const char kDisableTestFilter[] = "DISABLED_*:*/DISABLED_*";
1634 
1635 // A test case whose name matches this filter is considered a death
1636 // test case and will be run before test cases whose name doesn't
1637 // match this filter.
1638 static const char kDeathTestCaseFilter[] = "*DeathTest:*DeathTest/*";
1639 
1640 // A test filter that matches everything.
1641 static const char kUniversalFilter[] = "*";
1642 
1643 // The default output file for XML output.
1644 static const char kDefaultOutputFile[] = "test_detail.xml";
1645 
1646 // The environment variable name for the test shard index.
1647 static const char kTestShardIndex[] = "GTEST_SHARD_INDEX";
1648 // The environment variable name for the total number of test shards.
1649 static const char kTestTotalShards[] = "GTEST_TOTAL_SHARDS";
1650 // The environment variable name for the test shard status file.
1651 static const char kTestShardStatusFile[] = "GTEST_SHARD_STATUS_FILE";
1652 
1653 namespace internal {
1654 
1655 // The text used in failure messages to indicate the start of the
1656 // stack trace.
1657 const char kStackTraceMarker[] = "\nStack trace:\n";
1658 
1659 // g_help_flag is true iff the --help flag or an equivalent form is
1660 // specified on the command line.
1661 bool g_help_flag = false;
1662 
1663 }  // namespace internal
1664 
GetDefaultFilter()1665 static const char* GetDefaultFilter() { return kUniversalFilter; }
1666 
1667 GTEST_DEFINE_bool_(
1668     also_run_disabled_tests,
1669     internal::BoolFromGTestEnv("also_run_disabled_tests", false),
1670     "Run disabled tests too, in addition to the tests normally being run.");
1671 
1672 GTEST_DEFINE_bool_(
1673     break_on_failure, internal::BoolFromGTestEnv("break_on_failure", false),
1674     "True iff a failed assertion should be a debugger break-point.");
1675 
1676 GTEST_DEFINE_bool_(catch_exceptions,
1677                    internal::BoolFromGTestEnv("catch_exceptions", true),
1678                    "True iff " GTEST_NAME_
1679                    " should catch exceptions and treat them as test failures.");
1680 
1681 GTEST_DEFINE_string_(
1682     color, internal::StringFromGTestEnv("color", "auto"),
1683     "Whether to use colors in the output.  Valid values: yes, no, "
1684     "and auto.  'auto' means to use colors if the output is "
1685     "being sent to a terminal and the TERM environment variable "
1686     "is set to a terminal type that supports colors.");
1687 
1688 GTEST_DEFINE_string_(
1689     filter, internal::StringFromGTestEnv("filter", GetDefaultFilter()),
1690     "A colon-separated list of glob (not regex) patterns "
1691     "for filtering the tests to run, optionally followed by a "
1692     "'-' and a : separated list of negative patterns (tests to "
1693     "exclude).  A test is run if it matches one of the positive "
1694     "patterns and does not match any of the negative patterns.");
1695 
1696 GTEST_DEFINE_bool_(list_tests, false, "List all tests without running them.");
1697 
1698 GTEST_DEFINE_string_(
1699     output, internal::StringFromGTestEnv("output", ""),
1700     "A format (currently must be \"xml\"), optionally followed "
1701     "by a colon and an output file name or directory. A directory "
1702     "is indicated by a trailing pathname separator. "
1703     "Examples: \"xml:filename.xml\", \"xml::directoryname/\". "
1704     "If a directory is specified, output files will be created "
1705     "within that directory, with file-names based on the test "
1706     "executable's name and, if necessary, made unique by adding "
1707     "digits.");
1708 
1709 GTEST_DEFINE_bool_(print_time, internal::BoolFromGTestEnv("print_time", true),
1710                    "True iff " GTEST_NAME_
1711                    " should display elapsed time in text output.");
1712 
1713 GTEST_DEFINE_int32_(
1714     random_seed, internal::Int32FromGTestEnv("random_seed", 0),
1715     "Random number seed to use when shuffling test orders.  Must be in range "
1716     "[1, 99999], or 0 to use a seed based on the current time.");
1717 
1718 GTEST_DEFINE_int32_(
1719     repeat, internal::Int32FromGTestEnv("repeat", 1),
1720     "How many times to repeat each test.  Specify a negative number "
1721     "for repeating forever.  Useful for shaking out flaky tests.");
1722 
1723 GTEST_DEFINE_bool_(show_internal_stack_frames, false,
1724                    "True iff " GTEST_NAME_
1725                    " should include internal stack frames when "
1726                    "printing test failure stack traces.");
1727 
1728 GTEST_DEFINE_bool_(shuffle, internal::BoolFromGTestEnv("shuffle", false),
1729                    "True iff " GTEST_NAME_
1730                    " should randomize tests' order on every run.");
1731 
1732 GTEST_DEFINE_int32_(
1733     stack_trace_depth,
1734     internal::Int32FromGTestEnv("stack_trace_depth", kMaxStackTraceDepth),
1735     "The maximum number of stack frames to print when an "
1736     "assertion fails.  The valid range is 0 through 100, inclusive.");
1737 
1738 GTEST_DEFINE_string_(
1739     stream_result_to, internal::StringFromGTestEnv("stream_result_to", ""),
1740     "This flag specifies the host name and the port number on which to stream "
1741     "test results. Example: \"localhost:555\". The flag is effective only on "
1742     "Linux.");
1743 
1744 GTEST_DEFINE_bool_(
1745     throw_on_failure, internal::BoolFromGTestEnv("throw_on_failure", false),
1746     "When this flag is specified, a failed assertion will throw an exception "
1747     "if exceptions are enabled or exit the program with a non-zero code "
1748     "otherwise.");
1749 
1750 namespace internal {
1751 
1752 // Generates a random number from [0, range), using a Linear
1753 // Congruential Generator (LCG).  Crashes if 'range' is 0 or greater
1754 // than kMaxRange.
Generate(UInt32 range)1755 UInt32 Random::Generate(UInt32 range) {
1756   // These constants are the same as are used in glibc's rand(3).
1757   state_ = (1103515245U * state_ + 12345U) % kMaxRange;
1758 
1759   GTEST_CHECK_(range > 0) << "Cannot generate a number in the range [0, 0).";
1760   GTEST_CHECK_(range <= kMaxRange)
1761       << "Generation of a number in [0, " << range << ") was requested, "
1762       << "but this can only generate numbers in [0, " << kMaxRange << ").";
1763 
1764   // Converting via modulus introduces a bit of downward bias, but
1765   // it's simple, and a linear congruential generator isn't too good
1766   // to begin with.
1767   return state_ % range;
1768 }
1769 
1770 // GTestIsInitialized() returns true iff the user has initialized
1771 // Google Test.  Useful for catching the user mistake of not initializing
1772 // Google Test before calling RUN_ALL_TESTS().
1773 //
1774 // A user must call testing::InitGoogleTest() to initialize Google
1775 // Test.  g_init_gtest_count is set to the number of times
1776 // InitGoogleTest() has been called.  We don't protect this variable
1777 // under a mutex as it is only accessed in the main thread.
1778 GTEST_API_ int g_init_gtest_count = 0;
GTestIsInitialized()1779 static bool GTestIsInitialized() { return g_init_gtest_count != 0; }
1780 
1781 // Iterates over a vector of TestCases, keeping a running sum of the
1782 // results of calling a given int-returning method on each.
1783 // Returns the sum.
SumOverTestCaseList(const std::vector<TestCase * > & case_list,int (TestCase::* method)()const)1784 static int SumOverTestCaseList(const std::vector<TestCase*>& case_list,
1785                                int (TestCase::*method)() const) {
1786   int sum = 0;
1787   for (size_t i = 0; i < case_list.size(); i++) {
1788     sum += (case_list[i]->*method)();
1789   }
1790   return sum;
1791 }
1792 
1793 // Returns true iff the test case passed.
TestCasePassed(const TestCase * test_case)1794 static bool TestCasePassed(const TestCase* test_case) {
1795   return test_case->should_run() && test_case->Passed();
1796 }
1797 
1798 // Returns true iff the test case failed.
TestCaseFailed(const TestCase * test_case)1799 static bool TestCaseFailed(const TestCase* test_case) {
1800   return test_case->should_run() && test_case->Failed();
1801 }
1802 
1803 // Returns true iff test_case contains at least one test that should
1804 // run.
ShouldRunTestCase(const TestCase * test_case)1805 static bool ShouldRunTestCase(const TestCase* test_case) {
1806   return test_case->should_run();
1807 }
1808 
1809 // AssertHelper constructor.
AssertHelper(TestPartResult::Type type,const char * file,int line,const char * message)1810 AssertHelper::AssertHelper(TestPartResult::Type type, const char* file,
1811                            int line, const char* message)
1812     : data_(new AssertHelperData(type, file, line, message)) {}
1813 
~AssertHelper()1814 AssertHelper::~AssertHelper() { delete data_; }
1815 
1816 // Message assignment, for assertion streaming support.
operator =(const Message & message) const1817 void AssertHelper::operator=(const Message& message) const {
1818   UnitTest::GetInstance()->AddTestPartResult(
1819       data_->type, data_->file, data_->line,
1820       AppendUserMessage(data_->message, message),
1821       UnitTest::GetInstance()->impl()->CurrentOsStackTraceExceptTop(1)
1822       // Skips the stack frame for this function itself.
1823   );  // NOLINT
1824 }
1825 
1826 // Mutex for linked pointers.
1827 GTEST_API_ GTEST_DEFINE_STATIC_MUTEX_(g_linked_ptr_mutex);
1828 
1829 // Application pathname gotten in InitGoogleTest.
1830 std::string g_executable_path;
1831 
1832 // Returns the current application's name, removing directory path if that
1833 // is present.
GetCurrentExecutableName()1834 FilePath GetCurrentExecutableName() {
1835   FilePath result;
1836 
1837 #if GTEST_OS_WINDOWS
1838   result.Set(FilePath(g_executable_path).RemoveExtension("exe"));
1839 #else
1840   result.Set(FilePath(g_executable_path));
1841 #endif  // GTEST_OS_WINDOWS
1842 
1843   return result.RemoveDirectoryName();
1844 }
1845 
1846 // Functions for processing the gtest_output flag.
1847 
1848 // Returns the output format, or "" for normal printed output.
GetOutputFormat()1849 std::string UnitTestOptions::GetOutputFormat() {
1850   const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
1851   if (gtest_output_flag == NULL) return std::string("");
1852 
1853   const char* const colon = strchr(gtest_output_flag, ':');
1854   return (colon == NULL)
1855              ? std::string(gtest_output_flag)
1856              : std::string(gtest_output_flag, colon - gtest_output_flag);
1857 }
1858 
1859 // Returns the name of the requested output file, or the default if none
1860 // was explicitly specified.
GetAbsolutePathToOutputFile()1861 std::string UnitTestOptions::GetAbsolutePathToOutputFile() {
1862   const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
1863   if (gtest_output_flag == NULL) return "";
1864 
1865   const char* const colon = strchr(gtest_output_flag, ':');
1866   if (colon == NULL)
1867     return internal::FilePath::ConcatPaths(
1868                internal::FilePath(
1869                    UnitTest::GetInstance()->original_working_dir()),
1870                internal::FilePath(kDefaultOutputFile))
1871         .string();
1872 
1873   internal::FilePath output_name(colon + 1);
1874   if (!output_name.IsAbsolutePath())
1875     // TODO(wan@google.com): on Windows \some\path is not an absolute
1876     // path (as its meaning depends on the current drive), yet the
1877     // following logic for turning it into an absolute path is wrong.
1878     // Fix it.
1879     output_name = internal::FilePath::ConcatPaths(
1880         internal::FilePath(UnitTest::GetInstance()->original_working_dir()),
1881         internal::FilePath(colon + 1));
1882 
1883   if (!output_name.IsDirectory()) return output_name.string();
1884 
1885   internal::FilePath result(internal::FilePath::GenerateUniqueFileName(
1886       output_name, internal::GetCurrentExecutableName(),
1887       GetOutputFormat().c_str()));
1888   return result.string();
1889 }
1890 
1891 // Returns true iff the wildcard pattern matches the string.  The
1892 // first ':' or '\0' character in pattern marks the end of it.
1893 //
1894 // This recursive algorithm isn't very efficient, but is clear and
1895 // works well enough for matching test names, which are short.
PatternMatchesString(const char * pattern,const char * str)1896 bool UnitTestOptions::PatternMatchesString(const char* pattern,
1897                                            const char* str) {
1898   switch (*pattern) {
1899   case '\0':
1900   case ':':  // Either ':' or '\0' marks the end of the pattern.
1901     return *str == '\0';
1902   case '?':  // Matches any single character.
1903     return *str != '\0' && PatternMatchesString(pattern + 1, str + 1);
1904   case '*':  // Matches any string (possibly empty) of characters.
1905     return (*str != '\0' && PatternMatchesString(pattern, str + 1)) ||
1906            PatternMatchesString(pattern + 1, str);
1907   default:  // Non-special character.  Matches itself.
1908     return *pattern == *str && PatternMatchesString(pattern + 1, str + 1);
1909   }
1910 }
1911 
MatchesFilter(const std::string & name,const char * filter)1912 bool UnitTestOptions::MatchesFilter(const std::string& name,
1913                                     const char* filter) {
1914   const char* cur_pattern = filter;
1915   for (;;) {
1916     if (PatternMatchesString(cur_pattern, name.c_str())) {
1917       return true;
1918     }
1919 
1920     // Finds the next pattern in the filter.
1921     cur_pattern = strchr(cur_pattern, ':');
1922 
1923     // Returns if no more pattern can be found.
1924     if (cur_pattern == NULL) {
1925       return false;
1926     }
1927 
1928     // Skips the pattern separater (the ':' character).
1929     cur_pattern++;
1930   }
1931 }
1932 
1933 // Returns true iff the user-specified filter matches the test case
1934 // name and the test name.
FilterMatchesTest(const std::string & test_case_name,const std::string & test_name)1935 bool UnitTestOptions::FilterMatchesTest(const std::string& test_case_name,
1936                                         const std::string& test_name) {
1937   const std::string& full_name = test_case_name + "." + test_name.c_str();
1938 
1939   // Split --gtest_filter at '-', if there is one, to separate into
1940   // positive filter and negative filter portions
1941   const char* const p = GTEST_FLAG(filter).c_str();
1942   const char* const dash = strchr(p, '-');
1943   std::string positive;
1944   std::string negative;
1945   if (dash == NULL) {
1946     positive = GTEST_FLAG(filter).c_str();  // Whole string is a positive filter
1947     negative = "";
1948   } else {
1949     positive = std::string(p, dash);   // Everything up to the dash
1950     negative = std::string(dash + 1);  // Everything after the dash
1951     if (positive.empty()) {
1952       // Treat '-test1' as the same as '*-test1'
1953       positive = kUniversalFilter;
1954     }
1955   }
1956 
1957   // A filter is a colon-separated list of patterns.  It matches a
1958   // test if any pattern in it matches the test.
1959   return (MatchesFilter(full_name, positive.c_str()) &&
1960           !MatchesFilter(full_name, negative.c_str()));
1961 }
1962 
1963 #if GTEST_HAS_SEH
1964 // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
1965 // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
1966 // This function is useful as an __except condition.
GTestShouldProcessSEH(DWORD exception_code)1967 int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) {
1968   // Google Test should handle a SEH exception if:
1969   //   1. the user wants it to, AND
1970   //   2. this is not a breakpoint exception, AND
1971   //   3. this is not a C++ exception (VC++ implements them via SEH,
1972   //      apparently).
1973   //
1974   // SEH exception code for C++ exceptions.
1975   // (see http://support.microsoft.com/kb/185294 for more information).
1976   const DWORD kCxxExceptionCode = 0xe06d7363;
1977 
1978   bool should_handle = true;
1979 
1980   if (!GTEST_FLAG(catch_exceptions))
1981     should_handle = false;
1982   else if (exception_code == EXCEPTION_BREAKPOINT)
1983     should_handle = false;
1984   else if (exception_code == kCxxExceptionCode)
1985     should_handle = false;
1986 
1987   return should_handle ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH;
1988 }
1989 #endif  // GTEST_HAS_SEH
1990 
1991 }  // namespace internal
1992 
1993 // The c'tor sets this object as the test part result reporter used by
1994 // Google Test.  The 'result' parameter specifies where to report the
1995 // results. Intercepts only failures from the current thread.
ScopedFakeTestPartResultReporter(TestPartResultArray * result)1996 ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
1997     TestPartResultArray* result)
1998     : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD), result_(result) {
1999   Init();
2000 }
2001 
2002 // The c'tor sets this object as the test part result reporter used by
2003 // Google Test.  The 'result' parameter specifies where to report the
2004 // results.
ScopedFakeTestPartResultReporter(InterceptMode intercept_mode,TestPartResultArray * result)2005 ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
2006     InterceptMode intercept_mode, TestPartResultArray* result)
2007     : intercept_mode_(intercept_mode), result_(result) {
2008   Init();
2009 }
2010 
Init()2011 void ScopedFakeTestPartResultReporter::Init() {
2012   internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
2013   if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
2014     old_reporter_ = impl->GetGlobalTestPartResultReporter();
2015     impl->SetGlobalTestPartResultReporter(this);
2016   } else {
2017     old_reporter_ = impl->GetTestPartResultReporterForCurrentThread();
2018     impl->SetTestPartResultReporterForCurrentThread(this);
2019   }
2020 }
2021 
2022 // The d'tor restores the test part result reporter used by Google Test
2023 // before.
~ScopedFakeTestPartResultReporter()2024 ScopedFakeTestPartResultReporter::~ScopedFakeTestPartResultReporter() {
2025   internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
2026   if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
2027     impl->SetGlobalTestPartResultReporter(old_reporter_);
2028   } else {
2029     impl->SetTestPartResultReporterForCurrentThread(old_reporter_);
2030   }
2031 }
2032 
2033 // Increments the test part result count and remembers the result.
2034 // This method is from the TestPartResultReporterInterface interface.
ReportTestPartResult(const TestPartResult & result)2035 void ScopedFakeTestPartResultReporter::ReportTestPartResult(
2036     const TestPartResult& result) {
2037   result_->Append(result);
2038 }
2039 
2040 namespace internal {
2041 
2042 // Returns the type ID of ::testing::Test.  We should always call this
2043 // instead of GetTypeId< ::testing::Test>() to get the type ID of
2044 // testing::Test.  This is to work around a suspected linker bug when
2045 // using Google Test as a framework on Mac OS X.  The bug causes
2046 // GetTypeId< ::testing::Test>() to return different values depending
2047 // on whether the call is from the Google Test framework itself or
2048 // from user test code.  GetTestTypeId() is guaranteed to always
2049 // return the same value, as it always calls GetTypeId<>() from the
2050 // gtest.cc, which is within the Google Test framework.
GetTestTypeId()2051 TypeId GetTestTypeId() { return GetTypeId<Test>(); }
2052 
2053 // The value of GetTestTypeId() as seen from within the Google Test
2054 // library.  This is solely for testing GetTestTypeId().
2055 extern const TypeId kTestTypeIdInGoogleTest = GetTestTypeId();
2056 
2057 // This predicate-formatter checks that 'results' contains a test part
2058 // failure of the given type and that the failure message contains the
2059 // given substring.
HasOneFailure(const char *,const char *,const char *,const TestPartResultArray & results,TestPartResult::Type type,const string & substr)2060 AssertionResult HasOneFailure(const char* /* results_expr */,
2061                               const char* /* type_expr */,
2062                               const char* /* substr_expr */,
2063                               const TestPartResultArray& results,
2064                               TestPartResult::Type type, const string& substr) {
2065   const std::string expected(type == TestPartResult::kFatalFailure
2066                                  ? "1 fatal failure"
2067                                  : "1 non-fatal failure");
2068   Message msg;
2069   if (results.size() != 1) {
2070     msg << "Expected: " << expected << "\n"
2071         << "  Actual: " << results.size() << " failures";
2072     for (int i = 0; i < results.size(); i++) {
2073       msg << "\n" << results.GetTestPartResult(i);
2074     }
2075     return AssertionFailure() << msg;
2076   }
2077 
2078   const TestPartResult& r = results.GetTestPartResult(0);
2079   if (r.type() != type) {
2080     return AssertionFailure() << "Expected: " << expected << "\n"
2081                               << "  Actual:\n"
2082                               << r;
2083   }
2084 
2085   if (strstr(r.message(), substr.c_str()) == NULL) {
2086     return AssertionFailure()
2087            << "Expected: " << expected << " containing \"" << substr << "\"\n"
2088            << "  Actual:\n"
2089            << r;
2090   }
2091 
2092   return AssertionSuccess();
2093 }
2094 
2095 // The constructor of SingleFailureChecker remembers where to look up
2096 // test part results, what type of failure we expect, and what
2097 // substring the failure message should contain.
SingleFailureChecker(const TestPartResultArray * results,TestPartResult::Type type,const string & substr)2098 SingleFailureChecker::SingleFailureChecker(const TestPartResultArray* results,
2099                                            TestPartResult::Type type,
2100                                            const string& substr)
2101     : results_(results), type_(type), substr_(substr) {}
2102 
2103 // The destructor of SingleFailureChecker verifies that the given
2104 // TestPartResultArray contains exactly one failure that has the given
2105 // type and contains the given substring.  If that's not the case, a
2106 // non-fatal failure will be generated.
~SingleFailureChecker()2107 SingleFailureChecker::~SingleFailureChecker() {
2108   EXPECT_PRED_FORMAT3(HasOneFailure, *results_, type_, substr_);
2109 }
2110 
DefaultGlobalTestPartResultReporter(UnitTestImpl * unit_test)2111 DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter(
2112     UnitTestImpl* unit_test)
2113     : unit_test_(unit_test) {}
2114 
ReportTestPartResult(const TestPartResult & result)2115 void DefaultGlobalTestPartResultReporter::ReportTestPartResult(
2116     const TestPartResult& result) {
2117   unit_test_->current_test_result()->AddTestPartResult(result);
2118   unit_test_->listeners()->repeater()->OnTestPartResult(result);
2119 }
2120 
DefaultPerThreadTestPartResultReporter(UnitTestImpl * unit_test)2121 DefaultPerThreadTestPartResultReporter::DefaultPerThreadTestPartResultReporter(
2122     UnitTestImpl* unit_test)
2123     : unit_test_(unit_test) {}
2124 
ReportTestPartResult(const TestPartResult & result)2125 void DefaultPerThreadTestPartResultReporter::ReportTestPartResult(
2126     const TestPartResult& result) {
2127   unit_test_->GetGlobalTestPartResultReporter()->ReportTestPartResult(result);
2128 }
2129 
2130 // Returns the global test part result reporter.
2131 TestPartResultReporterInterface*
GetGlobalTestPartResultReporter()2132 UnitTestImpl::GetGlobalTestPartResultReporter() {
2133   internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
2134   return global_test_part_result_repoter_;
2135 }
2136 
2137 // Sets the global test part result reporter.
SetGlobalTestPartResultReporter(TestPartResultReporterInterface * reporter)2138 void UnitTestImpl::SetGlobalTestPartResultReporter(
2139     TestPartResultReporterInterface* reporter) {
2140   internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
2141   global_test_part_result_repoter_ = reporter;
2142 }
2143 
2144 // Returns the test part result reporter for the current thread.
2145 TestPartResultReporterInterface*
GetTestPartResultReporterForCurrentThread()2146 UnitTestImpl::GetTestPartResultReporterForCurrentThread() {
2147   return per_thread_test_part_result_reporter_.get();
2148 }
2149 
2150 // Sets the test part result reporter for the current thread.
SetTestPartResultReporterForCurrentThread(TestPartResultReporterInterface * reporter)2151 void UnitTestImpl::SetTestPartResultReporterForCurrentThread(
2152     TestPartResultReporterInterface* reporter) {
2153   per_thread_test_part_result_reporter_.set(reporter);
2154 }
2155 
2156 // Gets the number of successful test cases.
successful_test_case_count() const2157 int UnitTestImpl::successful_test_case_count() const {
2158   return CountIf(test_cases_, TestCasePassed);
2159 }
2160 
2161 // Gets the number of failed test cases.
failed_test_case_count() const2162 int UnitTestImpl::failed_test_case_count() const {
2163   return CountIf(test_cases_, TestCaseFailed);
2164 }
2165 
2166 // Gets the number of all test cases.
total_test_case_count() const2167 int UnitTestImpl::total_test_case_count() const {
2168   return static_cast<int>(test_cases_.size());
2169 }
2170 
2171 // Gets the number of all test cases that contain at least one test
2172 // that should run.
test_case_to_run_count() const2173 int UnitTestImpl::test_case_to_run_count() const {
2174   return CountIf(test_cases_, ShouldRunTestCase);
2175 }
2176 
2177 // Gets the number of successful tests.
successful_test_count() const2178 int UnitTestImpl::successful_test_count() const {
2179   return SumOverTestCaseList(test_cases_, &TestCase::successful_test_count);
2180 }
2181 
2182 // Gets the number of failed tests.
failed_test_count() const2183 int UnitTestImpl::failed_test_count() const {
2184   return SumOverTestCaseList(test_cases_, &TestCase::failed_test_count);
2185 }
2186 
2187 // Gets the number of disabled tests that will be reported in the XML report.
reportable_disabled_test_count() const2188 int UnitTestImpl::reportable_disabled_test_count() const {
2189   return SumOverTestCaseList(test_cases_,
2190                              &TestCase::reportable_disabled_test_count);
2191 }
2192 
2193 // Gets the number of disabled tests.
disabled_test_count() const2194 int UnitTestImpl::disabled_test_count() const {
2195   return SumOverTestCaseList(test_cases_, &TestCase::disabled_test_count);
2196 }
2197 
2198 // Gets the number of tests to be printed in the XML report.
reportable_test_count() const2199 int UnitTestImpl::reportable_test_count() const {
2200   return SumOverTestCaseList(test_cases_, &TestCase::reportable_test_count);
2201 }
2202 
2203 // Gets the number of all tests.
total_test_count() const2204 int UnitTestImpl::total_test_count() const {
2205   return SumOverTestCaseList(test_cases_, &TestCase::total_test_count);
2206 }
2207 
2208 // Gets the number of tests that should run.
test_to_run_count() const2209 int UnitTestImpl::test_to_run_count() const {
2210   return SumOverTestCaseList(test_cases_, &TestCase::test_to_run_count);
2211 }
2212 
2213 // Returns the current OS stack trace as an std::string.
2214 //
2215 // The maximum number of stack frames to be included is specified by
2216 // the gtest_stack_trace_depth flag.  The skip_count parameter
2217 // specifies the number of top frames to be skipped, which doesn't
2218 // count against the number of frames to be included.
2219 //
2220 // For example, if Foo() calls Bar(), which in turn calls
2221 // CurrentOsStackTraceExceptTop(1), Foo() will be included in the
2222 // trace but Bar() and CurrentOsStackTraceExceptTop() won't.
CurrentOsStackTraceExceptTop(int skip_count)2223 std::string UnitTestImpl::CurrentOsStackTraceExceptTop(int skip_count) {
2224   (void)skip_count;
2225   return "";
2226 }
2227 
2228 // Returns the current time in milliseconds.
GetTimeInMillis()2229 TimeInMillis GetTimeInMillis() {
2230 #if GTEST_OS_WINDOWS_MOBILE || defined(__BORLANDC__)
2231   // Difference between 1970-01-01 and 1601-01-01 in milliseconds.
2232   // http://analogous.blogspot.com/2005/04/epoch.html
2233   const TimeInMillis kJavaEpochToWinFileTimeDelta =
2234       static_cast<TimeInMillis>(116444736UL) * 100000UL;
2235   const DWORD kTenthMicrosInMilliSecond = 10000;
2236 
2237   SYSTEMTIME now_systime;
2238   FILETIME now_filetime;
2239   ULARGE_INTEGER now_int64;
2240   // TODO(kenton@google.com): Shouldn't this just use
2241   //   GetSystemTimeAsFileTime()?
2242   GetSystemTime(&now_systime);
2243   if (SystemTimeToFileTime(&now_systime, &now_filetime)) {
2244     now_int64.LowPart = now_filetime.dwLowDateTime;
2245     now_int64.HighPart = now_filetime.dwHighDateTime;
2246     now_int64.QuadPart = (now_int64.QuadPart / kTenthMicrosInMilliSecond) -
2247                          kJavaEpochToWinFileTimeDelta;
2248     return now_int64.QuadPart;
2249   }
2250   return 0;
2251 #elif GTEST_OS_WINDOWS && !GTEST_HAS_GETTIMEOFDAY_
2252   __timeb64 now;
2253 
2254 #  ifdef _MSC_VER
2255 
2256   // MSVC 8 deprecates _ftime64(), so we want to suppress warning 4996
2257   // (deprecated function) there.
2258   // TODO(kenton@google.com): Use GetTickCount()?  Or use
2259   //   SystemTimeToFileTime()
2260 #    pragma warning(push)            // Saves the current warning state.
2261 #    pragma warning(disable : 4996)  // Temporarily disables warning 4996.
2262   _ftime64(&now);
2263 #    pragma warning(pop)             // Restores the warning state.
2264 #  else
2265 
2266   _ftime64(&now);
2267 
2268 #  endif  // _MSC_VER
2269 
2270   return static_cast<TimeInMillis>(now.time) * 1000 + now.millitm;
2271 #elif GTEST_HAS_GETTIMEOFDAY_
2272   struct timeval now;
2273   gettimeofday(&now, NULL);
2274   return static_cast<TimeInMillis>(now.tv_sec) * 1000 + now.tv_usec / 1000;
2275 #else
2276 #  error "Don't know how to get the current time on your system."
2277 #endif
2278 }
2279 
2280 // Utilities
2281 
2282 // class String.
2283 
2284 #if GTEST_OS_WINDOWS_MOBILE
2285 // Creates a UTF-16 wide string from the given ANSI string, allocating
2286 // memory using new. The caller is responsible for deleting the return
2287 // value using delete[]. Returns the wide string, or NULL if the
2288 // input is NULL.
AnsiToUtf16(const char * ansi)2289 LPCWSTR String::AnsiToUtf16(const char* ansi) {
2290   if (!ansi) return NULL;
2291   const int length = strlen(ansi);
2292   const int unicode_length =
2293       MultiByteToWideChar(CP_ACP, 0, ansi, length, NULL, 0);
2294   WCHAR* unicode = new WCHAR[unicode_length + 1];
2295   MultiByteToWideChar(CP_ACP, 0, ansi, length, unicode, unicode_length);
2296   unicode[unicode_length] = 0;
2297   return unicode;
2298 }
2299 
2300 // Creates an ANSI string from the given wide string, allocating
2301 // memory using new. The caller is responsible for deleting the return
2302 // value using delete[]. Returns the ANSI string, or NULL if the
2303 // input is NULL.
Utf16ToAnsi(LPCWSTR utf16_str)2304 const char* String::Utf16ToAnsi(LPCWSTR utf16_str) {
2305   if (!utf16_str) return NULL;
2306   const int ansi_length =
2307       WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, NULL, 0, NULL, NULL);
2308   char* ansi = new char[ansi_length + 1];
2309   WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, ansi, ansi_length, NULL, NULL);
2310   ansi[ansi_length] = 0;
2311   return ansi;
2312 }
2313 
2314 #endif  // GTEST_OS_WINDOWS_MOBILE
2315 
2316 // Compares two C strings.  Returns true iff they have the same content.
2317 //
2318 // Unlike strcmp(), this function can handle NULL argument(s).  A NULL
2319 // C string is considered different to any non-NULL C string,
2320 // including the empty string.
CStringEquals(const char * lhs,const char * rhs)2321 bool String::CStringEquals(const char* lhs, const char* rhs) {
2322   if (lhs == NULL) return rhs == NULL;
2323 
2324   if (rhs == NULL) return false;
2325 
2326   return strcmp(lhs, rhs) == 0;
2327 }
2328 
2329 #if GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
2330 
2331 // Converts an array of wide chars to a narrow string using the UTF-8
2332 // encoding, and streams the result to the given Message object.
StreamWideCharsToMessage(const wchar_t * wstr,size_t length,Message * msg)2333 static void StreamWideCharsToMessage(const wchar_t* wstr, size_t length,
2334                                      Message* msg) {
2335   for (size_t i = 0; i != length;) {  // NOLINT
2336     if (wstr[i] != L'\0') {
2337       *msg << WideStringToUtf8(wstr + i, static_cast<int>(length - i));
2338       while (i != length && wstr[i] != L'\0') i++;
2339     } else {
2340       *msg << '\0';
2341       i++;
2342     }
2343   }
2344 }
2345 
2346 #endif  // GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
2347 
2348 }  // namespace internal
2349 
2350 // Constructs an empty Message.
2351 // We allocate the stringstream separately because otherwise each use of
2352 // ASSERT/EXPECT in a procedure adds over 200 bytes to the procedure's
2353 // stack frame leading to huge stack frames in some cases; gcc does not reuse
2354 // the stack space.
Message()2355 Message::Message() : ss_(new ::std::stringstream) {
2356   // By default, we want there to be enough precision when printing
2357   // a double to a Message.
2358   *ss_ << std::setprecision(std::numeric_limits<double>::digits10 + 2);
2359 }
2360 
2361 // These two overloads allow streaming a wide C string to a Message
2362 // using the UTF-8 encoding.
operator <<(const wchar_t * wide_c_str)2363 Message& Message::operator<<(const wchar_t* wide_c_str) {
2364   return *this << internal::String::ShowWideCString(wide_c_str);
2365 }
operator <<(wchar_t * wide_c_str)2366 Message& Message::operator<<(wchar_t* wide_c_str) {
2367   return *this << internal::String::ShowWideCString(wide_c_str);
2368 }
2369 
2370 #if GTEST_HAS_STD_WSTRING
2371 // Converts the given wide string to a narrow string using the UTF-8
2372 // encoding, and streams the result to this Message object.
operator <<(const::std::wstring & wstr)2373 Message& Message::operator<<(const ::std::wstring& wstr) {
2374   internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
2375   return *this;
2376 }
2377 #endif  // GTEST_HAS_STD_WSTRING
2378 
2379 #if GTEST_HAS_GLOBAL_WSTRING
2380 // Converts the given wide string to a narrow string using the UTF-8
2381 // encoding, and streams the result to this Message object.
operator <<(const::wstring & wstr)2382 Message& Message::operator<<(const ::wstring& wstr) {
2383   internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
2384   return *this;
2385 }
2386 #endif  // GTEST_HAS_GLOBAL_WSTRING
2387 
2388 // Gets the text streamed to this object so far as an std::string.
2389 // Each '\0' character in the buffer is replaced with "\\0".
GetString() const2390 std::string Message::GetString() const {
2391   return internal::StringStreamToString(ss_.get());
2392 }
2393 
2394 // AssertionResult constructors.
2395 // Used in EXPECT_TRUE/FALSE(assertion_result).
AssertionResult(const AssertionResult & other)2396 AssertionResult::AssertionResult(const AssertionResult& other)
2397     : success_(other.success_),
2398       message_(other.message_.get() != NULL
2399                    ? new ::std::string(*other.message_)
2400                    : static_cast< ::std::string*>(NULL)) {}
2401 
2402 // Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE.
operator !() const2403 AssertionResult AssertionResult::operator!() const {
2404   AssertionResult negation(!success_);
2405   if (message_.get() != NULL) negation << *message_;
2406   return negation;
2407 }
2408 
2409 // Makes a successful assertion result.
AssertionSuccess()2410 AssertionResult AssertionSuccess() { return AssertionResult(true); }
2411 
2412 // Makes a failed assertion result.
AssertionFailure()2413 AssertionResult AssertionFailure() { return AssertionResult(false); }
2414 
2415 // Makes a failed assertion result with the given failure message.
2416 // Deprecated; use AssertionFailure() << message.
AssertionFailure(const Message & message)2417 AssertionResult AssertionFailure(const Message& message) {
2418   return AssertionFailure() << message;
2419 }
2420 
2421 namespace internal {
2422 
2423 // Constructs and returns the message for an equality assertion
2424 // (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure.
2425 //
2426 // The first four parameters are the expressions used in the assertion
2427 // and their values, as strings.  For example, for ASSERT_EQ(foo, bar)
2428 // where foo is 5 and bar is 6, we have:
2429 //
2430 //   expected_expression: "foo"
2431 //   actual_expression:   "bar"
2432 //   expected_value:      "5"
2433 //   actual_value:        "6"
2434 //
2435 // The ignoring_case parameter is true iff the assertion is a
2436 // *_STRCASEEQ*.  When it's true, the string " (ignoring case)" will
2437 // be inserted into the message.
EqFailure(const char * expected_expression,const char * actual_expression,const std::string & expected_value,const std::string & actual_value,bool ignoring_case)2438 AssertionResult EqFailure(const char* expected_expression,
2439                           const char* actual_expression,
2440                           const std::string& expected_value,
2441                           const std::string& actual_value, bool ignoring_case) {
2442   Message msg;
2443   msg << "Value of: " << actual_expression;
2444   if (actual_value != actual_expression) {
2445     msg << "\n  Actual: " << actual_value;
2446   }
2447 
2448   msg << "\nExpected: " << expected_expression;
2449   if (ignoring_case) {
2450     msg << " (ignoring case)";
2451   }
2452   if (expected_value != expected_expression) {
2453     msg << "\nWhich is: " << expected_value;
2454   }
2455 
2456   return AssertionFailure() << msg;
2457 }
2458 
2459 // Constructs a failure message for Boolean assertions such as EXPECT_TRUE.
GetBoolAssertionFailureMessage(const AssertionResult & assertion_result,const char * expression_text,const char * actual_predicate_value,const char * expected_predicate_value)2460 std::string GetBoolAssertionFailureMessage(
2461     const AssertionResult& assertion_result, const char* expression_text,
2462     const char* actual_predicate_value, const char* expected_predicate_value) {
2463   const char* actual_message = assertion_result.message();
2464   Message msg;
2465   msg << "Value of: " << expression_text
2466       << "\n  Actual: " << actual_predicate_value;
2467   if (actual_message[0] != '\0') msg << " (" << actual_message << ")";
2468   msg << "\nExpected: " << expected_predicate_value;
2469   return msg.GetString();
2470 }
2471 
2472 // Helper function for implementing ASSERT_NEAR.
DoubleNearPredFormat(const char * expr1,const char * expr2,const char * abs_error_expr,double val1,double val2,double abs_error)2473 AssertionResult DoubleNearPredFormat(const char* expr1, const char* expr2,
2474                                      const char* abs_error_expr, double val1,
2475                                      double val2, double abs_error) {
2476   const double diff = fabs(val1 - val2);
2477   if (diff <= abs_error) return AssertionSuccess();
2478 
2479   // TODO(wan): do not print the value of an expression if it's
2480   // already a literal.
2481   return AssertionFailure()
2482          << "The difference between " << expr1 << " and " << expr2 << " is "
2483          << diff << ", which exceeds " << abs_error_expr << ", where\n"
2484          << expr1 << " evaluates to " << val1 << ",\n"
2485          << expr2 << " evaluates to " << val2 << ", and\n"
2486          << abs_error_expr << " evaluates to " << abs_error << ".";
2487 }
2488 
2489 // Helper template for implementing FloatLE() and DoubleLE().
2490 template <typename RawType>
FloatingPointLE(const char * expr1,const char * expr2,RawType val1,RawType val2)2491 AssertionResult FloatingPointLE(const char* expr1, const char* expr2,
2492                                 RawType val1, RawType val2) {
2493   // Returns success if val1 is less than val2,
2494   if (val1 < val2) {
2495     return AssertionSuccess();
2496   }
2497 
2498   // or if val1 is almost equal to val2.
2499   const FloatingPoint<RawType> lhs(val1), rhs(val2);
2500   if (lhs.AlmostEquals(rhs)) {
2501     return AssertionSuccess();
2502   }
2503 
2504   // Note that the above two checks will both fail if either val1 or
2505   // val2 is NaN, as the IEEE floating-point standard requires that
2506   // any predicate involving a NaN must return false.
2507 
2508   ::std::stringstream val1_ss;
2509   val1_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
2510           << val1;
2511 
2512   ::std::stringstream val2_ss;
2513   val2_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
2514           << val2;
2515 
2516   return AssertionFailure()
2517          << "Expected: (" << expr1 << ") <= (" << expr2 << ")\n"
2518          << "  Actual: " << StringStreamToString(&val1_ss) << " vs "
2519          << StringStreamToString(&val2_ss);
2520 }
2521 
2522 }  // namespace internal
2523 
2524 // Asserts that val1 is less than, or almost equal to, val2.  Fails
2525 // otherwise.  In particular, it fails if either val1 or val2 is NaN.
FloatLE(const char * expr1,const char * expr2,float val1,float val2)2526 AssertionResult FloatLE(const char* expr1, const char* expr2, float val1,
2527                         float val2) {
2528   return internal::FloatingPointLE<float>(expr1, expr2, val1, val2);
2529 }
2530 
2531 // Asserts that val1 is less than, or almost equal to, val2.  Fails
2532 // otherwise.  In particular, it fails if either val1 or val2 is NaN.
DoubleLE(const char * expr1,const char * expr2,double val1,double val2)2533 AssertionResult DoubleLE(const char* expr1, const char* expr2, double val1,
2534                          double val2) {
2535   return internal::FloatingPointLE<double>(expr1, expr2, val1, val2);
2536 }
2537 
2538 namespace internal {
2539 
2540 // The helper function for {ASSERT|EXPECT}_EQ with int or enum
2541 // arguments.
CmpHelperEQ(const char * expected_expression,const char * actual_expression,BiggestInt expected,BiggestInt actual)2542 AssertionResult CmpHelperEQ(const char* expected_expression,
2543                             const char* actual_expression, BiggestInt expected,
2544                             BiggestInt actual) {
2545   if (expected == actual) {
2546     return AssertionSuccess();
2547   }
2548 
2549   return EqFailure(expected_expression, actual_expression,
2550                    FormatForComparisonFailureMessage(expected, actual),
2551                    FormatForComparisonFailureMessage(actual, expected), false);
2552 }
2553 
2554 // A macro for implementing the helper functions needed to implement
2555 // ASSERT_?? and EXPECT_?? with integer or enum arguments.  It is here
2556 // just to avoid copy-and-paste of similar code.
2557 #define GTEST_IMPL_CMP_HELPER_(op_name, op)                                    \
2558   AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2,     \
2559                                      BiggestInt val1, BiggestInt val2) {       \
2560     if (val1 op val2) {                                                        \
2561       return AssertionSuccess();                                               \
2562     } else {                                                                   \
2563       return AssertionFailure()                                                \
2564              << "Expected: (" << expr1 << ") " #op " (" << expr2               \
2565              << "), actual: " << FormatForComparisonFailureMessage(val1, val2) \
2566              << " vs " << FormatForComparisonFailureMessage(val2, val1);       \
2567     }                                                                          \
2568   }
2569 
2570 // Implements the helper function for {ASSERT|EXPECT}_NE with int or
2571 // enum arguments.
2572 GTEST_IMPL_CMP_HELPER_(NE, !=)
2573 // Implements the helper function for {ASSERT|EXPECT}_LE with int or
2574 // enum arguments.
2575 GTEST_IMPL_CMP_HELPER_(LE, <=)
2576 // Implements the helper function for {ASSERT|EXPECT}_LT with int or
2577 // enum arguments.
2578 GTEST_IMPL_CMP_HELPER_(LT, <)
2579 // Implements the helper function for {ASSERT|EXPECT}_GE with int or
2580 // enum arguments.
2581 GTEST_IMPL_CMP_HELPER_(GE, >=)
2582 // Implements the helper function for {ASSERT|EXPECT}_GT with int or
2583 // enum arguments.
2584 GTEST_IMPL_CMP_HELPER_(GT, >)
2585 
2586 #undef GTEST_IMPL_CMP_HELPER_
2587 
2588 // The helper function for {ASSERT|EXPECT}_STREQ.
CmpHelperSTREQ(const char * expected_expression,const char * actual_expression,const char * expected,const char * actual)2589 AssertionResult CmpHelperSTREQ(const char* expected_expression,
2590                                const char* actual_expression,
2591                                const char* expected, const char* actual) {
2592   if (String::CStringEquals(expected, actual)) {
2593     return AssertionSuccess();
2594   }
2595 
2596   return EqFailure(expected_expression, actual_expression,
2597                    PrintToString(expected), PrintToString(actual), false);
2598 }
2599 
2600 // The helper function for {ASSERT|EXPECT}_STRCASEEQ.
CmpHelperSTRCASEEQ(const char * expected_expression,const char * actual_expression,const char * expected,const char * actual)2601 AssertionResult CmpHelperSTRCASEEQ(const char* expected_expression,
2602                                    const char* actual_expression,
2603                                    const char* expected, const char* actual) {
2604   if (String::CaseInsensitiveCStringEquals(expected, actual)) {
2605     return AssertionSuccess();
2606   }
2607 
2608   return EqFailure(expected_expression, actual_expression,
2609                    PrintToString(expected), PrintToString(actual), true);
2610 }
2611 
2612 // The helper function for {ASSERT|EXPECT}_STRNE.
CmpHelperSTRNE(const char * s1_expression,const char * s2_expression,const char * s1,const char * s2)2613 AssertionResult CmpHelperSTRNE(const char* s1_expression,
2614                                const char* s2_expression, const char* s1,
2615                                const char* s2) {
2616   if (!String::CStringEquals(s1, s2)) {
2617     return AssertionSuccess();
2618   } else {
2619     return AssertionFailure()
2620            << "Expected: (" << s1_expression << ") != (" << s2_expression
2621            << "), actual: \"" << s1 << "\" vs \"" << s2 << "\"";
2622   }
2623 }
2624 
2625 // The helper function for {ASSERT|EXPECT}_STRCASENE.
CmpHelperSTRCASENE(const char * s1_expression,const char * s2_expression,const char * s1,const char * s2)2626 AssertionResult CmpHelperSTRCASENE(const char* s1_expression,
2627                                    const char* s2_expression, const char* s1,
2628                                    const char* s2) {
2629   if (!String::CaseInsensitiveCStringEquals(s1, s2)) {
2630     return AssertionSuccess();
2631   } else {
2632     return AssertionFailure()
2633            << "Expected: (" << s1_expression << ") != (" << s2_expression
2634            << ") (ignoring case), actual: \"" << s1 << "\" vs \"" << s2 << "\"";
2635   }
2636 }
2637 
2638 }  // namespace internal
2639 
2640 namespace {
2641 
2642 // Helper functions for implementing IsSubString() and IsNotSubstring().
2643 
2644 // This group of overloaded functions return true iff needle is a
2645 // substring of haystack.  NULL is considered a substring of itself
2646 // only.
2647 
IsSubstringPred(const char * needle,const char * haystack)2648 bool IsSubstringPred(const char* needle, const char* haystack) {
2649   if (needle == NULL || haystack == NULL) return needle == haystack;
2650 
2651   return strstr(haystack, needle) != NULL;
2652 }
2653 
IsSubstringPred(const wchar_t * needle,const wchar_t * haystack)2654 bool IsSubstringPred(const wchar_t* needle, const wchar_t* haystack) {
2655   if (needle == NULL || haystack == NULL) return needle == haystack;
2656 
2657   return wcsstr(haystack, needle) != NULL;
2658 }
2659 
2660 // StringType here can be either ::std::string or ::std::wstring.
2661 template <typename StringType>
IsSubstringPred(const StringType & needle,const StringType & haystack)2662 bool IsSubstringPred(const StringType& needle, const StringType& haystack) {
2663   return haystack.find(needle) != StringType::npos;
2664 }
2665 
2666 // This function implements either IsSubstring() or IsNotSubstring(),
2667 // depending on the value of the expected_to_be_substring parameter.
2668 // StringType here can be const char*, const wchar_t*, ::std::string,
2669 // or ::std::wstring.
2670 template <typename StringType>
IsSubstringImpl(bool expected_to_be_substring,const char * needle_expr,const char * haystack_expr,const StringType & needle,const StringType & haystack)2671 AssertionResult IsSubstringImpl(bool expected_to_be_substring,
2672                                 const char* needle_expr,
2673                                 const char* haystack_expr,
2674                                 const StringType& needle,
2675                                 const StringType& haystack) {
2676   if (IsSubstringPred(needle, haystack) == expected_to_be_substring)
2677     return AssertionSuccess();
2678 
2679   const bool is_wide_string = sizeof(needle[0]) > 1;
2680   const char* const begin_string_quote = is_wide_string ? "L\"" : "\"";
2681   return AssertionFailure()
2682          << "Value of: " << needle_expr << "\n"
2683          << "  Actual: " << begin_string_quote << needle << "\"\n"
2684          << "Expected: " << (expected_to_be_substring ? "" : "not ")
2685          << "a substring of " << haystack_expr << "\n"
2686          << "Which is: " << begin_string_quote << haystack << "\"";
2687 }
2688 
2689 }  // namespace
2690 
2691 // IsSubstring() and IsNotSubstring() check whether needle is a
2692 // substring of haystack (NULL is considered a substring of itself
2693 // only), and return an appropriate error message when they fail.
2694 
IsSubstring(const char * needle_expr,const char * haystack_expr,const char * needle,const char * haystack)2695 AssertionResult IsSubstring(const char* needle_expr, const char* haystack_expr,
2696                             const char* needle, const char* haystack) {
2697   return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
2698 }
2699 
IsSubstring(const char * needle_expr,const char * haystack_expr,const wchar_t * needle,const wchar_t * haystack)2700 AssertionResult IsSubstring(const char* needle_expr, const char* haystack_expr,
2701                             const wchar_t* needle, const wchar_t* haystack) {
2702   return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
2703 }
2704 
IsNotSubstring(const char * needle_expr,const char * haystack_expr,const char * needle,const char * haystack)2705 AssertionResult IsNotSubstring(const char* needle_expr,
2706                                const char* haystack_expr, const char* needle,
2707                                const char* haystack) {
2708   return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
2709 }
2710 
IsNotSubstring(const char * needle_expr,const char * haystack_expr,const wchar_t * needle,const wchar_t * haystack)2711 AssertionResult IsNotSubstring(const char* needle_expr,
2712                                const char* haystack_expr, const wchar_t* needle,
2713                                const wchar_t* haystack) {
2714   return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
2715 }
2716 
IsSubstring(const char * needle_expr,const char * haystack_expr,const::std::string & needle,const::std::string & haystack)2717 AssertionResult IsSubstring(const char* needle_expr, const char* haystack_expr,
2718                             const ::std::string& needle,
2719                             const ::std::string& haystack) {
2720   return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
2721 }
2722 
IsNotSubstring(const char * needle_expr,const char * haystack_expr,const::std::string & needle,const::std::string & haystack)2723 AssertionResult IsNotSubstring(const char* needle_expr,
2724                                const char* haystack_expr,
2725                                const ::std::string& needle,
2726                                const ::std::string& haystack) {
2727   return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
2728 }
2729 
2730 #if GTEST_HAS_STD_WSTRING
IsSubstring(const char * needle_expr,const char * haystack_expr,const::std::wstring & needle,const::std::wstring & haystack)2731 AssertionResult IsSubstring(const char* needle_expr, const char* haystack_expr,
2732                             const ::std::wstring& needle,
2733                             const ::std::wstring& haystack) {
2734   return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
2735 }
2736 
IsNotSubstring(const char * needle_expr,const char * haystack_expr,const::std::wstring & needle,const::std::wstring & haystack)2737 AssertionResult IsNotSubstring(const char* needle_expr,
2738                                const char* haystack_expr,
2739                                const ::std::wstring& needle,
2740                                const ::std::wstring& haystack) {
2741   return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
2742 }
2743 #endif  // GTEST_HAS_STD_WSTRING
2744 
2745 namespace internal {
2746 
2747 #if GTEST_OS_WINDOWS
2748 
2749 namespace {
2750 
2751 // Helper function for IsHRESULT{SuccessFailure} predicates
HRESULTFailureHelper(const char * expr,const char * expected,long hr)2752 AssertionResult HRESULTFailureHelper(const char* expr, const char* expected,
2753                                      long hr) {  // NOLINT
2754 #  if GTEST_OS_WINDOWS_MOBILE
2755 
2756   // Windows CE doesn't support FormatMessage.
2757   const char error_text[] = "";
2758 
2759 #  else
2760 
2761   // Looks up the human-readable system message for the HRESULT code
2762   // and since we're not passing any params to FormatMessage, we don't
2763   // want inserts expanded.
2764   const DWORD kFlags =
2765       FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;
2766   const DWORD kBufSize = 4096;
2767   // Gets the system's human readable message string for this HRESULT.
2768   char error_text[kBufSize] = {'\0'};
2769   DWORD message_length = ::FormatMessageA(kFlags,
2770                                           0,   // no source, we're asking system
2771                                           hr,  // the error
2772                                           0,   // no line width restrictions
2773                                           error_text,  // output buffer
2774                                           kBufSize,    // buf size
2775                                           NULL);  // no arguments for inserts
2776   // Trims tailing white space (FormatMessage leaves a trailing CR-LF)
2777   for (; message_length && IsSpace(error_text[message_length - 1]);
2778        --message_length) {
2779     error_text[message_length - 1] = '\0';
2780   }
2781 
2782 #  endif  // GTEST_OS_WINDOWS_MOBILE
2783 
2784   const std::string error_hex("0x" + String::FormatHexInt(hr));
2785   return ::testing::AssertionFailure()
2786          << "Expected: " << expr << " " << expected << ".\n"
2787          << "  Actual: " << error_hex << " " << error_text << "\n";
2788 }
2789 
2790 }  // namespace
2791 
IsHRESULTSuccess(const char * expr,long hr)2792 AssertionResult IsHRESULTSuccess(const char* expr, long hr) {  // NOLINT
2793   if (SUCCEEDED(hr)) {
2794     return AssertionSuccess();
2795   }
2796   return HRESULTFailureHelper(expr, "succeeds", hr);
2797 }
2798 
IsHRESULTFailure(const char * expr,long hr)2799 AssertionResult IsHRESULTFailure(const char* expr, long hr) {  // NOLINT
2800   if (FAILED(hr)) {
2801     return AssertionSuccess();
2802   }
2803   return HRESULTFailureHelper(expr, "fails", hr);
2804 }
2805 
2806 #endif  // GTEST_OS_WINDOWS
2807 
2808 // Utility functions for encoding Unicode text (wide strings) in
2809 // UTF-8.
2810 
2811 // A Unicode code-point can have upto 21 bits, and is encoded in UTF-8
2812 // like this:
2813 //
2814 // Code-point length   Encoding
2815 //   0 -  7 bits       0xxxxxxx
2816 //   8 - 11 bits       110xxxxx 10xxxxxx
2817 //  12 - 16 bits       1110xxxx 10xxxxxx 10xxxxxx
2818 //  17 - 21 bits       11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
2819 
2820 // The maximum code-point a one-byte UTF-8 sequence can represent.
2821 const UInt32 kMaxCodePoint1 = (static_cast<UInt32>(1) << 7) - 1;
2822 
2823 // The maximum code-point a two-byte UTF-8 sequence can represent.
2824 const UInt32 kMaxCodePoint2 = (static_cast<UInt32>(1) << (5 + 6)) - 1;
2825 
2826 // The maximum code-point a three-byte UTF-8 sequence can represent.
2827 const UInt32 kMaxCodePoint3 = (static_cast<UInt32>(1) << (4 + 2 * 6)) - 1;
2828 
2829 // The maximum code-point a four-byte UTF-8 sequence can represent.
2830 const UInt32 kMaxCodePoint4 = (static_cast<UInt32>(1) << (3 + 3 * 6)) - 1;
2831 
2832 // Chops off the n lowest bits from a bit pattern.  Returns the n
2833 // lowest bits.  As a side effect, the original bit pattern will be
2834 // shifted to the right by n bits.
ChopLowBits(UInt32 * bits,int n)2835 inline UInt32 ChopLowBits(UInt32* bits, int n) {
2836   const UInt32 low_bits = *bits & ((static_cast<UInt32>(1) << n) - 1);
2837   *bits >>= n;
2838   return low_bits;
2839 }
2840 
2841 // Converts a Unicode code point to a narrow string in UTF-8 encoding.
2842 // code_point parameter is of type UInt32 because wchar_t may not be
2843 // wide enough to contain a code point.
2844 // If the code_point is not a valid Unicode code point
2845 // (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted
2846 // to "(Invalid Unicode 0xXXXXXXXX)".
CodePointToUtf8(UInt32 code_point)2847 std::string CodePointToUtf8(UInt32 code_point) {
2848   if (code_point > kMaxCodePoint4) {
2849     return "(Invalid Unicode 0x" + String::FormatHexInt(code_point) + ")";
2850   }
2851 
2852   char str[5];  // Big enough for the largest valid code point.
2853   if (code_point <= kMaxCodePoint1) {
2854     str[1] = '\0';
2855     str[0] = static_cast<char>(code_point);  // 0xxxxxxx
2856   } else if (code_point <= kMaxCodePoint2) {
2857     str[2] = '\0';
2858     str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx
2859     str[0] = static_cast<char>(0xC0 | code_point);                   // 110xxxxx
2860   } else if (code_point <= kMaxCodePoint3) {
2861     str[3] = '\0';
2862     str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx
2863     str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx
2864     str[0] = static_cast<char>(0xE0 | code_point);                   // 1110xxxx
2865   } else {  // code_point <= kMaxCodePoint4
2866     str[4] = '\0';
2867     str[3] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx
2868     str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx
2869     str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx
2870     str[0] = static_cast<char>(0xF0 | code_point);                   // 11110xxx
2871   }
2872   return str;
2873 }
2874 
2875 // The following two functions only make sense if the the system
2876 // uses UTF-16 for wide string encoding. All supported systems
2877 // with 16 bit wchar_t (Windows, Cygwin, Symbian OS) do use UTF-16.
2878 
2879 // Determines if the arguments constitute UTF-16 surrogate pair
2880 // and thus should be combined into a single Unicode code point
2881 // using CreateCodePointFromUtf16SurrogatePair.
IsUtf16SurrogatePair(wchar_t first,wchar_t second)2882 inline bool IsUtf16SurrogatePair(wchar_t first, wchar_t second) {
2883   return sizeof(wchar_t) == 2 && (first & 0xFC00) == 0xD800 &&
2884          (second & 0xFC00) == 0xDC00;
2885 }
2886 
2887 // Creates a Unicode code point from UTF16 surrogate pair.
CreateCodePointFromUtf16SurrogatePair(wchar_t first,wchar_t second)2888 inline UInt32 CreateCodePointFromUtf16SurrogatePair(wchar_t first,
2889                                                     wchar_t second) {
2890   const UInt32 mask = (1 << 10) - 1;
2891   return (sizeof(wchar_t) == 2)
2892              ? (((first & mask) << 10) | (second & mask)) + 0x10000
2893              :
2894              // This function should not be called when the condition is
2895              // false, but we provide a sensible default in case it is.
2896              static_cast<UInt32>(first);
2897 }
2898 
2899 // Converts a wide string to a narrow string in UTF-8 encoding.
2900 // The wide string is assumed to have the following encoding:
2901 //   UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS)
2902 //   UTF-32 if sizeof(wchar_t) == 4 (on Linux)
2903 // Parameter str points to a null-terminated wide string.
2904 // Parameter num_chars may additionally limit the number
2905 // of wchar_t characters processed. -1 is used when the entire string
2906 // should be processed.
2907 // If the string contains code points that are not valid Unicode code points
2908 // (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
2909 // as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
2910 // and contains invalid UTF-16 surrogate pairs, values in those pairs
2911 // will be encoded as individual Unicode characters from Basic Normal Plane.
WideStringToUtf8(const wchar_t * str,int num_chars)2912 std::string WideStringToUtf8(const wchar_t* str, int num_chars) {
2913   if (num_chars == -1) num_chars = static_cast<int>(wcslen(str));
2914 
2915   ::std::stringstream stream;
2916   for (int i = 0; i < num_chars; ++i) {
2917     UInt32 unicode_code_point;
2918 
2919     if (str[i] == L'\0') {
2920       break;
2921     } else if (i + 1 < num_chars && IsUtf16SurrogatePair(str[i], str[i + 1])) {
2922       unicode_code_point =
2923           CreateCodePointFromUtf16SurrogatePair(str[i], str[i + 1]);
2924       i++;
2925     } else {
2926       unicode_code_point = static_cast<UInt32>(str[i]);
2927     }
2928 
2929     stream << CodePointToUtf8(unicode_code_point);
2930   }
2931   return StringStreamToString(&stream);
2932 }
2933 
2934 // Converts a wide C string to an std::string using the UTF-8 encoding.
2935 // NULL will be converted to "(null)".
ShowWideCString(const wchar_t * wide_c_str)2936 std::string String::ShowWideCString(const wchar_t* wide_c_str) {
2937   if (wide_c_str == NULL) return "(null)";
2938 
2939   return internal::WideStringToUtf8(wide_c_str, -1);
2940 }
2941 
2942 // Compares two wide C strings.  Returns true iff they have the same
2943 // content.
2944 //
2945 // Unlike wcscmp(), this function can handle NULL argument(s).  A NULL
2946 // C string is considered different to any non-NULL C string,
2947 // including the empty string.
WideCStringEquals(const wchar_t * lhs,const wchar_t * rhs)2948 bool String::WideCStringEquals(const wchar_t* lhs, const wchar_t* rhs) {
2949   if (lhs == NULL) return rhs == NULL;
2950 
2951   if (rhs == NULL) return false;
2952 
2953   return wcscmp(lhs, rhs) == 0;
2954 }
2955 
2956 // Helper function for *_STREQ on wide strings.
CmpHelperSTREQ(const char * expected_expression,const char * actual_expression,const wchar_t * expected,const wchar_t * actual)2957 AssertionResult CmpHelperSTREQ(const char* expected_expression,
2958                                const char* actual_expression,
2959                                const wchar_t* expected, const wchar_t* actual) {
2960   if (String::WideCStringEquals(expected, actual)) {
2961     return AssertionSuccess();
2962   }
2963 
2964   return EqFailure(expected_expression, actual_expression,
2965                    PrintToString(expected), PrintToString(actual), false);
2966 }
2967 
2968 // Helper function for *_STRNE on wide strings.
CmpHelperSTRNE(const char * s1_expression,const char * s2_expression,const wchar_t * s1,const wchar_t * s2)2969 AssertionResult CmpHelperSTRNE(const char* s1_expression,
2970                                const char* s2_expression, const wchar_t* s1,
2971                                const wchar_t* s2) {
2972   if (!String::WideCStringEquals(s1, s2)) {
2973     return AssertionSuccess();
2974   }
2975 
2976   return AssertionFailure()
2977          << "Expected: (" << s1_expression << ") != (" << s2_expression
2978          << "), actual: " << PrintToString(s1) << " vs " << PrintToString(s2);
2979 }
2980 
2981 // Compares two C strings, ignoring case.  Returns true iff they have
2982 // the same content.
2983 //
2984 // Unlike strcasecmp(), this function can handle NULL argument(s).  A
2985 // NULL C string is considered different to any non-NULL C string,
2986 // including the empty string.
CaseInsensitiveCStringEquals(const char * lhs,const char * rhs)2987 bool String::CaseInsensitiveCStringEquals(const char* lhs, const char* rhs) {
2988   if (lhs == NULL) return rhs == NULL;
2989   if (rhs == NULL) return false;
2990   return posix::StrCaseCmp(lhs, rhs) == 0;
2991 }
2992 
2993 // Compares two wide C strings, ignoring case.  Returns true iff they
2994 // have the same content.
2995 //
2996 // Unlike wcscasecmp(), this function can handle NULL argument(s).
2997 // A NULL C string is considered different to any non-NULL wide C string,
2998 // including the empty string.
2999 // NB: The implementations on different platforms slightly differ.
3000 // On windows, this method uses _wcsicmp which compares according to LC_CTYPE
3001 // environment variable. On GNU platform this method uses wcscasecmp
3002 // which compares according to LC_CTYPE category of the current locale.
3003 // On MacOS X, it uses towlower, which also uses LC_CTYPE category of the
3004 // current locale.
CaseInsensitiveWideCStringEquals(const wchar_t * lhs,const wchar_t * rhs)3005 bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs,
3006                                               const wchar_t* rhs) {
3007   if (lhs == NULL) return rhs == NULL;
3008 
3009   if (rhs == NULL) return false;
3010 
3011 #if GTEST_OS_WINDOWS
3012   return _wcsicmp(lhs, rhs) == 0;
3013 #elif GTEST_OS_LINUX && !GTEST_OS_LINUX_ANDROID
3014   return wcscasecmp(lhs, rhs) == 0;
3015 #else
3016   // Android, Mac OS X and Cygwin don't define wcscasecmp.
3017   // Other unknown OSes may not define it either.
3018   wint_t left, right;
3019   do {
3020     left = towlower(*lhs++);
3021     right = towlower(*rhs++);
3022   } while (left && left == right);
3023   return left == right;
3024 #endif  // OS selector
3025 }
3026 
3027 // Returns true iff str ends with the given suffix, ignoring case.
3028 // Any string is considered to end with an empty suffix.
EndsWithCaseInsensitive(const std::string & str,const std::string & suffix)3029 bool String::EndsWithCaseInsensitive(const std::string& str,
3030                                      const std::string& suffix) {
3031   const size_t str_len = str.length();
3032   const size_t suffix_len = suffix.length();
3033   return (str_len >= suffix_len) &&
3034          CaseInsensitiveCStringEquals(str.c_str() + str_len - suffix_len,
3035                                       suffix.c_str());
3036 }
3037 
3038 // Formats an int value as "%02d".
FormatIntWidth2(int value)3039 std::string String::FormatIntWidth2(int value) {
3040   std::stringstream ss;
3041   ss << std::setfill('0') << std::setw(2) << value;
3042   return ss.str();
3043 }
3044 
3045 // Formats an int value as "%X".
FormatHexInt(int value)3046 std::string String::FormatHexInt(int value) {
3047   std::stringstream ss;
3048   ss << std::hex << std::uppercase << value;
3049   return ss.str();
3050 }
3051 
3052 // Formats a byte as "%02X".
FormatByte(unsigned char value)3053 std::string String::FormatByte(unsigned char value) {
3054   std::stringstream ss;
3055   ss << std::setfill('0') << std::setw(2) << std::hex << std::uppercase
3056      << static_cast<unsigned int>(value);
3057   return ss.str();
3058 }
3059 
3060 // Converts the buffer in a stringstream to an std::string, converting NUL
3061 // bytes to "\\0" along the way.
StringStreamToString(::std::stringstream * ss)3062 std::string StringStreamToString(::std::stringstream* ss) {
3063   const ::std::string& str = ss->str();
3064   const char* const start = str.c_str();
3065   const char* const end = start + str.length();
3066 
3067   std::string result;
3068   result.reserve(2 * (end - start));
3069   for (const char* ch = start; ch != end; ++ch) {
3070     if (*ch == '\0') {
3071       result += "\\0";  // Replaces NUL with "\\0";
3072     } else {
3073       result += *ch;
3074     }
3075   }
3076 
3077   return result;
3078 }
3079 
3080 // Appends the user-supplied message to the Google-Test-generated message.
AppendUserMessage(const std::string & gtest_msg,const Message & user_msg)3081 std::string AppendUserMessage(const std::string& gtest_msg,
3082                               const Message& user_msg) {
3083   // Appends the user message if it's non-empty.
3084   const std::string user_msg_string = user_msg.GetString();
3085   if (user_msg_string.empty()) {
3086     return gtest_msg;
3087   }
3088 
3089   return gtest_msg + "\n" + user_msg_string;
3090 }
3091 
3092 }  // namespace internal
3093 
3094 // class TestResult
3095 
3096 // Creates an empty TestResult.
TestResult()3097 TestResult::TestResult() : death_test_count_(0), elapsed_time_(0) {}
3098 
3099 // D'tor.
~TestResult()3100 TestResult::~TestResult() {}
3101 
3102 // Returns the i-th test part result among all the results. i can
3103 // range from 0 to total_part_count() - 1. If i is not in that range,
3104 // aborts the program.
GetTestPartResult(int i) const3105 const TestPartResult& TestResult::GetTestPartResult(int i) const {
3106   if (i < 0 || i >= total_part_count()) internal::posix::Abort();
3107   return test_part_results_.at(i);
3108 }
3109 
3110 // Returns the i-th test property. i can range from 0 to
3111 // test_property_count() - 1. If i is not in that range, aborts the
3112 // program.
GetTestProperty(int i) const3113 const TestProperty& TestResult::GetTestProperty(int i) const {
3114   if (i < 0 || i >= test_property_count()) internal::posix::Abort();
3115   return test_properties_.at(i);
3116 }
3117 
3118 // Clears the test part results.
ClearTestPartResults()3119 void TestResult::ClearTestPartResults() { test_part_results_.clear(); }
3120 
3121 // Adds a test part result to the list.
AddTestPartResult(const TestPartResult & test_part_result)3122 void TestResult::AddTestPartResult(const TestPartResult& test_part_result) {
3123   test_part_results_.push_back(test_part_result);
3124 }
3125 
3126 // Adds a test property to the list. If a property with the same key as the
3127 // supplied property is already represented, the value of this test_property
3128 // replaces the old value for that key.
RecordProperty(const std::string & xml_element,const TestProperty & test_property)3129 void TestResult::RecordProperty(const std::string& xml_element,
3130                                 const TestProperty& test_property) {
3131   if (!ValidateTestProperty(xml_element, test_property)) {
3132     return;
3133   }
3134   internal::MutexLock lock(&test_properites_mutex_);
3135   const std::vector<TestProperty>::iterator property_with_matching_key =
3136       std::find_if(test_properties_.begin(), test_properties_.end(),
3137                    internal::TestPropertyKeyIs(test_property.key()));
3138   if (property_with_matching_key == test_properties_.end()) {
3139     test_properties_.push_back(test_property);
3140     return;
3141   }
3142   property_with_matching_key->SetValue(test_property.value());
3143 }
3144 
3145 // The list of reserved attributes used in the <testsuites> element of XML
3146 // output.
3147 static const char* const kReservedTestSuitesAttributes[] = {
3148     "disabled",    "errors", "failures", "name",
3149     "random_seed", "tests",  "time",     "timestamp"};
3150 
3151 // The list of reserved attributes used in the <testsuite> element of XML
3152 // output.
3153 static const char* const kReservedTestSuiteAttributes[] = {
3154     "disabled", "errors", "failures", "name", "tests", "time"};
3155 
3156 // The list of reserved attributes used in the <testcase> element of XML output.
3157 static const char* const kReservedTestCaseAttributes[] = {
3158     "classname", "name", "status", "time", "type_param", "value_param"};
3159 
3160 template <int kSize>
ArrayAsVector(const char * const (& array)[kSize])3161 std::vector<std::string> ArrayAsVector(const char* const (&array)[kSize]) {
3162   return std::vector<std::string>(array, array + kSize);
3163 }
3164 
GetReservedAttributesForElement(const std::string & xml_element)3165 static std::vector<std::string> GetReservedAttributesForElement(
3166     const std::string& xml_element) {
3167   if (xml_element == "testsuites") {
3168     return ArrayAsVector(kReservedTestSuitesAttributes);
3169   } else if (xml_element == "testsuite") {
3170     return ArrayAsVector(kReservedTestSuiteAttributes);
3171   } else if (xml_element == "testcase") {
3172     return ArrayAsVector(kReservedTestCaseAttributes);
3173   } else {
3174     GTEST_CHECK_(false) << "Unrecognized xml_element provided: " << xml_element;
3175   }
3176   // This code is unreachable but some compilers may not realizes that.
3177   return std::vector<std::string>();
3178 }
3179 
FormatWordList(const std::vector<std::string> & words)3180 static std::string FormatWordList(const std::vector<std::string>& words) {
3181   Message word_list;
3182   for (size_t i = 0; i < words.size(); ++i) {
3183     if (i > 0 && words.size() > 2) {
3184       word_list << ", ";
3185     }
3186     if (i == words.size() - 1) {
3187       word_list << "and ";
3188     }
3189     word_list << "'" << words[i] << "'";
3190   }
3191   return word_list.GetString();
3192 }
3193 
ValidateTestPropertyName(const std::string & property_name,const std::vector<std::string> & reserved_names)3194 bool ValidateTestPropertyName(const std::string& property_name,
3195                               const std::vector<std::string>& reserved_names) {
3196   if (std::find(reserved_names.begin(), reserved_names.end(), property_name) !=
3197       reserved_names.end()) {
3198     ADD_FAILURE() << "Reserved key used in RecordProperty(): " << property_name
3199                   << " (" << FormatWordList(reserved_names)
3200                   << " are reserved by " << GTEST_NAME_ << ")";
3201     return false;
3202   }
3203   return true;
3204 }
3205 
3206 // Adds a failure if the key is a reserved attribute of the element named
3207 // xml_element.  Returns true if the property is valid.
ValidateTestProperty(const std::string & xml_element,const TestProperty & test_property)3208 bool TestResult::ValidateTestProperty(const std::string& xml_element,
3209                                       const TestProperty& test_property) {
3210   return ValidateTestPropertyName(test_property.key(),
3211                                   GetReservedAttributesForElement(xml_element));
3212 }
3213 
3214 // Clears the object.
Clear()3215 void TestResult::Clear() {
3216   test_part_results_.clear();
3217   test_properties_.clear();
3218   death_test_count_ = 0;
3219   elapsed_time_ = 0;
3220 }
3221 
3222 // Returns true iff the test failed.
Failed() const3223 bool TestResult::Failed() const {
3224   for (int i = 0; i < total_part_count(); ++i) {
3225     if (GetTestPartResult(i).failed()) return true;
3226   }
3227   return false;
3228 }
3229 
3230 // Returns true iff the test part fatally failed.
TestPartFatallyFailed(const TestPartResult & result)3231 static bool TestPartFatallyFailed(const TestPartResult& result) {
3232   return result.fatally_failed();
3233 }
3234 
3235 // Returns true iff the test fatally failed.
HasFatalFailure() const3236 bool TestResult::HasFatalFailure() const {
3237   return CountIf(test_part_results_, TestPartFatallyFailed) > 0;
3238 }
3239 
3240 // Returns true iff the test part non-fatally failed.
TestPartNonfatallyFailed(const TestPartResult & result)3241 static bool TestPartNonfatallyFailed(const TestPartResult& result) {
3242   return result.nonfatally_failed();
3243 }
3244 
3245 // Returns true iff the test has a non-fatal failure.
HasNonfatalFailure() const3246 bool TestResult::HasNonfatalFailure() const {
3247   return CountIf(test_part_results_, TestPartNonfatallyFailed) > 0;
3248 }
3249 
3250 // Gets the number of all test parts.  This is the sum of the number
3251 // of successful test parts and the number of failed test parts.
total_part_count() const3252 int TestResult::total_part_count() const {
3253   return static_cast<int>(test_part_results_.size());
3254 }
3255 
3256 // Returns the number of the test properties.
test_property_count() const3257 int TestResult::test_property_count() const {
3258   return static_cast<int>(test_properties_.size());
3259 }
3260 
3261 // class Test
3262 
3263 // Creates a Test object.
3264 
3265 // The c'tor saves the values of all Google Test flags.
Test()3266 Test::Test() : gtest_flag_saver_(new internal::GTestFlagSaver) {}
3267 
3268 // The d'tor restores the values of all Google Test flags.
~Test()3269 Test::~Test() { delete gtest_flag_saver_; }
3270 
3271 // Sets up the test fixture.
3272 //
3273 // A sub-class may override this.
SetUp()3274 void Test::SetUp() {}
3275 
3276 // Tears down the test fixture.
3277 //
3278 // A sub-class may override this.
TearDown()3279 void Test::TearDown() {}
3280 
3281 // Allows user supplied key value pairs to be recorded for later output.
RecordProperty(const std::string & key,const std::string & value)3282 void Test::RecordProperty(const std::string& key, const std::string& value) {
3283   UnitTest::GetInstance()->RecordProperty(key, value);
3284 }
3285 
3286 // Allows user supplied key value pairs to be recorded for later output.
RecordProperty(const std::string & key,int value)3287 void Test::RecordProperty(const std::string& key, int value) {
3288   Message value_message;
3289   value_message << value;
3290   RecordProperty(key, value_message.GetString().c_str());
3291 }
3292 
3293 namespace internal {
3294 
ReportFailureInUnknownLocation(TestPartResult::Type result_type,const std::string & message)3295 void ReportFailureInUnknownLocation(TestPartResult::Type result_type,
3296                                     const std::string& message) {
3297   // This function is a friend of UnitTest and as such has access to
3298   // AddTestPartResult.
3299   UnitTest::GetInstance()->AddTestPartResult(
3300       result_type,
3301       NULL,  // No info about the source file where the exception occurred.
3302       -1,    // We have no info on which line caused the exception.
3303       message,
3304       "");  // No stack trace, either.
3305 }
3306 
3307 }  // namespace internal
3308 
3309 // Google Test requires all tests in the same test case to use the same test
3310 // fixture class.  This function checks if the current test has the
3311 // same fixture class as the first test in the current test case.  If
3312 // yes, it returns true; otherwise it generates a Google Test failure and
3313 // returns false.
HasSameFixtureClass()3314 bool Test::HasSameFixtureClass() {
3315   internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
3316   const TestCase* const test_case = impl->current_test_case();
3317 
3318   // Info about the first test in the current test case.
3319   const TestInfo* const first_test_info = test_case->test_info_list()[0];
3320   const internal::TypeId first_fixture_id = first_test_info->fixture_class_id_;
3321   const char* const first_test_name = first_test_info->name();
3322 
3323   // Info about the current test.
3324   const TestInfo* const this_test_info = impl->current_test_info();
3325   const internal::TypeId this_fixture_id = this_test_info->fixture_class_id_;
3326   const char* const this_test_name = this_test_info->name();
3327 
3328   if (this_fixture_id != first_fixture_id) {
3329     // Is the first test defined using TEST?
3330     const bool first_is_TEST = first_fixture_id == internal::GetTestTypeId();
3331     // Is this test defined using TEST?
3332     const bool this_is_TEST = this_fixture_id == internal::GetTestTypeId();
3333 
3334     if (first_is_TEST || this_is_TEST) {
3335       // The user mixed TEST and TEST_F in this test case - we'll tell
3336       // him/her how to fix it.
3337 
3338       // Gets the name of the TEST and the name of the TEST_F.  Note
3339       // that first_is_TEST and this_is_TEST cannot both be true, as
3340       // the fixture IDs are different for the two tests.
3341       const char* const TEST_name =
3342           first_is_TEST ? first_test_name : this_test_name;
3343       const char* const TEST_F_name =
3344           first_is_TEST ? this_test_name : first_test_name;
3345 
3346       ADD_FAILURE()
3347           << "All tests in the same test case must use the same test fixture\n"
3348           << "class, so mixing TEST_F and TEST in the same test case is\n"
3349           << "illegal.  In test case " << this_test_info->test_case_name()
3350           << ",\n"
3351           << "test " << TEST_F_name << " is defined using TEST_F but\n"
3352           << "test " << TEST_name << " is defined using TEST.  You probably\n"
3353           << "want to change the TEST to TEST_F or move it to another test\n"
3354           << "case.";
3355     } else {
3356       // The user defined two fixture classes with the same name in
3357       // two namespaces - we'll tell him/her how to fix it.
3358       ADD_FAILURE()
3359           << "All tests in the same test case must use the same test fixture\n"
3360           << "class.  However, in test case "
3361           << this_test_info->test_case_name() << ",\n"
3362           << "you defined test " << first_test_name << " and test "
3363           << this_test_name << "\n"
3364           << "using two different test fixture classes.  This can happen if\n"
3365           << "the two classes are from different namespaces or translation\n"
3366           << "units and have the same name.  You should probably rename one\n"
3367           << "of the classes to put the tests into different test cases.";
3368     }
3369     return false;
3370   }
3371 
3372   return true;
3373 }
3374 
3375 #if GTEST_HAS_SEH
3376 
3377 // Adds an "exception thrown" fatal failure to the current test.  This
3378 // function returns its result via an output parameter pointer because VC++
3379 // prohibits creation of objects with destructors on stack in functions
3380 // using __try (see error C2712).
FormatSehExceptionMessage(DWORD exception_code,const char * location)3381 static std::string* FormatSehExceptionMessage(DWORD exception_code,
3382                                               const char* location) {
3383   Message message;
3384   message << "SEH exception with code 0x" << std::setbase(16) << exception_code
3385           << std::setbase(10) << " thrown in " << location << ".";
3386 
3387   return new std::string(message.GetString());
3388 }
3389 
3390 #endif  // GTEST_HAS_SEH
3391 
3392 namespace internal {
3393 
3394 #if GTEST_HAS_EXCEPTIONS
3395 
3396 // Adds an "exception thrown" fatal failure to the current test.
FormatCxxExceptionMessage(const char * description,const char * location)3397 static std::string FormatCxxExceptionMessage(const char* description,
3398                                              const char* location) {
3399   Message message;
3400   if (description != NULL) {
3401     message << "C++ exception with description \"" << description << "\"";
3402   } else {
3403     message << "Unknown C++ exception";
3404   }
3405   message << " thrown in " << location << ".";
3406 
3407   return message.GetString();
3408 }
3409 
3410 static std::string PrintTestPartResultToString(
3411     const TestPartResult& test_part_result);
3412 
GoogleTestFailureException(const TestPartResult & failure)3413 GoogleTestFailureException::GoogleTestFailureException(
3414     const TestPartResult& failure)
3415     : ::std::runtime_error(PrintTestPartResultToString(failure).c_str()) {}
3416 
3417 #endif  // GTEST_HAS_EXCEPTIONS
3418 
3419 // We put these helper functions in the internal namespace as IBM's xlC
3420 // compiler rejects the code if they were declared static.
3421 
3422 // Runs the given method and handles SEH exceptions it throws, when
3423 // SEH is supported; returns the 0-value for type Result in case of an
3424 // SEH exception.  (Microsoft compilers cannot handle SEH and C++
3425 // exceptions in the same function.  Therefore, we provide a separate
3426 // wrapper function for handling SEH exceptions.)
3427 template <class T, typename Result>
HandleSehExceptionsInMethodIfSupported(T * object,Result (T::* method)(),const char * location)3428 Result HandleSehExceptionsInMethodIfSupported(T* object, Result (T::*method)(),
3429                                               const char* location) {
3430 #if GTEST_HAS_SEH
3431   __try {
3432     return (object->*method)();
3433   } __except (internal::UnitTestOptions::GTestShouldProcessSEH(  // NOLINT
3434       GetExceptionCode())) {
3435     // We create the exception message on the heap because VC++ prohibits
3436     // creation of objects with destructors on stack in functions using __try
3437     // (see error C2712).
3438     std::string* exception_message =
3439         FormatSehExceptionMessage(GetExceptionCode(), location);
3440     internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure,
3441                                              *exception_message);
3442     delete exception_message;
3443     return static_cast<Result>(0);
3444   }
3445 #else
3446   (void)location;
3447   return (object->*method)();
3448 #endif  // GTEST_HAS_SEH
3449 }
3450 
3451 // Runs the given method and catches and reports C++ and/or SEH-style
3452 // exceptions, if they are supported; returns the 0-value for type
3453 // Result in case of an SEH exception.
3454 template <class T, typename Result>
HandleExceptionsInMethodIfSupported(T * object,Result (T::* method)(),const char * location)3455 Result HandleExceptionsInMethodIfSupported(T* object, Result (T::*method)(),
3456                                            const char* location) {
3457   // NOTE: The user code can affect the way in which Google Test handles
3458   // exceptions by setting GTEST_FLAG(catch_exceptions), but only before
3459   // RUN_ALL_TESTS() starts. It is technically possible to check the flag
3460   // after the exception is caught and either report or re-throw the
3461   // exception based on the flag's value:
3462   //
3463   // try {
3464   //   // Perform the test method.
3465   // } catch (...) {
3466   //   if (GTEST_FLAG(catch_exceptions))
3467   //     // Report the exception as failure.
3468   //   else
3469   //     throw;  // Re-throws the original exception.
3470   // }
3471   //
3472   // However, the purpose of this flag is to allow the program to drop into
3473   // the debugger when the exception is thrown. On most platforms, once the
3474   // control enters the catch block, the exception origin information is
3475   // lost and the debugger will stop the program at the point of the
3476   // re-throw in this function -- instead of at the point of the original
3477   // throw statement in the code under test.  For this reason, we perform
3478   // the check early, sacrificing the ability to affect Google Test's
3479   // exception handling in the method where the exception is thrown.
3480   if (internal::GetUnitTestImpl()->catch_exceptions()) {
3481 #if GTEST_HAS_EXCEPTIONS
3482     try {
3483       return HandleSehExceptionsInMethodIfSupported(object, method, location);
3484     } catch (const internal::GoogleTestFailureException&) {  // NOLINT
3485       // This exception type can only be thrown by a failed Google
3486       // Test assertion with the intention of letting another testing
3487       // framework catch it.  Therefore we just re-throw it.
3488       throw;
3489     } catch (const std::exception& e) {  // NOLINT
3490       internal::ReportFailureInUnknownLocation(
3491           TestPartResult::kFatalFailure,
3492           FormatCxxExceptionMessage(e.what(), location));
3493     } catch (...) {  // NOLINT
3494       internal::ReportFailureInUnknownLocation(
3495           TestPartResult::kFatalFailure,
3496           FormatCxxExceptionMessage(NULL, location));
3497     }
3498     return static_cast<Result>(0);
3499 #else
3500     return HandleSehExceptionsInMethodIfSupported(object, method, location);
3501 #endif  // GTEST_HAS_EXCEPTIONS
3502   } else {
3503     return (object->*method)();
3504   }
3505 }
3506 
3507 }  // namespace internal
3508 
3509 // Runs the test and updates the test result.
Run()3510 void Test::Run() {
3511   if (!HasSameFixtureClass()) return;
3512 
3513   internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
3514   impl->os_stack_trace_getter()->UponLeavingGTest();
3515   internal::HandleExceptionsInMethodIfSupported(this, &Test::SetUp, "SetUp()");
3516   // We will run the test only if SetUp() was successful.
3517   if (!HasFatalFailure()) {
3518     impl->os_stack_trace_getter()->UponLeavingGTest();
3519     internal::HandleExceptionsInMethodIfSupported(this, &Test::TestBody,
3520                                                   "the test body");
3521   }
3522 
3523   // However, we want to clean up as much as possible.  Hence we will
3524   // always call TearDown(), even if SetUp() or the test body has
3525   // failed.
3526   impl->os_stack_trace_getter()->UponLeavingGTest();
3527   internal::HandleExceptionsInMethodIfSupported(this, &Test::TearDown,
3528                                                 "TearDown()");
3529 }
3530 
3531 // Returns true iff the current test has a fatal failure.
HasFatalFailure()3532 bool Test::HasFatalFailure() {
3533   return internal::GetUnitTestImpl()->current_test_result()->HasFatalFailure();
3534 }
3535 
3536 // Returns true iff the current test has a non-fatal failure.
HasNonfatalFailure()3537 bool Test::HasNonfatalFailure() {
3538   return internal::GetUnitTestImpl()
3539       ->current_test_result()
3540       ->HasNonfatalFailure();
3541 }
3542 
3543 // class TestInfo
3544 
3545 // Constructs a TestInfo object. It assumes ownership of the test factory
3546 // object.
TestInfo(const std::string & a_test_case_name,const std::string & a_name,const char * a_type_param,const char * a_value_param,internal::TypeId fixture_class_id,internal::TestFactoryBase * factory)3547 TestInfo::TestInfo(const std::string& a_test_case_name,
3548                    const std::string& a_name, const char* a_type_param,
3549                    const char* a_value_param, internal::TypeId fixture_class_id,
3550                    internal::TestFactoryBase* factory)
3551     : test_case_name_(a_test_case_name),
3552       name_(a_name),
3553       type_param_(a_type_param ? new std::string(a_type_param) : NULL),
3554       value_param_(a_value_param ? new std::string(a_value_param) : NULL),
3555       fixture_class_id_(fixture_class_id),
3556       should_run_(false),
3557       is_disabled_(false),
3558       matches_filter_(false),
3559       factory_(factory),
3560       result_() {}
3561 
3562 // Destructs a TestInfo object.
~TestInfo()3563 TestInfo::~TestInfo() { delete factory_; }
3564 
3565 namespace internal {
3566 
3567 // Creates a new TestInfo object and registers it with Google Test;
3568 // returns the created object.
3569 //
3570 // Arguments:
3571 //
3572 //   test_case_name:   name of the test case
3573 //   name:             name of the test
3574 //   type_param:       the name of the test's type parameter, or NULL if
3575 //                     this is not a typed or a type-parameterized test.
3576 //   value_param:      text representation of the test's value parameter,
3577 //                     or NULL if this is not a value-parameterized test.
3578 //   fixture_class_id: ID of the test fixture class
3579 //   set_up_tc:        pointer to the function that sets up the test case
3580 //   tear_down_tc:     pointer to the function that tears down the test case
3581 //   factory:          pointer to the factory that creates a test object.
3582 //                     The newly created TestInfo instance will assume
3583 //                     ownership of the factory object.
MakeAndRegisterTestInfo(const char * test_case_name,const char * name,const char * type_param,const char * value_param,TypeId fixture_class_id,SetUpTestCaseFunc set_up_tc,TearDownTestCaseFunc tear_down_tc,TestFactoryBase * factory)3584 TestInfo* MakeAndRegisterTestInfo(const char* test_case_name, const char* name,
3585                                   const char* type_param,
3586                                   const char* value_param,
3587                                   TypeId fixture_class_id,
3588                                   SetUpTestCaseFunc set_up_tc,
3589                                   TearDownTestCaseFunc tear_down_tc,
3590                                   TestFactoryBase* factory) {
3591   TestInfo* const test_info = new TestInfo(
3592       test_case_name, name, type_param, value_param, fixture_class_id, factory);
3593   GetUnitTestImpl()->AddTestInfo(set_up_tc, tear_down_tc, test_info);
3594   return test_info;
3595 }
3596 
3597 #if GTEST_HAS_PARAM_TEST
ReportInvalidTestCaseType(const char * test_case_name,const char * file,int line)3598 void ReportInvalidTestCaseType(const char* test_case_name, const char* file,
3599                                int line) {
3600   Message errors;
3601   errors
3602       << "Attempted redefinition of test case " << test_case_name << ".\n"
3603       << "All tests in the same test case must use the same test fixture\n"
3604       << "class.  However, in test case " << test_case_name << ", you tried\n"
3605       << "to define a test using a fixture class different from the one\n"
3606       << "used earlier. This can happen if the two fixture classes are\n"
3607       << "from different namespaces and have the same name. You should\n"
3608       << "probably rename one of the classes to put the tests into different\n"
3609       << "test cases.";
3610 
3611   fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(),
3612           errors.GetString().c_str());
3613 }
3614 #endif  // GTEST_HAS_PARAM_TEST
3615 
3616 }  // namespace internal
3617 
3618 namespace {
3619 
3620 // A predicate that checks the test name of a TestInfo against a known
3621 // value.
3622 //
3623 // This is used for implementation of the TestCase class only.  We put
3624 // it in the anonymous namespace to prevent polluting the outer
3625 // namespace.
3626 //
3627 // TestNameIs is copyable.
3628 class TestNameIs {
3629  public:
3630   // Constructor.
3631   //
3632   // TestNameIs has NO default constructor.
TestNameIs(const char * name)3633   explicit TestNameIs(const char* name) : name_(name) {}
3634 
3635   // Returns true iff the test name of test_info matches name_.
operator ()(const TestInfo * test_info) const3636   bool operator()(const TestInfo* test_info) const {
3637     return test_info && test_info->name() == name_;
3638   }
3639 
3640  private:
3641   std::string name_;
3642 };
3643 
3644 }  // namespace
3645 
3646 namespace internal {
3647 
3648 // This method expands all parameterized tests registered with macros TEST_P
3649 // and INSTANTIATE_TEST_CASE_P into regular tests and registers those.
3650 // This will be done just once during the program runtime.
RegisterParameterizedTests()3651 void UnitTestImpl::RegisterParameterizedTests() {
3652 #if GTEST_HAS_PARAM_TEST
3653   if (!parameterized_tests_registered_) {
3654     parameterized_test_registry_.RegisterTests();
3655     parameterized_tests_registered_ = true;
3656   }
3657 #endif
3658 }
3659 
3660 }  // namespace internal
3661 
3662 // Creates the test object, runs it, records its result, and then
3663 // deletes it.
Run()3664 void TestInfo::Run() {
3665   if (!should_run_) return;
3666 
3667   // Tells UnitTest where to store test result.
3668   internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
3669   impl->set_current_test_info(this);
3670 
3671   TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
3672 
3673   // Notifies the unit test event listeners that a test is about to start.
3674   repeater->OnTestStart(*this);
3675 
3676   const TimeInMillis start = internal::GetTimeInMillis();
3677 
3678   impl->os_stack_trace_getter()->UponLeavingGTest();
3679 
3680   // Creates the test object.
3681   Test* const test = internal::HandleExceptionsInMethodIfSupported(
3682       factory_, &internal::TestFactoryBase::CreateTest,
3683       "the test fixture's constructor");
3684 
3685   // Runs the test only if the test object was created and its
3686   // constructor didn't generate a fatal failure.
3687   if ((test != NULL) && !Test::HasFatalFailure()) {
3688     // This doesn't throw as all user code that can throw are wrapped into
3689     // exception handling code.
3690     test->Run();
3691   }
3692 
3693   // Deletes the test object.
3694   impl->os_stack_trace_getter()->UponLeavingGTest();
3695   internal::HandleExceptionsInMethodIfSupported(
3696       test, &Test::DeleteSelf_, "the test fixture's destructor");
3697 
3698   result_.set_elapsed_time(internal::GetTimeInMillis() - start);
3699 
3700   // Notifies the unit test event listener that a test has just finished.
3701   repeater->OnTestEnd(*this);
3702 
3703   // Tells UnitTest to stop associating assertion results to this
3704   // test.
3705   impl->set_current_test_info(NULL);
3706 }
3707 
3708 // class TestCase
3709 
3710 // Gets the number of successful tests in this test case.
successful_test_count() const3711 int TestCase::successful_test_count() const {
3712   return CountIf(test_info_list_, TestPassed);
3713 }
3714 
3715 // Gets the number of failed tests in this test case.
failed_test_count() const3716 int TestCase::failed_test_count() const {
3717   return CountIf(test_info_list_, TestFailed);
3718 }
3719 
3720 // Gets the number of disabled tests that will be reported in the XML report.
reportable_disabled_test_count() const3721 int TestCase::reportable_disabled_test_count() const {
3722   return CountIf(test_info_list_, TestReportableDisabled);
3723 }
3724 
3725 // Gets the number of disabled tests in this test case.
disabled_test_count() const3726 int TestCase::disabled_test_count() const {
3727   return CountIf(test_info_list_, TestDisabled);
3728 }
3729 
3730 // Gets the number of tests to be printed in the XML report.
reportable_test_count() const3731 int TestCase::reportable_test_count() const {
3732   return CountIf(test_info_list_, TestReportable);
3733 }
3734 
3735 // Get the number of tests in this test case that should run.
test_to_run_count() const3736 int TestCase::test_to_run_count() const {
3737   return CountIf(test_info_list_, ShouldRunTest);
3738 }
3739 
3740 // Gets the number of all tests.
total_test_count() const3741 int TestCase::total_test_count() const {
3742   return static_cast<int>(test_info_list_.size());
3743 }
3744 
3745 // Creates a TestCase with the given name.
3746 //
3747 // Arguments:
3748 //
3749 //   name:         name of the test case
3750 //   a_type_param: the name of the test case's type parameter, or NULL if
3751 //                 this is not a typed or a type-parameterized test case.
3752 //   set_up_tc:    pointer to the function that sets up the test case
3753 //   tear_down_tc: pointer to the function that tears down the test case
TestCase(const char * a_name,const char * a_type_param,Test::SetUpTestCaseFunc set_up_tc,Test::TearDownTestCaseFunc tear_down_tc)3754 TestCase::TestCase(const char* a_name, const char* a_type_param,
3755                    Test::SetUpTestCaseFunc set_up_tc,
3756                    Test::TearDownTestCaseFunc tear_down_tc)
3757     : name_(a_name),
3758       type_param_(a_type_param ? new std::string(a_type_param) : NULL),
3759       set_up_tc_(set_up_tc),
3760       tear_down_tc_(tear_down_tc),
3761       should_run_(false),
3762       elapsed_time_(0) {}
3763 
3764 // Destructor of TestCase.
~TestCase()3765 TestCase::~TestCase() {
3766   // Deletes every Test in the collection.
3767   ForEach(test_info_list_, internal::Delete<TestInfo>);
3768 }
3769 
3770 // Returns the i-th test among all the tests. i can range from 0 to
3771 // total_test_count() - 1. If i is not in that range, returns NULL.
GetTestInfo(int i) const3772 const TestInfo* TestCase::GetTestInfo(int i) const {
3773   const int index = GetElementOr(test_indices_, i, -1);
3774   return index < 0 ? NULL : test_info_list_[index];
3775 }
3776 
3777 // Returns the i-th test among all the tests. i can range from 0 to
3778 // total_test_count() - 1. If i is not in that range, returns NULL.
GetMutableTestInfo(int i)3779 TestInfo* TestCase::GetMutableTestInfo(int i) {
3780   const int index = GetElementOr(test_indices_, i, -1);
3781   return index < 0 ? NULL : test_info_list_[index];
3782 }
3783 
3784 // Adds a test to this test case.  Will delete the test upon
3785 // destruction of the TestCase object.
AddTestInfo(TestInfo * test_info)3786 void TestCase::AddTestInfo(TestInfo* test_info) {
3787   test_info_list_.push_back(test_info);
3788   test_indices_.push_back(static_cast<int>(test_indices_.size()));
3789 }
3790 
3791 // Runs every test in this TestCase.
Run()3792 void TestCase::Run() {
3793   if (!should_run_) return;
3794 
3795   internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
3796   impl->set_current_test_case(this);
3797 
3798   TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
3799 
3800   repeater->OnTestCaseStart(*this);
3801   impl->os_stack_trace_getter()->UponLeavingGTest();
3802   internal::HandleExceptionsInMethodIfSupported(
3803       this, &TestCase::RunSetUpTestCase, "SetUpTestCase()");
3804 
3805   const internal::TimeInMillis start = internal::GetTimeInMillis();
3806   for (int i = 0; i < total_test_count(); i++) {
3807     GetMutableTestInfo(i)->Run();
3808   }
3809   elapsed_time_ = internal::GetTimeInMillis() - start;
3810 
3811   impl->os_stack_trace_getter()->UponLeavingGTest();
3812   internal::HandleExceptionsInMethodIfSupported(
3813       this, &TestCase::RunTearDownTestCase, "TearDownTestCase()");
3814 
3815   repeater->OnTestCaseEnd(*this);
3816   impl->set_current_test_case(NULL);
3817 }
3818 
3819 // Clears the results of all tests in this test case.
ClearResult()3820 void TestCase::ClearResult() {
3821   ad_hoc_test_result_.Clear();
3822   ForEach(test_info_list_, TestInfo::ClearTestResult);
3823 }
3824 
3825 // Shuffles the tests in this test case.
ShuffleTests(internal::Random * random)3826 void TestCase::ShuffleTests(internal::Random* random) {
3827   Shuffle(random, &test_indices_);
3828 }
3829 
3830 // Restores the test order to before the first shuffle.
UnshuffleTests()3831 void TestCase::UnshuffleTests() {
3832   for (size_t i = 0; i < test_indices_.size(); i++) {
3833     test_indices_[i] = static_cast<int>(i);
3834   }
3835 }
3836 
3837 // Formats a countable noun.  Depending on its quantity, either the
3838 // singular form or the plural form is used. e.g.
3839 //
3840 // FormatCountableNoun(1, "formula", "formuli") returns "1 formula".
3841 // FormatCountableNoun(5, "book", "books") returns "5 books".
FormatCountableNoun(int count,const char * singular_form,const char * plural_form)3842 static std::string FormatCountableNoun(int count, const char* singular_form,
3843                                        const char* plural_form) {
3844   return internal::StreamableToString(count) + " " +
3845          (count == 1 ? singular_form : plural_form);
3846 }
3847 
3848 // Formats the count of tests.
FormatTestCount(int test_count)3849 static std::string FormatTestCount(int test_count) {
3850   return FormatCountableNoun(test_count, "test", "tests");
3851 }
3852 
3853 // Formats the count of test cases.
FormatTestCaseCount(int test_case_count)3854 static std::string FormatTestCaseCount(int test_case_count) {
3855   return FormatCountableNoun(test_case_count, "test case", "test cases");
3856 }
3857 
3858 // Converts a TestPartResult::Type enum to human-friendly string
3859 // representation.  Both kNonFatalFailure and kFatalFailure are translated
3860 // to "Failure", as the user usually doesn't care about the difference
3861 // between the two when viewing the test result.
TestPartResultTypeToString(TestPartResult::Type type)3862 static const char* TestPartResultTypeToString(TestPartResult::Type type) {
3863   switch (type) {
3864   case TestPartResult::kSuccess:
3865     return "Success";
3866 
3867   case TestPartResult::kNonFatalFailure:
3868   case TestPartResult::kFatalFailure:
3869 #ifdef _MSC_VER
3870     return "error: ";
3871 #else
3872     return "Failure\n";
3873 #endif
3874   default:
3875     return "Unknown result type";
3876   }
3877 }
3878 
3879 namespace internal {
3880 
3881 // Prints a TestPartResult to an std::string.
PrintTestPartResultToString(const TestPartResult & test_part_result)3882 static std::string PrintTestPartResultToString(
3883     const TestPartResult& test_part_result) {
3884   return (Message() << internal::FormatFileLocation(
3885                            test_part_result.file_name(),
3886                            test_part_result.line_number())
3887                     << " "
3888                     << TestPartResultTypeToString(test_part_result.type())
3889                     << test_part_result.message())
3890       .GetString();
3891 }
3892 
3893 // Prints a TestPartResult.
PrintTestPartResult(const TestPartResult & test_part_result)3894 static void PrintTestPartResult(const TestPartResult& test_part_result) {
3895   const std::string& result = PrintTestPartResultToString(test_part_result);
3896   printf("%s\n", result.c_str());
3897   fflush(stdout);
3898   // If the test program runs in Visual Studio or a debugger, the
3899   // following statements add the test part result message to the Output
3900   // window such that the user can double-click on it to jump to the
3901   // corresponding source code location; otherwise they do nothing.
3902 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
3903   // We don't call OutputDebugString*() on Windows Mobile, as printing
3904   // to stdout is done by OutputDebugString() there already - we don't
3905   // want the same message printed twice.
3906   ::OutputDebugStringA(result.c_str());
3907   ::OutputDebugStringA("\n");
3908 #endif
3909 }
3910 
3911 // class PrettyUnitTestResultPrinter
3912 
3913 enum GTestColor { COLOR_DEFAULT, COLOR_RED, COLOR_GREEN, COLOR_YELLOW };
3914 
3915 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
3916 
3917 // Returns the character attribute for the given color.
GetColorAttribute(GTestColor color)3918 WORD GetColorAttribute(GTestColor color) {
3919   switch (color) {
3920   case COLOR_RED:
3921     return FOREGROUND_RED;
3922   case COLOR_GREEN:
3923     return FOREGROUND_GREEN;
3924   case COLOR_YELLOW:
3925     return FOREGROUND_RED | FOREGROUND_GREEN;
3926   default:
3927     return 0;
3928   }
3929 }
3930 
3931 #else
3932 
3933 // Returns the ANSI color code for the given color.  COLOR_DEFAULT is
3934 // an invalid input.
GetAnsiColorCode(GTestColor color)3935 const char* GetAnsiColorCode(GTestColor color) {
3936   switch (color) {
3937   case COLOR_RED:
3938     return "1";
3939   case COLOR_GREEN:
3940     return "2";
3941   case COLOR_YELLOW:
3942     return "3";
3943   default:
3944     return NULL;
3945   };
3946 }
3947 
3948 #endif  // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
3949 
3950 // Returns true iff Google Test should use colors in the output.
ShouldUseColor(bool stdout_is_tty)3951 bool ShouldUseColor(bool stdout_is_tty) {
3952   const char* const gtest_color = GTEST_FLAG(color).c_str();
3953 
3954   if (String::CaseInsensitiveCStringEquals(gtest_color, "auto")) {
3955 #if GTEST_OS_WINDOWS
3956     // On Windows the TERM variable is usually not set, but the
3957     // console there does support colors.
3958     return stdout_is_tty;
3959 #else
3960     // On non-Windows platforms, we rely on the TERM variable.
3961     const char* const term = posix::GetEnv("TERM");
3962     const bool term_supports_color =
3963         String::CStringEquals(term, "xterm") ||
3964         String::CStringEquals(term, "xterm-color") ||
3965         String::CStringEquals(term, "xterm-256color") ||
3966         String::CStringEquals(term, "screen") ||
3967         String::CStringEquals(term, "screen-256color") ||
3968         String::CStringEquals(term, "linux") ||
3969         String::CStringEquals(term, "cygwin");
3970     return stdout_is_tty && term_supports_color;
3971 #endif  // GTEST_OS_WINDOWS
3972   }
3973 
3974   return String::CaseInsensitiveCStringEquals(gtest_color, "yes") ||
3975          String::CaseInsensitiveCStringEquals(gtest_color, "true") ||
3976          String::CaseInsensitiveCStringEquals(gtest_color, "t") ||
3977          String::CStringEquals(gtest_color, "1");
3978   // We take "yes", "true", "t", and "1" as meaning "yes".  If the
3979   // value is neither one of these nor "auto", we treat it as "no" to
3980   // be conservative.
3981 }
3982 
3983 // Helpers for printing colored strings to stdout. Note that on Windows, we
3984 // cannot simply emit special characters and have the terminal change colors.
3985 // This routine must actually emit the characters rather than return a string
3986 // that would be colored when printed, as can be done on Linux.
ColoredPrintf(GTestColor color,const char * fmt,...)3987 void ColoredPrintf(GTestColor color, const char* fmt, ...) {
3988   va_list args;
3989   va_start(args, fmt);
3990 
3991 #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS || GTEST_OS_IOS
3992   const bool use_color = false;
3993 #else
3994   static const bool in_color_mode =
3995       ShouldUseColor(posix::IsATTY(posix::FileNo(stdout)) != 0);
3996   const bool use_color = in_color_mode && (color != COLOR_DEFAULT);
3997 #endif  // GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS
3998   // The '!= 0' comparison is necessary to satisfy MSVC 7.1.
3999 
4000   if (!use_color) {
4001     vprintf(fmt, args);
4002     va_end(args);
4003     return;
4004   }
4005 
4006 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
4007   const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
4008 
4009   // Gets the current text color.
4010   CONSOLE_SCREEN_BUFFER_INFO buffer_info;
4011   GetConsoleScreenBufferInfo(stdout_handle, &buffer_info);
4012   const WORD old_color_attrs = buffer_info.wAttributes;
4013 
4014   // We need to flush the stream buffers into the console before each
4015   // SetConsoleTextAttribute call lest it affect the text that is already
4016   // printed but has not yet reached the console.
4017   fflush(stdout);
4018   SetConsoleTextAttribute(stdout_handle,
4019                           GetColorAttribute(color) | FOREGROUND_INTENSITY);
4020   vprintf(fmt, args);
4021 
4022   fflush(stdout);
4023   // Restores the text color.
4024   SetConsoleTextAttribute(stdout_handle, old_color_attrs);
4025 #else
4026   printf("\033[0;3%sm", GetAnsiColorCode(color));
4027   vprintf(fmt, args);
4028   printf("\033[m");  // Resets the terminal to default.
4029 #endif  // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
4030   va_end(args);
4031 }
4032 
4033 // Text printed in Google Test's text output and --gunit_list_tests
4034 // output to label the type parameter and value parameter for a test.
4035 static const char kTypeParamLabel[] = "TypeParam";
4036 static const char kValueParamLabel[] = "GetParam()";
4037 
PrintFullTestCommentIfPresent(const TestInfo & test_info)4038 void PrintFullTestCommentIfPresent(const TestInfo& test_info) {
4039   const char* const type_param = test_info.type_param();
4040   const char* const value_param = test_info.value_param();
4041 
4042   if (type_param != NULL || value_param != NULL) {
4043     printf(", where ");
4044     if (type_param != NULL) {
4045       printf("%s = %s", kTypeParamLabel, type_param);
4046       if (value_param != NULL) printf(" and ");
4047     }
4048     if (value_param != NULL) {
4049       printf("%s = %s", kValueParamLabel, value_param);
4050     }
4051   }
4052 }
4053 
4054 // This class implements the TestEventListener interface.
4055 //
4056 // Class PrettyUnitTestResultPrinter is copyable.
4057 class PrettyUnitTestResultPrinter : public TestEventListener {
4058  public:
PrettyUnitTestResultPrinter()4059   PrettyUnitTestResultPrinter() {}
PrintTestName(const char * test_case,const char * test)4060   static void PrintTestName(const char* test_case, const char* test) {
4061     printf("%s.%s", test_case, test);
4062   }
4063 
4064   // The following methods override what's in the TestEventListener class.
OnTestProgramStart(const UnitTest &)4065   virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {}
4066   virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration);
4067   virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test);
OnEnvironmentsSetUpEnd(const UnitTest &)4068   virtual void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) {}
4069   virtual void OnTestCaseStart(const TestCase& test_case);
4070   virtual void OnTestStart(const TestInfo& test_info);
4071   virtual void OnTestPartResult(const TestPartResult& result);
4072   virtual void OnTestEnd(const TestInfo& test_info);
4073   virtual void OnTestCaseEnd(const TestCase& test_case);
4074   virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test);
OnEnvironmentsTearDownEnd(const UnitTest &)4075   virtual void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) {}
4076   virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
OnTestProgramEnd(const UnitTest &)4077   virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) {}
4078 
4079  private:
4080   static void PrintFailedTests(const UnitTest& unit_test);
4081 };
4082 
4083 // Fired before each iteration of tests starts.
OnTestIterationStart(const UnitTest & unit_test,int iteration)4084 void PrettyUnitTestResultPrinter::OnTestIterationStart(
4085     const UnitTest& unit_test, int iteration) {
4086   if (GTEST_FLAG(repeat) != 1)
4087     printf("\nRepeating all tests (iteration %d) . . .\n\n", iteration + 1);
4088 
4089   const char* const filter = GTEST_FLAG(filter).c_str();
4090 
4091   // Prints the filter if it's not *.  This reminds the user that some
4092   // tests may be skipped.
4093   if (!String::CStringEquals(filter, kUniversalFilter)) {
4094     ColoredPrintf(COLOR_YELLOW, "Note: %s filter = %s\n", GTEST_NAME_, filter);
4095   }
4096 
4097   if (internal::ShouldShard(kTestTotalShards, kTestShardIndex, false)) {
4098     const Int32 shard_index = Int32FromEnvOrDie(kTestShardIndex, -1);
4099     ColoredPrintf(COLOR_YELLOW, "Note: This is test shard %d of %s.\n",
4100                   static_cast<int>(shard_index) + 1,
4101                   internal::posix::GetEnv(kTestTotalShards));
4102   }
4103 
4104   if (GTEST_FLAG(shuffle)) {
4105     ColoredPrintf(COLOR_YELLOW,
4106                   "Note: Randomizing tests' orders with a seed of %d .\n",
4107                   unit_test.random_seed());
4108   }
4109 
4110   ColoredPrintf(COLOR_GREEN, "[==========] ");
4111   printf("Running %s from %s.\n",
4112          FormatTestCount(unit_test.test_to_run_count()).c_str(),
4113          FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str());
4114   fflush(stdout);
4115 }
4116 
OnEnvironmentsSetUpStart(const UnitTest &)4117 void PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart(
4118     const UnitTest& /*unit_test*/) {
4119   ColoredPrintf(COLOR_GREEN, "[----------] ");
4120   printf("Global test environment set-up.\n");
4121   fflush(stdout);
4122 }
4123 
OnTestCaseStart(const TestCase & test_case)4124 void PrettyUnitTestResultPrinter::OnTestCaseStart(const TestCase& test_case) {
4125   const std::string counts =
4126       FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
4127   ColoredPrintf(COLOR_GREEN, "[----------] ");
4128   printf("%s from %s", counts.c_str(), test_case.name());
4129   if (test_case.type_param() == NULL) {
4130     printf("\n");
4131   } else {
4132     printf(", where %s = %s\n", kTypeParamLabel, test_case.type_param());
4133   }
4134   fflush(stdout);
4135 }
4136 
OnTestStart(const TestInfo & test_info)4137 void PrettyUnitTestResultPrinter::OnTestStart(const TestInfo& test_info) {
4138   ColoredPrintf(COLOR_GREEN, "[ RUN      ] ");
4139   PrintTestName(test_info.test_case_name(), test_info.name());
4140   printf("\n");
4141   fflush(stdout);
4142 }
4143 
4144 // Called after an assertion failure.
OnTestPartResult(const TestPartResult & result)4145 void PrettyUnitTestResultPrinter::OnTestPartResult(
4146     const TestPartResult& result) {
4147   // If the test part succeeded, we don't need to do anything.
4148   if (result.type() == TestPartResult::kSuccess) return;
4149 
4150   // Print failure message from the assertion (e.g. expected this and got that).
4151   PrintTestPartResult(result);
4152   fflush(stdout);
4153 }
4154 
OnTestEnd(const TestInfo & test_info)4155 void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) {
4156   if (test_info.result()->Passed()) {
4157     ColoredPrintf(COLOR_GREEN, "[       OK ] ");
4158   } else {
4159     ColoredPrintf(COLOR_RED, "[  FAILED  ] ");
4160   }
4161   PrintTestName(test_info.test_case_name(), test_info.name());
4162   if (test_info.result()->Failed()) PrintFullTestCommentIfPresent(test_info);
4163 
4164   if (GTEST_FLAG(print_time)) {
4165     printf(" (%s ms)\n",
4166            internal::StreamableToString(test_info.result()->elapsed_time())
4167                .c_str());
4168   } else {
4169     printf("\n");
4170   }
4171   fflush(stdout);
4172 }
4173 
OnTestCaseEnd(const TestCase & test_case)4174 void PrettyUnitTestResultPrinter::OnTestCaseEnd(const TestCase& test_case) {
4175   if (!GTEST_FLAG(print_time)) return;
4176 
4177   const std::string counts =
4178       FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
4179   ColoredPrintf(COLOR_GREEN, "[----------] ");
4180   printf("%s from %s (%s ms total)\n\n", counts.c_str(), test_case.name(),
4181          internal::StreamableToString(test_case.elapsed_time()).c_str());
4182   fflush(stdout);
4183 }
4184 
OnEnvironmentsTearDownStart(const UnitTest &)4185 void PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart(
4186     const UnitTest& /*unit_test*/) {
4187   ColoredPrintf(COLOR_GREEN, "[----------] ");
4188   printf("Global test environment tear-down\n");
4189   fflush(stdout);
4190 }
4191 
4192 // Internal helper for printing the list of failed tests.
PrintFailedTests(const UnitTest & unit_test)4193 void PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest& unit_test) {
4194   const int failed_test_count = unit_test.failed_test_count();
4195   if (failed_test_count == 0) {
4196     return;
4197   }
4198 
4199   for (int i = 0; i < unit_test.total_test_case_count(); ++i) {
4200     const TestCase& test_case = *unit_test.GetTestCase(i);
4201     if (!test_case.should_run() || (test_case.failed_test_count() == 0)) {
4202       continue;
4203     }
4204     for (int j = 0; j < test_case.total_test_count(); ++j) {
4205       const TestInfo& test_info = *test_case.GetTestInfo(j);
4206       if (!test_info.should_run() || test_info.result()->Passed()) {
4207         continue;
4208       }
4209       ColoredPrintf(COLOR_RED, "[  FAILED  ] ");
4210       printf("%s.%s", test_case.name(), test_info.name());
4211       PrintFullTestCommentIfPresent(test_info);
4212       printf("\n");
4213     }
4214   }
4215 }
4216 
OnTestIterationEnd(const UnitTest & unit_test,int)4217 void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
4218                                                      int /*iteration*/) {
4219   ColoredPrintf(COLOR_GREEN, "[==========] ");
4220   printf("%s from %s ran.",
4221          FormatTestCount(unit_test.test_to_run_count()).c_str(),
4222          FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str());
4223   if (GTEST_FLAG(print_time)) {
4224     printf(" (%s ms total)",
4225            internal::StreamableToString(unit_test.elapsed_time()).c_str());
4226   }
4227   printf("\n");
4228   ColoredPrintf(COLOR_GREEN, "[  PASSED  ] ");
4229   printf("%s.\n", FormatTestCount(unit_test.successful_test_count()).c_str());
4230 
4231   int num_failures = unit_test.failed_test_count();
4232   if (!unit_test.Passed()) {
4233     const int failed_test_count = unit_test.failed_test_count();
4234     ColoredPrintf(COLOR_RED, "[  FAILED  ] ");
4235     printf("%s, listed below:\n", FormatTestCount(failed_test_count).c_str());
4236     PrintFailedTests(unit_test);
4237     printf("\n%2d FAILED %s\n", num_failures,
4238            num_failures == 1 ? "TEST" : "TESTS");
4239   }
4240 
4241   int num_disabled = unit_test.reportable_disabled_test_count();
4242   if (num_disabled && !GTEST_FLAG(also_run_disabled_tests)) {
4243     if (!num_failures) {
4244       printf("\n");  // Add a spacer if no FAILURE banner is displayed.
4245     }
4246     ColoredPrintf(COLOR_YELLOW, "  YOU HAVE %d DISABLED %s\n\n", num_disabled,
4247                   num_disabled == 1 ? "TEST" : "TESTS");
4248   }
4249   // Ensure that Google Test output is printed before, e.g., heapchecker output.
4250   fflush(stdout);
4251 }
4252 
4253 // End PrettyUnitTestResultPrinter
4254 
4255 // class TestEventRepeater
4256 //
4257 // This class forwards events to other event listeners.
4258 class TestEventRepeater : public TestEventListener {
4259  public:
TestEventRepeater()4260   TestEventRepeater() : forwarding_enabled_(true) {}
4261   virtual ~TestEventRepeater();
4262   void Append(TestEventListener* listener);
4263   TestEventListener* Release(TestEventListener* listener);
4264 
4265   // Controls whether events will be forwarded to listeners_. Set to false
4266   // in death test child processes.
forwarding_enabled() const4267   bool forwarding_enabled() const { return forwarding_enabled_; }
set_forwarding_enabled(bool enable)4268   void set_forwarding_enabled(bool enable) { forwarding_enabled_ = enable; }
4269 
4270   virtual void OnTestProgramStart(const UnitTest& unit_test);
4271   virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration);
4272   virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test);
4273   virtual void OnEnvironmentsSetUpEnd(const UnitTest& unit_test);
4274   virtual void OnTestCaseStart(const TestCase& test_case);
4275   virtual void OnTestStart(const TestInfo& test_info);
4276   virtual void OnTestPartResult(const TestPartResult& result);
4277   virtual void OnTestEnd(const TestInfo& test_info);
4278   virtual void OnTestCaseEnd(const TestCase& test_case);
4279   virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test);
4280   virtual void OnEnvironmentsTearDownEnd(const UnitTest& unit_test);
4281   virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
4282   virtual void OnTestProgramEnd(const UnitTest& unit_test);
4283 
4284  private:
4285   // Controls whether events will be forwarded to listeners_. Set to false
4286   // in death test child processes.
4287   bool forwarding_enabled_;
4288   // The list of listeners that receive events.
4289   std::vector<TestEventListener*> listeners_;
4290 
4291   GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventRepeater);
4292 };
4293 
~TestEventRepeater()4294 TestEventRepeater::~TestEventRepeater() {
4295   ForEach(listeners_, Delete<TestEventListener>);
4296 }
4297 
Append(TestEventListener * listener)4298 void TestEventRepeater::Append(TestEventListener* listener) {
4299   listeners_.push_back(listener);
4300 }
4301 
4302 // TODO(vladl@google.com): Factor the search functionality into Vector::Find.
Release(TestEventListener * listener)4303 TestEventListener* TestEventRepeater::Release(TestEventListener* listener) {
4304   for (size_t i = 0; i < listeners_.size(); ++i) {
4305     if (listeners_[i] == listener) {
4306       listeners_.erase(listeners_.begin() + i);
4307       return listener;
4308     }
4309   }
4310 
4311   return NULL;
4312 }
4313 
4314 // Since most methods are very similar, use macros to reduce boilerplate.
4315 // This defines a member that forwards the call to all listeners.
4316 #define GTEST_REPEATER_METHOD_(Name, Type)              \
4317   void TestEventRepeater::Name(const Type& parameter) { \
4318     if (forwarding_enabled_) {                          \
4319       for (size_t i = 0; i < listeners_.size(); i++) {  \
4320         listeners_[i]->Name(parameter);                 \
4321       }                                                 \
4322     }                                                   \
4323   }
4324 // This defines a member that forwards the call to all listeners in reverse
4325 // order.
4326 #define GTEST_REVERSE_REPEATER_METHOD_(Name, Type)                         \
4327   void TestEventRepeater::Name(const Type& parameter) {                    \
4328     if (forwarding_enabled_) {                                             \
4329       for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) { \
4330         listeners_[i]->Name(parameter);                                    \
4331       }                                                                    \
4332     }                                                                      \
4333   }
4334 
GTEST_REPEATER_METHOD_(OnTestProgramStart,UnitTest)4335 GTEST_REPEATER_METHOD_(OnTestProgramStart, UnitTest)
4336 GTEST_REPEATER_METHOD_(OnEnvironmentsSetUpStart, UnitTest)
4337 GTEST_REPEATER_METHOD_(OnTestCaseStart, TestCase)
4338 GTEST_REPEATER_METHOD_(OnTestStart, TestInfo)
4339 GTEST_REPEATER_METHOD_(OnTestPartResult, TestPartResult)
4340 GTEST_REPEATER_METHOD_(OnEnvironmentsTearDownStart, UnitTest)
4341 GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsSetUpEnd, UnitTest)
4342 GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsTearDownEnd, UnitTest)
4343 GTEST_REVERSE_REPEATER_METHOD_(OnTestEnd, TestInfo)
4344 GTEST_REVERSE_REPEATER_METHOD_(OnTestCaseEnd, TestCase)
4345 GTEST_REVERSE_REPEATER_METHOD_(OnTestProgramEnd, UnitTest)
4346 
4347 #undef GTEST_REPEATER_METHOD_
4348 #undef GTEST_REVERSE_REPEATER_METHOD_
4349 
4350 void TestEventRepeater::OnTestIterationStart(const UnitTest& unit_test,
4351                                              int iteration) {
4352   if (forwarding_enabled_) {
4353     for (size_t i = 0; i < listeners_.size(); i++) {
4354       listeners_[i]->OnTestIterationStart(unit_test, iteration);
4355     }
4356   }
4357 }
4358 
OnTestIterationEnd(const UnitTest & unit_test,int iteration)4359 void TestEventRepeater::OnTestIterationEnd(const UnitTest& unit_test,
4360                                            int iteration) {
4361   if (forwarding_enabled_) {
4362     for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) {
4363       listeners_[i]->OnTestIterationEnd(unit_test, iteration);
4364     }
4365   }
4366 }
4367 
4368 // End TestEventRepeater
4369 
4370 // This class generates an XML output file.
4371 class XmlUnitTestResultPrinter : public EmptyTestEventListener {
4372  public:
4373   explicit XmlUnitTestResultPrinter(const char* output_file);
4374 
4375   virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
4376 
4377  private:
4378   // Is c a whitespace character that is normalized to a space character
4379   // when it appears in an XML attribute value?
IsNormalizableWhitespace(char c)4380   static bool IsNormalizableWhitespace(char c) {
4381     return c == 0x9 || c == 0xA || c == 0xD;
4382   }
4383 
4384   // May c appear in a well-formed XML document?
IsValidXmlCharacter(char c)4385   static bool IsValidXmlCharacter(char c) {
4386     return IsNormalizableWhitespace(c) || c >= 0x20;
4387   }
4388 
4389   // Returns an XML-escaped copy of the input string str.  If
4390   // is_attribute is true, the text is meant to appear as an attribute
4391   // value, and normalizable whitespace is preserved by replacing it
4392   // with character references.
4393   static std::string EscapeXml(const std::string& str, bool is_attribute);
4394 
4395   // Returns the given string with all characters invalid in XML removed.
4396   static std::string RemoveInvalidXmlCharacters(const std::string& str);
4397 
4398   // Convenience wrapper around EscapeXml when str is an attribute value.
EscapeXmlAttribute(const std::string & str)4399   static std::string EscapeXmlAttribute(const std::string& str) {
4400     return EscapeXml(str, true);
4401   }
4402 
4403   // Convenience wrapper around EscapeXml when str is not an attribute value.
EscapeXmlText(const char * str)4404   static std::string EscapeXmlText(const char* str) {
4405     return EscapeXml(str, false);
4406   }
4407 
4408   // Verifies that the given attribute belongs to the given element and
4409   // streams the attribute as XML.
4410   static void OutputXmlAttribute(std::ostream* stream,
4411                                  const std::string& element_name,
4412                                  const std::string& name,
4413                                  const std::string& value);
4414 
4415   // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
4416   static void OutputXmlCDataSection(::std::ostream* stream, const char* data);
4417 
4418   // Streams an XML representation of a TestInfo object.
4419   static void OutputXmlTestInfo(::std::ostream* stream,
4420                                 const char* test_case_name,
4421                                 const TestInfo& test_info);
4422 
4423   // Prints an XML representation of a TestCase object
4424   static void PrintXmlTestCase(::std::ostream* stream,
4425                                const TestCase& test_case);
4426 
4427   // Prints an XML summary of unit_test to output stream out.
4428   static void PrintXmlUnitTest(::std::ostream* stream,
4429                                const UnitTest& unit_test);
4430 
4431   // Produces a string representing the test properties in a result as space
4432   // delimited XML attributes based on the property key="value" pairs.
4433   // When the std::string is not empty, it includes a space at the beginning,
4434   // to delimit this attribute from prior attributes.
4435   static std::string TestPropertiesAsXmlAttributes(const TestResult& result);
4436 
4437   // The output file.
4438   const std::string output_file_;
4439 
4440   GTEST_DISALLOW_COPY_AND_ASSIGN_(XmlUnitTestResultPrinter);
4441 };
4442 
4443 // Creates a new XmlUnitTestResultPrinter.
XmlUnitTestResultPrinter(const char * output_file)4444 XmlUnitTestResultPrinter::XmlUnitTestResultPrinter(const char* output_file)
4445     : output_file_(output_file) {
4446   if (output_file_.c_str() == NULL || output_file_.empty()) {
4447     fprintf(stderr, "XML output file may not be null\n");
4448     fflush(stderr);
4449     exit(EXIT_FAILURE);
4450   }
4451 }
4452 
4453 // Called after the unit test ends.
OnTestIterationEnd(const UnitTest & unit_test,int)4454 void XmlUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
4455                                                   int /*iteration*/) {
4456   FILE* xmlout = NULL;
4457   FilePath output_file(output_file_);
4458   FilePath output_dir(output_file.RemoveFileName());
4459 
4460   if (output_dir.CreateDirectoriesRecursively()) {
4461     xmlout = posix::FOpen(output_file_.c_str(), "w");
4462   }
4463   if (xmlout == NULL) {
4464     // TODO(wan): report the reason of the failure.
4465     //
4466     // We don't do it for now as:
4467     //
4468     //   1. There is no urgent need for it.
4469     //   2. It's a bit involved to make the errno variable thread-safe on
4470     //      all three operating systems (Linux, Windows, and Mac OS).
4471     //   3. To interpret the meaning of errno in a thread-safe way,
4472     //      we need the strerror_r() function, which is not available on
4473     //      Windows.
4474     fprintf(stderr, "Unable to open file \"%s\"\n", output_file_.c_str());
4475     fflush(stderr);
4476     exit(EXIT_FAILURE);
4477   }
4478   std::stringstream stream;
4479   PrintXmlUnitTest(&stream, unit_test);
4480   fprintf(xmlout, "%s", StringStreamToString(&stream).c_str());
4481   fclose(xmlout);
4482 }
4483 
4484 // Returns an XML-escaped copy of the input string str.  If is_attribute
4485 // is true, the text is meant to appear as an attribute value, and
4486 // normalizable whitespace is preserved by replacing it with character
4487 // references.
4488 //
4489 // Invalid XML characters in str, if any, are stripped from the output.
4490 // It is expected that most, if not all, of the text processed by this
4491 // module will consist of ordinary English text.
4492 // If this module is ever modified to produce version 1.1 XML output,
4493 // most invalid characters can be retained using character references.
4494 // TODO(wan): It might be nice to have a minimally invasive, human-readable
4495 // escaping scheme for invalid characters, rather than dropping them.
EscapeXml(const std::string & str,bool is_attribute)4496 std::string XmlUnitTestResultPrinter::EscapeXml(const std::string& str,
4497                                                 bool is_attribute) {
4498   Message m;
4499 
4500   for (size_t i = 0; i < str.size(); ++i) {
4501     const char ch = str[i];
4502     switch (ch) {
4503     case '<':
4504       m << "&lt;";
4505       break;
4506     case '>':
4507       m << "&gt;";
4508       break;
4509     case '&':
4510       m << "&amp;";
4511       break;
4512     case '\'':
4513       if (is_attribute)
4514         m << "&apos;";
4515       else
4516         m << '\'';
4517       break;
4518     case '"':
4519       if (is_attribute)
4520         m << "&quot;";
4521       else
4522         m << '"';
4523       break;
4524     default:
4525       if (IsValidXmlCharacter(ch)) {
4526         if (is_attribute && IsNormalizableWhitespace(ch))
4527           m << "&#x" << String::FormatByte(static_cast<unsigned char>(ch))
4528             << ";";
4529         else
4530           m << ch;
4531       }
4532       break;
4533     }
4534   }
4535 
4536   return m.GetString();
4537 }
4538 
4539 // Returns the given string with all characters invalid in XML removed.
4540 // Currently invalid characters are dropped from the string. An
4541 // alternative is to replace them with certain characters such as . or ?.
RemoveInvalidXmlCharacters(const std::string & str)4542 std::string XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters(
4543     const std::string& str) {
4544   std::string output;
4545   output.reserve(str.size());
4546   for (std::string::const_iterator it = str.begin(); it != str.end(); ++it)
4547     if (IsValidXmlCharacter(*it)) output.push_back(*it);
4548 
4549   return output;
4550 }
4551 
4552 // The following routines generate an XML representation of a UnitTest
4553 // object.
4554 //
4555 // This is how Google Test concepts map to the DTD:
4556 //
4557 // <testsuites name="AllTests">        <-- corresponds to a UnitTest object
4558 //   <testsuite name="testcase-name">  <-- corresponds to a TestCase object
4559 //     <testcase name="test-name">     <-- corresponds to a TestInfo object
4560 //       <failure message="...">...</failure>
4561 //       <failure message="...">...</failure>
4562 //       <failure message="...">...</failure>
4563 //                                     <-- individual assertion failures
4564 //     </testcase>
4565 //   </testsuite>
4566 // </testsuites>
4567 
4568 // Formats the given time in milliseconds as seconds.
FormatTimeInMillisAsSeconds(TimeInMillis ms)4569 std::string FormatTimeInMillisAsSeconds(TimeInMillis ms) {
4570   ::std::stringstream ss;
4571   ss << ms / 1000.0;
4572   return ss.str();
4573 }
4574 
4575 // Converts the given epoch time in milliseconds to a date string in the ISO
4576 // 8601 format, without the timezone information.
FormatEpochTimeInMillisAsIso8601(TimeInMillis ms)4577 std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms) {
4578   // Using non-reentrant version as localtime_r is not portable.
4579   time_t seconds = static_cast<time_t>(ms / 1000);
4580 #ifdef _MSC_VER
4581 #  pragma warning(push)            // Saves the current warning state.
4582 #  pragma warning(disable : 4996)  // Temporarily disables warning 4996
4583                                    // (function or variable may be unsafe).
4584   const struct tm* const time_struct = localtime(&seconds);  // NOLINT
4585 #  pragma warning(pop)  // Restores the warning state again.
4586 #else
4587   const struct tm* const time_struct = localtime(&seconds);  // NOLINT
4588 #endif
4589   if (time_struct == NULL) return "";  // Invalid ms value
4590 
4591   // YYYY-MM-DDThh:mm:ss
4592   return StreamableToString(time_struct->tm_year + 1900) + "-" +
4593          String::FormatIntWidth2(time_struct->tm_mon + 1) + "-" +
4594          String::FormatIntWidth2(time_struct->tm_mday) + "T" +
4595          String::FormatIntWidth2(time_struct->tm_hour) + ":" +
4596          String::FormatIntWidth2(time_struct->tm_min) + ":" +
4597          String::FormatIntWidth2(time_struct->tm_sec);
4598 }
4599 
4600 // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
OutputXmlCDataSection(::std::ostream * stream,const char * data)4601 void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream,
4602                                                      const char* data) {
4603   const char* segment = data;
4604   *stream << "<![CDATA[";
4605   for (;;) {
4606     const char* const next_segment = strstr(segment, "]]>");
4607     if (next_segment != NULL) {
4608       stream->write(segment,
4609                     static_cast<std::streamsize>(next_segment - segment));
4610       *stream << "]]>]]&gt;<![CDATA[";
4611       segment = next_segment + strlen("]]>");
4612     } else {
4613       *stream << segment;
4614       break;
4615     }
4616   }
4617   *stream << "]]>";
4618 }
4619 
OutputXmlAttribute(std::ostream * stream,const std::string & element_name,const std::string & name,const std::string & value)4620 void XmlUnitTestResultPrinter::OutputXmlAttribute(
4621     std::ostream* stream, const std::string& element_name,
4622     const std::string& name, const std::string& value) {
4623   const std::vector<std::string>& allowed_names =
4624       GetReservedAttributesForElement(element_name);
4625 
4626   GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
4627                allowed_names.end())
4628       << "Attribute " << name << " is not allowed for element <" << element_name
4629       << ">.";
4630 
4631   *stream << " " << name << "=\"" << EscapeXmlAttribute(value) << "\"";
4632 }
4633 
4634 // Prints an XML representation of a TestInfo object.
4635 // TODO(wan): There is also value in printing properties with the plain printer.
OutputXmlTestInfo(::std::ostream * stream,const char * test_case_name,const TestInfo & test_info)4636 void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream,
4637                                                  const char* test_case_name,
4638                                                  const TestInfo& test_info) {
4639   const TestResult& result = *test_info.result();
4640   const std::string kTestcase = "testcase";
4641 
4642   *stream << "    <testcase";
4643   OutputXmlAttribute(stream, kTestcase, "name", test_info.name());
4644 
4645   if (test_info.value_param() != NULL) {
4646     OutputXmlAttribute(stream, kTestcase, "value_param",
4647                        test_info.value_param());
4648   }
4649   if (test_info.type_param() != NULL) {
4650     OutputXmlAttribute(stream, kTestcase, "type_param", test_info.type_param());
4651   }
4652 
4653   OutputXmlAttribute(stream, kTestcase, "status",
4654                      test_info.should_run() ? "run" : "notrun");
4655   OutputXmlAttribute(stream, kTestcase, "time",
4656                      FormatTimeInMillisAsSeconds(result.elapsed_time()));
4657   OutputXmlAttribute(stream, kTestcase, "classname", test_case_name);
4658   *stream << TestPropertiesAsXmlAttributes(result);
4659 
4660   int failures = 0;
4661   for (int i = 0; i < result.total_part_count(); ++i) {
4662     const TestPartResult& part = result.GetTestPartResult(i);
4663     if (part.failed()) {
4664       if (++failures == 1) {
4665         *stream << ">\n";
4666       }
4667       const string location = internal::FormatCompilerIndependentFileLocation(
4668           part.file_name(), part.line_number());
4669       const string summary = location + "\n" + part.summary();
4670       *stream << "      <failure message=\""
4671               << EscapeXmlAttribute(summary.c_str()) << "\" type=\"\">";
4672       const string detail = location + "\n" + part.message();
4673       OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str());
4674       *stream << "</failure>\n";
4675     }
4676   }
4677 
4678   if (failures == 0)
4679     *stream << " />\n";
4680   else
4681     *stream << "    </testcase>\n";
4682 }
4683 
4684 // Prints an XML representation of a TestCase object
PrintXmlTestCase(std::ostream * stream,const TestCase & test_case)4685 void XmlUnitTestResultPrinter::PrintXmlTestCase(std::ostream* stream,
4686                                                 const TestCase& test_case) {
4687   const std::string kTestsuite = "testsuite";
4688   *stream << "  <" << kTestsuite;
4689   OutputXmlAttribute(stream, kTestsuite, "name", test_case.name());
4690   OutputXmlAttribute(stream, kTestsuite, "tests",
4691                      StreamableToString(test_case.reportable_test_count()));
4692   OutputXmlAttribute(stream, kTestsuite, "failures",
4693                      StreamableToString(test_case.failed_test_count()));
4694   OutputXmlAttribute(
4695       stream, kTestsuite, "disabled",
4696       StreamableToString(test_case.reportable_disabled_test_count()));
4697   OutputXmlAttribute(stream, kTestsuite, "errors", "0");
4698   OutputXmlAttribute(stream, kTestsuite, "time",
4699                      FormatTimeInMillisAsSeconds(test_case.elapsed_time()));
4700   *stream << TestPropertiesAsXmlAttributes(test_case.ad_hoc_test_result())
4701           << ">\n";
4702 
4703   for (int i = 0; i < test_case.total_test_count(); ++i) {
4704     if (test_case.GetTestInfo(i)->is_reportable())
4705       OutputXmlTestInfo(stream, test_case.name(), *test_case.GetTestInfo(i));
4706   }
4707   *stream << "  </" << kTestsuite << ">\n";
4708 }
4709 
4710 // Prints an XML summary of unit_test to output stream out.
PrintXmlUnitTest(std::ostream * stream,const UnitTest & unit_test)4711 void XmlUnitTestResultPrinter::PrintXmlUnitTest(std::ostream* stream,
4712                                                 const UnitTest& unit_test) {
4713   const std::string kTestsuites = "testsuites";
4714 
4715   *stream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
4716   *stream << "<" << kTestsuites;
4717 
4718   OutputXmlAttribute(stream, kTestsuites, "tests",
4719                      StreamableToString(unit_test.reportable_test_count()));
4720   OutputXmlAttribute(stream, kTestsuites, "failures",
4721                      StreamableToString(unit_test.failed_test_count()));
4722   OutputXmlAttribute(
4723       stream, kTestsuites, "disabled",
4724       StreamableToString(unit_test.reportable_disabled_test_count()));
4725   OutputXmlAttribute(stream, kTestsuites, "errors", "0");
4726   OutputXmlAttribute(
4727       stream, kTestsuites, "timestamp",
4728       FormatEpochTimeInMillisAsIso8601(unit_test.start_timestamp()));
4729   OutputXmlAttribute(stream, kTestsuites, "time",
4730                      FormatTimeInMillisAsSeconds(unit_test.elapsed_time()));
4731 
4732   if (GTEST_FLAG(shuffle)) {
4733     OutputXmlAttribute(stream, kTestsuites, "random_seed",
4734                        StreamableToString(unit_test.random_seed()));
4735   }
4736 
4737   *stream << TestPropertiesAsXmlAttributes(unit_test.ad_hoc_test_result());
4738 
4739   OutputXmlAttribute(stream, kTestsuites, "name", "AllTests");
4740   *stream << ">\n";
4741 
4742   for (int i = 0; i < unit_test.total_test_case_count(); ++i) {
4743     if (unit_test.GetTestCase(i)->reportable_test_count() > 0)
4744       PrintXmlTestCase(stream, *unit_test.GetTestCase(i));
4745   }
4746   *stream << "</" << kTestsuites << ">\n";
4747 }
4748 
4749 // Produces a string representing the test properties in a result as space
4750 // delimited XML attributes based on the property key="value" pairs.
TestPropertiesAsXmlAttributes(const TestResult & result)4751 std::string XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes(
4752     const TestResult& result) {
4753   Message attributes;
4754   for (int i = 0; i < result.test_property_count(); ++i) {
4755     const TestProperty& property = result.GetTestProperty(i);
4756     attributes << " " << property.key() << "="
4757                << "\"" << EscapeXmlAttribute(property.value()) << "\"";
4758   }
4759   return attributes.GetString();
4760 }
4761 
4762 // End XmlUnitTestResultPrinter
4763 
4764 #if GTEST_CAN_STREAM_RESULTS_
4765 
4766 // Checks if str contains '=', '&', '%' or '\n' characters. If yes,
4767 // replaces them by "%xx" where xx is their hexadecimal value. For
4768 // example, replaces "=" with "%3D".  This algorithm is O(strlen(str))
4769 // in both time and space -- important as the input str may contain an
4770 // arbitrarily long test failure message and stack trace.
UrlEncode(const char * str)4771 string StreamingListener::UrlEncode(const char* str) {
4772   string result;
4773   result.reserve(strlen(str) + 1);
4774   for (char ch = *str; ch != '\0'; ch = *++str) {
4775     switch (ch) {
4776     case '%':
4777     case '=':
4778     case '&':
4779     case '\n':
4780       result.append("%" + String::FormatByte(static_cast<unsigned char>(ch)));
4781       break;
4782     default:
4783       result.push_back(ch);
4784       break;
4785     }
4786   }
4787   return result;
4788 }
4789 
MakeConnection()4790 void StreamingListener::SocketWriter::MakeConnection() {
4791   GTEST_CHECK_(sockfd_ == -1)
4792       << "MakeConnection() can't be called when there is already a connection.";
4793 
4794   addrinfo hints;
4795   memset(&hints, 0, sizeof(hints));
4796   hints.ai_family = AF_UNSPEC;  // To allow both IPv4 and IPv6 addresses.
4797   hints.ai_socktype = SOCK_STREAM;
4798   addrinfo* servinfo = NULL;
4799 
4800   // Use the getaddrinfo() to get a linked list of IP addresses for
4801   // the given host name.
4802   const int error_num =
4803       getaddrinfo(host_name_.c_str(), port_num_.c_str(), &hints, &servinfo);
4804   if (error_num != 0) {
4805     GTEST_LOG_(WARNING) << "stream_result_to: getaddrinfo() failed: "
4806                         << gai_strerror(error_num);
4807   }
4808 
4809   // Loop through all the results and connect to the first we can.
4810   for (addrinfo* cur_addr = servinfo; sockfd_ == -1 && cur_addr != NULL;
4811        cur_addr = cur_addr->ai_next) {
4812     sockfd_ = socket(cur_addr->ai_family, cur_addr->ai_socktype,
4813                      cur_addr->ai_protocol);
4814     if (sockfd_ != -1) {
4815       // Connect the client socket to the server socket.
4816       if (connect(sockfd_, cur_addr->ai_addr, cur_addr->ai_addrlen) == -1) {
4817         close(sockfd_);
4818         sockfd_ = -1;
4819       }
4820     }
4821   }
4822 
4823   freeaddrinfo(servinfo);  // all done with this structure
4824 
4825   if (sockfd_ == -1) {
4826     GTEST_LOG_(WARNING) << "stream_result_to: failed to connect to "
4827                         << host_name_ << ":" << port_num_;
4828   }
4829 }
4830 
4831 // End of class Streaming Listener
4832 #endif  // GTEST_CAN_STREAM_RESULTS__
4833 
4834 // Class ScopedTrace
4835 
4836 // Pushes the given source file location and message onto a per-thread
4837 // trace stack maintained by Google Test.
ScopedTrace(const char * file,int line,const Message & message)4838 ScopedTrace::ScopedTrace(const char* file, int line, const Message& message)
4839     GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) {
4840   TraceInfo trace;
4841   trace.file = file;
4842   trace.line = line;
4843   trace.message = message.GetString();
4844 
4845   UnitTest::GetInstance()->PushGTestTrace(trace);
4846 }
4847 
4848 // Pops the info pushed by the c'tor.
~ScopedTrace()4849 ScopedTrace::~ScopedTrace() GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) {
4850   UnitTest::GetInstance()->PopGTestTrace();
4851 }
4852 
4853 // class OsStackTraceGetter
4854 
4855 // Returns the current OS stack trace as an std::string.  Parameters:
4856 //
4857 //   max_depth  - the maximum number of stack frames to be included
4858 //                in the trace.
4859 //   skip_count - the number of top frames to be skipped; doesn't count
4860 //                against max_depth.
4861 //
CurrentStackTrace(int,int)4862 string OsStackTraceGetter::CurrentStackTrace(int /* max_depth */,
4863                                              int /* skip_count */)
4864     GTEST_LOCK_EXCLUDED_(mutex_) {
4865   return "";
4866 }
4867 
UponLeavingGTest()4868 void OsStackTraceGetter::UponLeavingGTest() GTEST_LOCK_EXCLUDED_(mutex_) {}
4869 
4870 const char* const OsStackTraceGetter::kElidedFramesMarker =
4871     "... " GTEST_NAME_ " internal frames ...";
4872 
4873 // A helper class that creates the premature-exit file in its
4874 // constructor and deletes the file in its destructor.
4875 class ScopedPrematureExitFile {
4876  public:
ScopedPrematureExitFile(const char * premature_exit_filepath)4877   explicit ScopedPrematureExitFile(const char* premature_exit_filepath)
4878       : premature_exit_filepath_(premature_exit_filepath) {
4879     // If a path to the premature-exit file is specified...
4880     if (premature_exit_filepath != NULL && *premature_exit_filepath != '\0') {
4881       // create the file with a single "0" character in it.  I/O
4882       // errors are ignored as there's nothing better we can do and we
4883       // don't want to fail the test because of this.
4884       FILE* pfile = posix::FOpen(premature_exit_filepath, "w");
4885       fwrite("0", 1, 1, pfile);
4886       fclose(pfile);
4887     }
4888   }
4889 
~ScopedPrematureExitFile()4890   ~ScopedPrematureExitFile() {
4891     if (premature_exit_filepath_ != NULL && *premature_exit_filepath_ != '\0') {
4892       remove(premature_exit_filepath_);
4893     }
4894   }
4895 
4896  private:
4897   const char* const premature_exit_filepath_;
4898 
4899   GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedPrematureExitFile);
4900 };
4901 
4902 }  // namespace internal
4903 
4904 // class TestEventListeners
4905 
TestEventListeners()4906 TestEventListeners::TestEventListeners()
4907     : repeater_(new internal::TestEventRepeater()),
4908       default_result_printer_(NULL),
4909       default_xml_generator_(NULL) {}
4910 
~TestEventListeners()4911 TestEventListeners::~TestEventListeners() { delete repeater_; }
4912 
4913 // Returns the standard listener responsible for the default console
4914 // output.  Can be removed from the listeners list to shut down default
4915 // console output.  Note that removing this object from the listener list
4916 // with Release transfers its ownership to the user.
Append(TestEventListener * listener)4917 void TestEventListeners::Append(TestEventListener* listener) {
4918   repeater_->Append(listener);
4919 }
4920 
4921 // Removes the given event listener from the list and returns it.  It then
4922 // becomes the caller's responsibility to delete the listener. Returns
4923 // NULL if the listener is not found in the list.
Release(TestEventListener * listener)4924 TestEventListener* TestEventListeners::Release(TestEventListener* listener) {
4925   if (listener == default_result_printer_)
4926     default_result_printer_ = NULL;
4927   else if (listener == default_xml_generator_)
4928     default_xml_generator_ = NULL;
4929   return repeater_->Release(listener);
4930 }
4931 
4932 // Returns repeater that broadcasts the TestEventListener events to all
4933 // subscribers.
repeater()4934 TestEventListener* TestEventListeners::repeater() { return repeater_; }
4935 
4936 // Sets the default_result_printer attribute to the provided listener.
4937 // The listener is also added to the listener list and previous
4938 // default_result_printer is removed from it and deleted. The listener can
4939 // also be NULL in which case it will not be added to the list. Does
4940 // nothing if the previous and the current listener objects are the same.
SetDefaultResultPrinter(TestEventListener * listener)4941 void TestEventListeners::SetDefaultResultPrinter(TestEventListener* listener) {
4942   if (default_result_printer_ != listener) {
4943     // It is an error to pass this method a listener that is already in the
4944     // list.
4945     delete Release(default_result_printer_);
4946     default_result_printer_ = listener;
4947     if (listener != NULL) Append(listener);
4948   }
4949 }
4950 
4951 // Sets the default_xml_generator attribute to the provided listener.  The
4952 // listener is also added to the listener list and previous
4953 // default_xml_generator is removed from it and deleted. The listener can
4954 // also be NULL in which case it will not be added to the list. Does
4955 // nothing if the previous and the current listener objects are the same.
SetDefaultXmlGenerator(TestEventListener * listener)4956 void TestEventListeners::SetDefaultXmlGenerator(TestEventListener* listener) {
4957   if (default_xml_generator_ != listener) {
4958     // It is an error to pass this method a listener that is already in the
4959     // list.
4960     delete Release(default_xml_generator_);
4961     default_xml_generator_ = listener;
4962     if (listener != NULL) Append(listener);
4963   }
4964 }
4965 
4966 // Controls whether events will be forwarded by the repeater to the
4967 // listeners in the list.
EventForwardingEnabled() const4968 bool TestEventListeners::EventForwardingEnabled() const {
4969   return repeater_->forwarding_enabled();
4970 }
4971 
SuppressEventForwarding()4972 void TestEventListeners::SuppressEventForwarding() {
4973   repeater_->set_forwarding_enabled(false);
4974 }
4975 
4976 // class UnitTest
4977 
4978 // Gets the singleton UnitTest object.  The first time this method is
4979 // called, a UnitTest object is constructed and returned.  Consecutive
4980 // calls will return the same object.
4981 //
4982 // We don't protect this under mutex_ as a user is not supposed to
4983 // call this before main() starts, from which point on the return
4984 // value will never change.
GetInstance()4985 UnitTest* UnitTest::GetInstance() {
4986   // When compiled with MSVC 7.1 in optimized mode, destroying the
4987   // UnitTest object upon exiting the program messes up the exit code,
4988   // causing successful tests to appear failed.  We have to use a
4989   // different implementation in this case to bypass the compiler bug.
4990   // This implementation makes the compiler happy, at the cost of
4991   // leaking the UnitTest object.
4992 
4993   // CodeGear C++Builder insists on a public destructor for the
4994   // default implementation.  Use this implementation to keep good OO
4995   // design with private destructor.
4996 
4997 #if (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)
4998   static UnitTest* const instance = new UnitTest;
4999   return instance;
5000 #else
5001   static UnitTest instance;
5002   return &instance;
5003 #endif  // (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)
5004 }
5005 
5006 // Gets the number of successful test cases.
successful_test_case_count() const5007 int UnitTest::successful_test_case_count() const {
5008   return impl()->successful_test_case_count();
5009 }
5010 
5011 // Gets the number of failed test cases.
failed_test_case_count() const5012 int UnitTest::failed_test_case_count() const {
5013   return impl()->failed_test_case_count();
5014 }
5015 
5016 // Gets the number of all test cases.
total_test_case_count() const5017 int UnitTest::total_test_case_count() const {
5018   return impl()->total_test_case_count();
5019 }
5020 
5021 // Gets the number of all test cases that contain at least one test
5022 // that should run.
test_case_to_run_count() const5023 int UnitTest::test_case_to_run_count() const {
5024   return impl()->test_case_to_run_count();
5025 }
5026 
5027 // Gets the number of successful tests.
successful_test_count() const5028 int UnitTest::successful_test_count() const {
5029   return impl()->successful_test_count();
5030 }
5031 
5032 // Gets the number of failed tests.
failed_test_count() const5033 int UnitTest::failed_test_count() const { return impl()->failed_test_count(); }
5034 
5035 // Gets the number of disabled tests that will be reported in the XML report.
reportable_disabled_test_count() const5036 int UnitTest::reportable_disabled_test_count() const {
5037   return impl()->reportable_disabled_test_count();
5038 }
5039 
5040 // Gets the number of disabled tests.
disabled_test_count() const5041 int UnitTest::disabled_test_count() const {
5042   return impl()->disabled_test_count();
5043 }
5044 
5045 // Gets the number of tests to be printed in the XML report.
reportable_test_count() const5046 int UnitTest::reportable_test_count() const {
5047   return impl()->reportable_test_count();
5048 }
5049 
5050 // Gets the number of all tests.
total_test_count() const5051 int UnitTest::total_test_count() const { return impl()->total_test_count(); }
5052 
5053 // Gets the number of tests that should run.
test_to_run_count() const5054 int UnitTest::test_to_run_count() const { return impl()->test_to_run_count(); }
5055 
5056 // Gets the time of the test program start, in ms from the start of the
5057 // UNIX epoch.
start_timestamp() const5058 internal::TimeInMillis UnitTest::start_timestamp() const {
5059   return impl()->start_timestamp();
5060 }
5061 
5062 // Gets the elapsed time, in milliseconds.
elapsed_time() const5063 internal::TimeInMillis UnitTest::elapsed_time() const {
5064   return impl()->elapsed_time();
5065 }
5066 
5067 // Returns true iff the unit test passed (i.e. all test cases passed).
Passed() const5068 bool UnitTest::Passed() const { return impl()->Passed(); }
5069 
5070 // Returns true iff the unit test failed (i.e. some test case failed
5071 // or something outside of all tests failed).
Failed() const5072 bool UnitTest::Failed() const { return impl()->Failed(); }
5073 
5074 // Gets the i-th test case among all the test cases. i can range from 0 to
5075 // total_test_case_count() - 1. If i is not in that range, returns NULL.
GetTestCase(int i) const5076 const TestCase* UnitTest::GetTestCase(int i) const {
5077   return impl()->GetTestCase(i);
5078 }
5079 
5080 // Returns the TestResult containing information on test failures and
5081 // properties logged outside of individual test cases.
ad_hoc_test_result() const5082 const TestResult& UnitTest::ad_hoc_test_result() const {
5083   return *impl()->ad_hoc_test_result();
5084 }
5085 
5086 // Gets the i-th test case among all the test cases. i can range from 0 to
5087 // total_test_case_count() - 1. If i is not in that range, returns NULL.
GetMutableTestCase(int i)5088 TestCase* UnitTest::GetMutableTestCase(int i) {
5089   return impl()->GetMutableTestCase(i);
5090 }
5091 
5092 // Returns the list of event listeners that can be used to track events
5093 // inside Google Test.
listeners()5094 TestEventListeners& UnitTest::listeners() { return *impl()->listeners(); }
5095 
5096 // Registers and returns a global test environment.  When a test
5097 // program is run, all global test environments will be set-up in the
5098 // order they were registered.  After all tests in the program have
5099 // finished, all global test environments will be torn-down in the
5100 // *reverse* order they were registered.
5101 //
5102 // The UnitTest object takes ownership of the given environment.
5103 //
5104 // We don't protect this under mutex_, as we only support calling it
5105 // from the main thread.
AddEnvironment(Environment * env)5106 Environment* UnitTest::AddEnvironment(Environment* env) {
5107   if (env == NULL) {
5108     return NULL;
5109   }
5110 
5111   impl_->environments().push_back(env);
5112   return env;
5113 }
5114 
5115 // Adds a TestPartResult to the current TestResult object.  All Google Test
5116 // assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) eventually call
5117 // this to report their results.  The user code should use the
5118 // assertion macros instead of calling this directly.
AddTestPartResult(TestPartResult::Type result_type,const char * file_name,int line_number,const std::string & message,const std::string & os_stack_trace)5119 void UnitTest::AddTestPartResult(TestPartResult::Type result_type,
5120                                  const char* file_name, int line_number,
5121                                  const std::string& message,
5122                                  const std::string& os_stack_trace)
5123     GTEST_LOCK_EXCLUDED_(mutex_) {
5124   Message msg;
5125   msg << message;
5126 
5127   internal::MutexLock lock(&mutex_);
5128   if (impl_->gtest_trace_stack().size() > 0) {
5129     msg << "\n" << GTEST_NAME_ << " trace:";
5130 
5131     for (int i = static_cast<int>(impl_->gtest_trace_stack().size()); i > 0;
5132          --i) {
5133       const internal::TraceInfo& trace = impl_->gtest_trace_stack()[i - 1];
5134       msg << "\n"
5135           << internal::FormatFileLocation(trace.file, trace.line) << " "
5136           << trace.message;
5137     }
5138   }
5139 
5140   if (os_stack_trace.c_str() != NULL && !os_stack_trace.empty()) {
5141     msg << internal::kStackTraceMarker << os_stack_trace;
5142   }
5143 
5144   const TestPartResult result = TestPartResult(
5145       result_type, file_name, line_number, msg.GetString().c_str());
5146   impl_->GetTestPartResultReporterForCurrentThread()->ReportTestPartResult(
5147       result);
5148 
5149   if (result_type != TestPartResult::kSuccess) {
5150     // gtest_break_on_failure takes precedence over
5151     // gtest_throw_on_failure.  This allows a user to set the latter
5152     // in the code (perhaps in order to use Google Test assertions
5153     // with another testing framework) and specify the former on the
5154     // command line for debugging.
5155     if (GTEST_FLAG(break_on_failure)) {
5156 #if GTEST_OS_WINDOWS
5157       // Using DebugBreak on Windows allows gtest to still break into a debugger
5158       // when a failure happens and both the --gtest_break_on_failure and
5159       // the --gtest_catch_exceptions flags are specified.
5160       DebugBreak();
5161 #else
5162       // Dereference NULL through a volatile pointer to prevent the compiler
5163       // from removing. We use this rather than abort() or __builtin_trap() for
5164       // portability: Symbian doesn't implement abort() well, and some debuggers
5165       // don't correctly trap abort().
5166       *static_cast<volatile int*>(NULL) = 1;
5167 #endif  // GTEST_OS_WINDOWS
5168     } else if (GTEST_FLAG(throw_on_failure)) {
5169 #if GTEST_HAS_EXCEPTIONS
5170       throw internal::GoogleTestFailureException(result);
5171 #else
5172       // We cannot call abort() as it generates a pop-up in debug mode
5173       // that cannot be suppressed in VC 7.1 or below.
5174       exit(1);
5175 #endif
5176     }
5177   }
5178 }
5179 
5180 // Adds a TestProperty to the current TestResult object when invoked from
5181 // inside a test, to current TestCase's ad_hoc_test_result_ when invoked
5182 // from SetUpTestCase or TearDownTestCase, or to the global property set
5183 // when invoked elsewhere.  If the result already contains a property with
5184 // the same key, the value will be updated.
RecordProperty(const std::string & key,const std::string & value)5185 void UnitTest::RecordProperty(const std::string& key,
5186                               const std::string& value) {
5187   impl_->RecordProperty(TestProperty(key, value));
5188 }
5189 
5190 // Runs all tests in this UnitTest object and prints the result.
5191 // Returns 0 if successful, or 1 otherwise.
5192 //
5193 // We don't protect this under mutex_, as we only support calling it
5194 // from the main thread.
Run()5195 int UnitTest::Run() {
5196   const bool in_death_test_child_process =
5197       internal::GTEST_FLAG(internal_run_death_test).length() > 0;
5198 
5199   // Google Test implements this protocol for catching that a test
5200   // program exits before returning control to Google Test:
5201   //
5202   //   1. Upon start, Google Test creates a file whose absolute path
5203   //      is specified by the environment variable
5204   //      TEST_PREMATURE_EXIT_FILE.
5205   //   2. When Google Test has finished its work, it deletes the file.
5206   //
5207   // This allows a test runner to set TEST_PREMATURE_EXIT_FILE before
5208   // running a Google-Test-based test program and check the existence
5209   // of the file at the end of the test execution to see if it has
5210   // exited prematurely.
5211 
5212   // If we are in the child process of a death test, don't
5213   // create/delete the premature exit file, as doing so is unnecessary
5214   // and will confuse the parent process.  Otherwise, create/delete
5215   // the file upon entering/leaving this function.  If the program
5216   // somehow exits before this function has a chance to return, the
5217   // premature-exit file will be left undeleted, causing a test runner
5218   // that understands the premature-exit-file protocol to report the
5219   // test as having failed.
5220   const internal::ScopedPrematureExitFile premature_exit_file(
5221       in_death_test_child_process
5222           ? NULL
5223           : internal::posix::GetEnv("TEST_PREMATURE_EXIT_FILE"));
5224 
5225   // Captures the value of GTEST_FLAG(catch_exceptions).  This value will be
5226   // used for the duration of the program.
5227   impl()->set_catch_exceptions(GTEST_FLAG(catch_exceptions));
5228 
5229 #if GTEST_HAS_SEH
5230   // Either the user wants Google Test to catch exceptions thrown by the
5231   // tests or this is executing in the context of death test child
5232   // process. In either case the user does not want to see pop-up dialogs
5233   // about crashes - they are expected.
5234   if (impl()->catch_exceptions() || in_death_test_child_process) {
5235 #  if !GTEST_OS_WINDOWS_MOBILE
5236     // SetErrorMode doesn't exist on CE.
5237     SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT |
5238                  SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);
5239 #  endif  // !GTEST_OS_WINDOWS_MOBILE
5240 
5241 #  if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE
5242     // Death test children can be terminated with _abort().  On Windows,
5243     // _abort() can show a dialog with a warning message.  This forces the
5244     // abort message to go to stderr instead.
5245     _set_error_mode(_OUT_TO_STDERR);
5246 #  endif
5247 
5248 #  if _MSC_VER >= 1400 && !GTEST_OS_WINDOWS_MOBILE
5249     // In the debug version, Visual Studio pops up a separate dialog
5250     // offering a choice to debug the aborted program. We need to suppress
5251     // this dialog or it will pop up for every EXPECT/ASSERT_DEATH statement
5252     // executed. Google Test will notify the user of any unexpected
5253     // failure via stderr.
5254     //
5255     // VC++ doesn't define _set_abort_behavior() prior to the version 8.0.
5256     // Users of prior VC versions shall suffer the agony and pain of
5257     // clicking through the countless debug dialogs.
5258     // TODO(vladl@google.com): find a way to suppress the abort dialog() in the
5259     // debug mode when compiled with VC 7.1 or lower.
5260     if (!GTEST_FLAG(break_on_failure))
5261       _set_abort_behavior(
5262           0x0,                                    // Clear the following flags:
5263           _WRITE_ABORT_MSG | _CALL_REPORTFAULT);  // pop-up window, core dump.
5264 #  endif
5265   }
5266 #endif  // GTEST_HAS_SEH
5267 
5268   return internal::HandleExceptionsInMethodIfSupported(
5269              impl(), &internal::UnitTestImpl::RunAllTests,
5270              "auxiliary test code (environments or event listeners)")
5271              ? 0
5272              : 1;
5273 }
5274 
5275 // Returns the working directory when the first TEST() or TEST_F() was
5276 // executed.
original_working_dir() const5277 const char* UnitTest::original_working_dir() const {
5278   return impl_->original_working_dir_.c_str();
5279 }
5280 
5281 // Returns the TestCase object for the test that's currently running,
5282 // or NULL if no test is running.
current_test_case() const5283 const TestCase* UnitTest::current_test_case() const
5284     GTEST_LOCK_EXCLUDED_(mutex_) {
5285   internal::MutexLock lock(&mutex_);
5286   return impl_->current_test_case();
5287 }
5288 
5289 // Returns the TestInfo object for the test that's currently running,
5290 // or NULL if no test is running.
current_test_info() const5291 const TestInfo* UnitTest::current_test_info() const
5292     GTEST_LOCK_EXCLUDED_(mutex_) {
5293   internal::MutexLock lock(&mutex_);
5294   return impl_->current_test_info();
5295 }
5296 
5297 // Returns the random seed used at the start of the current test run.
random_seed() const5298 int UnitTest::random_seed() const { return impl_->random_seed(); }
5299 
5300 #if GTEST_HAS_PARAM_TEST
5301 // Returns ParameterizedTestCaseRegistry object used to keep track of
5302 // value-parameterized tests and instantiate and register them.
parameterized_test_registry()5303 internal::ParameterizedTestCaseRegistry& UnitTest::parameterized_test_registry()
5304     GTEST_LOCK_EXCLUDED_(mutex_) {
5305   return impl_->parameterized_test_registry();
5306 }
5307 #endif  // GTEST_HAS_PARAM_TEST
5308 
5309 // Creates an empty UnitTest.
UnitTest()5310 UnitTest::UnitTest() { impl_ = new internal::UnitTestImpl(this); }
5311 
5312 // Destructor of UnitTest.
~UnitTest()5313 UnitTest::~UnitTest() { delete impl_; }
5314 
5315 // Pushes a trace defined by SCOPED_TRACE() on to the per-thread
5316 // Google Test trace stack.
PushGTestTrace(const internal::TraceInfo & trace)5317 void UnitTest::PushGTestTrace(const internal::TraceInfo& trace)
5318     GTEST_LOCK_EXCLUDED_(mutex_) {
5319   internal::MutexLock lock(&mutex_);
5320   impl_->gtest_trace_stack().push_back(trace);
5321 }
5322 
5323 // Pops a trace from the per-thread Google Test trace stack.
PopGTestTrace()5324 void UnitTest::PopGTestTrace() GTEST_LOCK_EXCLUDED_(mutex_) {
5325   internal::MutexLock lock(&mutex_);
5326   impl_->gtest_trace_stack().pop_back();
5327 }
5328 
5329 namespace internal {
5330 
UnitTestImpl(UnitTest * parent)5331 UnitTestImpl::UnitTestImpl(UnitTest* parent)
5332     : parent_(parent),
5333 #ifdef _MSC_VER
5334 #  pragma warning(push)            // Saves the current warning state.
5335 #  pragma warning(disable : 4355)  // Temporarily disables warning 4355
5336                                    // (using this in initializer).
5337       default_global_test_part_result_reporter_(this),
5338       default_per_thread_test_part_result_reporter_(this),
5339 #  pragma warning(pop)  // Restores the warning state again.
5340 #else
5341       default_global_test_part_result_reporter_(this),
5342       default_per_thread_test_part_result_reporter_(this),
5343 #endif  // _MSC_VER
5344       global_test_part_result_repoter_(
5345           &default_global_test_part_result_reporter_),
5346       per_thread_test_part_result_reporter_(
5347           &default_per_thread_test_part_result_reporter_),
5348 #if GTEST_HAS_PARAM_TEST
5349       parameterized_test_registry_(),
5350       parameterized_tests_registered_(false),
5351 #endif  // GTEST_HAS_PARAM_TEST
5352       last_death_test_case_(-1),
5353       current_test_case_(NULL),
5354       current_test_info_(NULL),
5355       ad_hoc_test_result_(),
5356       os_stack_trace_getter_(NULL),
5357       post_flag_parse_init_performed_(false),
5358       random_seed_(0),  // Will be overridden by the flag before first use.
5359       random_(0),       // Will be reseeded before first use.
5360       start_timestamp_(0),
5361       elapsed_time_(0),
5362 #if GTEST_HAS_DEATH_TEST
5363       death_test_factory_(new DefaultDeathTestFactory),
5364 #endif
5365       // Will be overridden by the flag before first use.
5366       catch_exceptions_(false) {
5367   listeners()->SetDefaultResultPrinter(new PrettyUnitTestResultPrinter);
5368 }
5369 
~UnitTestImpl()5370 UnitTestImpl::~UnitTestImpl() {
5371   // Deletes every TestCase.
5372   ForEach(test_cases_, internal::Delete<TestCase>);
5373 
5374   // Deletes every Environment.
5375   ForEach(environments_, internal::Delete<Environment>);
5376 
5377   delete os_stack_trace_getter_;
5378 }
5379 
5380 // Adds a TestProperty to the current TestResult object when invoked in a
5381 // context of a test, to current test case's ad_hoc_test_result when invoke
5382 // from SetUpTestCase/TearDownTestCase, or to the global property set
5383 // otherwise.  If the result already contains a property with the same key,
5384 // the value will be updated.
RecordProperty(const TestProperty & test_property)5385 void UnitTestImpl::RecordProperty(const TestProperty& test_property) {
5386   std::string xml_element;
5387   TestResult* test_result;  // TestResult appropriate for property recording.
5388 
5389   if (current_test_info_ != NULL) {
5390     xml_element = "testcase";
5391     test_result = &(current_test_info_->result_);
5392   } else if (current_test_case_ != NULL) {
5393     xml_element = "testsuite";
5394     test_result = &(current_test_case_->ad_hoc_test_result_);
5395   } else {
5396     xml_element = "testsuites";
5397     test_result = &ad_hoc_test_result_;
5398   }
5399   test_result->RecordProperty(xml_element, test_property);
5400 }
5401 
5402 #if GTEST_HAS_DEATH_TEST
5403 // Disables event forwarding if the control is currently in a death test
5404 // subprocess. Must not be called before InitGoogleTest.
SuppressTestEventsIfInSubprocess()5405 void UnitTestImpl::SuppressTestEventsIfInSubprocess() {
5406   if (internal_run_death_test_flag_.get() != NULL)
5407     listeners()->SuppressEventForwarding();
5408 }
5409 #endif  // GTEST_HAS_DEATH_TEST
5410 
5411 // Initializes event listeners performing XML output as specified by
5412 // UnitTestOptions. Must not be called before InitGoogleTest.
ConfigureXmlOutput()5413 void UnitTestImpl::ConfigureXmlOutput() {
5414   const std::string& output_format = UnitTestOptions::GetOutputFormat();
5415   if (output_format == "xml") {
5416     listeners()->SetDefaultXmlGenerator(new XmlUnitTestResultPrinter(
5417         UnitTestOptions::GetAbsolutePathToOutputFile().c_str()));
5418   } else if (output_format != "") {
5419     printf("WARNING: unrecognized output format \"%s\" ignored.\n",
5420            output_format.c_str());
5421     fflush(stdout);
5422   }
5423 }
5424 
5425 #if GTEST_CAN_STREAM_RESULTS_
5426 // Initializes event listeners for streaming test results in string form.
5427 // Must not be called before InitGoogleTest.
ConfigureStreamingOutput()5428 void UnitTestImpl::ConfigureStreamingOutput() {
5429   const std::string& target = GTEST_FLAG(stream_result_to);
5430   if (!target.empty()) {
5431     const size_t pos = target.find(':');
5432     if (pos != std::string::npos) {
5433       listeners()->Append(
5434           new StreamingListener(target.substr(0, pos), target.substr(pos + 1)));
5435     } else {
5436       printf("WARNING: unrecognized streaming target \"%s\" ignored.\n",
5437              target.c_str());
5438       fflush(stdout);
5439     }
5440   }
5441 }
5442 #endif  // GTEST_CAN_STREAM_RESULTS_
5443 
5444 // Performs initialization dependent upon flag values obtained in
5445 // ParseGoogleTestFlagsOnly.  Is called from InitGoogleTest after the call to
5446 // ParseGoogleTestFlagsOnly.  In case a user neglects to call InitGoogleTest
5447 // this function is also called from RunAllTests.  Since this function can be
5448 // called more than once, it has to be idempotent.
PostFlagParsingInit()5449 void UnitTestImpl::PostFlagParsingInit() {
5450   // Ensures that this function does not execute more than once.
5451   if (!post_flag_parse_init_performed_) {
5452     post_flag_parse_init_performed_ = true;
5453 
5454 #if GTEST_HAS_DEATH_TEST
5455     InitDeathTestSubprocessControlInfo();
5456     SuppressTestEventsIfInSubprocess();
5457 #endif  // GTEST_HAS_DEATH_TEST
5458 
5459     // Registers parameterized tests. This makes parameterized tests
5460     // available to the UnitTest reflection API without running
5461     // RUN_ALL_TESTS.
5462     RegisterParameterizedTests();
5463 
5464     // Configures listeners for XML output. This makes it possible for users
5465     // to shut down the default XML output before invoking RUN_ALL_TESTS.
5466     ConfigureXmlOutput();
5467 
5468 #if GTEST_CAN_STREAM_RESULTS_
5469     // Configures listeners for streaming test results to the specified server.
5470     ConfigureStreamingOutput();
5471 #endif  // GTEST_CAN_STREAM_RESULTS_
5472   }
5473 }
5474 
5475 // A predicate that checks the name of a TestCase against a known
5476 // value.
5477 //
5478 // This is used for implementation of the UnitTest class only.  We put
5479 // it in the anonymous namespace to prevent polluting the outer
5480 // namespace.
5481 //
5482 // TestCaseNameIs is copyable.
5483 class TestCaseNameIs {
5484  public:
5485   // Constructor.
TestCaseNameIs(const std::string & name)5486   explicit TestCaseNameIs(const std::string& name) : name_(name) {}
5487 
5488   // Returns true iff the name of test_case matches name_.
operator ()(const TestCase * test_case) const5489   bool operator()(const TestCase* test_case) const {
5490     return test_case != NULL && strcmp(test_case->name(), name_.c_str()) == 0;
5491   }
5492 
5493  private:
5494   std::string name_;
5495 };
5496 
5497 // Finds and returns a TestCase with the given name.  If one doesn't
5498 // exist, creates one and returns it.  It's the CALLER'S
5499 // RESPONSIBILITY to ensure that this function is only called WHEN THE
5500 // TESTS ARE NOT SHUFFLED.
5501 //
5502 // Arguments:
5503 //
5504 //   test_case_name: name of the test case
5505 //   type_param:     the name of the test case's type parameter, or NULL if
5506 //                   this is not a typed or a type-parameterized test case.
5507 //   set_up_tc:      pointer to the function that sets up the test case
5508 //   tear_down_tc:   pointer to the function that tears down the test case
GetTestCase(const char * test_case_name,const char * type_param,Test::SetUpTestCaseFunc set_up_tc,Test::TearDownTestCaseFunc tear_down_tc)5509 TestCase* UnitTestImpl::GetTestCase(const char* test_case_name,
5510                                     const char* type_param,
5511                                     Test::SetUpTestCaseFunc set_up_tc,
5512                                     Test::TearDownTestCaseFunc tear_down_tc) {
5513   // Can we find a TestCase with the given name?
5514   const std::vector<TestCase*>::const_iterator test_case = std::find_if(
5515       test_cases_.begin(), test_cases_.end(), TestCaseNameIs(test_case_name));
5516 
5517   if (test_case != test_cases_.end()) return *test_case;
5518 
5519   // No.  Let's create one.
5520   TestCase* const new_test_case =
5521       new TestCase(test_case_name, type_param, set_up_tc, tear_down_tc);
5522 
5523   // Is this a death test case?
5524   if (internal::UnitTestOptions::MatchesFilter(test_case_name,
5525                                                kDeathTestCaseFilter)) {
5526     // Yes.  Inserts the test case after the last death test case
5527     // defined so far.  This only works when the test cases haven't
5528     // been shuffled.  Otherwise we may end up running a death test
5529     // after a non-death test.
5530     ++last_death_test_case_;
5531     test_cases_.insert(test_cases_.begin() + last_death_test_case_,
5532                        new_test_case);
5533   } else {
5534     // No.  Appends to the end of the list.
5535     test_cases_.push_back(new_test_case);
5536   }
5537 
5538   test_case_indices_.push_back(static_cast<int>(test_case_indices_.size()));
5539   return new_test_case;
5540 }
5541 
5542 // Helpers for setting up / tearing down the given environment.  They
5543 // are for use in the ForEach() function.
SetUpEnvironment(Environment * env)5544 static void SetUpEnvironment(Environment* env) { env->SetUp(); }
TearDownEnvironment(Environment * env)5545 static void TearDownEnvironment(Environment* env) { env->TearDown(); }
5546 
5547 // Runs all tests in this UnitTest object, prints the result, and
5548 // returns true if all tests are successful.  If any exception is
5549 // thrown during a test, the test is considered to be failed, but the
5550 // rest of the tests will still be run.
5551 //
5552 // When parameterized tests are enabled, it expands and registers
5553 // parameterized tests first in RegisterParameterizedTests().
5554 // All other functions called from RunAllTests() may safely assume that
5555 // parameterized tests are ready to be counted and run.
RunAllTests()5556 bool UnitTestImpl::RunAllTests() {
5557   // Makes sure InitGoogleTest() was called.
5558   if (!GTestIsInitialized()) {
5559     printf("%s",
5560            "\nThis test program did NOT call ::testing::InitGoogleTest "
5561            "before calling RUN_ALL_TESTS().  Please fix it.\n");
5562     return false;
5563   }
5564 
5565   // Do not run any test if the --help flag was specified.
5566   if (g_help_flag) return true;
5567 
5568   // Repeats the call to the post-flag parsing initialization in case the
5569   // user didn't call InitGoogleTest.
5570   PostFlagParsingInit();
5571 
5572   // Even if sharding is not on, test runners may want to use the
5573   // GTEST_SHARD_STATUS_FILE to query whether the test supports the sharding
5574   // protocol.
5575   internal::WriteToShardStatusFileIfNeeded();
5576 
5577   // True iff we are in a subprocess for running a thread-safe-style
5578   // death test.
5579   bool in_subprocess_for_death_test = false;
5580 
5581 #if GTEST_HAS_DEATH_TEST
5582   in_subprocess_for_death_test = (internal_run_death_test_flag_.get() != NULL);
5583 #endif  // GTEST_HAS_DEATH_TEST
5584 
5585   const bool should_shard = ShouldShard(kTestTotalShards, kTestShardIndex,
5586                                         in_subprocess_for_death_test);
5587 
5588   // Compares the full test names with the filter to decide which
5589   // tests to run.
5590   const bool has_tests_to_run =
5591       FilterTests(should_shard ? HONOR_SHARDING_PROTOCOL
5592                                : IGNORE_SHARDING_PROTOCOL) > 0;
5593 
5594   // Lists the tests and exits if the --gtest_list_tests flag was specified.
5595   if (GTEST_FLAG(list_tests)) {
5596     // This must be called *after* FilterTests() has been called.
5597     ListTestsMatchingFilter();
5598     return true;
5599   }
5600 
5601   random_seed_ =
5602       GTEST_FLAG(shuffle) ? GetRandomSeedFromFlag(GTEST_FLAG(random_seed)) : 0;
5603 
5604   // True iff at least one test has failed.
5605   bool failed = false;
5606 
5607   TestEventListener* repeater = listeners()->repeater();
5608 
5609   start_timestamp_ = GetTimeInMillis();
5610   repeater->OnTestProgramStart(*parent_);
5611 
5612   // How many times to repeat the tests?  We don't want to repeat them
5613   // when we are inside the subprocess of a death test.
5614   const int repeat = in_subprocess_for_death_test ? 1 : GTEST_FLAG(repeat);
5615   // Repeats forever if the repeat count is negative.
5616   const bool forever = repeat < 0;
5617   for (int i = 0; forever || i != repeat; i++) {
5618     // We want to preserve failures generated by ad-hoc test
5619     // assertions executed before RUN_ALL_TESTS().
5620     ClearNonAdHocTestResult();
5621 
5622     const TimeInMillis start = GetTimeInMillis();
5623 
5624     // Shuffles test cases and tests if requested.
5625     if (has_tests_to_run && GTEST_FLAG(shuffle)) {
5626       random()->Reseed(random_seed_);
5627       // This should be done before calling OnTestIterationStart(),
5628       // such that a test event listener can see the actual test order
5629       // in the event.
5630       ShuffleTests();
5631     }
5632 
5633     // Tells the unit test event listeners that the tests are about to start.
5634     repeater->OnTestIterationStart(*parent_, i);
5635 
5636     // Runs each test case if there is at least one test to run.
5637     if (has_tests_to_run) {
5638       // Sets up all environments beforehand.
5639       repeater->OnEnvironmentsSetUpStart(*parent_);
5640       ForEach(environments_, SetUpEnvironment);
5641       repeater->OnEnvironmentsSetUpEnd(*parent_);
5642 
5643       // Runs the tests only if there was no fatal failure during global
5644       // set-up.
5645       if (!Test::HasFatalFailure()) {
5646         for (int test_index = 0; test_index < total_test_case_count();
5647              test_index++) {
5648           GetMutableTestCase(test_index)->Run();
5649         }
5650       }
5651 
5652       // Tears down all environments in reverse order afterwards.
5653       repeater->OnEnvironmentsTearDownStart(*parent_);
5654       std::for_each(environments_.rbegin(), environments_.rend(),
5655                     TearDownEnvironment);
5656       repeater->OnEnvironmentsTearDownEnd(*parent_);
5657     }
5658 
5659     elapsed_time_ = GetTimeInMillis() - start;
5660 
5661     // Tells the unit test event listener that the tests have just finished.
5662     repeater->OnTestIterationEnd(*parent_, i);
5663 
5664     // Gets the result and clears it.
5665     if (!Passed()) {
5666       failed = true;
5667     }
5668 
5669     // Restores the original test order after the iteration.  This
5670     // allows the user to quickly repro a failure that happens in the
5671     // N-th iteration without repeating the first (N - 1) iterations.
5672     // This is not enclosed in "if (GTEST_FLAG(shuffle)) { ... }", in
5673     // case the user somehow changes the value of the flag somewhere
5674     // (it's always safe to unshuffle the tests).
5675     UnshuffleTests();
5676 
5677     if (GTEST_FLAG(shuffle)) {
5678       // Picks a new random seed for each iteration.
5679       random_seed_ = GetNextRandomSeed(random_seed_);
5680     }
5681   }
5682 
5683   repeater->OnTestProgramEnd(*parent_);
5684 
5685   return !failed;
5686 }
5687 
5688 // Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
5689 // if the variable is present. If a file already exists at this location, this
5690 // function will write over it. If the variable is present, but the file cannot
5691 // be created, prints an error and exits.
WriteToShardStatusFileIfNeeded()5692 void WriteToShardStatusFileIfNeeded() {
5693   const char* const test_shard_file = posix::GetEnv(kTestShardStatusFile);
5694   if (test_shard_file != NULL) {
5695     FILE* const file = posix::FOpen(test_shard_file, "w");
5696     if (file == NULL) {
5697       ColoredPrintf(COLOR_RED,
5698                     "Could not write to the test shard status file \"%s\" "
5699                     "specified by the %s environment variable.\n",
5700                     test_shard_file, kTestShardStatusFile);
5701       fflush(stdout);
5702       exit(EXIT_FAILURE);
5703     }
5704     fclose(file);
5705   }
5706 }
5707 
5708 // Checks whether sharding is enabled by examining the relevant
5709 // environment variable values. If the variables are present,
5710 // but inconsistent (i.e., shard_index >= total_shards), prints
5711 // an error and exits. If in_subprocess_for_death_test, sharding is
5712 // disabled because it must only be applied to the original test
5713 // process. Otherwise, we could filter out death tests we intended to execute.
ShouldShard(const char * total_shards_env,const char * shard_index_env,bool in_subprocess_for_death_test)5714 bool ShouldShard(const char* total_shards_env, const char* shard_index_env,
5715                  bool in_subprocess_for_death_test) {
5716   if (in_subprocess_for_death_test) {
5717     return false;
5718   }
5719 
5720   const Int32 total_shards = Int32FromEnvOrDie(total_shards_env, -1);
5721   const Int32 shard_index = Int32FromEnvOrDie(shard_index_env, -1);
5722 
5723   if (total_shards == -1 && shard_index == -1) {
5724     return false;
5725   } else if (total_shards == -1 && shard_index != -1) {
5726     const Message msg = Message() << "Invalid environment variables: you have "
5727                                   << kTestShardIndex << " = " << shard_index
5728                                   << ", but have left " << kTestTotalShards
5729                                   << " unset.\n";
5730     ColoredPrintf(COLOR_RED, msg.GetString().c_str());
5731     fflush(stdout);
5732     exit(EXIT_FAILURE);
5733   } else if (total_shards != -1 && shard_index == -1) {
5734     const Message msg = Message()
5735                         << "Invalid environment variables: you have "
5736                         << kTestTotalShards << " = " << total_shards
5737                         << ", but have left " << kTestShardIndex << " unset.\n";
5738     ColoredPrintf(COLOR_RED, msg.GetString().c_str());
5739     fflush(stdout);
5740     exit(EXIT_FAILURE);
5741   } else if (shard_index < 0 || shard_index >= total_shards) {
5742     const Message msg =
5743         Message() << "Invalid environment variables: we require 0 <= "
5744                   << kTestShardIndex << " < " << kTestTotalShards
5745                   << ", but you have " << kTestShardIndex << "=" << shard_index
5746                   << ", " << kTestTotalShards << "=" << total_shards << ".\n";
5747     ColoredPrintf(COLOR_RED, msg.GetString().c_str());
5748     fflush(stdout);
5749     exit(EXIT_FAILURE);
5750   }
5751 
5752   return total_shards > 1;
5753 }
5754 
5755 // Parses the environment variable var as an Int32. If it is unset,
5756 // returns default_val. If it is not an Int32, prints an error
5757 // and aborts.
Int32FromEnvOrDie(const char * var,Int32 default_val)5758 Int32 Int32FromEnvOrDie(const char* var, Int32 default_val) {
5759   const char* str_val = posix::GetEnv(var);
5760   if (str_val == NULL) {
5761     return default_val;
5762   }
5763 
5764   Int32 result;
5765   if (!ParseInt32(Message() << "The value of environment variable " << var,
5766                   str_val, &result)) {
5767     exit(EXIT_FAILURE);
5768   }
5769   return result;
5770 }
5771 
5772 // Given the total number of shards, the shard index, and the test id,
5773 // returns true iff the test should be run on this shard. The test id is
5774 // some arbitrary but unique non-negative integer assigned to each test
5775 // method. Assumes that 0 <= shard_index < total_shards.
ShouldRunTestOnShard(int total_shards,int shard_index,int test_id)5776 bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) {
5777   return (test_id % total_shards) == shard_index;
5778 }
5779 
5780 // Compares the name of each test with the user-specified filter to
5781 // decide whether the test should be run, then records the result in
5782 // each TestCase and TestInfo object.
5783 // If shard_tests == true, further filters tests based on sharding
5784 // variables in the environment - see
5785 // http://code.google.com/p/googletest/wiki/GoogleTestAdvancedGuide.
5786 // Returns the number of tests that should run.
FilterTests(ReactionToSharding shard_tests)5787 int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) {
5788   const Int32 total_shards = shard_tests == HONOR_SHARDING_PROTOCOL
5789                                  ? Int32FromEnvOrDie(kTestTotalShards, -1)
5790                                  : -1;
5791   const Int32 shard_index = shard_tests == HONOR_SHARDING_PROTOCOL
5792                                 ? Int32FromEnvOrDie(kTestShardIndex, -1)
5793                                 : -1;
5794 
5795   // num_runnable_tests are the number of tests that will
5796   // run across all shards (i.e., match filter and are not disabled).
5797   // num_selected_tests are the number of tests to be run on
5798   // this shard.
5799   int num_runnable_tests = 0;
5800   int num_selected_tests = 0;
5801   for (size_t i = 0; i < test_cases_.size(); i++) {
5802     TestCase* const test_case = test_cases_[i];
5803     const std::string& test_case_name = test_case->name();
5804     test_case->set_should_run(false);
5805 
5806     for (size_t j = 0; j < test_case->test_info_list().size(); j++) {
5807       TestInfo* const test_info = test_case->test_info_list()[j];
5808       const std::string test_name(test_info->name());
5809       // A test is disabled if test case name or test name matches
5810       // kDisableTestFilter.
5811       const bool is_disabled = internal::UnitTestOptions::MatchesFilter(
5812                                    test_case_name, kDisableTestFilter) ||
5813                                internal::UnitTestOptions::MatchesFilter(
5814                                    test_name, kDisableTestFilter);
5815       test_info->is_disabled_ = is_disabled;
5816 
5817       const bool matches_filter = internal::UnitTestOptions::FilterMatchesTest(
5818           test_case_name, test_name);
5819       test_info->matches_filter_ = matches_filter;
5820 
5821       const bool is_runnable =
5822           (GTEST_FLAG(also_run_disabled_tests) || !is_disabled) &&
5823           matches_filter;
5824 
5825       const bool is_selected =
5826           is_runnable &&
5827           (shard_tests == IGNORE_SHARDING_PROTOCOL ||
5828            ShouldRunTestOnShard(total_shards, shard_index, num_runnable_tests));
5829 
5830       num_runnable_tests += is_runnable;
5831       num_selected_tests += is_selected;
5832 
5833       test_info->should_run_ = is_selected;
5834       test_case->set_should_run(test_case->should_run() || is_selected);
5835     }
5836   }
5837   return num_selected_tests;
5838 }
5839 
5840 // Prints the given C-string on a single line by replacing all '\n'
5841 // characters with string "\\n".  If the output takes more than
5842 // max_length characters, only prints the first max_length characters
5843 // and "...".
PrintOnOneLine(const char * str,int max_length)5844 static void PrintOnOneLine(const char* str, int max_length) {
5845   if (str != NULL) {
5846     for (int i = 0; *str != '\0'; ++str) {
5847       if (i >= max_length) {
5848         printf("...");
5849         break;
5850       }
5851       if (*str == '\n') {
5852         printf("\\n");
5853         i += 2;
5854       } else {
5855         printf("%c", *str);
5856         ++i;
5857       }
5858     }
5859   }
5860 }
5861 
5862 // Prints the names of the tests matching the user-specified filter flag.
ListTestsMatchingFilter()5863 void UnitTestImpl::ListTestsMatchingFilter() {
5864   // Print at most this many characters for each type/value parameter.
5865   const int kMaxParamLength = 250;
5866 
5867   for (size_t i = 0; i < test_cases_.size(); i++) {
5868     const TestCase* const test_case = test_cases_[i];
5869     bool printed_test_case_name = false;
5870 
5871     for (size_t j = 0; j < test_case->test_info_list().size(); j++) {
5872       const TestInfo* const test_info = test_case->test_info_list()[j];
5873       if (test_info->matches_filter_) {
5874         if (!printed_test_case_name) {
5875           printed_test_case_name = true;
5876           printf("%s.", test_case->name());
5877           if (test_case->type_param() != NULL) {
5878             printf("  # %s = ", kTypeParamLabel);
5879             // We print the type parameter on a single line to make
5880             // the output easy to parse by a program.
5881             PrintOnOneLine(test_case->type_param(), kMaxParamLength);
5882           }
5883           printf("\n");
5884         }
5885         printf("  %s", test_info->name());
5886         if (test_info->value_param() != NULL) {
5887           printf("  # %s = ", kValueParamLabel);
5888           // We print the value parameter on a single line to make the
5889           // output easy to parse by a program.
5890           PrintOnOneLine(test_info->value_param(), kMaxParamLength);
5891         }
5892         printf("\n");
5893       }
5894     }
5895   }
5896   fflush(stdout);
5897 }
5898 
5899 // Sets the OS stack trace getter.
5900 //
5901 // Does nothing if the input and the current OS stack trace getter are
5902 // the same; otherwise, deletes the old getter and makes the input the
5903 // current getter.
set_os_stack_trace_getter(OsStackTraceGetterInterface * getter)5904 void UnitTestImpl::set_os_stack_trace_getter(
5905     OsStackTraceGetterInterface* getter) {
5906   if (os_stack_trace_getter_ != getter) {
5907     delete os_stack_trace_getter_;
5908     os_stack_trace_getter_ = getter;
5909   }
5910 }
5911 
5912 // Returns the current OS stack trace getter if it is not NULL;
5913 // otherwise, creates an OsStackTraceGetter, makes it the current
5914 // getter, and returns it.
os_stack_trace_getter()5915 OsStackTraceGetterInterface* UnitTestImpl::os_stack_trace_getter() {
5916   if (os_stack_trace_getter_ == NULL) {
5917     os_stack_trace_getter_ = new OsStackTraceGetter;
5918   }
5919 
5920   return os_stack_trace_getter_;
5921 }
5922 
5923 // Returns the TestResult for the test that's currently running, or
5924 // the TestResult for the ad hoc test if no test is running.
current_test_result()5925 TestResult* UnitTestImpl::current_test_result() {
5926   return current_test_info_ ? &(current_test_info_->result_)
5927                             : &ad_hoc_test_result_;
5928 }
5929 
5930 // Shuffles all test cases, and the tests within each test case,
5931 // making sure that death tests are still run first.
ShuffleTests()5932 void UnitTestImpl::ShuffleTests() {
5933   // Shuffles the death test cases.
5934   ShuffleRange(random(), 0, last_death_test_case_ + 1, &test_case_indices_);
5935 
5936   // Shuffles the non-death test cases.
5937   ShuffleRange(random(), last_death_test_case_ + 1,
5938                static_cast<int>(test_cases_.size()), &test_case_indices_);
5939 
5940   // Shuffles the tests inside each test case.
5941   for (size_t i = 0; i < test_cases_.size(); i++) {
5942     test_cases_[i]->ShuffleTests(random());
5943   }
5944 }
5945 
5946 // Restores the test cases and tests to their order before the first shuffle.
UnshuffleTests()5947 void UnitTestImpl::UnshuffleTests() {
5948   for (size_t i = 0; i < test_cases_.size(); i++) {
5949     // Unshuffles the tests in each test case.
5950     test_cases_[i]->UnshuffleTests();
5951     // Resets the index of each test case.
5952     test_case_indices_[i] = static_cast<int>(i);
5953   }
5954 }
5955 
5956 // Returns the current OS stack trace as an std::string.
5957 //
5958 // The maximum number of stack frames to be included is specified by
5959 // the gtest_stack_trace_depth flag.  The skip_count parameter
5960 // specifies the number of top frames to be skipped, which doesn't
5961 // count against the number of frames to be included.
5962 //
5963 // For example, if Foo() calls Bar(), which in turn calls
5964 // GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in
5965 // the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.
GetCurrentOsStackTraceExceptTop(UnitTest *,int skip_count)5966 std::string GetCurrentOsStackTraceExceptTop(UnitTest* /*unit_test*/,
5967                                             int skip_count) {
5968   // We pass skip_count + 1 to skip this wrapper function in addition
5969   // to what the user really wants to skip.
5970   return GetUnitTestImpl()->CurrentOsStackTraceExceptTop(skip_count + 1);
5971 }
5972 
5973 // Used by the GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_ macro to
5974 // suppress unreachable code warnings.
5975 namespace {
5976 class ClassUniqueToAlwaysTrue {};
5977 }  // namespace
5978 
IsTrue(bool condition)5979 bool IsTrue(bool condition) { return condition; }
5980 
AlwaysTrue()5981 bool AlwaysTrue() {
5982 #if GTEST_HAS_EXCEPTIONS
5983   // This condition is always false so AlwaysTrue() never actually throws,
5984   // but it makes the compiler think that it may throw.
5985   if (IsTrue(false)) throw ClassUniqueToAlwaysTrue();
5986 #endif  // GTEST_HAS_EXCEPTIONS
5987   return true;
5988 }
5989 
5990 // If *pstr starts with the given prefix, modifies *pstr to be right
5991 // past the prefix and returns true; otherwise leaves *pstr unchanged
5992 // and returns false.  None of pstr, *pstr, and prefix can be NULL.
SkipPrefix(const char * prefix,const char ** pstr)5993 bool SkipPrefix(const char* prefix, const char** pstr) {
5994   const size_t prefix_len = strlen(prefix);
5995   if (strncmp(*pstr, prefix, prefix_len) == 0) {
5996     *pstr += prefix_len;
5997     return true;
5998   }
5999   return false;
6000 }
6001 
6002 // Parses a string as a command line flag.  The string should have
6003 // the format "--flag=value".  When def_optional is true, the "=value"
6004 // part can be omitted.
6005 //
6006 // Returns the value of the flag, or NULL if the parsing failed.
ParseFlagValue(const char * str,const char * flag,bool def_optional)6007 const char* ParseFlagValue(const char* str, const char* flag,
6008                            bool def_optional) {
6009   // str and flag must not be NULL.
6010   if (str == NULL || flag == NULL) return NULL;
6011 
6012   // The flag must start with "--" followed by GTEST_FLAG_PREFIX_.
6013   const std::string flag_str = std::string("--") + GTEST_FLAG_PREFIX_ + flag;
6014   const size_t flag_len = flag_str.length();
6015   if (strncmp(str, flag_str.c_str(), flag_len) != 0) return NULL;
6016 
6017   // Skips the flag name.
6018   const char* flag_end = str + flag_len;
6019 
6020   // When def_optional is true, it's OK to not have a "=value" part.
6021   if (def_optional && (flag_end[0] == '\0')) {
6022     return flag_end;
6023   }
6024 
6025   // If def_optional is true and there are more characters after the
6026   // flag name, or if def_optional is false, there must be a '=' after
6027   // the flag name.
6028   if (flag_end[0] != '=') return NULL;
6029 
6030   // Returns the string after "=".
6031   return flag_end + 1;
6032 }
6033 
6034 // Parses a string for a bool flag, in the form of either
6035 // "--flag=value" or "--flag".
6036 //
6037 // In the former case, the value is taken as true as long as it does
6038 // not start with '0', 'f', or 'F'.
6039 //
6040 // In the latter case, the value is taken as true.
6041 //
6042 // On success, stores the value of the flag in *value, and returns
6043 // true.  On failure, returns false without changing *value.
ParseBoolFlag(const char * str,const char * flag,bool * value)6044 bool ParseBoolFlag(const char* str, const char* flag, bool* value) {
6045   // Gets the value of the flag as a string.
6046   const char* const value_str = ParseFlagValue(str, flag, true);
6047 
6048   // Aborts if the parsing failed.
6049   if (value_str == NULL) return false;
6050 
6051   // Converts the string value to a bool.
6052   *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F');
6053   return true;
6054 }
6055 
6056 // Parses a string for an Int32 flag, in the form of
6057 // "--flag=value".
6058 //
6059 // On success, stores the value of the flag in *value, and returns
6060 // true.  On failure, returns false without changing *value.
ParseInt32Flag(const char * str,const char * flag,Int32 * value)6061 bool ParseInt32Flag(const char* str, const char* flag, Int32* value) {
6062   // Gets the value of the flag as a string.
6063   const char* const value_str = ParseFlagValue(str, flag, false);
6064 
6065   // Aborts if the parsing failed.
6066   if (value_str == NULL) return false;
6067 
6068   // Sets *value to the value of the flag.
6069   return ParseInt32(Message() << "The value of flag --" << flag, value_str,
6070                     value);
6071 }
6072 
6073 // Parses a string for a string flag, in the form of
6074 // "--flag=value".
6075 //
6076 // On success, stores the value of the flag in *value, and returns
6077 // true.  On failure, returns false without changing *value.
ParseStringFlag(const char * str,const char * flag,std::string * value)6078 bool ParseStringFlag(const char* str, const char* flag, std::string* value) {
6079   // Gets the value of the flag as a string.
6080   const char* const value_str = ParseFlagValue(str, flag, false);
6081 
6082   // Aborts if the parsing failed.
6083   if (value_str == NULL) return false;
6084 
6085   // Sets *value to the value of the flag.
6086   *value = value_str;
6087   return true;
6088 }
6089 
6090 // Determines whether a string has a prefix that Google Test uses for its
6091 // flags, i.e., starts with GTEST_FLAG_PREFIX_ or GTEST_FLAG_PREFIX_DASH_.
6092 // If Google Test detects that a command line flag has its prefix but is not
6093 // recognized, it will print its help message. Flags starting with
6094 // GTEST_INTERNAL_PREFIX_ followed by "internal_" are considered Google Test
6095 // internal flags and do not trigger the help message.
HasGoogleTestFlagPrefix(const char * str)6096 static bool HasGoogleTestFlagPrefix(const char* str) {
6097   return (SkipPrefix("--", &str) || SkipPrefix("-", &str) ||
6098           SkipPrefix("/", &str)) &&
6099          !SkipPrefix(GTEST_FLAG_PREFIX_ "internal_", &str) &&
6100          (SkipPrefix(GTEST_FLAG_PREFIX_, &str) ||
6101           SkipPrefix(GTEST_FLAG_PREFIX_DASH_, &str));
6102 }
6103 
6104 // Prints a string containing code-encoded text.  The following escape
6105 // sequences can be used in the string to control the text color:
6106 //
6107 //   @@    prints a single '@' character.
6108 //   @R    changes the color to red.
6109 //   @G    changes the color to green.
6110 //   @Y    changes the color to yellow.
6111 //   @D    changes to the default terminal text color.
6112 //
6113 // TODO(wan@google.com): Write tests for this once we add stdout
6114 // capturing to Google Test.
PrintColorEncoded(const char * str)6115 static void PrintColorEncoded(const char* str) {
6116   GTestColor color = COLOR_DEFAULT;  // The current color.
6117 
6118   // Conceptually, we split the string into segments divided by escape
6119   // sequences.  Then we print one segment at a time.  At the end of
6120   // each iteration, the str pointer advances to the beginning of the
6121   // next segment.
6122   for (;;) {
6123     const char* p = strchr(str, '@');
6124     if (p == NULL) {
6125       ColoredPrintf(color, "%s", str);
6126       return;
6127     }
6128 
6129     ColoredPrintf(color, "%s", std::string(str, p).c_str());
6130 
6131     const char ch = p[1];
6132     str = p + 2;
6133     if (ch == '@') {
6134       ColoredPrintf(color, "@");
6135     } else if (ch == 'D') {
6136       color = COLOR_DEFAULT;
6137     } else if (ch == 'R') {
6138       color = COLOR_RED;
6139     } else if (ch == 'G') {
6140       color = COLOR_GREEN;
6141     } else if (ch == 'Y') {
6142       color = COLOR_YELLOW;
6143     } else {
6144       --str;
6145     }
6146   }
6147 }
6148 
6149 static const char kColorEncodedHelpMessage[] =
6150     "This program contains tests written using " GTEST_NAME_
6151     ". You can use the\n"
6152     "following command line flags to control its behavior:\n"
6153     "\n"
6154     "Test Selection:\n"
6155     "  @G--" GTEST_FLAG_PREFIX_
6156     "list_tests@D\n"
6157     "      List the names of all tests instead of running them. The name of\n"
6158     "      TEST(Foo, Bar) is \"Foo.Bar\".\n"
6159     "  @G--" GTEST_FLAG_PREFIX_
6160     "filter=@YPOSTIVE_PATTERNS"
6161     "[@G-@YNEGATIVE_PATTERNS]@D\n"
6162     "      Run only the tests whose name matches one of the positive patterns "
6163     "but\n"
6164     "      none of the negative patterns. '?' matches any single character; "
6165     "'*'\n"
6166     "      matches any substring; ':' separates two patterns.\n"
6167     "  @G--" GTEST_FLAG_PREFIX_
6168     "also_run_disabled_tests@D\n"
6169     "      Run all disabled tests too.\n"
6170     "\n"
6171     "Test Execution:\n"
6172     "  @G--" GTEST_FLAG_PREFIX_
6173     "repeat=@Y[COUNT]@D\n"
6174     "      Run the tests repeatedly; use a negative count to repeat forever.\n"
6175     "  @G--" GTEST_FLAG_PREFIX_
6176     "shuffle@D\n"
6177     "      Randomize tests' orders on every iteration.\n"
6178     "  @G--" GTEST_FLAG_PREFIX_
6179     "random_seed=@Y[NUMBER]@D\n"
6180     "      Random number seed to use for shuffling test orders (between 1 and\n"
6181     "      99999, or 0 to use a seed based on the current time).\n"
6182     "\n"
6183     "Test Output:\n"
6184     "  @G--" GTEST_FLAG_PREFIX_
6185     "color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\n"
6186     "      Enable/disable colored output. The default is @Gauto@D.\n"
6187     "  -@G-" GTEST_FLAG_PREFIX_
6188     "print_time=0@D\n"
6189     "      Don't print the elapsed time of each test.\n"
6190     "  @G--" GTEST_FLAG_PREFIX_
6191     "output=xml@Y[@G:@YDIRECTORY_PATH@G" GTEST_PATH_SEP_
6192     "@Y|@G:@YFILE_PATH]@D\n"
6193     "      Generate an XML report in the given directory or with the given "
6194     "file\n"
6195     "      name. @YFILE_PATH@D defaults to @Gtest_details.xml@D.\n"
6196 #if GTEST_CAN_STREAM_RESULTS_
6197     "  @G--" GTEST_FLAG_PREFIX_
6198     "stream_result_to=@YHOST@G:@YPORT@D\n"
6199     "      Stream test results to the given server.\n"
6200 #endif  // GTEST_CAN_STREAM_RESULTS_
6201     "\n"
6202     "Assertion Behavior:\n"
6203 #if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
6204     "  @G--" GTEST_FLAG_PREFIX_
6205     "death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n"
6206     "      Set the default death test style.\n"
6207 #endif  // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
6208     "  @G--" GTEST_FLAG_PREFIX_
6209     "break_on_failure@D\n"
6210     "      Turn assertion failures into debugger break-points.\n"
6211     "  @G--" GTEST_FLAG_PREFIX_
6212     "throw_on_failure@D\n"
6213     "      Turn assertion failures into C++ exceptions.\n"
6214     "  @G--" GTEST_FLAG_PREFIX_
6215     "catch_exceptions=0@D\n"
6216     "      Do not report exceptions as test failures. Instead, allow them\n"
6217     "      to crash the program or throw a pop-up (on Windows).\n"
6218     "\n"
6219     "Except for @G--" GTEST_FLAG_PREFIX_
6220     "list_tests@D, you can alternatively set "
6221     "the corresponding\n"
6222     "environment variable of a flag (all letters in upper-case). For example, "
6223     "to\n"
6224     "disable colored text output, you can either specify "
6225     "@G--" GTEST_FLAG_PREFIX_
6226     "color=no@D or set\n"
6227     "the @G" GTEST_FLAG_PREFIX_UPPER_
6228     "COLOR@D environment variable to @Gno@D.\n"
6229     "\n"
6230     "For more information, please read the " GTEST_NAME_
6231     " documentation at\n"
6232     "@G" GTEST_PROJECT_URL_ "@D. If you find a bug in " GTEST_NAME_
6233     "\n"
6234     "(not one in your own code or tests), please report it to\n"
6235     "@G<" GTEST_DEV_EMAIL_ ">@D.\n";
6236 
6237 // Parses the command line for Google Test flags, without initializing
6238 // other parts of Google Test.  The type parameter CharType can be
6239 // instantiated to either char or wchar_t.
6240 template <typename CharType>
ParseGoogleTestFlagsOnlyImpl(int * argc,CharType ** argv)6241 void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) {
6242   for (int i = 1; i < *argc; i++) {
6243     const std::string arg_string = StreamableToString(argv[i]);
6244     const char* const arg = arg_string.c_str();
6245 
6246     using internal::ParseBoolFlag;
6247     using internal::ParseInt32Flag;
6248     using internal::ParseStringFlag;
6249 
6250     // Do we see a Google Test flag?
6251     if (ParseBoolFlag(arg, kAlsoRunDisabledTestsFlag,
6252                       &GTEST_FLAG(also_run_disabled_tests)) ||
6253         ParseBoolFlag(arg, kBreakOnFailureFlag,
6254                       &GTEST_FLAG(break_on_failure)) ||
6255         ParseBoolFlag(arg, kCatchExceptionsFlag,
6256                       &GTEST_FLAG(catch_exceptions)) ||
6257         ParseStringFlag(arg, kColorFlag, &GTEST_FLAG(color)) ||
6258         ParseStringFlag(arg, kDeathTestStyleFlag,
6259                         &GTEST_FLAG(death_test_style)) ||
6260         ParseBoolFlag(arg, kDeathTestUseFork,
6261                       &GTEST_FLAG(death_test_use_fork)) ||
6262         ParseStringFlag(arg, kFilterFlag, &GTEST_FLAG(filter)) ||
6263         ParseStringFlag(arg, kInternalRunDeathTestFlag,
6264                         &GTEST_FLAG(internal_run_death_test)) ||
6265         ParseBoolFlag(arg, kListTestsFlag, &GTEST_FLAG(list_tests)) ||
6266         ParseStringFlag(arg, kOutputFlag, &GTEST_FLAG(output)) ||
6267         ParseBoolFlag(arg, kPrintTimeFlag, &GTEST_FLAG(print_time)) ||
6268         ParseInt32Flag(arg, kRandomSeedFlag, &GTEST_FLAG(random_seed)) ||
6269         ParseInt32Flag(arg, kRepeatFlag, &GTEST_FLAG(repeat)) ||
6270         ParseBoolFlag(arg, kShuffleFlag, &GTEST_FLAG(shuffle)) ||
6271         ParseInt32Flag(arg, kStackTraceDepthFlag,
6272                        &GTEST_FLAG(stack_trace_depth)) ||
6273         ParseStringFlag(arg, kStreamResultToFlag,
6274                         &GTEST_FLAG(stream_result_to)) ||
6275         ParseBoolFlag(arg, kThrowOnFailureFlag,
6276                       &GTEST_FLAG(throw_on_failure))) {
6277       // Yes.  Shift the remainder of the argv list left by one.  Note
6278       // that argv has (*argc + 1) elements, the last one always being
6279       // NULL.  The following loop moves the trailing NULL element as
6280       // well.
6281       for (int j = i; j != *argc; j++) {
6282         argv[j] = argv[j + 1];
6283       }
6284 
6285       // Decrements the argument count.
6286       (*argc)--;
6287 
6288       // We also need to decrement the iterator as we just removed
6289       // an element.
6290       i--;
6291     } else if (arg_string == "--help" || arg_string == "-h" ||
6292                arg_string == "-?" || arg_string == "/?" ||
6293                HasGoogleTestFlagPrefix(arg)) {
6294       // Both help flag and unrecognized Google Test flags (excluding
6295       // internal ones) trigger help display.
6296       g_help_flag = true;
6297     }
6298   }
6299 
6300   if (g_help_flag) {
6301     // We print the help here instead of in RUN_ALL_TESTS(), as the
6302     // latter may not be called at all if the user is using Google
6303     // Test with another testing framework.
6304     PrintColorEncoded(kColorEncodedHelpMessage);
6305   }
6306 }
6307 
6308 // Parses the command line for Google Test flags, without initializing
6309 // other parts of Google Test.
ParseGoogleTestFlagsOnly(int * argc,char ** argv)6310 void ParseGoogleTestFlagsOnly(int* argc, char** argv) {
6311   ParseGoogleTestFlagsOnlyImpl(argc, argv);
6312 }
ParseGoogleTestFlagsOnly(int * argc,wchar_t ** argv)6313 void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv) {
6314   ParseGoogleTestFlagsOnlyImpl(argc, argv);
6315 }
6316 
6317 // The internal implementation of InitGoogleTest().
6318 //
6319 // The type parameter CharType can be instantiated to either char or
6320 // wchar_t.
6321 template <typename CharType>
InitGoogleTestImpl(int * argc,CharType ** argv)6322 void InitGoogleTestImpl(int* argc, CharType** argv) {
6323   g_init_gtest_count++;
6324 
6325   // We don't want to run the initialization code twice.
6326   if (g_init_gtest_count != 1) return;
6327 
6328   if (*argc <= 0) return;
6329 
6330   internal::g_executable_path = internal::StreamableToString(argv[0]);
6331 
6332 #if GTEST_HAS_DEATH_TEST
6333 
6334   g_argvs.clear();
6335   for (int i = 0; i != *argc; i++) {
6336     g_argvs.push_back(StreamableToString(argv[i]));
6337   }
6338 
6339 #endif  // GTEST_HAS_DEATH_TEST
6340 
6341   ParseGoogleTestFlagsOnly(argc, argv);
6342   GetUnitTestImpl()->PostFlagParsingInit();
6343 }
6344 
6345 }  // namespace internal
6346 
6347 // Initializes Google Test.  This must be called before calling
6348 // RUN_ALL_TESTS().  In particular, it parses a command line for the
6349 // flags that Google Test recognizes.  Whenever a Google Test flag is
6350 // seen, it is removed from argv, and *argc is decremented.
6351 //
6352 // No value is returned.  Instead, the Google Test flag variables are
6353 // updated.
6354 //
6355 // Calling the function for the second time has no user-visible effect.
InitGoogleTest(int * argc,char ** argv)6356 void InitGoogleTest(int* argc, char** argv) {
6357   internal::InitGoogleTestImpl(argc, argv);
6358 }
6359 
6360 // This overloaded version can be used in Windows programs compiled in
6361 // UNICODE mode.
InitGoogleTest(int * argc,wchar_t ** argv)6362 void InitGoogleTest(int* argc, wchar_t** argv) {
6363   internal::InitGoogleTestImpl(argc, argv);
6364 }
6365 
6366 }  // namespace testing
6367 // Copyright 2005, Google Inc.
6368 // All rights reserved.
6369 //
6370 // Redistribution and use in source and binary forms, with or without
6371 // modification, are permitted provided that the following conditions are
6372 // met:
6373 //
6374 //     * Redistributions of source code must retain the above copyright
6375 // notice, this list of conditions and the following disclaimer.
6376 //     * Redistributions in binary form must reproduce the above
6377 // copyright notice, this list of conditions and the following disclaimer
6378 // in the documentation and/or other materials provided with the
6379 // distribution.
6380 //     * Neither the name of Google Inc. nor the names of its
6381 // contributors may be used to endorse or promote products derived from
6382 // this software without specific prior written permission.
6383 //
6384 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
6385 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
6386 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
6387 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
6388 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
6389 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
6390 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
6391 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
6392 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
6393 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
6394 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
6395 //
6396 // Author: wan@google.com (Zhanyong Wan), vladl@google.com (Vlad Losev)
6397 //
6398 // This file implements death tests.
6399 
6400 #if GTEST_HAS_DEATH_TEST
6401 
6402 #  if GTEST_OS_MAC
6403 #    include <crt_externs.h>
6404 #  endif  // GTEST_OS_MAC
6405 
6406 #  include <errno.h>
6407 #  include <fcntl.h>
6408 #  include <limits.h>
6409 
6410 #  if GTEST_OS_LINUX
6411 #    include <signal.h>
6412 #  endif  // GTEST_OS_LINUX
6413 
6414 #  include <stdarg.h>
6415 
6416 #  if GTEST_OS_WINDOWS
6417 #    include <windows.h>
6418 #  else
6419 #    include <sys/mman.h>
6420 #    include <sys/wait.h>
6421 #  endif  // GTEST_OS_WINDOWS
6422 
6423 #  if GTEST_OS_QNX
6424 #    include <spawn.h>
6425 #  endif  // GTEST_OS_QNX
6426 
6427 #endif  // GTEST_HAS_DEATH_TEST
6428 
6429 // Indicates that this translation unit is part of Google Test's
6430 // implementation.  It must come before gtest-internal-inl.h is
6431 // included, or there will be a compiler error.  This trick is to
6432 // prevent a user from accidentally including gtest-internal-inl.h in
6433 // his code.
6434 #define GTEST_IMPLEMENTATION_ 1
6435 #undef GTEST_IMPLEMENTATION_
6436 
6437 namespace testing {
6438 
6439 // Constants.
6440 
6441 // The default death test style.
6442 static const char kDefaultDeathTestStyle[] = "fast";
6443 
6444 GTEST_DEFINE_string_(
6445     death_test_style,
6446     internal::StringFromGTestEnv("death_test_style", kDefaultDeathTestStyle),
6447     "Indicates how to run a death test in a forked child process: "
6448     "\"threadsafe\" (child process re-executes the test binary "
6449     "from the beginning, running only the specific death test) or "
6450     "\"fast\" (child process runs the death test immediately "
6451     "after forking).");
6452 
6453 GTEST_DEFINE_bool_(
6454     death_test_use_fork,
6455     internal::BoolFromGTestEnv("death_test_use_fork", false),
6456     "Instructs to use fork()/_exit() instead of clone() in death tests. "
6457     "Ignored and always uses fork() on POSIX systems where clone() is not "
6458     "implemented. Useful when running under valgrind or similar tools if "
6459     "those do not support clone(). Valgrind 3.3.1 will just fail if "
6460     "it sees an unsupported combination of clone() flags. "
6461     "It is not recommended to use this flag w/o valgrind though it will "
6462     "work in 99% of the cases. Once valgrind is fixed, this flag will "
6463     "most likely be removed.");
6464 
6465 namespace internal {
6466 GTEST_DEFINE_string_(
6467     internal_run_death_test, "",
6468     "Indicates the file, line number, temporal index of "
6469     "the single death test to run, and a file descriptor to "
6470     "which a success code may be sent, all separated by "
6471     "the '|' characters.  This flag is specified if and only if the current "
6472     "process is a sub-process launched for running a thread-safe "
6473     "death test.  FOR INTERNAL USE ONLY.");
6474 }  // namespace internal
6475 
6476 #if GTEST_HAS_DEATH_TEST
6477 
6478 namespace internal {
6479 
6480 // Valid only for fast death tests. Indicates the code is running in the
6481 // child process of a fast style death test.
6482 static bool g_in_fast_death_test_child = false;
6483 
6484 // Returns a Boolean value indicating whether the caller is currently
6485 // executing in the context of the death test child process.  Tools such as
6486 // Valgrind heap checkers may need this to modify their behavior in death
6487 // tests.  IMPORTANT: This is an internal utility.  Using it may break the
6488 // implementation of death tests.  User code MUST NOT use it.
InDeathTestChild()6489 bool InDeathTestChild() {
6490 #  if GTEST_OS_WINDOWS
6491 
6492   // On Windows, death tests are thread-safe regardless of the value of the
6493   // death_test_style flag.
6494   return !GTEST_FLAG(internal_run_death_test).empty();
6495 
6496 #  else
6497 
6498   if (GTEST_FLAG(death_test_style) == "threadsafe")
6499     return !GTEST_FLAG(internal_run_death_test).empty();
6500   else
6501     return g_in_fast_death_test_child;
6502 #  endif
6503 }
6504 
6505 }  // namespace internal
6506 
6507 // ExitedWithCode constructor.
ExitedWithCode(int exit_code)6508 ExitedWithCode::ExitedWithCode(int exit_code) : exit_code_(exit_code) {}
6509 
6510 // ExitedWithCode function-call operator.
operator ()(int exit_status) const6511 bool ExitedWithCode::operator()(int exit_status) const {
6512 #  if GTEST_OS_WINDOWS
6513 
6514   return exit_status == exit_code_;
6515 
6516 #  else
6517 
6518   return WIFEXITED(exit_status) && WEXITSTATUS(exit_status) == exit_code_;
6519 
6520 #  endif  // GTEST_OS_WINDOWS
6521 }
6522 
6523 #  if !GTEST_OS_WINDOWS
6524 // KilledBySignal constructor.
KilledBySignal(int signum)6525 KilledBySignal::KilledBySignal(int signum) : signum_(signum) {}
6526 
6527 // KilledBySignal function-call operator.
operator ()(int exit_status) const6528 bool KilledBySignal::operator()(int exit_status) const {
6529   return WIFSIGNALED(exit_status) && WTERMSIG(exit_status) == signum_;
6530 }
6531 #  endif  // !GTEST_OS_WINDOWS
6532 
6533 namespace internal {
6534 
6535 // Utilities needed for death tests.
6536 
6537 // Generates a textual description of a given exit code, in the format
6538 // specified by wait(2).
ExitSummary(int exit_code)6539 static std::string ExitSummary(int exit_code) {
6540   Message m;
6541 
6542 #  if GTEST_OS_WINDOWS
6543 
6544   m << "Exited with exit status " << exit_code;
6545 
6546 #  else
6547 
6548   if (WIFEXITED(exit_code)) {
6549     m << "Exited with exit status " << WEXITSTATUS(exit_code);
6550   } else if (WIFSIGNALED(exit_code)) {
6551     m << "Terminated by signal " << WTERMSIG(exit_code);
6552   }
6553 #    ifdef WCOREDUMP
6554   if (WCOREDUMP(exit_code)) {
6555     m << " (core dumped)";
6556   }
6557 #    endif
6558 #  endif  // GTEST_OS_WINDOWS
6559 
6560   return m.GetString();
6561 }
6562 
6563 // Returns true if exit_status describes a process that was terminated
6564 // by a signal, or exited normally with a nonzero exit code.
ExitedUnsuccessfully(int exit_status)6565 bool ExitedUnsuccessfully(int exit_status) {
6566   return !ExitedWithCode(0)(exit_status);
6567 }
6568 
6569 #  if !GTEST_OS_WINDOWS
6570 // Generates a textual failure message when a death test finds more than
6571 // one thread running, or cannot determine the number of threads, prior
6572 // to executing the given statement.  It is the responsibility of the
6573 // caller not to pass a thread_count of 1.
DeathTestThreadWarning(size_t thread_count)6574 static std::string DeathTestThreadWarning(size_t thread_count) {
6575   Message msg;
6576   msg << "Death tests use fork(), which is unsafe particularly"
6577       << " in a threaded context. For this test, " << GTEST_NAME_ << " ";
6578   if (thread_count == 0)
6579     msg << "couldn't detect the number of threads.";
6580   else
6581     msg << "detected " << thread_count << " threads.";
6582   return msg.GetString();
6583 }
6584 #  endif  // !GTEST_OS_WINDOWS
6585 
6586 // Flag characters for reporting a death test that did not die.
6587 static const char kDeathTestLived = 'L';
6588 static const char kDeathTestReturned = 'R';
6589 static const char kDeathTestThrew = 'T';
6590 static const char kDeathTestInternalError = 'I';
6591 
6592 // An enumeration describing all of the possible ways that a death test can
6593 // conclude.  DIED means that the process died while executing the test
6594 // code; LIVED means that process lived beyond the end of the test code;
6595 // RETURNED means that the test statement attempted to execute a return
6596 // statement, which is not allowed; THREW means that the test statement
6597 // returned control by throwing an exception.  IN_PROGRESS means the test
6598 // has not yet concluded.
6599 // TODO(vladl@google.com): Unify names and possibly values for
6600 // AbortReason, DeathTestOutcome, and flag characters above.
6601 enum DeathTestOutcome { IN_PROGRESS, DIED, LIVED, RETURNED, THREW };
6602 
6603 // Routine for aborting the program which is safe to call from an
6604 // exec-style death test child process, in which case the error
6605 // message is propagated back to the parent process.  Otherwise, the
6606 // message is simply printed to stderr.  In either case, the program
6607 // then exits with status 1.
DeathTestAbort(const std::string & message)6608 void DeathTestAbort(const std::string& message) {
6609   // On a POSIX system, this function may be called from a threadsafe-style
6610   // death test child process, which operates on a very small stack.  Use
6611   // the heap for any additional non-minuscule memory requirements.
6612   const InternalRunDeathTestFlag* const flag =
6613       GetUnitTestImpl()->internal_run_death_test_flag();
6614   if (flag != NULL) {
6615     FILE* parent = posix::FDOpen(flag->write_fd(), "w");
6616     fputc(kDeathTestInternalError, parent);
6617     fprintf(parent, "%s", message.c_str());
6618     fflush(parent);
6619     _exit(1);
6620   } else {
6621     fprintf(stderr, "%s", message.c_str());
6622     fflush(stderr);
6623     posix::Abort();
6624   }
6625 }
6626 
6627 // A replacement for CHECK that calls DeathTestAbort if the assertion
6628 // fails.
6629 #  define GTEST_DEATH_TEST_CHECK_(expression)                              \
6630     do {                                                                   \
6631       if (!::testing::internal::IsTrue(expression)) {                      \
6632         DeathTestAbort(::std::string("CHECK failed: File ") + __FILE__ +   \
6633                        ", line " +                                         \
6634                        ::testing::internal::StreamableToString(__LINE__) + \
6635                        ": " + #expression);                                \
6636       }                                                                    \
6637     } while (::testing::internal::AlwaysFalse())
6638 
6639 // This macro is similar to GTEST_DEATH_TEST_CHECK_, but it is meant for
6640 // evaluating any system call that fulfills two conditions: it must return
6641 // -1 on failure, and set errno to EINTR when it is interrupted and
6642 // should be tried again.  The macro expands to a loop that repeatedly
6643 // evaluates the expression as long as it evaluates to -1 and sets
6644 // errno to EINTR.  If the expression evaluates to -1 but errno is
6645 // something other than EINTR, DeathTestAbort is called.
6646 #  define GTEST_DEATH_TEST_CHECK_SYSCALL_(expression)                      \
6647     do {                                                                   \
6648       int gtest_retval;                                                    \
6649       do {                                                                 \
6650         gtest_retval = (expression);                                       \
6651       } while (gtest_retval == -1 && errno == EINTR);                      \
6652       if (gtest_retval == -1) {                                            \
6653         DeathTestAbort(::std::string("CHECK failed: File ") + __FILE__ +   \
6654                        ", line " +                                         \
6655                        ::testing::internal::StreamableToString(__LINE__) + \
6656                        ": " + #expression + " != -1");                     \
6657       }                                                                    \
6658     } while (::testing::internal::AlwaysFalse())
6659 
6660 // Returns the message describing the last system error in errno.
GetLastErrnoDescription()6661 std::string GetLastErrnoDescription() {
6662   return errno == 0 ? "" : posix::StrError(errno);
6663 }
6664 
6665 // This is called from a death test parent process to read a failure
6666 // message from the death test child process and log it with the FATAL
6667 // severity. On Windows, the message is read from a pipe handle. On other
6668 // platforms, it is read from a file descriptor.
FailFromInternalError(int fd)6669 static void FailFromInternalError(int fd) {
6670   Message error;
6671   char buffer[256];
6672   int num_read;
6673 
6674   do {
6675     while ((num_read = posix::Read(fd, buffer, 255)) > 0) {
6676       buffer[num_read] = '\0';
6677       error << buffer;
6678     }
6679   } while (num_read == -1 && errno == EINTR);
6680 
6681   if (num_read == 0) {
6682     GTEST_LOG_(FATAL) << error.GetString();
6683   } else {
6684     const int last_error = errno;
6685     GTEST_LOG_(FATAL) << "Error while reading death test internal: "
6686                       << GetLastErrnoDescription() << " [" << last_error << "]";
6687   }
6688 }
6689 
6690 // Death test constructor.  Increments the running death test count
6691 // for the current test.
DeathTest()6692 DeathTest::DeathTest() {
6693   TestInfo* const info = GetUnitTestImpl()->current_test_info();
6694   if (info == NULL) {
6695     DeathTestAbort(
6696         "Cannot run a death test outside of a TEST or "
6697         "TEST_F construct");
6698   }
6699 }
6700 
6701 // Creates and returns a death test by dispatching to the current
6702 // death test factory.
Create(const char * statement,const RE * regex,const char * file,int line,DeathTest ** test)6703 bool DeathTest::Create(const char* statement, const RE* regex, const char* file,
6704                        int line, DeathTest** test) {
6705   return GetUnitTestImpl()->death_test_factory()->Create(statement, regex, file,
6706                                                          line, test);
6707 }
6708 
LastMessage()6709 const char* DeathTest::LastMessage() {
6710   return last_death_test_message_.c_str();
6711 }
6712 
set_last_death_test_message(const std::string & message)6713 void DeathTest::set_last_death_test_message(const std::string& message) {
6714   last_death_test_message_ = message;
6715 }
6716 
6717 std::string DeathTest::last_death_test_message_;
6718 
6719 // Provides cross platform implementation for some death functionality.
6720 class DeathTestImpl : public DeathTest {
6721  protected:
DeathTestImpl(const char * a_statement,const RE * a_regex)6722   DeathTestImpl(const char* a_statement, const RE* a_regex)
6723       : statement_(a_statement),
6724         regex_(a_regex),
6725         spawned_(false),
6726         status_(-1),
6727         outcome_(IN_PROGRESS),
6728         read_fd_(-1),
6729         write_fd_(-1) {}
6730 
6731   // read_fd_ is expected to be closed and cleared by a derived class.
~DeathTestImpl()6732   ~DeathTestImpl() { GTEST_DEATH_TEST_CHECK_(read_fd_ == -1); }
6733 
6734   void Abort(AbortReason reason);
6735   virtual bool Passed(bool status_ok);
6736 
statement() const6737   const char* statement() const { return statement_; }
regex() const6738   const RE* regex() const { return regex_; }
spawned() const6739   bool spawned() const { return spawned_; }
set_spawned(bool is_spawned)6740   void set_spawned(bool is_spawned) { spawned_ = is_spawned; }
status() const6741   int status() const { return status_; }
set_status(int a_status)6742   void set_status(int a_status) { status_ = a_status; }
outcome() const6743   DeathTestOutcome outcome() const { return outcome_; }
set_outcome(DeathTestOutcome an_outcome)6744   void set_outcome(DeathTestOutcome an_outcome) { outcome_ = an_outcome; }
read_fd() const6745   int read_fd() const { return read_fd_; }
set_read_fd(int fd)6746   void set_read_fd(int fd) { read_fd_ = fd; }
write_fd() const6747   int write_fd() const { return write_fd_; }
set_write_fd(int fd)6748   void set_write_fd(int fd) { write_fd_ = fd; }
6749 
6750   // Called in the parent process only. Reads the result code of the death
6751   // test child process via a pipe, interprets it to set the outcome_
6752   // member, and closes read_fd_.  Outputs diagnostics and terminates in
6753   // case of unexpected codes.
6754   void ReadAndInterpretStatusByte();
6755 
6756  private:
6757   // The textual content of the code this object is testing.  This class
6758   // doesn't own this string and should not attempt to delete it.
6759   const char* const statement_;
6760   // The regular expression which test output must match.  DeathTestImpl
6761   // doesn't own this object and should not attempt to delete it.
6762   const RE* const regex_;
6763   // True if the death test child process has been successfully spawned.
6764   bool spawned_;
6765   // The exit status of the child process.
6766   int status_;
6767   // How the death test concluded.
6768   DeathTestOutcome outcome_;
6769   // Descriptor to the read end of the pipe to the child process.  It is
6770   // always -1 in the child process.  The child keeps its write end of the
6771   // pipe in write_fd_.
6772   int read_fd_;
6773   // Descriptor to the child's write end of the pipe to the parent process.
6774   // It is always -1 in the parent process.  The parent keeps its end of the
6775   // pipe in read_fd_.
6776   int write_fd_;
6777 };
6778 
6779 // Called in the parent process only. Reads the result code of the death
6780 // test child process via a pipe, interprets it to set the outcome_
6781 // member, and closes read_fd_.  Outputs diagnostics and terminates in
6782 // case of unexpected codes.
ReadAndInterpretStatusByte()6783 void DeathTestImpl::ReadAndInterpretStatusByte() {
6784   char flag;
6785   int bytes_read;
6786 
6787   // The read() here blocks until data is available (signifying the
6788   // failure of the death test) or until the pipe is closed (signifying
6789   // its success), so it's okay to call this in the parent before
6790   // the child process has exited.
6791   do {
6792     bytes_read = posix::Read(read_fd(), &flag, 1);
6793   } while (bytes_read == -1 && errno == EINTR);
6794 
6795   if (bytes_read == 0) {
6796     set_outcome(DIED);
6797   } else if (bytes_read == 1) {
6798     switch (flag) {
6799     case kDeathTestReturned:
6800       set_outcome(RETURNED);
6801       break;
6802     case kDeathTestThrew:
6803       set_outcome(THREW);
6804       break;
6805     case kDeathTestLived:
6806       set_outcome(LIVED);
6807       break;
6808     case kDeathTestInternalError:
6809       FailFromInternalError(read_fd());  // Does not return.
6810       break;
6811     default:
6812       GTEST_LOG_(FATAL) << "Death test child process reported "
6813                         << "unexpected status byte ("
6814                         << static_cast<unsigned int>(flag) << ")";
6815     }
6816   } else {
6817     GTEST_LOG_(FATAL) << "Read from death test child process failed: "
6818                       << GetLastErrnoDescription();
6819   }
6820   GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Close(read_fd()));
6821   set_read_fd(-1);
6822 }
6823 
6824 // Signals that the death test code which should have exited, didn't.
6825 // Should be called only in a death test child process.
6826 // Writes a status byte to the child's status file descriptor, then
6827 // calls _exit(1).
Abort(AbortReason reason)6828 void DeathTestImpl::Abort(AbortReason reason) {
6829   // The parent process considers the death test to be a failure if
6830   // it finds any data in our pipe.  So, here we write a single flag byte
6831   // to the pipe, then exit.
6832   const char status_ch = reason == TEST_DID_NOT_DIE
6833                              ? kDeathTestLived
6834                              : reason == TEST_THREW_EXCEPTION
6835                                    ? kDeathTestThrew
6836                                    : kDeathTestReturned;
6837 
6838   GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Write(write_fd(), &status_ch, 1));
6839   // We are leaking the descriptor here because on some platforms (i.e.,
6840   // when built as Windows DLL), destructors of global objects will still
6841   // run after calling _exit(). On such systems, write_fd_ will be
6842   // indirectly closed from the destructor of UnitTestImpl, causing double
6843   // close if it is also closed here. On debug configurations, double close
6844   // may assert. As there are no in-process buffers to flush here, we are
6845   // relying on the OS to close the descriptor after the process terminates
6846   // when the destructors are not run.
6847   _exit(1);  // Exits w/o any normal exit hooks (we were supposed to crash)
6848 }
6849 
6850 // Returns an indented copy of stderr output for a death test.
6851 // This makes distinguishing death test output lines from regular log lines
6852 // much easier.
FormatDeathTestOutput(const::std::string & output)6853 static ::std::string FormatDeathTestOutput(const ::std::string& output) {
6854   ::std::string ret;
6855   for (size_t at = 0;;) {
6856     const size_t line_end = output.find('\n', at);
6857     ret += "[  DEATH   ] ";
6858     if (line_end == ::std::string::npos) {
6859       ret += output.substr(at);
6860       break;
6861     }
6862     ret += output.substr(at, line_end + 1 - at);
6863     at = line_end + 1;
6864   }
6865   return ret;
6866 }
6867 
6868 // Assesses the success or failure of a death test, using both private
6869 // members which have previously been set, and one argument:
6870 //
6871 // Private data members:
6872 //   outcome:  An enumeration describing how the death test
6873 //             concluded: DIED, LIVED, THREW, or RETURNED.  The death test
6874 //             fails in the latter three cases.
6875 //   status:   The exit status of the child process. On *nix, it is in the
6876 //             in the format specified by wait(2). On Windows, this is the
6877 //             value supplied to the ExitProcess() API or a numeric code
6878 //             of the exception that terminated the program.
6879 //   regex:    A regular expression object to be applied to
6880 //             the test's captured standard error output; the death test
6881 //             fails if it does not match.
6882 //
6883 // Argument:
6884 //   status_ok: true if exit_status is acceptable in the context of
6885 //              this particular death test, which fails if it is false
6886 //
6887 // Returns true iff all of the above conditions are met.  Otherwise, the
6888 // first failing condition, in the order given above, is the one that is
6889 // reported. Also sets the last death test message string.
Passed(bool status_ok)6890 bool DeathTestImpl::Passed(bool status_ok) {
6891   if (!spawned()) return false;
6892 
6893   const std::string error_message = GetCapturedStderr();
6894 
6895   bool success = false;
6896   Message buffer;
6897 
6898   buffer << "Death test: " << statement() << "\n";
6899   switch (outcome()) {
6900   case LIVED:
6901     buffer << "    Result: failed to die.\n"
6902            << " Error msg:\n"
6903            << FormatDeathTestOutput(error_message);
6904     break;
6905   case THREW:
6906     buffer << "    Result: threw an exception.\n"
6907            << " Error msg:\n"
6908            << FormatDeathTestOutput(error_message);
6909     break;
6910   case RETURNED:
6911     buffer << "    Result: illegal return in test statement.\n"
6912            << " Error msg:\n"
6913            << FormatDeathTestOutput(error_message);
6914     break;
6915   case DIED:
6916     if (status_ok) {
6917       const bool matched = RE::PartialMatch(error_message.c_str(), *regex());
6918       if (matched) {
6919         success = true;
6920       } else {
6921         buffer << "    Result: died but not with expected error.\n"
6922                << "  Expected: " << regex()->pattern() << "\n"
6923                << "Actual msg:\n"
6924                << FormatDeathTestOutput(error_message);
6925       }
6926     } else {
6927       buffer << "    Result: died but not with expected exit code:\n"
6928              << "            " << ExitSummary(status()) << "\n"
6929              << "Actual msg:\n"
6930              << FormatDeathTestOutput(error_message);
6931     }
6932     break;
6933   case IN_PROGRESS:
6934   default:
6935     GTEST_LOG_(FATAL)
6936         << "DeathTest::Passed somehow called before conclusion of test";
6937   }
6938 
6939   DeathTest::set_last_death_test_message(buffer.GetString());
6940   return success;
6941 }
6942 
6943 #  if GTEST_OS_WINDOWS
6944 // WindowsDeathTest implements death tests on Windows. Due to the
6945 // specifics of starting new processes on Windows, death tests there are
6946 // always threadsafe, and Google Test considers the
6947 // --gtest_death_test_style=fast setting to be equivalent to
6948 // --gtest_death_test_style=threadsafe there.
6949 //
6950 // A few implementation notes:  Like the Linux version, the Windows
6951 // implementation uses pipes for child-to-parent communication. But due to
6952 // the specifics of pipes on Windows, some extra steps are required:
6953 //
6954 // 1. The parent creates a communication pipe and stores handles to both
6955 //    ends of it.
6956 // 2. The parent starts the child and provides it with the information
6957 //    necessary to acquire the handle to the write end of the pipe.
6958 // 3. The child acquires the write end of the pipe and signals the parent
6959 //    using a Windows event.
6960 // 4. Now the parent can release the write end of the pipe on its side. If
6961 //    this is done before step 3, the object's reference count goes down to
6962 //    0 and it is destroyed, preventing the child from acquiring it. The
6963 //    parent now has to release it, or read operations on the read end of
6964 //    the pipe will not return when the child terminates.
6965 // 5. The parent reads child's output through the pipe (outcome code and
6966 //    any possible error messages) from the pipe, and its stderr and then
6967 //    determines whether to fail the test.
6968 //
6969 // Note: to distinguish Win32 API calls from the local method and function
6970 // calls, the former are explicitly resolved in the global namespace.
6971 //
6972 class WindowsDeathTest : public DeathTestImpl {
6973  public:
WindowsDeathTest(const char * a_statement,const RE * a_regex,const char * file,int line)6974   WindowsDeathTest(const char* a_statement, const RE* a_regex, const char* file,
6975                    int line)
6976       : DeathTestImpl(a_statement, a_regex), file_(file), line_(line) {}
6977 
6978   // All of these virtual functions are inherited from DeathTest.
6979   virtual int Wait();
6980   virtual TestRole AssumeRole();
6981 
6982  private:
6983   // The name of the file in which the death test is located.
6984   const char* const file_;
6985   // The line number on which the death test is located.
6986   const int line_;
6987   // Handle to the write end of the pipe to the child process.
6988   AutoHandle write_handle_;
6989   // Child process handle.
6990   AutoHandle child_handle_;
6991   // Event the child process uses to signal the parent that it has
6992   // acquired the handle to the write end of the pipe. After seeing this
6993   // event the parent can release its own handles to make sure its
6994   // ReadFile() calls return when the child terminates.
6995   AutoHandle event_handle_;
6996 };
6997 
6998 // Waits for the child in a death test to exit, returning its exit
6999 // status, or 0 if no child process exists.  As a side effect, sets the
7000 // outcome data member.
Wait()7001 int WindowsDeathTest::Wait() {
7002   if (!spawned()) return 0;
7003 
7004   // Wait until the child either signals that it has acquired the write end
7005   // of the pipe or it dies.
7006   const HANDLE wait_handles[2] = {child_handle_.Get(), event_handle_.Get()};
7007   switch (::WaitForMultipleObjects(2, wait_handles,
7008                                    FALSE,  // Waits for any of the handles.
7009                                    INFINITE)) {
7010   case WAIT_OBJECT_0:
7011   case WAIT_OBJECT_0 + 1:
7012     break;
7013   default:
7014     GTEST_DEATH_TEST_CHECK_(false);  // Should not get here.
7015   }
7016 
7017   // The child has acquired the write end of the pipe or exited.
7018   // We release the handle on our side and continue.
7019   write_handle_.Reset();
7020   event_handle_.Reset();
7021 
7022   ReadAndInterpretStatusByte();
7023 
7024   // Waits for the child process to exit if it haven't already. This
7025   // returns immediately if the child has already exited, regardless of
7026   // whether previous calls to WaitForMultipleObjects synchronized on this
7027   // handle or not.
7028   GTEST_DEATH_TEST_CHECK_(WAIT_OBJECT_0 ==
7029                           ::WaitForSingleObject(child_handle_.Get(), INFINITE));
7030   DWORD status_code;
7031   GTEST_DEATH_TEST_CHECK_(
7032       ::GetExitCodeProcess(child_handle_.Get(), &status_code) != FALSE);
7033   child_handle_.Reset();
7034   set_status(static_cast<int>(status_code));
7035   return status();
7036 }
7037 
7038 // The AssumeRole process for a Windows death test.  It creates a child
7039 // process with the same executable as the current process to run the
7040 // death test.  The child process is given the --gtest_filter and
7041 // --gtest_internal_run_death_test flags such that it knows to run the
7042 // current death test only.
AssumeRole()7043 DeathTest::TestRole WindowsDeathTest::AssumeRole() {
7044   const UnitTestImpl* const impl = GetUnitTestImpl();
7045   const InternalRunDeathTestFlag* const flag =
7046       impl->internal_run_death_test_flag();
7047   const TestInfo* const info = impl->current_test_info();
7048   const int death_test_index = info->result()->death_test_count();
7049 
7050   if (flag != NULL) {
7051     // ParseInternalRunDeathTestFlag() has performed all the necessary
7052     // processing.
7053     set_write_fd(flag->write_fd());
7054     return EXECUTE_TEST;
7055   }
7056 
7057   // WindowsDeathTest uses an anonymous pipe to communicate results of
7058   // a death test.
7059   SECURITY_ATTRIBUTES handles_are_inheritable = {sizeof(SECURITY_ATTRIBUTES),
7060                                                  NULL, TRUE};
7061   HANDLE read_handle, write_handle;
7062   GTEST_DEATH_TEST_CHECK_(::CreatePipe(&read_handle, &write_handle,
7063                                        &handles_are_inheritable,
7064                                        0)  // Default buffer size.
7065                           != FALSE);
7066   set_read_fd(
7067       ::_open_osfhandle(reinterpret_cast<intptr_t>(read_handle), O_RDONLY));
7068   write_handle_.Reset(write_handle);
7069   event_handle_.Reset(::CreateEvent(
7070       &handles_are_inheritable,
7071       TRUE,    // The event will automatically reset to non-signaled state.
7072       FALSE,   // The initial state is non-signalled.
7073       NULL));  // The even is unnamed.
7074   GTEST_DEATH_TEST_CHECK_(event_handle_.Get() != NULL);
7075   const std::string filter_flag = std::string("--") + GTEST_FLAG_PREFIX_ +
7076                                   kFilterFlag + "=" + info->test_case_name() +
7077                                   "." + info->name();
7078   const std::string internal_flag =
7079       std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag + "=" +
7080       file_ + "|" + StreamableToString(line_) + "|" +
7081       StreamableToString(death_test_index) + "|" +
7082       StreamableToString(static_cast<unsigned int>(::GetCurrentProcessId())) +
7083       // size_t has the same width as pointers on both 32-bit and 64-bit
7084       // Windows platforms.
7085       // See http://msdn.microsoft.com/en-us/library/tcxf1dw6.aspx.
7086       "|" + StreamableToString(reinterpret_cast<size_t>(write_handle)) + "|" +
7087       StreamableToString(reinterpret_cast<size_t>(event_handle_.Get()));
7088 
7089   char executable_path[_MAX_PATH + 1];  // NOLINT
7090   GTEST_DEATH_TEST_CHECK_(
7091       _MAX_PATH + 1 != ::GetModuleFileNameA(NULL, executable_path, _MAX_PATH));
7092 
7093   std::string command_line = std::string(::GetCommandLineA()) + " " +
7094                              filter_flag + " \"" + internal_flag + "\"";
7095 
7096   DeathTest::set_last_death_test_message("");
7097 
7098   CaptureStderr();
7099   // Flush the log buffers since the log streams are shared with the child.
7100   FlushInfoLog();
7101 
7102   // The child process will share the standard handles with the parent.
7103   STARTUPINFOA startup_info;
7104   memset(&startup_info, 0, sizeof(STARTUPINFO));
7105   startup_info.dwFlags = STARTF_USESTDHANDLES;
7106   startup_info.hStdInput = ::GetStdHandle(STD_INPUT_HANDLE);
7107   startup_info.hStdOutput = ::GetStdHandle(STD_OUTPUT_HANDLE);
7108   startup_info.hStdError = ::GetStdHandle(STD_ERROR_HANDLE);
7109 
7110   PROCESS_INFORMATION process_info;
7111   GTEST_DEATH_TEST_CHECK_(
7112       ::CreateProcessA(
7113           executable_path, const_cast<char*>(command_line.c_str()),
7114           NULL,  // Retuned process handle is not inheritable.
7115           NULL,  // Retuned thread handle is not inheritable.
7116           TRUE,  // Child inherits all inheritable handles (for write_handle_).
7117           0x0,   // Default creation flags.
7118           NULL,  // Inherit the parent's environment.
7119           UnitTest::GetInstance()->original_working_dir(), &startup_info,
7120           &process_info) != FALSE);
7121   child_handle_.Reset(process_info.hProcess);
7122   ::CloseHandle(process_info.hThread);
7123   set_spawned(true);
7124   return OVERSEE_TEST;
7125 }
7126 #  else  // We are not on Windows.
7127 
7128 // ForkingDeathTest provides implementations for most of the abstract
7129 // methods of the DeathTest interface.  Only the AssumeRole method is
7130 // left undefined.
7131 class ForkingDeathTest : public DeathTestImpl {
7132  public:
7133   ForkingDeathTest(const char* statement, const RE* regex);
7134 
7135   // All of these virtual functions are inherited from DeathTest.
7136   virtual int Wait();
7137 
7138  protected:
set_child_pid(pid_t child_pid)7139   void set_child_pid(pid_t child_pid) { child_pid_ = child_pid; }
7140 
7141  private:
7142   // PID of child process during death test; 0 in the child process itself.
7143   pid_t child_pid_;
7144 };
7145 
7146 // Constructs a ForkingDeathTest.
ForkingDeathTest(const char * a_statement,const RE * a_regex)7147 ForkingDeathTest::ForkingDeathTest(const char* a_statement, const RE* a_regex)
7148     : DeathTestImpl(a_statement, a_regex), child_pid_(-1) {}
7149 
7150 // Waits for the child in a death test to exit, returning its exit
7151 // status, or 0 if no child process exists.  As a side effect, sets the
7152 // outcome data member.
Wait()7153 int ForkingDeathTest::Wait() {
7154   if (!spawned()) return 0;
7155 
7156   ReadAndInterpretStatusByte();
7157 
7158   int status_value;
7159   GTEST_DEATH_TEST_CHECK_SYSCALL_(waitpid(child_pid_, &status_value, 0));
7160   set_status(status_value);
7161   return status_value;
7162 }
7163 
7164 // A concrete death test class that forks, then immediately runs the test
7165 // in the child process.
7166 class NoExecDeathTest : public ForkingDeathTest {
7167  public:
NoExecDeathTest(const char * a_statement,const RE * a_regex)7168   NoExecDeathTest(const char* a_statement, const RE* a_regex)
7169       : ForkingDeathTest(a_statement, a_regex) {}
7170   virtual TestRole AssumeRole();
7171 };
7172 
7173 // The AssumeRole process for a fork-and-run death test.  It implements a
7174 // straightforward fork, with a simple pipe to transmit the status byte.
AssumeRole()7175 DeathTest::TestRole NoExecDeathTest::AssumeRole() {
7176   const size_t thread_count = GetThreadCount();
7177   if (thread_count != 1) {
7178     GTEST_LOG_(WARNING) << DeathTestThreadWarning(thread_count);
7179   }
7180 
7181   int pipe_fd[2];
7182   GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
7183 
7184   DeathTest::set_last_death_test_message("");
7185   CaptureStderr();
7186   // When we fork the process below, the log file buffers are copied, but the
7187   // file descriptors are shared.  We flush all log files here so that closing
7188   // the file descriptors in the child process doesn't throw off the
7189   // synchronization between descriptors and buffers in the parent process.
7190   // This is as close to the fork as possible to avoid a race condition in case
7191   // there are multiple threads running before the death test, and another
7192   // thread writes to the log file.
7193   FlushInfoLog();
7194 
7195   const pid_t child_pid = fork();
7196   GTEST_DEATH_TEST_CHECK_(child_pid != -1);
7197   set_child_pid(child_pid);
7198   if (child_pid == 0) {
7199     GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[0]));
7200     set_write_fd(pipe_fd[1]);
7201     // Redirects all logging to stderr in the child process to prevent
7202     // concurrent writes to the log files.  We capture stderr in the parent
7203     // process and append the child process' output to a log.
7204     LogToStderr();
7205     // Event forwarding to the listeners of event listener API mush be shut
7206     // down in death test subprocesses.
7207     GetUnitTestImpl()->listeners()->SuppressEventForwarding();
7208     g_in_fast_death_test_child = true;
7209     return EXECUTE_TEST;
7210   } else {
7211     GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
7212     set_read_fd(pipe_fd[0]);
7213     set_spawned(true);
7214     return OVERSEE_TEST;
7215   }
7216 }
7217 
7218 // A concrete death test class that forks and re-executes the main
7219 // program from the beginning, with command-line flags set that cause
7220 // only this specific death test to be run.
7221 class ExecDeathTest : public ForkingDeathTest {
7222  public:
ExecDeathTest(const char * a_statement,const RE * a_regex,const char * file,int line)7223   ExecDeathTest(const char* a_statement, const RE* a_regex, const char* file,
7224                 int line)
7225       : ForkingDeathTest(a_statement, a_regex), file_(file), line_(line) {}
7226   virtual TestRole AssumeRole();
7227 
7228  private:
7229   static ::std::vector<testing::internal::string>
GetArgvsForDeathTestChildProcess()7230   GetArgvsForDeathTestChildProcess() {
7231     ::std::vector<testing::internal::string> args = GetInjectableArgvs();
7232     return args;
7233   }
7234   // The name of the file in which the death test is located.
7235   const char* const file_;
7236   // The line number on which the death test is located.
7237   const int line_;
7238 };
7239 
7240 // Utility class for accumulating command-line arguments.
7241 class Arguments {
7242  public:
Arguments()7243   Arguments() { args_.push_back(NULL); }
7244 
~Arguments()7245   ~Arguments() {
7246     for (std::vector<char*>::iterator i = args_.begin(); i != args_.end();
7247          ++i) {
7248       free(*i);
7249     }
7250   }
AddArgument(const char * argument)7251   void AddArgument(const char* argument) {
7252     args_.insert(args_.end() - 1, posix::StrDup(argument));
7253   }
7254 
7255   template <typename Str>
AddArguments(const::std::vector<Str> & arguments)7256   void AddArguments(const ::std::vector<Str>& arguments) {
7257     for (typename ::std::vector<Str>::const_iterator i = arguments.begin();
7258          i != arguments.end(); ++i) {
7259       args_.insert(args_.end() - 1, posix::StrDup(i->c_str()));
7260     }
7261   }
Argv()7262   char* const* Argv() { return &args_[0]; }
7263 
7264  private:
7265   std::vector<char*> args_;
7266 };
7267 
7268 // A struct that encompasses the arguments to the child process of a
7269 // threadsafe-style death test process.
7270 struct ExecDeathTestArgs {
7271   char* const* argv;  // Command-line arguments for the child's call to exec
7272   int close_fd;       // File descriptor to close; the read end of a pipe
7273 };
7274 
7275 #    if GTEST_OS_MAC
GetEnviron()7276 inline char** GetEnviron() {
7277   // When Google Test is built as a framework on MacOS X, the environ variable
7278   // is unavailable. Apple's documentation (man environ) recommends using
7279   // _NSGetEnviron() instead.
7280   return *_NSGetEnviron();
7281 }
7282 #    else
7283 // Some POSIX platforms expect you to declare environ. extern "C" makes
7284 // it reside in the global namespace.
7285 extern "C" char** environ;
GetEnviron()7286 inline char** GetEnviron() { return environ; }
7287 #    endif  // GTEST_OS_MAC
7288 
7289 #    if !GTEST_OS_QNX
7290 // The main function for a threadsafe-style death test child process.
7291 // This function is called in a clone()-ed process and thus must avoid
7292 // any potentially unsafe operations like malloc or libc functions.
ExecDeathTestChildMain(void * child_arg)7293 static int ExecDeathTestChildMain(void* child_arg) {
7294   ExecDeathTestArgs* const args = static_cast<ExecDeathTestArgs*>(child_arg);
7295   GTEST_DEATH_TEST_CHECK_SYSCALL_(close(args->close_fd));
7296 
7297   // We need to execute the test program in the same environment where
7298   // it was originally invoked.  Therefore we change to the original
7299   // working directory first.
7300   const char* const original_dir =
7301       UnitTest::GetInstance()->original_working_dir();
7302   // We can safely call chdir() as it's a direct system call.
7303   if (chdir(original_dir) != 0) {
7304     DeathTestAbort(std::string("chdir(\"") + original_dir +
7305                    "\") failed: " + GetLastErrnoDescription());
7306     return EXIT_FAILURE;
7307   }
7308 
7309   // We can safely call execve() as it's a direct system call.  We
7310   // cannot use execvp() as it's a libc function and thus potentially
7311   // unsafe.  Since execve() doesn't search the PATH, the user must
7312   // invoke the test program via a valid path that contains at least
7313   // one path separator.
7314   execve(args->argv[0], args->argv, GetEnviron());
7315   DeathTestAbort(std::string("execve(") + args->argv[0] + ", ...) in " +
7316                  original_dir + " failed: " + GetLastErrnoDescription());
7317   return EXIT_FAILURE;
7318 }
7319 #    endif  // !GTEST_OS_QNX
7320 
7321 // Two utility routines that together determine the direction the stack
7322 // grows.
7323 // This could be accomplished more elegantly by a single recursive
7324 // function, but we want to guard against the unlikely possibility of
7325 // a smart compiler optimizing the recursion away.
7326 //
7327 // GTEST_NO_INLINE_ is required to prevent GCC 4.6 from inlining
7328 // StackLowerThanAddress into StackGrowsDown, which then doesn't give
7329 // correct answer.
7330 void StackLowerThanAddress(const void* ptr, bool* result) GTEST_NO_INLINE_;
StackLowerThanAddress(const void * ptr,bool * result)7331 void StackLowerThanAddress(const void* ptr, bool* result) {
7332   int dummy;
7333   *result = (&dummy < ptr);
7334 }
7335 
StackGrowsDown()7336 bool StackGrowsDown() {
7337   int dummy;
7338   bool result;
7339   StackLowerThanAddress(&dummy, &result);
7340   return result;
7341 }
7342 
7343 // Spawns a child process with the same executable as the current process in
7344 // a thread-safe manner and instructs it to run the death test.  The
7345 // implementation uses fork(2) + exec.  On systems where clone(2) is
7346 // available, it is used instead, being slightly more thread-safe.  On QNX,
7347 // fork supports only single-threaded environments, so this function uses
7348 // spawn(2) there instead.  The function dies with an error message if
7349 // anything goes wrong.
ExecDeathTestSpawnChild(char * const * argv,int close_fd)7350 static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) {
7351   ExecDeathTestArgs args = {argv, close_fd};
7352   pid_t child_pid = -1;
7353 
7354 #    if GTEST_OS_QNX
7355   // Obtains the current directory and sets it to be closed in the child
7356   // process.
7357   const int cwd_fd = open(".", O_RDONLY);
7358   GTEST_DEATH_TEST_CHECK_(cwd_fd != -1);
7359   GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(cwd_fd, F_SETFD, FD_CLOEXEC));
7360   // We need to execute the test program in the same environment where
7361   // it was originally invoked.  Therefore we change to the original
7362   // working directory first.
7363   const char* const original_dir =
7364       UnitTest::GetInstance()->original_working_dir();
7365   // We can safely call chdir() as it's a direct system call.
7366   if (chdir(original_dir) != 0) {
7367     DeathTestAbort(std::string("chdir(\"") + original_dir +
7368                    "\") failed: " + GetLastErrnoDescription());
7369     return EXIT_FAILURE;
7370   }
7371 
7372   int fd_flags;
7373   // Set close_fd to be closed after spawn.
7374   GTEST_DEATH_TEST_CHECK_SYSCALL_(fd_flags = fcntl(close_fd, F_GETFD));
7375   GTEST_DEATH_TEST_CHECK_SYSCALL_(
7376       fcntl(close_fd, F_SETFD, fd_flags | FD_CLOEXEC));
7377   struct inheritance inherit = {0};
7378   // spawn is a system call.
7379   child_pid = spawn(args.argv[0], 0, NULL, &inherit, args.argv, GetEnviron());
7380   // Restores the current working directory.
7381   GTEST_DEATH_TEST_CHECK_(fchdir(cwd_fd) != -1);
7382   GTEST_DEATH_TEST_CHECK_SYSCALL_(close(cwd_fd));
7383 
7384 #    else  // GTEST_OS_QNX
7385 #      if GTEST_OS_LINUX
7386   // When a SIGPROF signal is received while fork() or clone() are executing,
7387   // the process may hang. To avoid this, we ignore SIGPROF here and re-enable
7388   // it after the call to fork()/clone() is complete.
7389   struct sigaction saved_sigprof_action;
7390   struct sigaction ignore_sigprof_action;
7391   memset(&ignore_sigprof_action, 0, sizeof(ignore_sigprof_action));
7392   sigemptyset(&ignore_sigprof_action.sa_mask);
7393   ignore_sigprof_action.sa_handler = SIG_IGN;
7394   GTEST_DEATH_TEST_CHECK_SYSCALL_(
7395       sigaction(SIGPROF, &ignore_sigprof_action, &saved_sigprof_action));
7396 #      endif  // GTEST_OS_LINUX
7397 
7398 #      if GTEST_HAS_CLONE
7399   const bool use_fork = GTEST_FLAG(death_test_use_fork);
7400 
7401   if (!use_fork) {
7402     static const bool stack_grows_down = StackGrowsDown();
7403     const size_t stack_size = getpagesize();
7404     // MMAP_ANONYMOUS is not defined on Mac, so we use MAP_ANON instead.
7405     void* const stack = mmap(NULL, stack_size, PROT_READ | PROT_WRITE,
7406                              MAP_ANON | MAP_PRIVATE, -1, 0);
7407     GTEST_DEATH_TEST_CHECK_(stack != MAP_FAILED);
7408 
7409     // Maximum stack alignment in bytes:  For a downward-growing stack, this
7410     // amount is subtracted from size of the stack space to get an address
7411     // that is within the stack space and is aligned on all systems we care
7412     // about.  As far as I know there is no ABI with stack alignment greater
7413     // than 64.  We assume stack and stack_size already have alignment of
7414     // kMaxStackAlignment.
7415     const size_t kMaxStackAlignment = 64;
7416     void* const stack_top =
7417         static_cast<char*>(stack) +
7418         (stack_grows_down ? stack_size - kMaxStackAlignment : 0);
7419     GTEST_DEATH_TEST_CHECK_(
7420         stack_size > kMaxStackAlignment &&
7421         reinterpret_cast<intptr_t>(stack_top) % kMaxStackAlignment == 0);
7422 
7423     child_pid = clone(&ExecDeathTestChildMain, stack_top, SIGCHLD, &args);
7424 
7425     GTEST_DEATH_TEST_CHECK_(munmap(stack, stack_size) != -1);
7426   }
7427 #      else
7428   const bool use_fork = true;
7429 #      endif  // GTEST_HAS_CLONE
7430 
7431   if (use_fork && (child_pid = fork()) == 0) {
7432     ExecDeathTestChildMain(&args);
7433     _exit(0);
7434   }
7435 #    endif    // GTEST_OS_QNX
7436 #    if GTEST_OS_LINUX
7437   GTEST_DEATH_TEST_CHECK_SYSCALL_(
7438       sigaction(SIGPROF, &saved_sigprof_action, NULL));
7439 #    endif  // GTEST_OS_LINUX
7440 
7441   GTEST_DEATH_TEST_CHECK_(child_pid != -1);
7442   return child_pid;
7443 }
7444 
7445 // The AssumeRole process for a fork-and-exec death test.  It re-executes the
7446 // main program from the beginning, setting the --gtest_filter
7447 // and --gtest_internal_run_death_test flags to cause only the current
7448 // death test to be re-run.
AssumeRole()7449 DeathTest::TestRole ExecDeathTest::AssumeRole() {
7450   const UnitTestImpl* const impl = GetUnitTestImpl();
7451   const InternalRunDeathTestFlag* const flag =
7452       impl->internal_run_death_test_flag();
7453   const TestInfo* const info = impl->current_test_info();
7454   const int death_test_index = info->result()->death_test_count();
7455 
7456   if (flag != NULL) {
7457     set_write_fd(flag->write_fd());
7458     return EXECUTE_TEST;
7459   }
7460 
7461   int pipe_fd[2];
7462   GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
7463   // Clear the close-on-exec flag on the write end of the pipe, lest
7464   // it be closed when the child process does an exec:
7465   GTEST_DEATH_TEST_CHECK_(fcntl(pipe_fd[1], F_SETFD, 0) != -1);
7466 
7467   const std::string filter_flag = std::string("--") + GTEST_FLAG_PREFIX_ +
7468                                   kFilterFlag + "=" + info->test_case_name() +
7469                                   "." + info->name();
7470   const std::string internal_flag = std::string("--") + GTEST_FLAG_PREFIX_ +
7471                                     kInternalRunDeathTestFlag + "=" + file_ +
7472                                     "|" + StreamableToString(line_) + "|" +
7473                                     StreamableToString(death_test_index) + "|" +
7474                                     StreamableToString(pipe_fd[1]);
7475   Arguments args;
7476   args.AddArguments(GetArgvsForDeathTestChildProcess());
7477   args.AddArgument(filter_flag.c_str());
7478   args.AddArgument(internal_flag.c_str());
7479 
7480   DeathTest::set_last_death_test_message("");
7481 
7482   CaptureStderr();
7483   // See the comment in NoExecDeathTest::AssumeRole for why the next line
7484   // is necessary.
7485   FlushInfoLog();
7486 
7487   const pid_t child_pid = ExecDeathTestSpawnChild(args.Argv(), pipe_fd[0]);
7488   GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
7489   set_child_pid(child_pid);
7490   set_read_fd(pipe_fd[0]);
7491   set_spawned(true);
7492   return OVERSEE_TEST;
7493 }
7494 
7495 #  endif  // !GTEST_OS_WINDOWS
7496 
7497 // Creates a concrete DeathTest-derived class that depends on the
7498 // --gtest_death_test_style flag, and sets the pointer pointed to
7499 // by the "test" argument to its address.  If the test should be
7500 // skipped, sets that pointer to NULL.  Returns true, unless the
7501 // flag is set to an invalid value.
Create(const char * statement,const RE * regex,const char * file,int line,DeathTest ** test)7502 bool DefaultDeathTestFactory::Create(const char* statement, const RE* regex,
7503                                      const char* file, int line,
7504                                      DeathTest** test) {
7505   UnitTestImpl* const impl = GetUnitTestImpl();
7506   const InternalRunDeathTestFlag* const flag =
7507       impl->internal_run_death_test_flag();
7508   const int death_test_index =
7509       impl->current_test_info()->increment_death_test_count();
7510 
7511   if (flag != NULL) {
7512     if (death_test_index > flag->index()) {
7513       DeathTest::set_last_death_test_message(
7514           "Death test count (" + StreamableToString(death_test_index) +
7515           ") somehow exceeded expected maximum (" +
7516           StreamableToString(flag->index()) + ")");
7517       return false;
7518     }
7519 
7520     if (!(flag->file() == file && flag->line() == line &&
7521           flag->index() == death_test_index)) {
7522       *test = NULL;
7523       return true;
7524     }
7525   }
7526 
7527 #  if GTEST_OS_WINDOWS
7528 
7529   if (GTEST_FLAG(death_test_style) == "threadsafe" ||
7530       GTEST_FLAG(death_test_style) == "fast") {
7531     *test = new WindowsDeathTest(statement, regex, file, line);
7532   }
7533 
7534 #  else
7535 
7536   if (GTEST_FLAG(death_test_style) == "threadsafe") {
7537     *test = new ExecDeathTest(statement, regex, file, line);
7538   } else if (GTEST_FLAG(death_test_style) == "fast") {
7539     *test = new NoExecDeathTest(statement, regex);
7540   }
7541 
7542 #  endif  // GTEST_OS_WINDOWS
7543 
7544   else {  // NOLINT - this is more readable than unbalanced brackets inside #if.
7545     DeathTest::set_last_death_test_message("Unknown death test style \"" +
7546                                            GTEST_FLAG(death_test_style) +
7547                                            "\" encountered");
7548     return false;
7549   }
7550 
7551   return true;
7552 }
7553 
7554 // Splits a given string on a given delimiter, populating a given
7555 // vector with the fields.  GTEST_HAS_DEATH_TEST implies that we have
7556 // ::std::string, so we can use it here.
SplitString(const::std::string & str,char delimiter,::std::vector<::std::string> * dest)7557 static void SplitString(const ::std::string& str, char delimiter,
7558                         ::std::vector< ::std::string>* dest) {
7559   ::std::vector< ::std::string> parsed;
7560   ::std::string::size_type pos = 0;
7561   while (::testing::internal::AlwaysTrue()) {
7562     const ::std::string::size_type colon = str.find(delimiter, pos);
7563     if (colon == ::std::string::npos) {
7564       parsed.push_back(str.substr(pos));
7565       break;
7566     } else {
7567       parsed.push_back(str.substr(pos, colon - pos));
7568       pos = colon + 1;
7569     }
7570   }
7571   dest->swap(parsed);
7572 }
7573 
7574 #  if GTEST_OS_WINDOWS
7575 // Recreates the pipe and event handles from the provided parameters,
7576 // signals the event, and returns a file descriptor wrapped around the pipe
7577 // handle. This function is called in the child process only.
GetStatusFileDescriptor(unsigned int parent_process_id,size_t write_handle_as_size_t,size_t event_handle_as_size_t)7578 int GetStatusFileDescriptor(unsigned int parent_process_id,
7579                             size_t write_handle_as_size_t,
7580                             size_t event_handle_as_size_t) {
7581   AutoHandle parent_process_handle(::OpenProcess(PROCESS_DUP_HANDLE,
7582                                                  FALSE,  // Non-inheritable.
7583                                                  parent_process_id));
7584   if (parent_process_handle.Get() == INVALID_HANDLE_VALUE) {
7585     DeathTestAbort("Unable to open parent process " +
7586                    StreamableToString(parent_process_id));
7587   }
7588 
7589   // TODO(vladl@google.com): Replace the following check with a
7590   // compile-time assertion when available.
7591   GTEST_CHECK_(sizeof(HANDLE) <= sizeof(size_t));
7592 
7593   const HANDLE write_handle = reinterpret_cast<HANDLE>(write_handle_as_size_t);
7594   HANDLE dup_write_handle;
7595 
7596   // The newly initialized handle is accessible only in in the parent
7597   // process. To obtain one accessible within the child, we need to use
7598   // DuplicateHandle.
7599   if (!::DuplicateHandle(parent_process_handle.Get(), write_handle,
7600                          ::GetCurrentProcess(), &dup_write_handle,
7601                          0x0,    // Requested privileges ignored since
7602                                  // DUPLICATE_SAME_ACCESS is used.
7603                          FALSE,  // Request non-inheritable handler.
7604                          DUPLICATE_SAME_ACCESS)) {
7605     DeathTestAbort("Unable to duplicate the pipe handle " +
7606                    StreamableToString(write_handle_as_size_t) +
7607                    " from the parent process " +
7608                    StreamableToString(parent_process_id));
7609   }
7610 
7611   const HANDLE event_handle = reinterpret_cast<HANDLE>(event_handle_as_size_t);
7612   HANDLE dup_event_handle;
7613 
7614   if (!::DuplicateHandle(parent_process_handle.Get(), event_handle,
7615                          ::GetCurrentProcess(), &dup_event_handle, 0x0, FALSE,
7616                          DUPLICATE_SAME_ACCESS)) {
7617     DeathTestAbort("Unable to duplicate the event handle " +
7618                    StreamableToString(event_handle_as_size_t) +
7619                    " from the parent process " +
7620                    StreamableToString(parent_process_id));
7621   }
7622 
7623   const int write_fd =
7624       ::_open_osfhandle(reinterpret_cast<intptr_t>(dup_write_handle), O_APPEND);
7625   if (write_fd == -1) {
7626     DeathTestAbort("Unable to convert pipe handle " +
7627                    StreamableToString(write_handle_as_size_t) +
7628                    " to a file descriptor");
7629   }
7630 
7631   // Signals the parent that the write end of the pipe has been acquired
7632   // so the parent can release its own write end.
7633   ::SetEvent(dup_event_handle);
7634 
7635   return write_fd;
7636 }
7637 #  endif  // GTEST_OS_WINDOWS
7638 
7639 // Returns a newly created InternalRunDeathTestFlag object with fields
7640 // initialized from the GTEST_FLAG(internal_run_death_test) flag if
7641 // the flag is specified; otherwise returns NULL.
ParseInternalRunDeathTestFlag()7642 InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() {
7643   if (GTEST_FLAG(internal_run_death_test) == "") return NULL;
7644 
7645   // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we
7646   // can use it here.
7647   int line = -1;
7648   int index = -1;
7649   ::std::vector< ::std::string> fields;
7650   SplitString(GTEST_FLAG(internal_run_death_test).c_str(), '|', &fields);
7651   int write_fd = -1;
7652 
7653 #  if GTEST_OS_WINDOWS
7654 
7655   unsigned int parent_process_id = 0;
7656   size_t write_handle_as_size_t = 0;
7657   size_t event_handle_as_size_t = 0;
7658 
7659   if (fields.size() != 6 || !ParseNaturalNumber(fields[1], &line) ||
7660       !ParseNaturalNumber(fields[2], &index) ||
7661       !ParseNaturalNumber(fields[3], &parent_process_id) ||
7662       !ParseNaturalNumber(fields[4], &write_handle_as_size_t) ||
7663       !ParseNaturalNumber(fields[5], &event_handle_as_size_t)) {
7664     DeathTestAbort("Bad --gtest_internal_run_death_test flag: " +
7665                    GTEST_FLAG(internal_run_death_test));
7666   }
7667   write_fd = GetStatusFileDescriptor(parent_process_id, write_handle_as_size_t,
7668                                      event_handle_as_size_t);
7669 #  else
7670 
7671   if (fields.size() != 4 || !ParseNaturalNumber(fields[1], &line) ||
7672       !ParseNaturalNumber(fields[2], &index) ||
7673       !ParseNaturalNumber(fields[3], &write_fd)) {
7674     DeathTestAbort("Bad --gtest_internal_run_death_test flag: " +
7675                    GTEST_FLAG(internal_run_death_test));
7676   }
7677 
7678 #  endif  // GTEST_OS_WINDOWS
7679 
7680   return new InternalRunDeathTestFlag(fields[0], line, index, write_fd);
7681 }
7682 
7683 }  // namespace internal
7684 
7685 #endif  // GTEST_HAS_DEATH_TEST
7686 
7687 }  // namespace testing
7688 // Copyright 2008, Google Inc.
7689 // All rights reserved.
7690 //
7691 // Redistribution and use in source and binary forms, with or without
7692 // modification, are permitted provided that the following conditions are
7693 // met:
7694 //
7695 //     * Redistributions of source code must retain the above copyright
7696 // notice, this list of conditions and the following disclaimer.
7697 //     * Redistributions in binary form must reproduce the above
7698 // copyright notice, this list of conditions and the following disclaimer
7699 // in the documentation and/or other materials provided with the
7700 // distribution.
7701 //     * Neither the name of Google Inc. nor the names of its
7702 // contributors may be used to endorse or promote products derived from
7703 // this software without specific prior written permission.
7704 //
7705 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
7706 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
7707 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
7708 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
7709 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
7710 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
7711 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
7712 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
7713 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
7714 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
7715 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
7716 //
7717 // Authors: keith.ray@gmail.com (Keith Ray)
7718 
7719 #include <stdlib.h>
7720 
7721 #if GTEST_OS_WINDOWS_MOBILE
7722 #  include <windows.h>
7723 #elif GTEST_OS_WINDOWS
7724 #  include <direct.h>
7725 #  include <io.h>
7726 #elif GTEST_OS_SYMBIAN
7727 // Symbian OpenC has PATH_MAX in sys/syslimits.h
7728 #  include <sys/syslimits.h>
7729 #else
7730 #  include <limits.h>
7731 #  include <climits>  // Some Linux distributions define PATH_MAX here.
7732 #endif                // GTEST_OS_WINDOWS_MOBILE
7733 
7734 #if GTEST_OS_WINDOWS
7735 #  define GTEST_PATH_MAX_ _MAX_PATH
7736 #elif defined(PATH_MAX)
7737 #  define GTEST_PATH_MAX_ PATH_MAX
7738 #elif defined(_XOPEN_PATH_MAX)
7739 #  define GTEST_PATH_MAX_ _XOPEN_PATH_MAX
7740 #else
7741 #  define GTEST_PATH_MAX_ _POSIX_PATH_MAX
7742 #endif  // GTEST_OS_WINDOWS
7743 
7744 namespace testing {
7745 namespace internal {
7746 
7747 #if GTEST_OS_WINDOWS
7748 // On Windows, '\\' is the standard path separator, but many tools and the
7749 // Windows API also accept '/' as an alternate path separator. Unless otherwise
7750 // noted, a file path can contain either kind of path separators, or a mixture
7751 // of them.
7752 const char kPathSeparator = '\\';
7753 const char kAlternatePathSeparator = '/';
7754 const char kPathSeparatorString[] = "\\";
7755 const char kAlternatePathSeparatorString[] = "/";
7756 #  if GTEST_OS_WINDOWS_MOBILE
7757 // Windows CE doesn't have a current directory. You should not use
7758 // the current directory in tests on Windows CE, but this at least
7759 // provides a reasonable fallback.
7760 const char kCurrentDirectoryString[] = "\\";
7761 // Windows CE doesn't define INVALID_FILE_ATTRIBUTES
7762 const DWORD kInvalidFileAttributes = 0xffffffff;
7763 #  else
7764 const char kCurrentDirectoryString[] = ".\\";
7765 #  endif  // GTEST_OS_WINDOWS_MOBILE
7766 #else
7767 const char kPathSeparator = '/';
7768 const char kPathSeparatorString[] = "/";
7769 const char kCurrentDirectoryString[] = "./";
7770 #endif  // GTEST_OS_WINDOWS
7771 
7772 // Returns whether the given character is a valid path separator.
IsPathSeparator(char c)7773 static bool IsPathSeparator(char c) {
7774 #if GTEST_HAS_ALT_PATH_SEP_
7775   return (c == kPathSeparator) || (c == kAlternatePathSeparator);
7776 #else
7777   return c == kPathSeparator;
7778 #endif
7779 }
7780 
7781 // Returns the current working directory, or "" if unsuccessful.
GetCurrentDir()7782 FilePath FilePath::GetCurrentDir() {
7783 #if GTEST_OS_WINDOWS_MOBILE
7784   // Windows CE doesn't have a current directory, so we just return
7785   // something reasonable.
7786   return FilePath(kCurrentDirectoryString);
7787 #elif GTEST_OS_WINDOWS
7788   char cwd[GTEST_PATH_MAX_ + 1] = {'\0'};
7789   return FilePath(_getcwd(cwd, sizeof(cwd)) == NULL ? "" : cwd);
7790 #else
7791   char cwd[GTEST_PATH_MAX_ + 1] = {'\0'};
7792   return FilePath(getcwd(cwd, sizeof(cwd)) == NULL ? "" : cwd);
7793 #endif  // GTEST_OS_WINDOWS_MOBILE
7794 }
7795 
7796 // Returns a copy of the FilePath with the case-insensitive extension removed.
7797 // Example: FilePath("dir/file.exe").RemoveExtension("EXE") returns
7798 // FilePath("dir/file"). If a case-insensitive extension is not
7799 // found, returns a copy of the original FilePath.
RemoveExtension(const char * extension) const7800 FilePath FilePath::RemoveExtension(const char* extension) const {
7801   const std::string dot_extension = std::string(".") + extension;
7802   if (String::EndsWithCaseInsensitive(pathname_, dot_extension)) {
7803     return FilePath(
7804         pathname_.substr(0, pathname_.length() - dot_extension.length()));
7805   }
7806   return *this;
7807 }
7808 
7809 // Returns a pointer to the last occurence of a valid path separator in
7810 // the FilePath. On Windows, for example, both '/' and '\' are valid path
7811 // separators. Returns NULL if no path separator was found.
FindLastPathSeparator() const7812 const char* FilePath::FindLastPathSeparator() const {
7813   const char* const last_sep = strrchr(c_str(), kPathSeparator);
7814 #if GTEST_HAS_ALT_PATH_SEP_
7815   const char* const last_alt_sep = strrchr(c_str(), kAlternatePathSeparator);
7816   // Comparing two pointers of which only one is NULL is undefined.
7817   if (last_alt_sep != NULL && (last_sep == NULL || last_alt_sep > last_sep)) {
7818     return last_alt_sep;
7819   }
7820 #endif
7821   return last_sep;
7822 }
7823 
7824 // Returns a copy of the FilePath with the directory part removed.
7825 // Example: FilePath("path/to/file").RemoveDirectoryName() returns
7826 // FilePath("file"). If there is no directory part ("just_a_file"), it returns
7827 // the FilePath unmodified. If there is no file part ("just_a_dir/") it
7828 // returns an empty FilePath ("").
7829 // On Windows platform, '\' is the path separator, otherwise it is '/'.
RemoveDirectoryName() const7830 FilePath FilePath::RemoveDirectoryName() const {
7831   const char* const last_sep = FindLastPathSeparator();
7832   return last_sep ? FilePath(last_sep + 1) : *this;
7833 }
7834 
7835 // RemoveFileName returns the directory path with the filename removed.
7836 // Example: FilePath("path/to/file").RemoveFileName() returns "path/to/".
7837 // If the FilePath is "a_file" or "/a_file", RemoveFileName returns
7838 // FilePath("./") or, on Windows, FilePath(".\\"). If the filepath does
7839 // not have a file, like "just/a/dir/", it returns the FilePath unmodified.
7840 // On Windows platform, '\' is the path separator, otherwise it is '/'.
RemoveFileName() const7841 FilePath FilePath::RemoveFileName() const {
7842   const char* const last_sep = FindLastPathSeparator();
7843   std::string dir;
7844   if (last_sep) {
7845     dir = std::string(c_str(), last_sep + 1 - c_str());
7846   } else {
7847     dir = kCurrentDirectoryString;
7848   }
7849   return FilePath(dir);
7850 }
7851 
7852 // Helper functions for naming files in a directory for xml output.
7853 
7854 // Given directory = "dir", base_name = "test", number = 0,
7855 // extension = "xml", returns "dir/test.xml". If number is greater
7856 // than zero (e.g., 12), returns "dir/test_12.xml".
7857 // On Windows platform, uses \ as the separator rather than /.
MakeFileName(const FilePath & directory,const FilePath & base_name,int number,const char * extension)7858 FilePath FilePath::MakeFileName(const FilePath& directory,
7859                                 const FilePath& base_name, int number,
7860                                 const char* extension) {
7861   std::string file;
7862   if (number == 0) {
7863     file = base_name.string() + "." + extension;
7864   } else {
7865     file =
7866         base_name.string() + "_" + StreamableToString(number) + "." + extension;
7867   }
7868   return ConcatPaths(directory, FilePath(file));
7869 }
7870 
7871 // Given directory = "dir", relative_path = "test.xml", returns "dir/test.xml".
7872 // On Windows, uses \ as the separator rather than /.
ConcatPaths(const FilePath & directory,const FilePath & relative_path)7873 FilePath FilePath::ConcatPaths(const FilePath& directory,
7874                                const FilePath& relative_path) {
7875   if (directory.IsEmpty()) return relative_path;
7876   const FilePath dir(directory.RemoveTrailingPathSeparator());
7877   return FilePath(dir.string() + kPathSeparator + relative_path.string());
7878 }
7879 
7880 // Returns true if pathname describes something findable in the file-system,
7881 // either a file, directory, or whatever.
FileOrDirectoryExists() const7882 bool FilePath::FileOrDirectoryExists() const {
7883 #if GTEST_OS_WINDOWS_MOBILE
7884   LPCWSTR unicode = String::AnsiToUtf16(pathname_.c_str());
7885   const DWORD attributes = GetFileAttributes(unicode);
7886   delete[] unicode;
7887   return attributes != kInvalidFileAttributes;
7888 #else
7889   posix::StatStruct file_stat;
7890   return posix::Stat(pathname_.c_str(), &file_stat) == 0;
7891 #endif  // GTEST_OS_WINDOWS_MOBILE
7892 }
7893 
7894 // Returns true if pathname describes a directory in the file-system
7895 // that exists.
DirectoryExists() const7896 bool FilePath::DirectoryExists() const {
7897   bool result = false;
7898 #if GTEST_OS_WINDOWS
7899   // Don't strip off trailing separator if path is a root directory on
7900   // Windows (like "C:\\").
7901   const FilePath& path(IsRootDirectory() ? *this
7902                                          : RemoveTrailingPathSeparator());
7903 #else
7904   const FilePath& path(*this);
7905 #endif
7906 
7907 #if GTEST_OS_WINDOWS_MOBILE
7908   LPCWSTR unicode = String::AnsiToUtf16(path.c_str());
7909   const DWORD attributes = GetFileAttributes(unicode);
7910   delete[] unicode;
7911   if ((attributes != kInvalidFileAttributes) &&
7912       (attributes & FILE_ATTRIBUTE_DIRECTORY)) {
7913     result = true;
7914   }
7915 #else
7916   posix::StatStruct file_stat;
7917   result =
7918       posix::Stat(path.c_str(), &file_stat) == 0 && posix::IsDir(file_stat);
7919 #endif  // GTEST_OS_WINDOWS_MOBILE
7920 
7921   return result;
7922 }
7923 
7924 // Returns true if pathname describes a root directory. (Windows has one
7925 // root directory per disk drive.)
IsRootDirectory() const7926 bool FilePath::IsRootDirectory() const {
7927 #if GTEST_OS_WINDOWS
7928   // TODO(wan@google.com): on Windows a network share like
7929   // \\server\share can be a root directory, although it cannot be the
7930   // current directory.  Handle this properly.
7931   return pathname_.length() == 3 && IsAbsolutePath();
7932 #else
7933   return pathname_.length() == 1 && IsPathSeparator(pathname_.c_str()[0]);
7934 #endif
7935 }
7936 
7937 // Returns true if pathname describes an absolute path.
IsAbsolutePath() const7938 bool FilePath::IsAbsolutePath() const {
7939   const char* const name = pathname_.c_str();
7940 #if GTEST_OS_WINDOWS
7941   return pathname_.length() >= 3 &&
7942          ((name[0] >= 'a' && name[0] <= 'z') ||
7943           (name[0] >= 'A' && name[0] <= 'Z')) &&
7944          name[1] == ':' && IsPathSeparator(name[2]);
7945 #else
7946   return IsPathSeparator(name[0]);
7947 #endif
7948 }
7949 
7950 // Returns a pathname for a file that does not currently exist. The pathname
7951 // will be directory/base_name.extension or
7952 // directory/base_name_<number>.extension if directory/base_name.extension
7953 // already exists. The number will be incremented until a pathname is found
7954 // that does not already exist.
7955 // Examples: 'dir/foo_test.xml' or 'dir/foo_test_1.xml'.
7956 // There could be a race condition if two or more processes are calling this
7957 // function at the same time -- they could both pick the same filename.
GenerateUniqueFileName(const FilePath & directory,const FilePath & base_name,const char * extension)7958 FilePath FilePath::GenerateUniqueFileName(const FilePath& directory,
7959                                           const FilePath& base_name,
7960                                           const char* extension) {
7961   FilePath full_pathname;
7962   int number = 0;
7963   do {
7964     full_pathname.Set(MakeFileName(directory, base_name, number++, extension));
7965   } while (full_pathname.FileOrDirectoryExists());
7966   return full_pathname;
7967 }
7968 
7969 // Returns true if FilePath ends with a path separator, which indicates that
7970 // it is intended to represent a directory. Returns false otherwise.
7971 // This does NOT check that a directory (or file) actually exists.
IsDirectory() const7972 bool FilePath::IsDirectory() const {
7973   return !pathname_.empty() &&
7974          IsPathSeparator(pathname_.c_str()[pathname_.length() - 1]);
7975 }
7976 
7977 // Create directories so that path exists. Returns true if successful or if
7978 // the directories already exist; returns false if unable to create directories
7979 // for any reason.
CreateDirectoriesRecursively() const7980 bool FilePath::CreateDirectoriesRecursively() const {
7981   if (!this->IsDirectory()) {
7982     return false;
7983   }
7984 
7985   if (pathname_.length() == 0 || this->DirectoryExists()) {
7986     return true;
7987   }
7988 
7989   const FilePath parent(this->RemoveTrailingPathSeparator().RemoveFileName());
7990   return parent.CreateDirectoriesRecursively() && this->CreateFolder();
7991 }
7992 
7993 // Create the directory so that path exists. Returns true if successful or
7994 // if the directory already exists; returns false if unable to create the
7995 // directory for any reason, including if the parent directory does not
7996 // exist. Not named "CreateDirectory" because that's a macro on Windows.
CreateFolder() const7997 bool FilePath::CreateFolder() const {
7998 #if GTEST_OS_WINDOWS_MOBILE
7999   FilePath removed_sep(this->RemoveTrailingPathSeparator());
8000   LPCWSTR unicode = String::AnsiToUtf16(removed_sep.c_str());
8001   int result = CreateDirectory(unicode, NULL) ? 0 : -1;
8002   delete[] unicode;
8003 #elif GTEST_OS_WINDOWS
8004   int result = _mkdir(pathname_.c_str());
8005 #else
8006   int result = mkdir(pathname_.c_str(), 0777);
8007 #endif  // GTEST_OS_WINDOWS_MOBILE
8008 
8009   if (result == -1) {
8010     return this->DirectoryExists();  // An error is OK if the directory exists.
8011   }
8012   return true;  // No error.
8013 }
8014 
8015 // If input name has a trailing separator character, remove it and return the
8016 // name, otherwise return the name string unmodified.
8017 // On Windows platform, uses \ as the separator, other platforms use /.
RemoveTrailingPathSeparator() const8018 FilePath FilePath::RemoveTrailingPathSeparator() const {
8019   return IsDirectory() ? FilePath(pathname_.substr(0, pathname_.length() - 1))
8020                        : *this;
8021 }
8022 
8023 // Removes any redundant separators that might be in the pathname.
8024 // For example, "bar///foo" becomes "bar/foo". Does not eliminate other
8025 // redundancies that might be in a pathname involving "." or "..".
8026 // TODO(wan@google.com): handle Windows network shares (e.g. \\server\share).
Normalize()8027 void FilePath::Normalize() {
8028   if (pathname_.c_str() == NULL) {
8029     pathname_ = "";
8030     return;
8031   }
8032   const char* src = pathname_.c_str();
8033   char* const dest = new char[pathname_.length() + 1];
8034   char* dest_ptr = dest;
8035   memset(dest_ptr, 0, pathname_.length() + 1);
8036 
8037   while (*src != '\0') {
8038     *dest_ptr = *src;
8039     if (!IsPathSeparator(*src)) {
8040       src++;
8041     } else {
8042 #if GTEST_HAS_ALT_PATH_SEP_
8043       if (*dest_ptr == kAlternatePathSeparator) {
8044         *dest_ptr = kPathSeparator;
8045       }
8046 #endif
8047       while (IsPathSeparator(*src)) src++;
8048     }
8049     dest_ptr++;
8050   }
8051   *dest_ptr = '\0';
8052   pathname_ = dest;
8053   delete[] dest;
8054 }
8055 
8056 }  // namespace internal
8057 }  // namespace testing
8058 // Copyright 2008, Google Inc.
8059 // All rights reserved.
8060 //
8061 // Redistribution and use in source and binary forms, with or without
8062 // modification, are permitted provided that the following conditions are
8063 // met:
8064 //
8065 //     * Redistributions of source code must retain the above copyright
8066 // notice, this list of conditions and the following disclaimer.
8067 //     * Redistributions in binary form must reproduce the above
8068 // copyright notice, this list of conditions and the following disclaimer
8069 // in the documentation and/or other materials provided with the
8070 // distribution.
8071 //     * Neither the name of Google Inc. nor the names of its
8072 // contributors may be used to endorse or promote products derived from
8073 // this software without specific prior written permission.
8074 //
8075 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
8076 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
8077 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
8078 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
8079 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
8080 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
8081 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
8082 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
8083 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
8084 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
8085 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
8086 //
8087 // Author: wan@google.com (Zhanyong Wan)
8088 
8089 #include <limits.h>
8090 #include <stdio.h>
8091 #include <stdlib.h>
8092 #include <string.h>
8093 
8094 #if GTEST_OS_WINDOWS_MOBILE
8095 #  include <windows.h>  // For TerminateProcess()
8096 #elif GTEST_OS_WINDOWS
8097 #  include <io.h>
8098 #  include <sys/stat.h>
8099 #else
8100 #  include <unistd.h>
8101 #endif  // GTEST_OS_WINDOWS_MOBILE
8102 
8103 #if GTEST_OS_MAC
8104 #  include <mach/mach_init.h>
8105 #  include <mach/task.h>
8106 #  include <mach/vm_map.h>
8107 #endif  // GTEST_OS_MAC
8108 
8109 #if GTEST_OS_QNX
8110 #  include <devctl.h>
8111 #  include <sys/procfs.h>
8112 #endif  // GTEST_OS_QNX
8113 
8114 // Indicates that this translation unit is part of Google Test's
8115 // implementation.  It must come before gtest-internal-inl.h is
8116 // included, or there will be a compiler error.  This trick is to
8117 // prevent a user from accidentally including gtest-internal-inl.h in
8118 // his code.
8119 #define GTEST_IMPLEMENTATION_ 1
8120 #undef GTEST_IMPLEMENTATION_
8121 
8122 namespace testing {
8123 namespace internal {
8124 
8125 #if defined(_MSC_VER) || defined(__BORLANDC__)
8126 // MSVC and C++Builder do not provide a definition of STDERR_FILENO.
8127 const int kStdOutFileno = 1;
8128 const int kStdErrFileno = 2;
8129 #else
8130 const int kStdOutFileno = STDOUT_FILENO;
8131 const int kStdErrFileno = STDERR_FILENO;
8132 #endif  // _MSC_VER
8133 
8134 #if GTEST_OS_MAC
8135 
8136 // Returns the number of threads running in the process, or 0 to indicate that
8137 // we cannot detect it.
GetThreadCount()8138 size_t GetThreadCount() {
8139   const task_t task = mach_task_self();
8140   mach_msg_type_number_t thread_count;
8141   thread_act_array_t thread_list;
8142   const kern_return_t status = task_threads(task, &thread_list, &thread_count);
8143   if (status == KERN_SUCCESS) {
8144     // task_threads allocates resources in thread_list and we need to free them
8145     // to avoid leaks.
8146     vm_deallocate(task, reinterpret_cast<vm_address_t>(thread_list),
8147                   sizeof(thread_t) * thread_count);
8148     return static_cast<size_t>(thread_count);
8149   } else {
8150     return 0;
8151   }
8152 }
8153 
8154 #elif GTEST_OS_QNX
8155 
8156 // Returns the number of threads running in the process, or 0 to indicate that
8157 // we cannot detect it.
GetThreadCount()8158 size_t GetThreadCount() {
8159   const int fd = open("/proc/self/as", O_RDONLY);
8160   if (fd < 0) {
8161     return 0;
8162   }
8163   procfs_info process_info;
8164   const int status =
8165       devctl(fd, DCMD_PROC_INFO, &process_info, sizeof(process_info), NULL);
8166   close(fd);
8167   if (status == EOK) {
8168     return static_cast<size_t>(process_info.num_threads);
8169   } else {
8170     return 0;
8171   }
8172 }
8173 
8174 #else
8175 
GetThreadCount()8176 size_t GetThreadCount() {
8177   // There's no portable way to detect the number of threads, so we just
8178   // return 0 to indicate that we cannot detect it.
8179   return 0;
8180 }
8181 
8182 #endif  // GTEST_OS_MAC
8183 
8184 #if GTEST_USES_POSIX_RE
8185 
8186 // Implements RE.  Currently only needed for death tests.
8187 
~RE()8188 RE::~RE() {
8189   if (is_valid_) {
8190     // regfree'ing an invalid regex might crash because the content
8191     // of the regex is undefined. Since the regex's are essentially
8192     // the same, one cannot be valid (or invalid) without the other
8193     // being so too.
8194     regfree(&partial_regex_);
8195     regfree(&full_regex_);
8196   }
8197   free(const_cast<char*>(pattern_));
8198 }
8199 
8200 // Returns true iff regular expression re matches the entire str.
FullMatch(const char * str,const RE & re)8201 bool RE::FullMatch(const char* str, const RE& re) {
8202   if (!re.is_valid_) return false;
8203 
8204   regmatch_t match;
8205   return regexec(&re.full_regex_, str, 1, &match, 0) == 0;
8206 }
8207 
8208 // Returns true iff regular expression re matches a substring of str
8209 // (including str itself).
PartialMatch(const char * str,const RE & re)8210 bool RE::PartialMatch(const char* str, const RE& re) {
8211   if (!re.is_valid_) return false;
8212 
8213   regmatch_t match;
8214   return regexec(&re.partial_regex_, str, 1, &match, 0) == 0;
8215 }
8216 
8217 // Initializes an RE from its string representation.
Init(const char * regex)8218 void RE::Init(const char* regex) {
8219   pattern_ = posix::StrDup(regex);
8220 
8221   // Reserves enough bytes to hold the regular expression used for a
8222   // full match.
8223   const size_t full_regex_len = strlen(regex) + 10;
8224   char* const full_pattern = new char[full_regex_len];
8225 
8226   snprintf(full_pattern, full_regex_len, "^(%s)$", regex);
8227   is_valid_ = regcomp(&full_regex_, full_pattern, REG_EXTENDED) == 0;
8228   // We want to call regcomp(&partial_regex_, ...) even if the
8229   // previous expression returns false.  Otherwise partial_regex_ may
8230   // not be properly initialized can may cause trouble when it's
8231   // freed.
8232   //
8233   // Some implementation of POSIX regex (e.g. on at least some
8234   // versions of Cygwin) doesn't accept the empty string as a valid
8235   // regex.  We change it to an equivalent form "()" to be safe.
8236   if (is_valid_) {
8237     const char* const partial_regex = (*regex == '\0') ? "()" : regex;
8238     is_valid_ = regcomp(&partial_regex_, partial_regex, REG_EXTENDED) == 0;
8239   }
8240   EXPECT_TRUE(is_valid_)
8241       << "Regular expression \"" << regex
8242       << "\" is not a valid POSIX Extended regular expression.";
8243 
8244   delete[] full_pattern;
8245 }
8246 
8247 #elif GTEST_USES_SIMPLE_RE
8248 
8249 // Returns true iff ch appears anywhere in str (excluding the
8250 // terminating '\0' character).
IsInSet(char ch,const char * str)8251 bool IsInSet(char ch, const char* str) {
8252   return ch != '\0' && strchr(str, ch) != NULL;
8253 }
8254 
8255 // Returns true iff ch belongs to the given classification.  Unlike
8256 // similar functions in <ctype.h>, these aren't affected by the
8257 // current locale.
IsAsciiDigit(char ch)8258 bool IsAsciiDigit(char ch) { return '0' <= ch && ch <= '9'; }
IsAsciiPunct(char ch)8259 bool IsAsciiPunct(char ch) {
8260   return IsInSet(ch, "^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~");
8261 }
IsRepeat(char ch)8262 bool IsRepeat(char ch) { return IsInSet(ch, "?*+"); }
IsAsciiWhiteSpace(char ch)8263 bool IsAsciiWhiteSpace(char ch) { return IsInSet(ch, " \f\n\r\t\v"); }
IsAsciiWordChar(char ch)8264 bool IsAsciiWordChar(char ch) {
8265   return ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') ||
8266          ('0' <= ch && ch <= '9') || ch == '_';
8267 }
8268 
8269 // Returns true iff "\\c" is a supported escape sequence.
IsValidEscape(char c)8270 bool IsValidEscape(char c) {
8271   return (IsAsciiPunct(c) || IsInSet(c, "dDfnrsStvwW"));
8272 }
8273 
8274 // Returns true iff the given atom (specified by escaped and pattern)
8275 // matches ch.  The result is undefined if the atom is invalid.
AtomMatchesChar(bool escaped,char pattern_char,char ch)8276 bool AtomMatchesChar(bool escaped, char pattern_char, char ch) {
8277   if (escaped) {  // "\\p" where p is pattern_char.
8278     switch (pattern_char) {
8279     case 'd':
8280       return IsAsciiDigit(ch);
8281     case 'D':
8282       return !IsAsciiDigit(ch);
8283     case 'f':
8284       return ch == '\f';
8285     case 'n':
8286       return ch == '\n';
8287     case 'r':
8288       return ch == '\r';
8289     case 's':
8290       return IsAsciiWhiteSpace(ch);
8291     case 'S':
8292       return !IsAsciiWhiteSpace(ch);
8293     case 't':
8294       return ch == '\t';
8295     case 'v':
8296       return ch == '\v';
8297     case 'w':
8298       return IsAsciiWordChar(ch);
8299     case 'W':
8300       return !IsAsciiWordChar(ch);
8301     }
8302     return IsAsciiPunct(pattern_char) && pattern_char == ch;
8303   }
8304 
8305   return (pattern_char == '.' && ch != '\n') || pattern_char == ch;
8306 }
8307 
8308 // Helper function used by ValidateRegex() to format error messages.
FormatRegexSyntaxError(const char * regex,int index)8309 std::string FormatRegexSyntaxError(const char* regex, int index) {
8310   return (Message() << "Syntax error at index " << index
8311                     << " in simple regular expression \"" << regex << "\": ")
8312       .GetString();
8313 }
8314 
8315 // Generates non-fatal failures and returns false if regex is invalid;
8316 // otherwise returns true.
ValidateRegex(const char * regex)8317 bool ValidateRegex(const char* regex) {
8318   if (regex == NULL) {
8319     // TODO(wan@google.com): fix the source file location in the
8320     // assertion failures to match where the regex is used in user
8321     // code.
8322     ADD_FAILURE() << "NULL is not a valid simple regular expression.";
8323     return false;
8324   }
8325 
8326   bool is_valid = true;
8327 
8328   // True iff ?, *, or + can follow the previous atom.
8329   bool prev_repeatable = false;
8330   for (int i = 0; regex[i]; i++) {
8331     if (regex[i] == '\\') {  // An escape sequence
8332       i++;
8333       if (regex[i] == '\0') {
8334         ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
8335                       << "'\\' cannot appear at the end.";
8336         return false;
8337       }
8338 
8339       if (!IsValidEscape(regex[i])) {
8340         ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
8341                       << "invalid escape sequence \"\\" << regex[i] << "\".";
8342         is_valid = false;
8343       }
8344       prev_repeatable = true;
8345     } else {  // Not an escape sequence.
8346       const char ch = regex[i];
8347 
8348       if (ch == '^' && i > 0) {
8349         ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
8350                       << "'^' can only appear at the beginning.";
8351         is_valid = false;
8352       } else if (ch == '$' && regex[i + 1] != '\0') {
8353         ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
8354                       << "'$' can only appear at the end.";
8355         is_valid = false;
8356       } else if (IsInSet(ch, "()[]{}|")) {
8357         ADD_FAILURE() << FormatRegexSyntaxError(regex, i) << "'" << ch
8358                       << "' is unsupported.";
8359         is_valid = false;
8360       } else if (IsRepeat(ch) && !prev_repeatable) {
8361         ADD_FAILURE() << FormatRegexSyntaxError(regex, i) << "'" << ch
8362                       << "' can only follow a repeatable token.";
8363         is_valid = false;
8364       }
8365 
8366       prev_repeatable = !IsInSet(ch, "^$?*+");
8367     }
8368   }
8369 
8370   return is_valid;
8371 }
8372 
8373 // Matches a repeated regex atom followed by a valid simple regular
8374 // expression.  The regex atom is defined as c if escaped is false,
8375 // or \c otherwise.  repeat is the repetition meta character (?, *,
8376 // or +).  The behavior is undefined if str contains too many
8377 // characters to be indexable by size_t, in which case the test will
8378 // probably time out anyway.  We are fine with this limitation as
8379 // std::string has it too.
MatchRepetitionAndRegexAtHead(bool escaped,char c,char repeat,const char * regex,const char * str)8380 bool MatchRepetitionAndRegexAtHead(bool escaped, char c, char repeat,
8381                                    const char* regex, const char* str) {
8382   const size_t min_count = (repeat == '+') ? 1 : 0;
8383   const size_t max_count = (repeat == '?') ? 1 : static_cast<size_t>(-1) - 1;
8384   // We cannot call numeric_limits::max() as it conflicts with the
8385   // max() macro on Windows.
8386 
8387   for (size_t i = 0; i <= max_count; ++i) {
8388     // We know that the atom matches each of the first i characters in str.
8389     if (i >= min_count && MatchRegexAtHead(regex, str + i)) {
8390       // We have enough matches at the head, and the tail matches too.
8391       // Since we only care about *whether* the pattern matches str
8392       // (as opposed to *how* it matches), there is no need to find a
8393       // greedy match.
8394       return true;
8395     }
8396     if (str[i] == '\0' || !AtomMatchesChar(escaped, c, str[i])) return false;
8397   }
8398   return false;
8399 }
8400 
8401 // Returns true iff regex matches a prefix of str.  regex must be a
8402 // valid simple regular expression and not start with "^", or the
8403 // result is undefined.
MatchRegexAtHead(const char * regex,const char * str)8404 bool MatchRegexAtHead(const char* regex, const char* str) {
8405   if (*regex == '\0')  // An empty regex matches a prefix of anything.
8406     return true;
8407 
8408   // "$" only matches the end of a string.  Note that regex being
8409   // valid guarantees that there's nothing after "$" in it.
8410   if (*regex == '$') return *str == '\0';
8411 
8412   // Is the first thing in regex an escape sequence?
8413   const bool escaped = *regex == '\\';
8414   if (escaped) ++regex;
8415   if (IsRepeat(regex[1])) {
8416     // MatchRepetitionAndRegexAtHead() calls MatchRegexAtHead(), so
8417     // here's an indirect recursion.  It terminates as the regex gets
8418     // shorter in each recursion.
8419     return MatchRepetitionAndRegexAtHead(escaped, regex[0], regex[1], regex + 2,
8420                                          str);
8421   } else {
8422     // regex isn't empty, isn't "$", and doesn't start with a
8423     // repetition.  We match the first atom of regex with the first
8424     // character of str and recurse.
8425     return (*str != '\0') && AtomMatchesChar(escaped, *regex, *str) &&
8426            MatchRegexAtHead(regex + 1, str + 1);
8427   }
8428 }
8429 
8430 // Returns true iff regex matches any substring of str.  regex must be
8431 // a valid simple regular expression, or the result is undefined.
8432 //
8433 // The algorithm is recursive, but the recursion depth doesn't exceed
8434 // the regex length, so we won't need to worry about running out of
8435 // stack space normally.  In rare cases the time complexity can be
8436 // exponential with respect to the regex length + the string length,
8437 // but usually it's must faster (often close to linear).
MatchRegexAnywhere(const char * regex,const char * str)8438 bool MatchRegexAnywhere(const char* regex, const char* str) {
8439   if (regex == NULL || str == NULL) return false;
8440 
8441   if (*regex == '^') return MatchRegexAtHead(regex + 1, str);
8442 
8443   // A successful match can be anywhere in str.
8444   do {
8445     if (MatchRegexAtHead(regex, str)) return true;
8446   } while (*str++ != '\0');
8447   return false;
8448 }
8449 
8450 // Implements the RE class.
8451 
~RE()8452 RE::~RE() {
8453   free(const_cast<char*>(pattern_));
8454   free(const_cast<char*>(full_pattern_));
8455 }
8456 
8457 // Returns true iff regular expression re matches the entire str.
FullMatch(const char * str,const RE & re)8458 bool RE::FullMatch(const char* str, const RE& re) {
8459   return re.is_valid_ && MatchRegexAnywhere(re.full_pattern_, str);
8460 }
8461 
8462 // Returns true iff regular expression re matches a substring of str
8463 // (including str itself).
PartialMatch(const char * str,const RE & re)8464 bool RE::PartialMatch(const char* str, const RE& re) {
8465   return re.is_valid_ && MatchRegexAnywhere(re.pattern_, str);
8466 }
8467 
8468 // Initializes an RE from its string representation.
Init(const char * regex)8469 void RE::Init(const char* regex) {
8470   pattern_ = full_pattern_ = NULL;
8471   if (regex != NULL) {
8472     pattern_ = posix::StrDup(regex);
8473   }
8474 
8475   is_valid_ = ValidateRegex(regex);
8476   if (!is_valid_) {
8477     // No need to calculate the full pattern when the regex is invalid.
8478     return;
8479   }
8480 
8481   const size_t len = strlen(regex);
8482   // Reserves enough bytes to hold the regular expression used for a
8483   // full match: we need space to prepend a '^', append a '$', and
8484   // terminate the string with '\0'.
8485   char* buffer = static_cast<char*>(malloc(len + 3));
8486   full_pattern_ = buffer;
8487 
8488   if (*regex != '^')
8489     *buffer++ = '^';  // Makes sure full_pattern_ starts with '^'.
8490 
8491   // We don't use snprintf or strncpy, as they trigger a warning when
8492   // compiled with VC++ 8.0.
8493   memcpy(buffer, regex, len);
8494   buffer += len;
8495 
8496   if (len == 0 || regex[len - 1] != '$')
8497     *buffer++ = '$';  // Makes sure full_pattern_ ends with '$'.
8498 
8499   *buffer = '\0';
8500 }
8501 
8502 #endif  // GTEST_USES_POSIX_RE
8503 
8504 const char kUnknownFile[] = "unknown file";
8505 
8506 // Formats a source file path and a line number as they would appear
8507 // in an error message from the compiler used to compile this code.
FormatFileLocation(const char * file,int line)8508 GTEST_API_ ::std::string FormatFileLocation(const char* file, int line) {
8509   const std::string file_name(file == NULL ? kUnknownFile : file);
8510 
8511   if (line < 0) {
8512     return file_name + ":";
8513   }
8514 #ifdef _MSC_VER
8515   return file_name + "(" + StreamableToString(line) + "):";
8516 #else
8517   return file_name + ":" + StreamableToString(line) + ":";
8518 #endif  // _MSC_VER
8519 }
8520 
8521 // Formats a file location for compiler-independent XML output.
8522 // Although this function is not platform dependent, we put it next to
8523 // FormatFileLocation in order to contrast the two functions.
8524 // Note that FormatCompilerIndependentFileLocation() does NOT append colon
8525 // to the file location it produces, unlike FormatFileLocation().
FormatCompilerIndependentFileLocation(const char * file,int line)8526 GTEST_API_ ::std::string FormatCompilerIndependentFileLocation(const char* file,
8527                                                                int line) {
8528   const std::string file_name(file == NULL ? kUnknownFile : file);
8529 
8530   if (line < 0)
8531     return file_name;
8532   else
8533     return file_name + ":" + StreamableToString(line);
8534 }
8535 
GTestLog(GTestLogSeverity severity,const char * file,int line)8536 GTestLog::GTestLog(GTestLogSeverity severity, const char* file, int line)
8537     : severity_(severity) {
8538   const char* const marker =
8539       severity == GTEST_INFO
8540           ? "[  INFO ]"
8541           : severity == GTEST_WARNING
8542                 ? "[WARNING]"
8543                 : severity == GTEST_ERROR ? "[ ERROR ]" : "[ FATAL ]";
8544   GetStream() << ::std::endl
8545               << marker << " " << FormatFileLocation(file, line).c_str()
8546               << ": ";
8547 }
8548 
8549 // Flushes the buffers and, if severity is GTEST_FATAL, aborts the program.
~GTestLog()8550 GTestLog::~GTestLog() {
8551   GetStream() << ::std::endl;
8552   if (severity_ == GTEST_FATAL) {
8553     fflush(stderr);
8554     posix::Abort();
8555   }
8556 }
8557 // Disable Microsoft deprecation warnings for POSIX functions called from
8558 // this class (creat, dup, dup2, and close)
8559 #ifdef _MSC_VER
8560 #  pragma warning(push)
8561 #  pragma warning(disable : 4996)
8562 #endif  // _MSC_VER
8563 
8564 #if GTEST_HAS_STREAM_REDIRECTION
8565 
8566 // Object that captures an output stream (stdout/stderr).
8567 class CapturedStream {
8568  public:
8569   // The ctor redirects the stream to a temporary file.
CapturedStream(int fd)8570   explicit CapturedStream(int fd) : fd_(fd), uncaptured_fd_(dup(fd)) {
8571 #  if GTEST_OS_WINDOWS
8572     char temp_dir_path[MAX_PATH + 1] = {'\0'};   // NOLINT
8573     char temp_file_path[MAX_PATH + 1] = {'\0'};  // NOLINT
8574 
8575     ::GetTempPathA(sizeof(temp_dir_path), temp_dir_path);
8576     const UINT success = ::GetTempFileNameA(temp_dir_path, "gtest_redir",
8577                                             0,  // Generate unique file name.
8578                                             temp_file_path);
8579     GTEST_CHECK_(success != 0)
8580         << "Unable to create a temporary file in " << temp_dir_path;
8581     const int captured_fd = creat(temp_file_path, _S_IREAD | _S_IWRITE);
8582     GTEST_CHECK_(captured_fd != -1)
8583         << "Unable to open temporary file " << temp_file_path;
8584     filename_ = temp_file_path;
8585 #  else
8586     // There's no guarantee that a test has write access to the current
8587     // directory, so we create the temporary file in the /tmp directory
8588     // instead. We use /tmp on most systems, and /sdcard on Android.
8589     // That's because Android doesn't have /tmp.
8590 #    if GTEST_OS_LINUX_ANDROID
8591     // Note: Android applications are expected to call the framework's
8592     // Context.getExternalStorageDirectory() method through JNI to get
8593     // the location of the world-writable SD Card directory. However,
8594     // this requires a Context handle, which cannot be retrieved
8595     // globally from native code. Doing so also precludes running the
8596     // code as part of a regular standalone executable, which doesn't
8597     // run in a Dalvik process (e.g. when running it through 'adb shell').
8598     //
8599     // The location /sdcard is directly accessible from native code
8600     // and is the only location (unofficially) supported by the Android
8601     // team. It's generally a symlink to the real SD Card mount point
8602     // which can be /mnt/sdcard, /mnt/sdcard0, /system/media/sdcard, or
8603     // other OEM-customized locations. Never rely on these, and always
8604     // use /sdcard.
8605     char name_template[] = "/sdcard/gtest_captured_stream.XXXXXX";
8606 #    else
8607     char name_template[] = "/tmp/captured_stream.XXXXXX";
8608 #    endif  // GTEST_OS_LINUX_ANDROID
8609     const int captured_fd = mkstemp(name_template);
8610     filename_ = name_template;
8611 #  endif    // GTEST_OS_WINDOWS
8612     fflush(NULL);
8613     dup2(captured_fd, fd_);
8614     close(captured_fd);
8615   }
8616 
~CapturedStream()8617   ~CapturedStream() { remove(filename_.c_str()); }
8618 
GetCapturedString()8619   std::string GetCapturedString() {
8620     if (uncaptured_fd_ != -1) {
8621       // Restores the original stream.
8622       fflush(NULL);
8623       dup2(uncaptured_fd_, fd_);
8624       close(uncaptured_fd_);
8625       uncaptured_fd_ = -1;
8626     }
8627 
8628     FILE* const file = posix::FOpen(filename_.c_str(), "r");
8629     const std::string content = ReadEntireFile(file);
8630     posix::FClose(file);
8631     return content;
8632   }
8633 
8634  private:
8635   // Reads the entire content of a file as an std::string.
8636   static std::string ReadEntireFile(FILE* file);
8637 
8638   // Returns the size (in bytes) of a file.
8639   static size_t GetFileSize(FILE* file);
8640 
8641   const int fd_;  // A stream to capture.
8642   int uncaptured_fd_;
8643   // Name of the temporary file holding the stderr output.
8644   ::std::string filename_;
8645 
8646   GTEST_DISALLOW_COPY_AND_ASSIGN_(CapturedStream);
8647 };
8648 
8649 // Returns the size (in bytes) of a file.
GetFileSize(FILE * file)8650 size_t CapturedStream::GetFileSize(FILE* file) {
8651   fseek(file, 0, SEEK_END);
8652   return static_cast<size_t>(ftell(file));
8653 }
8654 
8655 // Reads the entire content of a file as a string.
ReadEntireFile(FILE * file)8656 std::string CapturedStream::ReadEntireFile(FILE* file) {
8657   const size_t file_size = GetFileSize(file);
8658   char* const buffer = new char[file_size];
8659 
8660   size_t bytes_last_read = 0;  // # of bytes read in the last fread()
8661   size_t bytes_read = 0;       // # of bytes read so far
8662 
8663   fseek(file, 0, SEEK_SET);
8664 
8665   // Keeps reading the file until we cannot read further or the
8666   // pre-determined file size is reached.
8667   do {
8668     bytes_last_read =
8669         fread(buffer + bytes_read, 1, file_size - bytes_read, file);
8670     bytes_read += bytes_last_read;
8671   } while (bytes_last_read > 0 && bytes_read < file_size);
8672 
8673   const std::string content(buffer, bytes_read);
8674   delete[] buffer;
8675 
8676   return content;
8677 }
8678 
8679 #  ifdef _MSC_VER
8680 #    pragma warning(pop)
8681 #  endif  // _MSC_VER
8682 
8683 static CapturedStream* g_captured_stderr = NULL;
8684 static CapturedStream* g_captured_stdout = NULL;
8685 
8686 // Starts capturing an output stream (stdout/stderr).
CaptureStream(int fd,const char * stream_name,CapturedStream ** stream)8687 void CaptureStream(int fd, const char* stream_name, CapturedStream** stream) {
8688   if (*stream != NULL) {
8689     GTEST_LOG_(FATAL) << "Only one " << stream_name
8690                       << " capturer can exist at a time.";
8691   }
8692   *stream = new CapturedStream(fd);
8693 }
8694 
8695 // Stops capturing the output stream and returns the captured string.
GetCapturedStream(CapturedStream ** captured_stream)8696 std::string GetCapturedStream(CapturedStream** captured_stream) {
8697   const std::string content = (*captured_stream)->GetCapturedString();
8698 
8699   delete *captured_stream;
8700   *captured_stream = NULL;
8701 
8702   return content;
8703 }
8704 
8705 // Starts capturing stdout.
CaptureStdout()8706 void CaptureStdout() {
8707   CaptureStream(kStdOutFileno, "stdout", &g_captured_stdout);
8708 }
8709 
8710 // Starts capturing stderr.
CaptureStderr()8711 void CaptureStderr() {
8712   CaptureStream(kStdErrFileno, "stderr", &g_captured_stderr);
8713 }
8714 
8715 // Stops capturing stdout and returns the captured string.
GetCapturedStdout()8716 std::string GetCapturedStdout() {
8717   return GetCapturedStream(&g_captured_stdout);
8718 }
8719 
8720 // Stops capturing stderr and returns the captured string.
GetCapturedStderr()8721 std::string GetCapturedStderr() {
8722   return GetCapturedStream(&g_captured_stderr);
8723 }
8724 
8725 #endif  // GTEST_HAS_STREAM_REDIRECTION
8726 
8727 #if GTEST_HAS_DEATH_TEST
8728 
8729 // A copy of all command line arguments.  Set by InitGoogleTest().
8730 ::std::vector<testing::internal::string> g_argvs;
8731 
8732 static const ::std::vector<testing::internal::string>* g_injected_test_argvs =
8733     NULL;  // Owned.
8734 
SetInjectableArgvs(const::std::vector<testing::internal::string> * argvs)8735 void SetInjectableArgvs(const ::std::vector<testing::internal::string>* argvs) {
8736   if (g_injected_test_argvs != argvs) delete g_injected_test_argvs;
8737   g_injected_test_argvs = argvs;
8738 }
8739 
GetInjectableArgvs()8740 const ::std::vector<testing::internal::string>& GetInjectableArgvs() {
8741   if (g_injected_test_argvs != NULL) {
8742     return *g_injected_test_argvs;
8743   }
8744   return g_argvs;
8745 }
8746 #endif  // GTEST_HAS_DEATH_TEST
8747 
8748 #if GTEST_OS_WINDOWS_MOBILE
8749 namespace posix {
Abort()8750 void Abort() {
8751   DebugBreak();
8752   TerminateProcess(GetCurrentProcess(), 1);
8753 }
8754 }  // namespace posix
8755 #endif  // GTEST_OS_WINDOWS_MOBILE
8756 
8757 // Returns the name of the environment variable corresponding to the
8758 // given flag.  For example, FlagToEnvVar("foo") will return
8759 // "GTEST_FOO" in the open-source version.
FlagToEnvVar(const char * flag)8760 static std::string FlagToEnvVar(const char* flag) {
8761   const std::string full_flag =
8762       (Message() << GTEST_FLAG_PREFIX_ << flag).GetString();
8763 
8764   Message env_var;
8765   for (size_t i = 0; i != full_flag.length(); i++) {
8766     env_var << ToUpper(full_flag.c_str()[i]);
8767   }
8768 
8769   return env_var.GetString();
8770 }
8771 
8772 // Parses 'str' for a 32-bit signed integer.  If successful, writes
8773 // the result to *value and returns true; otherwise leaves *value
8774 // unchanged and returns false.
ParseInt32(const Message & src_text,const char * str,Int32 * value)8775 bool ParseInt32(const Message& src_text, const char* str, Int32* value) {
8776   // Parses the environment variable as a decimal integer.
8777   char* end = NULL;
8778   const long long_value = strtol(str, &end, 10);  // NOLINT
8779 
8780   // Has strtol() consumed all characters in the string?
8781   if (*end != '\0') {
8782     // No - an invalid character was encountered.
8783     Message msg;
8784     msg << "WARNING: " << src_text
8785         << " is expected to be a 32-bit integer, but actually"
8786         << " has value \"" << str << "\".\n";
8787     printf("%s", msg.GetString().c_str());
8788     fflush(stdout);
8789     return false;
8790   }
8791 
8792   // Is the parsed value in the range of an Int32?
8793   const Int32 result = static_cast<Int32>(long_value);
8794   if (long_value == LONG_MAX || long_value == LONG_MIN ||
8795       // The parsed value overflows as a long.  (strtol() returns
8796       // LONG_MAX or LONG_MIN when the input overflows.)
8797       result != long_value
8798       // The parsed value overflows as an Int32.
8799   ) {
8800     Message msg;
8801     msg << "WARNING: " << src_text
8802         << " is expected to be a 32-bit integer, but actually"
8803         << " has value " << str << ", which overflows.\n";
8804     printf("%s", msg.GetString().c_str());
8805     fflush(stdout);
8806     return false;
8807   }
8808 
8809   *value = result;
8810   return true;
8811 }
8812 
8813 // Reads and returns the Boolean environment variable corresponding to
8814 // the given flag; if it's not set, returns default_value.
8815 //
8816 // The value is considered true iff it's not "0".
BoolFromGTestEnv(const char * flag,bool default_value)8817 bool BoolFromGTestEnv(const char* flag, bool default_value) {
8818   const std::string env_var = FlagToEnvVar(flag);
8819   const char* const string_value = posix::GetEnv(env_var.c_str());
8820   return string_value == NULL ? default_value : strcmp(string_value, "0") != 0;
8821 }
8822 
8823 // Reads and returns a 32-bit integer stored in the environment
8824 // variable corresponding to the given flag; if it isn't set or
8825 // doesn't represent a valid 32-bit integer, returns default_value.
Int32FromGTestEnv(const char * flag,Int32 default_value)8826 Int32 Int32FromGTestEnv(const char* flag, Int32 default_value) {
8827   const std::string env_var = FlagToEnvVar(flag);
8828   const char* const string_value = posix::GetEnv(env_var.c_str());
8829   if (string_value == NULL) {
8830     // The environment variable is not set.
8831     return default_value;
8832   }
8833 
8834   Int32 result = default_value;
8835   if (!ParseInt32(Message() << "Environment variable " << env_var, string_value,
8836                   &result)) {
8837     printf("The default value %s is used.\n",
8838            (Message() << default_value).GetString().c_str());
8839     fflush(stdout);
8840     return default_value;
8841   }
8842 
8843   return result;
8844 }
8845 
8846 // Reads and returns the string environment variable corresponding to
8847 // the given flag; if it's not set, returns default_value.
StringFromGTestEnv(const char * flag,const char * default_value)8848 const char* StringFromGTestEnv(const char* flag, const char* default_value) {
8849   const std::string env_var = FlagToEnvVar(flag);
8850   const char* const value = posix::GetEnv(env_var.c_str());
8851   return value == NULL ? default_value : value;
8852 }
8853 
8854 }  // namespace internal
8855 }  // namespace testing
8856 // Copyright 2007, Google Inc.
8857 // All rights reserved.
8858 //
8859 // Redistribution and use in source and binary forms, with or without
8860 // modification, are permitted provided that the following conditions are
8861 // met:
8862 //
8863 //     * Redistributions of source code must retain the above copyright
8864 // notice, this list of conditions and the following disclaimer.
8865 //     * Redistributions in binary form must reproduce the above
8866 // copyright notice, this list of conditions and the following disclaimer
8867 // in the documentation and/or other materials provided with the
8868 // distribution.
8869 //     * Neither the name of Google Inc. nor the names of its
8870 // contributors may be used to endorse or promote products derived from
8871 // this software without specific prior written permission.
8872 //
8873 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
8874 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
8875 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
8876 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
8877 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
8878 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
8879 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
8880 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
8881 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
8882 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
8883 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
8884 //
8885 // Author: wan@google.com (Zhanyong Wan)
8886 
8887 // Google Test - The Google C++ Testing Framework
8888 //
8889 // This file implements a universal value printer that can print a
8890 // value of any type T:
8891 //
8892 //   void ::testing::internal::UniversalPrinter<T>::Print(value, ostream_ptr);
8893 //
8894 // It uses the << operator when possible, and prints the bytes in the
8895 // object otherwise.  A user can override its behavior for a class
8896 // type Foo by defining either operator<<(::std::ostream&, const Foo&)
8897 // or void PrintTo(const Foo&, ::std::ostream*) in the namespace that
8898 // defines Foo.
8899 
8900 #include <ctype.h>
8901 #include <stdio.h>
8902 #include <ostream>  // NOLINT
8903 #include <string>
8904 
8905 namespace testing {
8906 
8907 namespace {
8908 
8909 using ::std::ostream;
8910 
8911 // Prints a segment of bytes in the given object.
PrintByteSegmentInObjectTo(const unsigned char * obj_bytes,size_t start,size_t count,ostream * os)8912 void PrintByteSegmentInObjectTo(const unsigned char* obj_bytes, size_t start,
8913                                 size_t count, ostream* os) {
8914   char text[5] = "";
8915   for (size_t i = 0; i != count; i++) {
8916     const size_t j = start + i;
8917     if (i != 0) {
8918       // Organizes the bytes into groups of 2 for easy parsing by
8919       // human.
8920       if ((j % 2) == 0)
8921         *os << ' ';
8922       else
8923         *os << '-';
8924     }
8925     GTEST_SNPRINTF_(text, sizeof(text), "%02X", obj_bytes[j]);
8926     *os << text;
8927   }
8928 }
8929 
8930 // Prints the bytes in the given value to the given ostream.
PrintBytesInObjectToImpl(const unsigned char * obj_bytes,size_t count,ostream * os)8931 void PrintBytesInObjectToImpl(const unsigned char* obj_bytes, size_t count,
8932                               ostream* os) {
8933   // Tells the user how big the object is.
8934   *os << count << "-byte object <";
8935 
8936   const size_t kThreshold = 132;
8937   const size_t kChunkSize = 64;
8938   // If the object size is bigger than kThreshold, we'll have to omit
8939   // some details by printing only the first and the last kChunkSize
8940   // bytes.
8941   // TODO(wan): let the user control the threshold using a flag.
8942   if (count < kThreshold) {
8943     PrintByteSegmentInObjectTo(obj_bytes, 0, count, os);
8944   } else {
8945     PrintByteSegmentInObjectTo(obj_bytes, 0, kChunkSize, os);
8946     *os << " ... ";
8947     // Rounds up to 2-byte boundary.
8948     const size_t resume_pos = (count - kChunkSize + 1) / 2 * 2;
8949     PrintByteSegmentInObjectTo(obj_bytes, resume_pos, count - resume_pos, os);
8950   }
8951   *os << ">";
8952 }
8953 
8954 }  // namespace
8955 
8956 namespace internal2 {
8957 
8958 // Delegates to PrintBytesInObjectToImpl() to print the bytes in the
8959 // given object.  The delegation simplifies the implementation, which
8960 // uses the << operator and thus is easier done outside of the
8961 // ::testing::internal namespace, which contains a << operator that
8962 // sometimes conflicts with the one in STL.
PrintBytesInObjectTo(const unsigned char * obj_bytes,size_t count,ostream * os)8963 void PrintBytesInObjectTo(const unsigned char* obj_bytes, size_t count,
8964                           ostream* os) {
8965   PrintBytesInObjectToImpl(obj_bytes, count, os);
8966 }
8967 
8968 }  // namespace internal2
8969 
8970 namespace internal {
8971 
8972 // Depending on the value of a char (or wchar_t), we print it in one
8973 // of three formats:
8974 //   - as is if it's a printable ASCII (e.g. 'a', '2', ' '),
8975 //   - as a hexidecimal escape sequence (e.g. '\x7F'), or
8976 //   - as a special escape sequence (e.g. '\r', '\n').
8977 enum CharFormat { kAsIs, kHexEscape, kSpecialEscape };
8978 
8979 // Returns true if c is a printable ASCII character.  We test the
8980 // value of c directly instead of calling isprint(), which is buggy on
8981 // Windows Mobile.
IsPrintableAscii(wchar_t c)8982 inline bool IsPrintableAscii(wchar_t c) { return 0x20 <= c && c <= 0x7E; }
8983 
8984 // Prints a wide or narrow char c as a character literal without the
8985 // quotes, escaping it when necessary; returns how c was formatted.
8986 // The template argument UnsignedChar is the unsigned version of Char,
8987 // which is the type of c.
8988 template <typename UnsignedChar, typename Char>
PrintAsCharLiteralTo(Char c,ostream * os)8989 static CharFormat PrintAsCharLiteralTo(Char c, ostream* os) {
8990   switch (static_cast<wchar_t>(c)) {
8991   case L'\0':
8992     *os << "\\0";
8993     break;
8994   case L'\'':
8995     *os << "\\'";
8996     break;
8997   case L'\\':
8998     *os << "\\\\";
8999     break;
9000   case L'\a':
9001     *os << "\\a";
9002     break;
9003   case L'\b':
9004     *os << "\\b";
9005     break;
9006   case L'\f':
9007     *os << "\\f";
9008     break;
9009   case L'\n':
9010     *os << "\\n";
9011     break;
9012   case L'\r':
9013     *os << "\\r";
9014     break;
9015   case L'\t':
9016     *os << "\\t";
9017     break;
9018   case L'\v':
9019     *os << "\\v";
9020     break;
9021   default:
9022     if (IsPrintableAscii(c)) {
9023       *os << static_cast<char>(c);
9024       return kAsIs;
9025     } else {
9026       *os << "\\x" + String::FormatHexInt(static_cast<UnsignedChar>(c));
9027       return kHexEscape;
9028     }
9029   }
9030   return kSpecialEscape;
9031 }
9032 
9033 // Prints a wchar_t c as if it's part of a string literal, escaping it when
9034 // necessary; returns how c was formatted.
PrintAsStringLiteralTo(wchar_t c,ostream * os)9035 static CharFormat PrintAsStringLiteralTo(wchar_t c, ostream* os) {
9036   switch (c) {
9037   case L'\'':
9038     *os << "'";
9039     return kAsIs;
9040   case L'"':
9041     *os << "\\\"";
9042     return kSpecialEscape;
9043   default:
9044     return PrintAsCharLiteralTo<wchar_t>(c, os);
9045   }
9046 }
9047 
9048 // Prints a char c as if it's part of a string literal, escaping it when
9049 // necessary; returns how c was formatted.
PrintAsStringLiteralTo(char c,ostream * os)9050 static CharFormat PrintAsStringLiteralTo(char c, ostream* os) {
9051   return PrintAsStringLiteralTo(
9052       static_cast<wchar_t>(static_cast<unsigned char>(c)), os);
9053 }
9054 
9055 // Prints a wide or narrow character c and its code.  '\0' is printed
9056 // as "'\\0'", other unprintable characters are also properly escaped
9057 // using the standard C++ escape sequence.  The template argument
9058 // UnsignedChar is the unsigned version of Char, which is the type of c.
9059 template <typename UnsignedChar, typename Char>
PrintCharAndCodeTo(Char c,ostream * os)9060 void PrintCharAndCodeTo(Char c, ostream* os) {
9061   // First, print c as a literal in the most readable form we can find.
9062   *os << ((sizeof(c) > 1) ? "L'" : "'");
9063   const CharFormat format = PrintAsCharLiteralTo<UnsignedChar>(c, os);
9064   *os << "'";
9065 
9066   // To aid user debugging, we also print c's code in decimal, unless
9067   // it's 0 (in which case c was printed as '\\0', making the code
9068   // obvious).
9069   if (c == 0) return;
9070   *os << " (" << static_cast<int>(c);
9071 
9072   // For more convenience, we print c's code again in hexidecimal,
9073   // unless c was already printed in the form '\x##' or the code is in
9074   // [1, 9].
9075   if (format == kHexEscape || (1 <= c && c <= 9)) {
9076     // Do nothing.
9077   } else {
9078     *os << ", 0x" << String::FormatHexInt(static_cast<UnsignedChar>(c));
9079   }
9080   *os << ")";
9081 }
9082 
PrintTo(unsigned char c,::std::ostream * os)9083 void PrintTo(unsigned char c, ::std::ostream* os) {
9084   PrintCharAndCodeTo<unsigned char>(c, os);
9085 }
PrintTo(signed char c,::std::ostream * os)9086 void PrintTo(signed char c, ::std::ostream* os) {
9087   PrintCharAndCodeTo<unsigned char>(c, os);
9088 }
9089 
9090 // Prints a wchar_t as a symbol if it is printable or as its internal
9091 // code otherwise and also as its code.  L'\0' is printed as "L'\\0'".
PrintTo(wchar_t wc,ostream * os)9092 void PrintTo(wchar_t wc, ostream* os) { PrintCharAndCodeTo<wchar_t>(wc, os); }
9093 
9094 // Prints the given array of characters to the ostream.  CharType must be either
9095 // char or wchar_t.
9096 // The array starts at begin, the length is len, it may include '\0' characters
9097 // and may not be NUL-terminated.
9098 template <typename CharType>
PrintCharsAsStringTo(const CharType * begin,size_t len,ostream * os)9099 static void PrintCharsAsStringTo(const CharType* begin, size_t len,
9100                                  ostream* os) {
9101   const char* const kQuoteBegin = sizeof(CharType) == 1 ? "\"" : "L\"";
9102   *os << kQuoteBegin;
9103   bool is_previous_hex = false;
9104   for (size_t index = 0; index < len; ++index) {
9105     const CharType cur = begin[index];
9106     if (is_previous_hex && IsXDigit(cur)) {
9107       // Previous character is of '\x..' form and this character can be
9108       // interpreted as another hexadecimal digit in its number. Break string to
9109       // disambiguate.
9110       *os << "\" " << kQuoteBegin;
9111     }
9112     is_previous_hex = PrintAsStringLiteralTo(cur, os) == kHexEscape;
9113   }
9114   *os << "\"";
9115 }
9116 
9117 // Prints a (const) char/wchar_t array of 'len' elements, starting at address
9118 // 'begin'.  CharType must be either char or wchar_t.
9119 template <typename CharType>
UniversalPrintCharArray(const CharType * begin,size_t len,ostream * os)9120 static void UniversalPrintCharArray(const CharType* begin, size_t len,
9121                                     ostream* os) {
9122   // The code
9123   //   const char kFoo[] = "foo";
9124   // generates an array of 4, not 3, elements, with the last one being '\0'.
9125   //
9126   // Therefore when printing a char array, we don't print the last element if
9127   // it's '\0', such that the output matches the string literal as it's
9128   // written in the source code.
9129   if (len > 0 && begin[len - 1] == '\0') {
9130     PrintCharsAsStringTo(begin, len - 1, os);
9131     return;
9132   }
9133 
9134   // If, however, the last element in the array is not '\0', e.g.
9135   //    const char kFoo[] = { 'f', 'o', 'o' };
9136   // we must print the entire array.  We also print a message to indicate
9137   // that the array is not NUL-terminated.
9138   PrintCharsAsStringTo(begin, len, os);
9139   *os << " (no terminating NUL)";
9140 }
9141 
9142 // Prints a (const) char array of 'len' elements, starting at address 'begin'.
UniversalPrintArray(const char * begin,size_t len,ostream * os)9143 void UniversalPrintArray(const char* begin, size_t len, ostream* os) {
9144   UniversalPrintCharArray(begin, len, os);
9145 }
9146 
9147 // Prints a (const) wchar_t array of 'len' elements, starting at address
9148 // 'begin'.
UniversalPrintArray(const wchar_t * begin,size_t len,ostream * os)9149 void UniversalPrintArray(const wchar_t* begin, size_t len, ostream* os) {
9150   UniversalPrintCharArray(begin, len, os);
9151 }
9152 
9153 // Prints the given C string to the ostream.
PrintTo(const char * s,ostream * os)9154 void PrintTo(const char* s, ostream* os) {
9155   if (s == NULL) {
9156     *os << "NULL";
9157   } else {
9158     *os << ImplicitCast_<const void*>(s) << " pointing to ";
9159     PrintCharsAsStringTo(s, strlen(s), os);
9160   }
9161 }
9162 
9163 // MSVC compiler can be configured to define whar_t as a typedef
9164 // of unsigned short. Defining an overload for const wchar_t* in that case
9165 // would cause pointers to unsigned shorts be printed as wide strings,
9166 // possibly accessing more memory than intended and causing invalid
9167 // memory accesses. MSVC defines _NATIVE_WCHAR_T_DEFINED symbol when
9168 // wchar_t is implemented as a native type.
9169 #if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED)
9170 // Prints the given wide C string to the ostream.
PrintTo(const wchar_t * s,ostream * os)9171 void PrintTo(const wchar_t* s, ostream* os) {
9172   if (s == NULL) {
9173     *os << "NULL";
9174   } else {
9175     *os << ImplicitCast_<const void*>(s) << " pointing to ";
9176     PrintCharsAsStringTo(s, wcslen(s), os);
9177   }
9178 }
9179 #endif  // wchar_t is native
9180 
9181 // Prints a ::string object.
9182 #if GTEST_HAS_GLOBAL_STRING
PrintStringTo(const::string & s,ostream * os)9183 void PrintStringTo(const ::string& s, ostream* os) {
9184   PrintCharsAsStringTo(s.data(), s.size(), os);
9185 }
9186 #endif  // GTEST_HAS_GLOBAL_STRING
9187 
PrintStringTo(const::std::string & s,ostream * os)9188 void PrintStringTo(const ::std::string& s, ostream* os) {
9189   PrintCharsAsStringTo(s.data(), s.size(), os);
9190 }
9191 
9192 // Prints a ::wstring object.
9193 #if GTEST_HAS_GLOBAL_WSTRING
PrintWideStringTo(const::wstring & s,ostream * os)9194 void PrintWideStringTo(const ::wstring& s, ostream* os) {
9195   PrintCharsAsStringTo(s.data(), s.size(), os);
9196 }
9197 #endif  // GTEST_HAS_GLOBAL_WSTRING
9198 
9199 #if GTEST_HAS_STD_WSTRING
PrintWideStringTo(const::std::wstring & s,ostream * os)9200 void PrintWideStringTo(const ::std::wstring& s, ostream* os) {
9201   PrintCharsAsStringTo(s.data(), s.size(), os);
9202 }
9203 #endif  // GTEST_HAS_STD_WSTRING
9204 
9205 }  // namespace internal
9206 
9207 }  // namespace testing
9208 // Copyright 2008, Google Inc.
9209 // All rights reserved.
9210 //
9211 // Redistribution and use in source and binary forms, with or without
9212 // modification, are permitted provided that the following conditions are
9213 // met:
9214 //
9215 //     * Redistributions of source code must retain the above copyright
9216 // notice, this list of conditions and the following disclaimer.
9217 //     * Redistributions in binary form must reproduce the above
9218 // copyright notice, this list of conditions and the following disclaimer
9219 // in the documentation and/or other materials provided with the
9220 // distribution.
9221 //     * Neither the name of Google Inc. nor the names of its
9222 // contributors may be used to endorse or promote products derived from
9223 // this software without specific prior written permission.
9224 //
9225 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
9226 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
9227 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
9228 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9229 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
9230 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9231 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
9232 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
9233 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
9234 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
9235 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
9236 //
9237 // Author: mheule@google.com (Markus Heule)
9238 //
9239 // The Google C++ Testing Framework (Google Test)
9240 
9241 // Indicates that this translation unit is part of Google Test's
9242 // implementation.  It must come before gtest-internal-inl.h is
9243 // included, or there will be a compiler error.  This trick is to
9244 // prevent a user from accidentally including gtest-internal-inl.h in
9245 // his code.
9246 #define GTEST_IMPLEMENTATION_ 1
9247 #undef GTEST_IMPLEMENTATION_
9248 
9249 namespace testing {
9250 
9251 using internal::GetUnitTestImpl;
9252 
9253 // Gets the summary of the failure message by omitting the stack trace
9254 // in it.
ExtractSummary(const char * message)9255 std::string TestPartResult::ExtractSummary(const char* message) {
9256   const char* const stack_trace = strstr(message, internal::kStackTraceMarker);
9257   return stack_trace == NULL ? message : std::string(message, stack_trace);
9258 }
9259 
9260 // Prints a TestPartResult object.
operator <<(std::ostream & os,const TestPartResult & result)9261 std::ostream& operator<<(std::ostream& os, const TestPartResult& result) {
9262   return os << result.file_name() << ":" << result.line_number() << ": "
9263             << (result.type() == TestPartResult::kSuccess
9264                     ? "Success"
9265                     : result.type() == TestPartResult::kFatalFailure
9266                           ? "Fatal failure"
9267                           : "Non-fatal failure")
9268             << ":\n"
9269             << result.message() << std::endl;
9270 }
9271 
9272 // Appends a TestPartResult to the array.
Append(const TestPartResult & result)9273 void TestPartResultArray::Append(const TestPartResult& result) {
9274   array_.push_back(result);
9275 }
9276 
9277 // Returns the TestPartResult at the given index (0-based).
GetTestPartResult(int index) const9278 const TestPartResult& TestPartResultArray::GetTestPartResult(int index) const {
9279   if (index < 0 || index >= size()) {
9280     printf("\nInvalid index (%d) into TestPartResultArray.\n", index);
9281     internal::posix::Abort();
9282   }
9283 
9284   return array_[index];
9285 }
9286 
9287 // Returns the number of TestPartResult objects in the array.
size() const9288 int TestPartResultArray::size() const {
9289   return static_cast<int>(array_.size());
9290 }
9291 
9292 namespace internal {
9293 
HasNewFatalFailureHelper()9294 HasNewFatalFailureHelper::HasNewFatalFailureHelper()
9295     : has_new_fatal_failure_(false),
9296       original_reporter_(
9297           GetUnitTestImpl()->GetTestPartResultReporterForCurrentThread()) {
9298   GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(this);
9299 }
9300 
~HasNewFatalFailureHelper()9301 HasNewFatalFailureHelper::~HasNewFatalFailureHelper() {
9302   GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(
9303       original_reporter_);
9304 }
9305 
ReportTestPartResult(const TestPartResult & result)9306 void HasNewFatalFailureHelper::ReportTestPartResult(
9307     const TestPartResult& result) {
9308   if (result.fatally_failed()) has_new_fatal_failure_ = true;
9309   original_reporter_->ReportTestPartResult(result);
9310 }
9311 
9312 }  // namespace internal
9313 
9314 }  // namespace testing
9315 // Copyright 2008 Google Inc.
9316 // All Rights Reserved.
9317 //
9318 // Redistribution and use in source and binary forms, with or without
9319 // modification, are permitted provided that the following conditions are
9320 // met:
9321 //
9322 //     * Redistributions of source code must retain the above copyright
9323 // notice, this list of conditions and the following disclaimer.
9324 //     * Redistributions in binary form must reproduce the above
9325 // copyright notice, this list of conditions and the following disclaimer
9326 // in the documentation and/or other materials provided with the
9327 // distribution.
9328 //     * Neither the name of Google Inc. nor the names of its
9329 // contributors may be used to endorse or promote products derived from
9330 // this software without specific prior written permission.
9331 //
9332 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
9333 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
9334 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
9335 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9336 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
9337 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9338 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
9339 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
9340 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
9341 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
9342 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
9343 //
9344 // Author: wan@google.com (Zhanyong Wan)
9345 
9346 namespace testing {
9347 namespace internal {
9348 
9349 #if GTEST_HAS_TYPED_TEST_P
9350 
9351 // Skips to the first non-space char in str. Returns an empty string if str
9352 // contains only whitespace characters.
SkipSpaces(const char * str)9353 static const char* SkipSpaces(const char* str) {
9354   while (IsSpace(*str)) str++;
9355   return str;
9356 }
9357 
9358 // Verifies that registered_tests match the test names in
9359 // defined_test_names_; returns registered_tests if successful, or
9360 // aborts the program otherwise.
VerifyRegisteredTestNames(const char * file,int line,const char * registered_tests)9361 const char* TypedTestCasePState::VerifyRegisteredTestNames(
9362     const char* file, int line, const char* registered_tests) {
9363   typedef ::std::set<const char*>::const_iterator DefinedTestIter;
9364   registered_ = true;
9365 
9366   // Skip initial whitespace in registered_tests since some
9367   // preprocessors prefix stringizied literals with whitespace.
9368   registered_tests = SkipSpaces(registered_tests);
9369 
9370   Message errors;
9371   ::std::set<std::string> tests;
9372   for (const char* names = registered_tests; names != NULL;
9373        names = SkipComma(names)) {
9374     const std::string name = GetPrefixUntilComma(names);
9375     if (tests.count(name) != 0) {
9376       errors << "Test " << name << " is listed more than once.\n";
9377       continue;
9378     }
9379 
9380     bool found = false;
9381     for (DefinedTestIter it = defined_test_names_.begin();
9382          it != defined_test_names_.end(); ++it) {
9383       if (name == *it) {
9384         found = true;
9385         break;
9386       }
9387     }
9388 
9389     if (found) {
9390       tests.insert(name);
9391     } else {
9392       errors << "No test named " << name
9393              << " can be found in this test case.\n";
9394     }
9395   }
9396 
9397   for (DefinedTestIter it = defined_test_names_.begin();
9398        it != defined_test_names_.end(); ++it) {
9399     if (tests.count(*it) == 0) {
9400       errors << "You forgot to list test " << *it << ".\n";
9401     }
9402   }
9403 
9404   const std::string& errors_str = errors.GetString();
9405   if (errors_str != "") {
9406     fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(),
9407             errors_str.c_str());
9408     fflush(stderr);
9409     posix::Abort();
9410   }
9411 
9412   return registered_tests;
9413 }
9414 
9415 #endif  // GTEST_HAS_TYPED_TEST_P
9416 
9417 }  // namespace internal
9418 }  // namespace testing
9419 // Copyright 2008, Google Inc.
9420 // All rights reserved.
9421 //
9422 // Redistribution and use in source and binary forms, with or without
9423 // modification, are permitted provided that the following conditions are
9424 // met:
9425 //
9426 //     * Redistributions of source code must retain the above copyright
9427 // notice, this list of conditions and the following disclaimer.
9428 //     * Redistributions in binary form must reproduce the above
9429 // copyright notice, this list of conditions and the following disclaimer
9430 // in the documentation and/or other materials provided with the
9431 // distribution.
9432 //     * Neither the name of Google Inc. nor the names of its
9433 // contributors may be used to endorse or promote products derived from
9434 // this software without specific prior written permission.
9435 //
9436 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
9437 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
9438 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
9439 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9440 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
9441 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9442 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
9443 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
9444 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
9445 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
9446 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
9447 //
9448 // Author: wan@google.com (Zhanyong Wan)
9449 //
9450 // Google C++ Mocking Framework (Google Mock)
9451 //
9452 // This file #includes all Google Mock implementation .cc files.  The
9453 // purpose is to allow a user to build Google Mock by compiling this
9454 // file alone.
9455 
9456 // This line ensures that gmock.h can be compiled on its own, even
9457 // when it's fused.
9458 #include "gmock/gmock.h"
9459 
9460 // The following lines pull in the real gmock *.cc files.
9461 // Copyright 2007, Google Inc.
9462 // All rights reserved.
9463 //
9464 // Redistribution and use in source and binary forms, with or without
9465 // modification, are permitted provided that the following conditions are
9466 // met:
9467 //
9468 //     * Redistributions of source code must retain the above copyright
9469 // notice, this list of conditions and the following disclaimer.
9470 //     * Redistributions in binary form must reproduce the above
9471 // copyright notice, this list of conditions and the following disclaimer
9472 // in the documentation and/or other materials provided with the
9473 // distribution.
9474 //     * Neither the name of Google Inc. nor the names of its
9475 // contributors may be used to endorse or promote products derived from
9476 // this software without specific prior written permission.
9477 //
9478 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
9479 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
9480 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
9481 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9482 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
9483 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9484 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
9485 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
9486 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
9487 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
9488 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
9489 //
9490 // Author: wan@google.com (Zhanyong Wan)
9491 
9492 // Google Mock - a framework for writing C++ mock classes.
9493 //
9494 // This file implements cardinalities.
9495 
9496 #include <limits.h>
9497 #include <ostream>  // NOLINT
9498 #include <sstream>
9499 #include <string>
9500 
9501 namespace testing {
9502 
9503 namespace {
9504 
9505 // Implements the Between(m, n) cardinality.
9506 class BetweenCardinalityImpl : public CardinalityInterface {
9507  public:
BetweenCardinalityImpl(int min,int max)9508   BetweenCardinalityImpl(int min, int max)
9509       : min_(min >= 0 ? min : 0), max_(max >= min_ ? max : min_) {
9510     std::stringstream ss;
9511     if (min < 0) {
9512       ss << "The invocation lower bound must be >= 0, "
9513          << "but is actually " << min << ".";
9514       internal::Expect(false, __FILE__, __LINE__, ss.str());
9515     } else if (max < 0) {
9516       ss << "The invocation upper bound must be >= 0, "
9517          << "but is actually " << max << ".";
9518       internal::Expect(false, __FILE__, __LINE__, ss.str());
9519     } else if (min > max) {
9520       ss << "The invocation upper bound (" << max
9521          << ") must be >= the invocation lower bound (" << min << ").";
9522       internal::Expect(false, __FILE__, __LINE__, ss.str());
9523     }
9524   }
9525 
9526   // Conservative estimate on the lower/upper bound of the number of
9527   // calls allowed.
ConservativeLowerBound() const9528   virtual int ConservativeLowerBound() const { return min_; }
ConservativeUpperBound() const9529   virtual int ConservativeUpperBound() const { return max_; }
9530 
IsSatisfiedByCallCount(int call_count) const9531   virtual bool IsSatisfiedByCallCount(int call_count) const {
9532     return min_ <= call_count && call_count <= max_;
9533   }
9534 
IsSaturatedByCallCount(int call_count) const9535   virtual bool IsSaturatedByCallCount(int call_count) const {
9536     return call_count >= max_;
9537   }
9538 
9539   virtual void DescribeTo(::std::ostream* os) const;
9540 
9541  private:
9542   const int min_;
9543   const int max_;
9544 
9545   GTEST_DISALLOW_COPY_AND_ASSIGN_(BetweenCardinalityImpl);
9546 };
9547 
9548 // Formats "n times" in a human-friendly way.
FormatTimes(int n)9549 inline internal::string FormatTimes(int n) {
9550   if (n == 1) {
9551     return "once";
9552   } else if (n == 2) {
9553     return "twice";
9554   } else {
9555     std::stringstream ss;
9556     ss << n << " times";
9557     return ss.str();
9558   }
9559 }
9560 
9561 // Describes the Between(m, n) cardinality in human-friendly text.
DescribeTo(::std::ostream * os) const9562 void BetweenCardinalityImpl::DescribeTo(::std::ostream* os) const {
9563   if (min_ == 0) {
9564     if (max_ == 0) {
9565       *os << "never called";
9566     } else if (max_ == INT_MAX) {
9567       *os << "called any number of times";
9568     } else {
9569       *os << "called at most " << FormatTimes(max_);
9570     }
9571   } else if (min_ == max_) {
9572     *os << "called " << FormatTimes(min_);
9573   } else if (max_ == INT_MAX) {
9574     *os << "called at least " << FormatTimes(min_);
9575   } else {
9576     // 0 < min_ < max_ < INT_MAX
9577     *os << "called between " << min_ << " and " << max_ << " times";
9578   }
9579 }
9580 
9581 }  // Unnamed namespace
9582 
9583 // Describes the given call count to an ostream.
DescribeActualCallCountTo(int actual_call_count,::std::ostream * os)9584 void Cardinality::DescribeActualCallCountTo(int actual_call_count,
9585                                             ::std::ostream* os) {
9586   if (actual_call_count > 0) {
9587     *os << "called " << FormatTimes(actual_call_count);
9588   } else {
9589     *os << "never called";
9590   }
9591 }
9592 
9593 // Creates a cardinality that allows at least n calls.
AtLeast(int n)9594 GTEST_API_ Cardinality AtLeast(int n) { return Between(n, INT_MAX); }
9595 
9596 // Creates a cardinality that allows at most n calls.
AtMost(int n)9597 GTEST_API_ Cardinality AtMost(int n) { return Between(0, n); }
9598 
9599 // Creates a cardinality that allows any number of calls.
AnyNumber()9600 GTEST_API_ Cardinality AnyNumber() { return AtLeast(0); }
9601 
9602 // Creates a cardinality that allows between min and max calls.
Between(int min,int max)9603 GTEST_API_ Cardinality Between(int min, int max) {
9604   return Cardinality(new BetweenCardinalityImpl(min, max));
9605 }
9606 
9607 // Creates a cardinality that allows exactly n calls.
Exactly(int n)9608 GTEST_API_ Cardinality Exactly(int n) { return Between(n, n); }
9609 
9610 }  // namespace testing
9611 // Copyright 2007, Google Inc.
9612 // All rights reserved.
9613 //
9614 // Redistribution and use in source and binary forms, with or without
9615 // modification, are permitted provided that the following conditions are
9616 // met:
9617 //
9618 //     * Redistributions of source code must retain the above copyright
9619 // notice, this list of conditions and the following disclaimer.
9620 //     * Redistributions in binary form must reproduce the above
9621 // copyright notice, this list of conditions and the following disclaimer
9622 // in the documentation and/or other materials provided with the
9623 // distribution.
9624 //     * Neither the name of Google Inc. nor the names of its
9625 // contributors may be used to endorse or promote products derived from
9626 // this software without specific prior written permission.
9627 //
9628 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
9629 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
9630 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
9631 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9632 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
9633 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9634 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
9635 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
9636 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
9637 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
9638 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
9639 //
9640 // Author: wan@google.com (Zhanyong Wan)
9641 
9642 // Google Mock - a framework for writing C++ mock classes.
9643 //
9644 // This file defines some utilities useful for implementing Google
9645 // Mock.  They are subject to change without notice, so please DO NOT
9646 // USE THEM IN USER CODE.
9647 
9648 #include <ctype.h>
9649 #include <ostream>  // NOLINT
9650 #include <string>
9651 
9652 namespace testing {
9653 namespace internal {
9654 
9655 // Converts an identifier name to a space-separated list of lower-case
9656 // words.  Each maximum substring of the form [A-Za-z][a-z]*|\d+ is
9657 // treated as one word.  For example, both "FooBar123" and
9658 // "foo_bar_123" are converted to "foo bar 123".
ConvertIdentifierNameToWords(const char * id_name)9659 GTEST_API_ string ConvertIdentifierNameToWords(const char* id_name) {
9660   string result;
9661   char prev_char = '\0';
9662   for (const char* p = id_name; *p != '\0'; prev_char = *(p++)) {
9663     // We don't care about the current locale as the input is
9664     // guaranteed to be a valid C++ identifier name.
9665     const bool starts_new_word = IsUpper(*p) ||
9666                                  (!IsAlpha(prev_char) && IsLower(*p)) ||
9667                                  (!IsDigit(prev_char) && IsDigit(*p));
9668 
9669     if (IsAlNum(*p)) {
9670       if (starts_new_word && result != "") result += ' ';
9671       result += ToLower(*p);
9672     }
9673   }
9674   return result;
9675 }
9676 
9677 // This class reports Google Mock failures as Google Test failures.  A
9678 // user can define another class in a similar fashion if he intends to
9679 // use Google Mock with a testing framework other than Google Test.
9680 class GoogleTestFailureReporter : public FailureReporterInterface {
9681  public:
ReportFailure(FailureType type,const char * file,int line,const string & message)9682   virtual void ReportFailure(FailureType type, const char* file, int line,
9683                              const string& message) {
9684     AssertHelper(type == kFatal ? TestPartResult::kFatalFailure
9685                                 : TestPartResult::kNonFatalFailure,
9686                  file, line, message.c_str()) = Message();
9687     if (type == kFatal) {
9688       posix::Abort();
9689     }
9690   }
9691 };
9692 
9693 // Returns the global failure reporter.  Will create a
9694 // GoogleTestFailureReporter and return it the first time called.
GetFailureReporter()9695 GTEST_API_ FailureReporterInterface* GetFailureReporter() {
9696   // Points to the global failure reporter used by Google Mock.  gcc
9697   // guarantees that the following use of failure_reporter is
9698   // thread-safe.  We may need to add additional synchronization to
9699   // protect failure_reporter if we port Google Mock to other
9700   // compilers.
9701   static FailureReporterInterface* const failure_reporter =
9702       new GoogleTestFailureReporter();
9703   return failure_reporter;
9704 }
9705 
9706 // Protects global resources (stdout in particular) used by Log().
9707 static GTEST_DEFINE_STATIC_MUTEX_(g_log_mutex);
9708 
9709 // Returns true iff a log with the given severity is visible according
9710 // to the --gmock_verbose flag.
LogIsVisible(LogSeverity severity)9711 GTEST_API_ bool LogIsVisible(LogSeverity severity) {
9712   if (GMOCK_FLAG(verbose) == kInfoVerbosity) {
9713     // Always show the log if --gmock_verbose=info.
9714     return true;
9715   } else if (GMOCK_FLAG(verbose) == kErrorVerbosity) {
9716     // Always hide it if --gmock_verbose=error.
9717     return false;
9718   } else {
9719     // If --gmock_verbose is neither "info" nor "error", we treat it
9720     // as "warning" (its default value).
9721     return severity == kWarning;
9722   }
9723 }
9724 
9725 // Prints the given message to stdout iff 'severity' >= the level
9726 // specified by the --gmock_verbose flag.  If stack_frames_to_skip >=
9727 // 0, also prints the stack trace excluding the top
9728 // stack_frames_to_skip frames.  In opt mode, any positive
9729 // stack_frames_to_skip is treated as 0, since we don't know which
9730 // function calls will be inlined by the compiler and need to be
9731 // conservative.
Log(LogSeverity severity,const string & message,int stack_frames_to_skip)9732 GTEST_API_ void Log(LogSeverity severity, const string& message,
9733                     int stack_frames_to_skip) {
9734   if (!LogIsVisible(severity)) return;
9735 
9736   // Ensures that logs from different threads don't interleave.
9737   MutexLock l(&g_log_mutex);
9738 
9739   // "using ::std::cout;" doesn't work with Symbian's STLport, where cout is a
9740   // macro.
9741 
9742   if (severity == kWarning) {
9743     // Prints a GMOCK WARNING marker to make the warnings easily searchable.
9744     std::cout << "\nGMOCK WARNING:";
9745   }
9746   // Pre-pends a new-line to message if it doesn't start with one.
9747   if (message.empty() || message[0] != '\n') {
9748     std::cout << "\n";
9749   }
9750   std::cout << message;
9751   if (stack_frames_to_skip >= 0) {
9752 #ifdef NDEBUG
9753     // In opt mode, we have to be conservative and skip no stack frame.
9754     const int actual_to_skip = 0;
9755 #else
9756     // In dbg mode, we can do what the caller tell us to do (plus one
9757     // for skipping this function's stack frame).
9758     const int actual_to_skip = stack_frames_to_skip + 1;
9759 #endif  // NDEBUG
9760 
9761     // Appends a new-line to message if it doesn't end with one.
9762     if (!message.empty() && *message.rbegin() != '\n') {
9763       std::cout << "\n";
9764     }
9765     std::cout << "Stack trace:\n"
9766               << ::testing::internal::GetCurrentOsStackTraceExceptTop(
9767                      ::testing::UnitTest::GetInstance(), actual_to_skip);
9768   }
9769   std::cout << ::std::flush;
9770 }
9771 
9772 }  // namespace internal
9773 }  // namespace testing
9774 // Copyright 2007, Google Inc.
9775 // All rights reserved.
9776 //
9777 // Redistribution and use in source and binary forms, with or without
9778 // modification, are permitted provided that the following conditions are
9779 // met:
9780 //
9781 //     * Redistributions of source code must retain the above copyright
9782 // notice, this list of conditions and the following disclaimer.
9783 //     * Redistributions in binary form must reproduce the above
9784 // copyright notice, this list of conditions and the following disclaimer
9785 // in the documentation and/or other materials provided with the
9786 // distribution.
9787 //     * Neither the name of Google Inc. nor the names of its
9788 // contributors may be used to endorse or promote products derived from
9789 // this software without specific prior written permission.
9790 //
9791 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
9792 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
9793 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
9794 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9795 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
9796 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9797 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
9798 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
9799 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
9800 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
9801 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
9802 //
9803 // Author: wan@google.com (Zhanyong Wan)
9804 
9805 // Google Mock - a framework for writing C++ mock classes.
9806 //
9807 // This file implements Matcher<const string&>, Matcher<string>, and
9808 // utilities for defining matchers.
9809 
9810 #include <string.h>
9811 #include <sstream>
9812 #include <string>
9813 
9814 namespace testing {
9815 
9816 // Constructs a matcher that matches a const string& whose value is
9817 // equal to s.
Matcher(const internal::string & s)9818 Matcher<const internal::string&>::Matcher(const internal::string& s) {
9819   *this = Eq(s);
9820 }
9821 
9822 // Constructs a matcher that matches a const string& whose value is
9823 // equal to s.
Matcher(const char * s)9824 Matcher<const internal::string&>::Matcher(const char* s) {
9825   *this = Eq(internal::string(s));
9826 }
9827 
9828 // Constructs a matcher that matches a string whose value is equal to s.
Matcher(const internal::string & s)9829 Matcher<internal::string>::Matcher(const internal::string& s) { *this = Eq(s); }
9830 
9831 // Constructs a matcher that matches a string whose value is equal to s.
Matcher(const char * s)9832 Matcher<internal::string>::Matcher(const char* s) {
9833   *this = Eq(internal::string(s));
9834 }
9835 
9836 #if GTEST_HAS_STRING_PIECE_
9837 // Constructs a matcher that matches a const StringPiece& whose value is
9838 // equal to s.
Matcher(const internal::string & s)9839 Matcher<const StringPiece&>::Matcher(const internal::string& s) {
9840   *this = Eq(s);
9841 }
9842 
9843 // Constructs a matcher that matches a const StringPiece& whose value is
9844 // equal to s.
Matcher(const char * s)9845 Matcher<const StringPiece&>::Matcher(const char* s) {
9846   *this = Eq(internal::string(s));
9847 }
9848 
9849 // Constructs a matcher that matches a const StringPiece& whose value is
9850 // equal to s.
Matcher(StringPiece s)9851 Matcher<const StringPiece&>::Matcher(StringPiece s) {
9852   *this = Eq(s.ToString());
9853 }
9854 
9855 // Constructs a matcher that matches a StringPiece whose value is equal to s.
Matcher(const internal::string & s)9856 Matcher<StringPiece>::Matcher(const internal::string& s) { *this = Eq(s); }
9857 
9858 // Constructs a matcher that matches a StringPiece whose value is equal to s.
Matcher(const char * s)9859 Matcher<StringPiece>::Matcher(const char* s) {
9860   *this = Eq(internal::string(s));
9861 }
9862 
9863 // Constructs a matcher that matches a StringPiece whose value is equal to s.
Matcher(StringPiece s)9864 Matcher<StringPiece>::Matcher(StringPiece s) { *this = Eq(s.ToString()); }
9865 #endif  // GTEST_HAS_STRING_PIECE_
9866 
9867 namespace internal {
9868 
9869 // Joins a vector of strings as if they are fields of a tuple; returns
9870 // the joined string.
JoinAsTuple(const Strings & fields)9871 GTEST_API_ string JoinAsTuple(const Strings& fields) {
9872   switch (fields.size()) {
9873   case 0:
9874     return "";
9875   case 1:
9876     return fields[0];
9877   default:
9878     string result = "(" + fields[0];
9879     for (size_t i = 1; i < fields.size(); i++) {
9880       result += ", ";
9881       result += fields[i];
9882     }
9883     result += ")";
9884     return result;
9885   }
9886 }
9887 
9888 // Returns the description for a matcher defined using the MATCHER*()
9889 // macro where the user-supplied description string is "", if
9890 // 'negation' is false; otherwise returns the description of the
9891 // negation of the matcher.  'param_values' contains a list of strings
9892 // that are the print-out of the matcher's parameters.
FormatMatcherDescription(bool negation,const char * matcher_name,const Strings & param_values)9893 GTEST_API_ string FormatMatcherDescription(bool negation,
9894                                            const char* matcher_name,
9895                                            const Strings& param_values) {
9896   string result = ConvertIdentifierNameToWords(matcher_name);
9897   if (param_values.size() >= 1) result += " " + JoinAsTuple(param_values);
9898   return negation ? "not (" + result + ")" : result;
9899 }
9900 
9901 // FindMaxBipartiteMatching and its helper class.
9902 //
9903 // Uses the well-known Ford-Fulkerson max flow method to find a maximum
9904 // bipartite matching. Flow is considered to be from left to right.
9905 // There is an implicit source node that is connected to all of the left
9906 // nodes, and an implicit sink node that is connected to all of the
9907 // right nodes. All edges have unit capacity.
9908 //
9909 // Neither the flow graph nor the residual flow graph are represented
9910 // explicitly. Instead, they are implied by the information in 'graph' and
9911 // a vector<int> called 'left_' whose elements are initialized to the
9912 // value kUnused. This represents the initial state of the algorithm,
9913 // where the flow graph is empty, and the residual flow graph has the
9914 // following edges:
9915 //   - An edge from source to each left_ node
9916 //   - An edge from each right_ node to sink
9917 //   - An edge from each left_ node to each right_ node, if the
9918 //     corresponding edge exists in 'graph'.
9919 //
9920 // When the TryAugment() method adds a flow, it sets left_[l] = r for some
9921 // nodes l and r. This induces the following changes:
9922 //   - The edges (source, l), (l, r), and (r, sink) are added to the
9923 //     flow graph.
9924 //   - The same three edges are removed from the residual flow graph.
9925 //   - The reverse edges (l, source), (r, l), and (sink, r) are added
9926 //     to the residual flow graph, which is a directional graph
9927 //     representing unused flow capacity.
9928 //
9929 // When the method augments a flow (moving left_[l] from some r1 to some
9930 // other r2), this can be thought of as "undoing" the above steps with
9931 // respect to r1 and "redoing" them with respect to r2.
9932 //
9933 // It bears repeating that the flow graph and residual flow graph are
9934 // never represented explicitly, but can be derived by looking at the
9935 // information in 'graph' and in left_.
9936 //
9937 // As an optimization, there is a second vector<int> called right_ which
9938 // does not provide any new information. Instead, it enables more
9939 // efficient queries about edges entering or leaving the right-side nodes
9940 // of the flow or residual flow graphs. The following invariants are
9941 // maintained:
9942 //
9943 // left[l] == kUnused or right[left[l]] == l
9944 // right[r] == kUnused or left[right[r]] == r
9945 //
9946 // . [ source ]                                        .
9947 // .   |||                                             .
9948 // .   |||                                             .
9949 // .   ||\--> left[0]=1  ---\    right[0]=-1 ----\     .
9950 // .   ||                   |                    |     .
9951 // .   |\---> left[1]=-1    \--> right[1]=0  ---\|     .
9952 // .   |                                        ||     .
9953 // .   \----> left[2]=2  ------> right[2]=2  --\||     .
9954 // .                                           |||     .
9955 // .         elements           matchers       vvv     .
9956 // .                                         [ sink ]  .
9957 //
9958 // See Also:
9959 //   [1] Cormen, et al (2001). "Section 26.2: The Ford–Fulkerson method".
9960 //       "Introduction to Algorithms (Second ed.)", pp. 651–664.
9961 //   [2] "Ford–Fulkerson algorithm", Wikipedia,
9962 //       'http://en.wikipedia.org/wiki/Ford%E2%80%93Fulkerson_algorithm'
9963 class MaxBipartiteMatchState {
9964  public:
MaxBipartiteMatchState(const MatchMatrix & graph)9965   explicit MaxBipartiteMatchState(const MatchMatrix& graph)
9966       : graph_(&graph),
9967         left_(graph_->LhsSize(), kUnused),
9968         right_(graph_->RhsSize(), kUnused) {}
9969 
9970   // Returns the edges of a maximal match, each in the form {left, right}.
Compute()9971   ElementMatcherPairs Compute() {
9972     // 'seen' is used for path finding { 0: unseen, 1: seen }.
9973     ::std::vector<char> seen;
9974     // Searches the residual flow graph for a path from each left node to
9975     // the sink in the residual flow graph, and if one is found, add flow
9976     // to the graph. It's okay to search through the left nodes once. The
9977     // edge from the implicit source node to each previously-visited left
9978     // node will have flow if that left node has any path to the sink
9979     // whatsoever. Subsequent augmentations can only add flow to the
9980     // network, and cannot take away that previous flow unit from the source.
9981     // Since the source-to-left edge can only carry one flow unit (or,
9982     // each element can be matched to only one matcher), there is no need
9983     // to visit the left nodes more than once looking for augmented paths.
9984     // The flow is known to be possible or impossible by looking at the
9985     // node once.
9986     for (size_t ilhs = 0; ilhs < graph_->LhsSize(); ++ilhs) {
9987       // Reset the path-marking vector and try to find a path from
9988       // source to sink starting at the left_[ilhs] node.
9989       GTEST_CHECK_(left_[ilhs] == kUnused)
9990           << "ilhs: " << ilhs << ", left_[ilhs]: " << left_[ilhs];
9991       // 'seen' initialized to 'graph_->RhsSize()' copies of 0.
9992       seen.assign(graph_->RhsSize(), 0);
9993       TryAugment(ilhs, &seen);
9994     }
9995     ElementMatcherPairs result;
9996     for (size_t ilhs = 0; ilhs < left_.size(); ++ilhs) {
9997       size_t irhs = left_[ilhs];
9998       if (irhs == kUnused) continue;
9999       result.push_back(ElementMatcherPair(ilhs, irhs));
10000     }
10001     return result;
10002   }
10003 
10004  private:
10005   static const size_t kUnused = static_cast<size_t>(-1);
10006 
10007   // Perform a depth-first search from left node ilhs to the sink.  If a
10008   // path is found, flow is added to the network by linking the left and
10009   // right vector elements corresponding each segment of the path.
10010   // Returns true if a path to sink was found, which means that a unit of
10011   // flow was added to the network. The 'seen' vector elements correspond
10012   // to right nodes and are marked to eliminate cycles from the search.
10013   //
10014   // Left nodes will only be explored at most once because they
10015   // are accessible from at most one right node in the residual flow
10016   // graph.
10017   //
10018   // Note that left_[ilhs] is the only element of left_ that TryAugment will
10019   // potentially transition from kUnused to another value. Any other
10020   // left_ element holding kUnused before TryAugment will be holding it
10021   // when TryAugment returns.
10022   //
TryAugment(size_t ilhs,::std::vector<char> * seen)10023   bool TryAugment(size_t ilhs, ::std::vector<char>* seen) {
10024     for (size_t irhs = 0; irhs < graph_->RhsSize(); ++irhs) {
10025       if ((*seen)[irhs]) continue;
10026       if (!graph_->HasEdge(ilhs, irhs)) continue;
10027       // There's an available edge from ilhs to irhs.
10028       (*seen)[irhs] = 1;
10029       // Next a search is performed to determine whether
10030       // this edge is a dead end or leads to the sink.
10031       //
10032       // right_[irhs] == kUnused means that there is residual flow from
10033       // right node irhs to the sink, so we can use that to finish this
10034       // flow path and return success.
10035       //
10036       // Otherwise there is residual flow to some ilhs. We push flow
10037       // along that path and call ourselves recursively to see if this
10038       // ultimately leads to sink.
10039       if (right_[irhs] == kUnused || TryAugment(right_[irhs], seen)) {
10040         // Add flow from left_[ilhs] to right_[irhs].
10041         left_[ilhs] = irhs;
10042         right_[irhs] = ilhs;
10043         return true;
10044       }
10045     }
10046     return false;
10047   }
10048 
10049   const MatchMatrix* graph_;  // not owned
10050   // Each element of the left_ vector represents a left hand side node
10051   // (i.e. an element) and each element of right_ is a right hand side
10052   // node (i.e. a matcher). The values in the left_ vector indicate
10053   // outflow from that node to a node on the the right_ side. The values
10054   // in the right_ indicate inflow, and specify which left_ node is
10055   // feeding that right_ node, if any. For example, left_[3] == 1 means
10056   // there's a flow from element #3 to matcher #1. Such a flow would also
10057   // be redundantly represented in the right_ vector as right_[1] == 3.
10058   // Elements of left_ and right_ are either kUnused or mutually
10059   // referent. Mutually referent means that left_[right_[i]] = i and
10060   // right_[left_[i]] = i.
10061   ::std::vector<size_t> left_;
10062   ::std::vector<size_t> right_;
10063 
10064   GTEST_DISALLOW_ASSIGN_(MaxBipartiteMatchState);
10065 };
10066 
10067 const size_t MaxBipartiteMatchState::kUnused;
10068 
FindMaxBipartiteMatching(const MatchMatrix & g)10069 GTEST_API_ ElementMatcherPairs FindMaxBipartiteMatching(const MatchMatrix& g) {
10070   return MaxBipartiteMatchState(g).Compute();
10071 }
10072 
LogElementMatcherPairVec(const ElementMatcherPairs & pairs,::std::ostream * stream)10073 static void LogElementMatcherPairVec(const ElementMatcherPairs& pairs,
10074                                      ::std::ostream* stream) {
10075   typedef ElementMatcherPairs::const_iterator Iter;
10076   ::std::ostream& os = *stream;
10077   os << "{";
10078   const char* sep = "";
10079   for (Iter it = pairs.begin(); it != pairs.end(); ++it) {
10080     os << sep << "\n  ("
10081        << "element #" << it->first << ", "
10082        << "matcher #" << it->second << ")";
10083     sep = ",";
10084   }
10085   os << "\n}";
10086 }
10087 
10088 // Tries to find a pairing, and explains the result.
FindPairing(const MatchMatrix & matrix,MatchResultListener * listener)10089 GTEST_API_ bool FindPairing(const MatchMatrix& matrix,
10090                             MatchResultListener* listener) {
10091   ElementMatcherPairs matches = FindMaxBipartiteMatching(matrix);
10092 
10093   size_t max_flow = matches.size();
10094   bool result = (max_flow == matrix.RhsSize());
10095 
10096   if (!result) {
10097     if (listener->IsInterested()) {
10098       *listener << "where no permutation of the elements can "
10099                    "satisfy all matchers, and the closest match is "
10100                 << max_flow << " of " << matrix.RhsSize()
10101                 << " matchers with the pairings:\n";
10102       LogElementMatcherPairVec(matches, listener->stream());
10103     }
10104     return false;
10105   }
10106 
10107   if (matches.size() > 1) {
10108     if (listener->IsInterested()) {
10109       const char* sep = "where:\n";
10110       for (size_t mi = 0; mi < matches.size(); ++mi) {
10111         *listener << sep << " - element #" << matches[mi].first
10112                   << " is matched by matcher #" << matches[mi].second;
10113         sep = ",\n";
10114       }
10115     }
10116   }
10117   return true;
10118 }
10119 
NextGraph()10120 bool MatchMatrix::NextGraph() {
10121   for (size_t ilhs = 0; ilhs < LhsSize(); ++ilhs) {
10122     for (size_t irhs = 0; irhs < RhsSize(); ++irhs) {
10123       char& b = matched_[SpaceIndex(ilhs, irhs)];
10124       if (!b) {
10125         b = 1;
10126         return true;
10127       }
10128       b = 0;
10129     }
10130   }
10131   return false;
10132 }
10133 
Randomize()10134 void MatchMatrix::Randomize() {
10135   for (size_t ilhs = 0; ilhs < LhsSize(); ++ilhs) {
10136     for (size_t irhs = 0; irhs < RhsSize(); ++irhs) {
10137       char& b = matched_[SpaceIndex(ilhs, irhs)];
10138       b = static_cast<char>(rand() & 1);  // NOLINT
10139     }
10140   }
10141 }
10142 
DebugString() const10143 string MatchMatrix::DebugString() const {
10144   ::std::stringstream ss;
10145   const char* sep = "";
10146   for (size_t i = 0; i < LhsSize(); ++i) {
10147     ss << sep;
10148     for (size_t j = 0; j < RhsSize(); ++j) {
10149       ss << HasEdge(i, j);
10150     }
10151     sep = ";";
10152   }
10153   return ss.str();
10154 }
10155 
DescribeToImpl(::std::ostream * os) const10156 void UnorderedElementsAreMatcherImplBase::DescribeToImpl(
10157     ::std::ostream* os) const {
10158   if (matcher_describers_.empty()) {
10159     *os << "is empty";
10160     return;
10161   }
10162   if (matcher_describers_.size() == 1) {
10163     *os << "has " << Elements(1) << " and that element ";
10164     matcher_describers_[0]->DescribeTo(os);
10165     return;
10166   }
10167   *os << "has " << Elements(matcher_describers_.size())
10168       << " and there exists some permutation of elements such that:\n";
10169   const char* sep = "";
10170   for (size_t i = 0; i != matcher_describers_.size(); ++i) {
10171     *os << sep << " - element #" << i << " ";
10172     matcher_describers_[i]->DescribeTo(os);
10173     sep = ", and\n";
10174   }
10175 }
10176 
DescribeNegationToImpl(::std::ostream * os) const10177 void UnorderedElementsAreMatcherImplBase::DescribeNegationToImpl(
10178     ::std::ostream* os) const {
10179   if (matcher_describers_.empty()) {
10180     *os << "isn't empty";
10181     return;
10182   }
10183   if (matcher_describers_.size() == 1) {
10184     *os << "doesn't have " << Elements(1) << ", or has " << Elements(1)
10185         << " that ";
10186     matcher_describers_[0]->DescribeNegationTo(os);
10187     return;
10188   }
10189   *os << "doesn't have " << Elements(matcher_describers_.size())
10190       << ", or there exists no permutation of elements such that:\n";
10191   const char* sep = "";
10192   for (size_t i = 0; i != matcher_describers_.size(); ++i) {
10193     *os << sep << " - element #" << i << " ";
10194     matcher_describers_[i]->DescribeTo(os);
10195     sep = ", and\n";
10196   }
10197 }
10198 
10199 // Checks that all matchers match at least one element, and that all
10200 // elements match at least one matcher. This enables faster matching
10201 // and better error reporting.
10202 // Returns false, writing an explanation to 'listener', if and only
10203 // if the success criteria are not met.
10204 bool UnorderedElementsAreMatcherImplBase::
VerifyAllElementsAndMatchersAreMatched(const::std::vector<string> & element_printouts,const MatchMatrix & matrix,MatchResultListener * listener) const10205     VerifyAllElementsAndMatchersAreMatched(
10206         const ::std::vector<string>& element_printouts,
10207         const MatchMatrix& matrix, MatchResultListener* listener) const {
10208   bool result = true;
10209   ::std::vector<char> element_matched(matrix.LhsSize(), 0);
10210   ::std::vector<char> matcher_matched(matrix.RhsSize(), 0);
10211 
10212   for (size_t ilhs = 0; ilhs < matrix.LhsSize(); ilhs++) {
10213     for (size_t irhs = 0; irhs < matrix.RhsSize(); irhs++) {
10214       char matched = matrix.HasEdge(ilhs, irhs);
10215       element_matched[ilhs] |= matched;
10216       matcher_matched[irhs] |= matched;
10217     }
10218   }
10219 
10220   {
10221     const char* sep =
10222         "where the following matchers don't match any elements:\n";
10223     for (size_t mi = 0; mi < matcher_matched.size(); ++mi) {
10224       if (matcher_matched[mi]) continue;
10225       result = false;
10226       if (listener->IsInterested()) {
10227         *listener << sep << "matcher #" << mi << ": ";
10228         matcher_describers_[mi]->DescribeTo(listener->stream());
10229         sep = ",\n";
10230       }
10231     }
10232   }
10233 
10234   {
10235     const char* sep =
10236         "where the following elements don't match any matchers:\n";
10237     const char* outer_sep = "";
10238     if (!result) {
10239       outer_sep = "\nand ";
10240     }
10241     for (size_t ei = 0; ei < element_matched.size(); ++ei) {
10242       if (element_matched[ei]) continue;
10243       result = false;
10244       if (listener->IsInterested()) {
10245         *listener << outer_sep << sep << "element #" << ei << ": "
10246                   << element_printouts[ei];
10247         sep = ",\n";
10248         outer_sep = "";
10249       }
10250     }
10251   }
10252   return result;
10253 }
10254 
10255 }  // namespace internal
10256 }  // namespace testing
10257 // Copyright 2007, Google Inc.
10258 // All rights reserved.
10259 //
10260 // Redistribution and use in source and binary forms, with or without
10261 // modification, are permitted provided that the following conditions are
10262 // met:
10263 //
10264 //     * Redistributions of source code must retain the above copyright
10265 // notice, this list of conditions and the following disclaimer.
10266 //     * Redistributions in binary form must reproduce the above
10267 // copyright notice, this list of conditions and the following disclaimer
10268 // in the documentation and/or other materials provided with the
10269 // distribution.
10270 //     * Neither the name of Google Inc. nor the names of its
10271 // contributors may be used to endorse or promote products derived from
10272 // this software without specific prior written permission.
10273 //
10274 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
10275 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
10276 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
10277 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
10278 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
10279 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
10280 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
10281 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
10282 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
10283 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
10284 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
10285 //
10286 // Author: wan@google.com (Zhanyong Wan)
10287 
10288 // Google Mock - a framework for writing C++ mock classes.
10289 //
10290 // This file implements the spec builder syntax (ON_CALL and
10291 // EXPECT_CALL).
10292 
10293 #include <stdlib.h>
10294 #include <iostream>  // NOLINT
10295 #include <map>
10296 #include <set>
10297 #include <string>
10298 
10299 #if GTEST_OS_CYGWIN || GTEST_OS_LINUX || GTEST_OS_MAC
10300 #  include <unistd.h>  // NOLINT
10301 #endif
10302 
10303 namespace testing {
10304 namespace internal {
10305 
10306 // Protects the mock object registry (in class Mock), all function
10307 // mockers, and all expectations.
10308 GTEST_API_ GTEST_DEFINE_STATIC_MUTEX_(g_gmock_mutex);
10309 
10310 // Logs a message including file and line number information.
LogWithLocation(testing::internal::LogSeverity severity,const char * file,int line,const string & message)10311 GTEST_API_ void LogWithLocation(testing::internal::LogSeverity severity,
10312                                 const char* file, int line,
10313                                 const string& message) {
10314   ::std::ostringstream s;
10315   s << file << ":" << line << ": " << message << ::std::endl;
10316   Log(severity, s.str(), 0);
10317 }
10318 
10319 // Constructs an ExpectationBase object.
ExpectationBase(const char * a_file,int a_line,const string & a_source_text)10320 ExpectationBase::ExpectationBase(const char* a_file, int a_line,
10321                                  const string& a_source_text)
10322     : file_(a_file),
10323       line_(a_line),
10324       source_text_(a_source_text),
10325       cardinality_specified_(false),
10326       cardinality_(Exactly(1)),
10327       call_count_(0),
10328       retired_(false),
10329       extra_matcher_specified_(false),
10330       repeated_action_specified_(false),
10331       retires_on_saturation_(false),
10332       last_clause_(kNone),
10333       action_count_checked_(false) {}
10334 
10335 // Destructs an ExpectationBase object.
~ExpectationBase()10336 ExpectationBase::~ExpectationBase() {}
10337 
10338 // Explicitly specifies the cardinality of this expectation.  Used by
10339 // the subclasses to implement the .Times() clause.
SpecifyCardinality(const Cardinality & a_cardinality)10340 void ExpectationBase::SpecifyCardinality(const Cardinality& a_cardinality) {
10341   cardinality_specified_ = true;
10342   cardinality_ = a_cardinality;
10343 }
10344 
10345 // Retires all pre-requisites of this expectation.
RetireAllPreRequisites()10346 void ExpectationBase::RetireAllPreRequisites()
10347     GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
10348   if (is_retired()) {
10349     // We can take this short-cut as we never retire an expectation
10350     // until we have retired all its pre-requisites.
10351     return;
10352   }
10353 
10354   for (ExpectationSet::const_iterator it = immediate_prerequisites_.begin();
10355        it != immediate_prerequisites_.end(); ++it) {
10356     ExpectationBase* const prerequisite = it->expectation_base().get();
10357     if (!prerequisite->is_retired()) {
10358       prerequisite->RetireAllPreRequisites();
10359       prerequisite->Retire();
10360     }
10361   }
10362 }
10363 
10364 // Returns true iff all pre-requisites of this expectation have been
10365 // satisfied.
AllPrerequisitesAreSatisfied() const10366 bool ExpectationBase::AllPrerequisitesAreSatisfied() const
10367     GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
10368   g_gmock_mutex.AssertHeld();
10369   for (ExpectationSet::const_iterator it = immediate_prerequisites_.begin();
10370        it != immediate_prerequisites_.end(); ++it) {
10371     if (!(it->expectation_base()->IsSatisfied()) ||
10372         !(it->expectation_base()->AllPrerequisitesAreSatisfied()))
10373       return false;
10374   }
10375   return true;
10376 }
10377 
10378 // Adds unsatisfied pre-requisites of this expectation to 'result'.
FindUnsatisfiedPrerequisites(ExpectationSet * result) const10379 void ExpectationBase::FindUnsatisfiedPrerequisites(ExpectationSet* result) const
10380     GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
10381   g_gmock_mutex.AssertHeld();
10382   for (ExpectationSet::const_iterator it = immediate_prerequisites_.begin();
10383        it != immediate_prerequisites_.end(); ++it) {
10384     if (it->expectation_base()->IsSatisfied()) {
10385       // If *it is satisfied and has a call count of 0, some of its
10386       // pre-requisites may not be satisfied yet.
10387       if (it->expectation_base()->call_count_ == 0) {
10388         it->expectation_base()->FindUnsatisfiedPrerequisites(result);
10389       }
10390     } else {
10391       // Now that we know *it is unsatisfied, we are not so interested
10392       // in whether its pre-requisites are satisfied.  Therefore we
10393       // don't recursively call FindUnsatisfiedPrerequisites() here.
10394       *result += *it;
10395     }
10396   }
10397 }
10398 
10399 // Describes how many times a function call matching this
10400 // expectation has occurred.
DescribeCallCountTo(::std::ostream * os) const10401 void ExpectationBase::DescribeCallCountTo(::std::ostream* os) const
10402     GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
10403   g_gmock_mutex.AssertHeld();
10404 
10405   // Describes how many times the function is expected to be called.
10406   *os << "         Expected: to be ";
10407   cardinality().DescribeTo(os);
10408   *os << "\n           Actual: ";
10409   Cardinality::DescribeActualCallCountTo(call_count(), os);
10410 
10411   // Describes the state of the expectation (e.g. is it satisfied?
10412   // is it active?).
10413   *os << " - "
10414       << (IsOverSaturated()
10415               ? "over-saturated"
10416               : IsSaturated() ? "saturated"
10417                               : IsSatisfied() ? "satisfied" : "unsatisfied")
10418       << " and " << (is_retired() ? "retired" : "active");
10419 }
10420 
10421 // Checks the action count (i.e. the number of WillOnce() and
10422 // WillRepeatedly() clauses) against the cardinality if this hasn't
10423 // been done before.  Prints a warning if there are too many or too
10424 // few actions.
CheckActionCountIfNotDone() const10425 void ExpectationBase::CheckActionCountIfNotDone() const
10426     GTEST_LOCK_EXCLUDED_(mutex_) {
10427   bool should_check = false;
10428   {
10429     MutexLock l(&mutex_);
10430     if (!action_count_checked_) {
10431       action_count_checked_ = true;
10432       should_check = true;
10433     }
10434   }
10435 
10436   if (should_check) {
10437     if (!cardinality_specified_) {
10438       // The cardinality was inferred - no need to check the action
10439       // count against it.
10440       return;
10441     }
10442 
10443     // The cardinality was explicitly specified.
10444     const int action_count = static_cast<int>(untyped_actions_.size());
10445     const int upper_bound = cardinality().ConservativeUpperBound();
10446     const int lower_bound = cardinality().ConservativeLowerBound();
10447     bool too_many;  // True if there are too many actions, or false
10448     // if there are too few.
10449     if (action_count > upper_bound ||
10450         (action_count == upper_bound && repeated_action_specified_)) {
10451       too_many = true;
10452     } else if (0 < action_count && action_count < lower_bound &&
10453                !repeated_action_specified_) {
10454       too_many = false;
10455     } else {
10456       return;
10457     }
10458 
10459     ::std::stringstream ss;
10460     DescribeLocationTo(&ss);
10461     ss << "Too " << (too_many ? "many" : "few") << " actions specified in "
10462        << source_text() << "...\n"
10463        << "Expected to be ";
10464     cardinality().DescribeTo(&ss);
10465     ss << ", but has " << (too_many ? "" : "only ") << action_count
10466        << " WillOnce()" << (action_count == 1 ? "" : "s");
10467     if (repeated_action_specified_) {
10468       ss << " and a WillRepeatedly()";
10469     }
10470     ss << ".";
10471     Log(kWarning, ss.str(), -1);  // -1 means "don't print stack trace".
10472   }
10473 }
10474 
10475 // Implements the .Times() clause.
UntypedTimes(const Cardinality & a_cardinality)10476 void ExpectationBase::UntypedTimes(const Cardinality& a_cardinality) {
10477   if (last_clause_ == kTimes) {
10478     ExpectSpecProperty(false,
10479                        ".Times() cannot appear "
10480                        "more than once in an EXPECT_CALL().");
10481   } else {
10482     ExpectSpecProperty(last_clause_ < kTimes,
10483                        ".Times() cannot appear after "
10484                        ".InSequence(), .WillOnce(), .WillRepeatedly(), "
10485                        "or .RetiresOnSaturation().");
10486   }
10487   last_clause_ = kTimes;
10488 
10489   SpecifyCardinality(a_cardinality);
10490 }
10491 
10492 // Points to the implicit sequence introduced by a living InSequence
10493 // object (if any) in the current thread or NULL.
10494 GTEST_API_ ThreadLocal<Sequence*> g_gmock_implicit_sequence;
10495 
10496 // Reports an uninteresting call (whose description is in msg) in the
10497 // manner specified by 'reaction'.
ReportUninterestingCall(CallReaction reaction,const string & msg)10498 void ReportUninterestingCall(CallReaction reaction, const string& msg) {
10499   switch (reaction) {
10500   case kAllow:
10501     Log(kInfo, msg, 3);
10502     break;
10503   case kWarn:
10504     Log(kWarning, msg, 3);
10505     break;
10506   default:  // FAIL
10507     Expect(false, NULL, -1, msg);
10508   }
10509 }
10510 
UntypedFunctionMockerBase()10511 UntypedFunctionMockerBase::UntypedFunctionMockerBase()
10512     : mock_obj_(NULL), name_("") {}
10513 
~UntypedFunctionMockerBase()10514 UntypedFunctionMockerBase::~UntypedFunctionMockerBase() {}
10515 
10516 // Sets the mock object this mock method belongs to, and registers
10517 // this information in the global mock registry.  Will be called
10518 // whenever an EXPECT_CALL() or ON_CALL() is executed on this mock
10519 // method.
RegisterOwner(const void * mock_obj)10520 void UntypedFunctionMockerBase::RegisterOwner(const void* mock_obj)
10521     GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
10522   {
10523     MutexLock l(&g_gmock_mutex);
10524     mock_obj_ = mock_obj;
10525   }
10526   Mock::Register(mock_obj, this);
10527 }
10528 
10529 // Sets the mock object this mock method belongs to, and sets the name
10530 // of the mock function.  Will be called upon each invocation of this
10531 // mock function.
SetOwnerAndName(const void * mock_obj,const char * name)10532 void UntypedFunctionMockerBase::SetOwnerAndName(const void* mock_obj,
10533                                                 const char* name)
10534     GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
10535   // We protect name_ under g_gmock_mutex in case this mock function
10536   // is called from two threads concurrently.
10537   MutexLock l(&g_gmock_mutex);
10538   mock_obj_ = mock_obj;
10539   name_ = name;
10540 }
10541 
10542 // Returns the name of the function being mocked.  Must be called
10543 // after RegisterOwner() or SetOwnerAndName() has been called.
MockObject() const10544 const void* UntypedFunctionMockerBase::MockObject() const
10545     GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
10546   const void* mock_obj;
10547   {
10548     // We protect mock_obj_ under g_gmock_mutex in case this mock
10549     // function is called from two threads concurrently.
10550     MutexLock l(&g_gmock_mutex);
10551     Assert(mock_obj_ != NULL, __FILE__, __LINE__,
10552            "MockObject() must not be called before RegisterOwner() or "
10553            "SetOwnerAndName() has been called.");
10554     mock_obj = mock_obj_;
10555   }
10556   return mock_obj;
10557 }
10558 
10559 // Returns the name of this mock method.  Must be called after
10560 // SetOwnerAndName() has been called.
Name() const10561 const char* UntypedFunctionMockerBase::Name() const
10562     GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
10563   const char* name;
10564   {
10565     // We protect name_ under g_gmock_mutex in case this mock
10566     // function is called from two threads concurrently.
10567     MutexLock l(&g_gmock_mutex);
10568     Assert(name_ != NULL, __FILE__, __LINE__,
10569            "Name() must not be called before SetOwnerAndName() has "
10570            "been called.");
10571     name = name_;
10572   }
10573   return name;
10574 }
10575 
10576 // Calculates the result of invoking this mock function with the given
10577 // arguments, prints it, and returns it.  The caller is responsible
10578 // for deleting the result.
10579 const UntypedActionResultHolderBase*
UntypedInvokeWith(const void * const untyped_args)10580 UntypedFunctionMockerBase::UntypedInvokeWith(const void* const untyped_args)
10581     GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
10582   if (untyped_expectations_.size() == 0) {
10583     // No expectation is set on this mock method - we have an
10584     // uninteresting call.
10585 
10586     // We must get Google Mock's reaction on uninteresting calls
10587     // made on this mock object BEFORE performing the action,
10588     // because the action may DELETE the mock object and make the
10589     // following expression meaningless.
10590     const CallReaction reaction =
10591         Mock::GetReactionOnUninterestingCalls(MockObject());
10592 
10593     // True iff we need to print this call's arguments and return
10594     // value.  This definition must be kept in sync with
10595     // the behavior of ReportUninterestingCall().
10596     const bool need_to_report_uninteresting_call =
10597         // If the user allows this uninteresting call, we print it
10598         // only when he wants informational messages.
10599         reaction == kAllow ? LogIsVisible(kInfo) :
10600                            // If the user wants this to be a warning, we print
10601                            // it only when he wants to see warnings.
10602             reaction == kWarn
10603                 ? LogIsVisible(kWarning)
10604                 :
10605                 // Otherwise, the user wants this to be an error, and we
10606                 // should always print detailed information in the error.
10607                 true;
10608 
10609     if (!need_to_report_uninteresting_call) {
10610       // Perform the action without printing the call information.
10611       return this->UntypedPerformDefaultAction(untyped_args, "");
10612     }
10613 
10614     // Warns about the uninteresting call.
10615     ::std::stringstream ss;
10616     this->UntypedDescribeUninterestingCall(untyped_args, &ss);
10617 
10618     // Calculates the function result.
10619     const UntypedActionResultHolderBase* const result =
10620         this->UntypedPerformDefaultAction(untyped_args, ss.str());
10621 
10622     // Prints the function result.
10623     if (result != NULL) result->PrintAsActionResult(&ss);
10624 
10625     ReportUninterestingCall(reaction, ss.str());
10626     return result;
10627   }
10628 
10629   bool is_excessive = false;
10630   ::std::stringstream ss;
10631   ::std::stringstream why;
10632   ::std::stringstream loc;
10633   const void* untyped_action = NULL;
10634 
10635   // The UntypedFindMatchingExpectation() function acquires and
10636   // releases g_gmock_mutex.
10637   const ExpectationBase* const untyped_expectation =
10638       this->UntypedFindMatchingExpectation(untyped_args, &untyped_action,
10639                                            &is_excessive, &ss, &why);
10640   const bool found = untyped_expectation != NULL;
10641 
10642   // True iff we need to print the call's arguments and return value.
10643   // This definition must be kept in sync with the uses of Expect()
10644   // and Log() in this function.
10645   const bool need_to_report_call =
10646       !found || is_excessive || LogIsVisible(kInfo);
10647   if (!need_to_report_call) {
10648     // Perform the action without printing the call information.
10649     return untyped_action == NULL
10650                ? this->UntypedPerformDefaultAction(untyped_args, "")
10651                : this->UntypedPerformAction(untyped_action, untyped_args);
10652   }
10653 
10654   ss << "    Function call: " << Name();
10655   this->UntypedPrintArgs(untyped_args, &ss);
10656 
10657   // In case the action deletes a piece of the expectation, we
10658   // generate the message beforehand.
10659   if (found && !is_excessive) {
10660     untyped_expectation->DescribeLocationTo(&loc);
10661   }
10662 
10663   const UntypedActionResultHolderBase* const result =
10664       untyped_action == NULL
10665           ? this->UntypedPerformDefaultAction(untyped_args, ss.str())
10666           : this->UntypedPerformAction(untyped_action, untyped_args);
10667   if (result != NULL) result->PrintAsActionResult(&ss);
10668   ss << "\n" << why.str();
10669 
10670   if (!found) {
10671     // No expectation matches this call - reports a failure.
10672     Expect(false, NULL, -1, ss.str());
10673   } else if (is_excessive) {
10674     // We had an upper-bound violation and the failure message is in ss.
10675     Expect(false, untyped_expectation->file(), untyped_expectation->line(),
10676            ss.str());
10677   } else {
10678     // We had an expected call and the matching expectation is
10679     // described in ss.
10680     Log(kInfo, loc.str() + ss.str(), 2);
10681   }
10682 
10683   return result;
10684 }
10685 
10686 // Returns an Expectation object that references and co-owns exp,
10687 // which must be an expectation on this mock function.
GetHandleOf(ExpectationBase * exp)10688 Expectation UntypedFunctionMockerBase::GetHandleOf(ExpectationBase* exp) {
10689   for (UntypedExpectations::const_iterator it = untyped_expectations_.begin();
10690        it != untyped_expectations_.end(); ++it) {
10691     if (it->get() == exp) {
10692       return Expectation(*it);
10693     }
10694   }
10695 
10696   Assert(false, __FILE__, __LINE__, "Cannot find expectation.");
10697   return Expectation();
10698   // The above statement is just to make the code compile, and will
10699   // never be executed.
10700 }
10701 
10702 // Verifies that all expectations on this mock function have been
10703 // satisfied.  Reports one or more Google Test non-fatal failures
10704 // and returns false if not.
VerifyAndClearExpectationsLocked()10705 bool UntypedFunctionMockerBase::VerifyAndClearExpectationsLocked()
10706     GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
10707   g_gmock_mutex.AssertHeld();
10708   bool expectations_met = true;
10709   for (UntypedExpectations::const_iterator it = untyped_expectations_.begin();
10710        it != untyped_expectations_.end(); ++it) {
10711     ExpectationBase* const untyped_expectation = it->get();
10712     if (untyped_expectation->IsOverSaturated()) {
10713       // There was an upper-bound violation.  Since the error was
10714       // already reported when it occurred, there is no need to do
10715       // anything here.
10716       expectations_met = false;
10717     } else if (!untyped_expectation->IsSatisfied()) {
10718       expectations_met = false;
10719       ::std::stringstream ss;
10720       ss << "Actual function call count doesn't match "
10721          << untyped_expectation->source_text() << "...\n";
10722       // No need to show the source file location of the expectation
10723       // in the description, as the Expect() call that follows already
10724       // takes care of it.
10725       untyped_expectation->MaybeDescribeExtraMatcherTo(&ss);
10726       untyped_expectation->DescribeCallCountTo(&ss);
10727       Expect(false, untyped_expectation->file(), untyped_expectation->line(),
10728              ss.str());
10729     }
10730   }
10731 
10732   // Deleting our expectations may trigger other mock objects to be deleted, for
10733   // example if an action contains a reference counted smart pointer to that
10734   // mock object, and that is the last reference. So if we delete our
10735   // expectations within the context of the global mutex we may deadlock when
10736   // this method is called again. Instead, make a copy of the set of
10737   // expectations to delete, clear our set within the mutex, and then clear the
10738   // copied set outside of it.
10739   UntypedExpectations expectations_to_delete;
10740   untyped_expectations_.swap(expectations_to_delete);
10741 
10742   g_gmock_mutex.Unlock();
10743   expectations_to_delete.clear();
10744   g_gmock_mutex.Lock();
10745 
10746   return expectations_met;
10747 }
10748 
10749 }  // namespace internal
10750 
10751 // Class Mock.
10752 
10753 namespace {
10754 
10755 typedef std::set<internal::UntypedFunctionMockerBase*> FunctionMockers;
10756 
10757 // The current state of a mock object.  Such information is needed for
10758 // detecting leaked mock objects and explicitly verifying a mock's
10759 // expectations.
10760 struct MockObjectState {
MockObjectStatetesting::__anonf4ff90250711::MockObjectState10761   MockObjectState()
10762       : first_used_file(NULL), first_used_line(-1), leakable(false) {}
10763 
10764   // Where in the source file an ON_CALL or EXPECT_CALL is first
10765   // invoked on this mock object.
10766   const char* first_used_file;
10767   int first_used_line;
10768   ::std::string first_used_test_case;
10769   ::std::string first_used_test;
10770   bool leakable;                     // true iff it's OK to leak the object.
10771   FunctionMockers function_mockers;  // All registered methods of the object.
10772 };
10773 
10774 // A global registry holding the state of all mock objects that are
10775 // alive.  A mock object is added to this registry the first time
10776 // Mock::AllowLeak(), ON_CALL(), or EXPECT_CALL() is called on it.  It
10777 // is removed from the registry in the mock object's destructor.
10778 class MockObjectRegistry {
10779  public:
10780   // Maps a mock object (identified by its address) to its state.
10781   typedef std::map<const void*, MockObjectState> StateMap;
10782 
10783   // This destructor will be called when a program exits, after all
10784   // tests in it have been run.  By then, there should be no mock
10785   // object alive.  Therefore we report any living object as test
10786   // failure, unless the user explicitly asked us to ignore it.
~MockObjectRegistry()10787   ~MockObjectRegistry() {
10788     // "using ::std::cout;" doesn't work with Symbian's STLport, where cout is
10789     // a macro.
10790 
10791     if (!GMOCK_FLAG(catch_leaked_mocks)) return;
10792 
10793     int leaked_count = 0;
10794     for (StateMap::const_iterator it = states_.begin(); it != states_.end();
10795          ++it) {
10796       if (it->second.leakable)  // The user said it's fine to leak this object.
10797         continue;
10798 
10799       // TODO(wan@google.com): Print the type of the leaked object.
10800       // This can help the user identify the leaked object.
10801       std::cout << "\n";
10802       const MockObjectState& state = it->second;
10803       std::cout << internal::FormatFileLocation(state.first_used_file,
10804                                                 state.first_used_line);
10805       std::cout << " ERROR: this mock object";
10806       if (state.first_used_test != "") {
10807         std::cout << " (used in test " << state.first_used_test_case << "."
10808                   << state.first_used_test << ")";
10809       }
10810       std::cout << " should be deleted but never is. Its address is @"
10811                 << it->first << ".";
10812       leaked_count++;
10813     }
10814     if (leaked_count > 0) {
10815       std::cout << "\nERROR: " << leaked_count << " leaked mock "
10816                 << (leaked_count == 1 ? "object" : "objects")
10817                 << " found at program exit.\n";
10818       std::cout.flush();
10819       ::std::cerr.flush();
10820       // RUN_ALL_TESTS() has already returned when this destructor is
10821       // called.  Therefore we cannot use the normal Google Test
10822       // failure reporting mechanism.
10823       _exit(1);  // We cannot call exit() as it is not reentrant and
10824                  // may already have been called.
10825     }
10826   }
10827 
states()10828   StateMap& states() { return states_; }
10829 
10830  private:
10831   StateMap states_;
10832 };
10833 
10834 // Protected by g_gmock_mutex.
10835 MockObjectRegistry g_mock_object_registry;
10836 
10837 // Maps a mock object to the reaction Google Mock should have when an
10838 // uninteresting method is called.  Protected by g_gmock_mutex.
10839 std::map<const void*, internal::CallReaction> g_uninteresting_call_reaction;
10840 
10841 // Sets the reaction Google Mock should have when an uninteresting
10842 // method of the given mock object is called.
SetReactionOnUninterestingCalls(const void * mock_obj,internal::CallReaction reaction)10843 void SetReactionOnUninterestingCalls(const void* mock_obj,
10844                                      internal::CallReaction reaction)
10845     GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
10846   internal::MutexLock l(&internal::g_gmock_mutex);
10847   g_uninteresting_call_reaction[mock_obj] = reaction;
10848 }
10849 
10850 }  // namespace
10851 
10852 // Tells Google Mock to allow uninteresting calls on the given mock
10853 // object.
AllowUninterestingCalls(const void * mock_obj)10854 void Mock::AllowUninterestingCalls(const void* mock_obj)
10855     GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
10856   SetReactionOnUninterestingCalls(mock_obj, internal::kAllow);
10857 }
10858 
10859 // Tells Google Mock to warn the user about uninteresting calls on the
10860 // given mock object.
WarnUninterestingCalls(const void * mock_obj)10861 void Mock::WarnUninterestingCalls(const void* mock_obj)
10862     GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
10863   SetReactionOnUninterestingCalls(mock_obj, internal::kWarn);
10864 }
10865 
10866 // Tells Google Mock to fail uninteresting calls on the given mock
10867 // object.
FailUninterestingCalls(const void * mock_obj)10868 void Mock::FailUninterestingCalls(const void* mock_obj)
10869     GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
10870   SetReactionOnUninterestingCalls(mock_obj, internal::kFail);
10871 }
10872 
10873 // Tells Google Mock the given mock object is being destroyed and its
10874 // entry in the call-reaction table should be removed.
UnregisterCallReaction(const void * mock_obj)10875 void Mock::UnregisterCallReaction(const void* mock_obj)
10876     GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
10877   internal::MutexLock l(&internal::g_gmock_mutex);
10878   g_uninteresting_call_reaction.erase(mock_obj);
10879 }
10880 
10881 // Returns the reaction Google Mock will have on uninteresting calls
10882 // made on the given mock object.
GetReactionOnUninterestingCalls(const void * mock_obj)10883 internal::CallReaction Mock::GetReactionOnUninterestingCalls(
10884     const void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
10885   internal::MutexLock l(&internal::g_gmock_mutex);
10886   return (g_uninteresting_call_reaction.count(mock_obj) == 0)
10887              ? internal::kDefault
10888              : g_uninteresting_call_reaction[mock_obj];
10889 }
10890 
10891 // Tells Google Mock to ignore mock_obj when checking for leaked mock
10892 // objects.
AllowLeak(const void * mock_obj)10893 void Mock::AllowLeak(const void* mock_obj)
10894     GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
10895   internal::MutexLock l(&internal::g_gmock_mutex);
10896   g_mock_object_registry.states()[mock_obj].leakable = true;
10897 }
10898 
10899 // Verifies and clears all expectations on the given mock object.  If
10900 // the expectations aren't satisfied, generates one or more Google
10901 // Test non-fatal failures and returns false.
VerifyAndClearExpectations(void * mock_obj)10902 bool Mock::VerifyAndClearExpectations(void* mock_obj)
10903     GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
10904   internal::MutexLock l(&internal::g_gmock_mutex);
10905   return VerifyAndClearExpectationsLocked(mock_obj);
10906 }
10907 
10908 // Verifies all expectations on the given mock object and clears its
10909 // default actions and expectations.  Returns true iff the
10910 // verification was successful.
VerifyAndClear(void * mock_obj)10911 bool Mock::VerifyAndClear(void* mock_obj)
10912     GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
10913   internal::MutexLock l(&internal::g_gmock_mutex);
10914   ClearDefaultActionsLocked(mock_obj);
10915   return VerifyAndClearExpectationsLocked(mock_obj);
10916 }
10917 
10918 // Verifies and clears all expectations on the given mock object.  If
10919 // the expectations aren't satisfied, generates one or more Google
10920 // Test non-fatal failures and returns false.
VerifyAndClearExpectationsLocked(void * mock_obj)10921 bool Mock::VerifyAndClearExpectationsLocked(void* mock_obj)
10922     GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) {
10923   internal::g_gmock_mutex.AssertHeld();
10924   if (g_mock_object_registry.states().count(mock_obj) == 0) {
10925     // No EXPECT_CALL() was set on the given mock object.
10926     return true;
10927   }
10928 
10929   // Verifies and clears the expectations on each mock method in the
10930   // given mock object.
10931   bool expectations_met = true;
10932   FunctionMockers& mockers =
10933       g_mock_object_registry.states()[mock_obj].function_mockers;
10934   for (FunctionMockers::const_iterator it = mockers.begin();
10935        it != mockers.end(); ++it) {
10936     if (!(*it)->VerifyAndClearExpectationsLocked()) {
10937       expectations_met = false;
10938     }
10939   }
10940 
10941   // We don't clear the content of mockers, as they may still be
10942   // needed by ClearDefaultActionsLocked().
10943   return expectations_met;
10944 }
10945 
10946 // Registers a mock object and a mock method it owns.
Register(const void * mock_obj,internal::UntypedFunctionMockerBase * mocker)10947 void Mock::Register(const void* mock_obj,
10948                     internal::UntypedFunctionMockerBase* mocker)
10949     GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
10950   internal::MutexLock l(&internal::g_gmock_mutex);
10951   g_mock_object_registry.states()[mock_obj].function_mockers.insert(mocker);
10952 }
10953 
10954 // Tells Google Mock where in the source code mock_obj is used in an
10955 // ON_CALL or EXPECT_CALL.  In case mock_obj is leaked, this
10956 // information helps the user identify which object it is.
RegisterUseByOnCallOrExpectCall(const void * mock_obj,const char * file,int line)10957 void Mock::RegisterUseByOnCallOrExpectCall(const void* mock_obj,
10958                                            const char* file, int line)
10959     GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
10960   internal::MutexLock l(&internal::g_gmock_mutex);
10961   MockObjectState& state = g_mock_object_registry.states()[mock_obj];
10962   if (state.first_used_file == NULL) {
10963     state.first_used_file = file;
10964     state.first_used_line = line;
10965     const TestInfo* const test_info =
10966         UnitTest::GetInstance()->current_test_info();
10967     if (test_info != NULL) {
10968       // TODO(wan@google.com): record the test case name when the
10969       // ON_CALL or EXPECT_CALL is invoked from SetUpTestCase() or
10970       // TearDownTestCase().
10971       state.first_used_test_case = test_info->test_case_name();
10972       state.first_used_test = test_info->name();
10973     }
10974   }
10975 }
10976 
10977 // Unregisters a mock method; removes the owning mock object from the
10978 // registry when the last mock method associated with it has been
10979 // unregistered.  This is called only in the destructor of
10980 // FunctionMockerBase.
UnregisterLocked(internal::UntypedFunctionMockerBase * mocker)10981 void Mock::UnregisterLocked(internal::UntypedFunctionMockerBase* mocker)
10982     GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) {
10983   internal::g_gmock_mutex.AssertHeld();
10984   for (MockObjectRegistry::StateMap::iterator it =
10985            g_mock_object_registry.states().begin();
10986        it != g_mock_object_registry.states().end(); ++it) {
10987     FunctionMockers& mockers = it->second.function_mockers;
10988     if (mockers.erase(mocker) > 0) {
10989       // mocker was in mockers and has been just removed.
10990       if (mockers.empty()) {
10991         g_mock_object_registry.states().erase(it);
10992       }
10993       return;
10994     }
10995   }
10996 }
10997 
10998 // Clears all ON_CALL()s set on the given mock object.
ClearDefaultActionsLocked(void * mock_obj)10999 void Mock::ClearDefaultActionsLocked(void* mock_obj)
11000     GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) {
11001   internal::g_gmock_mutex.AssertHeld();
11002 
11003   if (g_mock_object_registry.states().count(mock_obj) == 0) {
11004     // No ON_CALL() was set on the given mock object.
11005     return;
11006   }
11007 
11008   // Clears the default actions for each mock method in the given mock
11009   // object.
11010   FunctionMockers& mockers =
11011       g_mock_object_registry.states()[mock_obj].function_mockers;
11012   for (FunctionMockers::const_iterator it = mockers.begin();
11013        it != mockers.end(); ++it) {
11014     (*it)->ClearDefaultActionsLocked();
11015   }
11016 
11017   // We don't clear the content of mockers, as they may still be
11018   // needed by VerifyAndClearExpectationsLocked().
11019 }
11020 
Expectation()11021 Expectation::Expectation() {}
11022 
Expectation(const internal::linked_ptr<internal::ExpectationBase> & an_expectation_base)11023 Expectation::Expectation(
11024     const internal::linked_ptr<internal::ExpectationBase>& an_expectation_base)
11025     : expectation_base_(an_expectation_base) {}
11026 
~Expectation()11027 Expectation::~Expectation() {}
11028 
11029 // Adds an expectation to a sequence.
AddExpectation(const Expectation & expectation) const11030 void Sequence::AddExpectation(const Expectation& expectation) const {
11031   if (*last_expectation_ != expectation) {
11032     if (last_expectation_->expectation_base() != NULL) {
11033       expectation.expectation_base()->immediate_prerequisites_ +=
11034           *last_expectation_;
11035     }
11036     *last_expectation_ = expectation;
11037   }
11038 }
11039 
11040 // Creates the implicit sequence if there isn't one.
InSequence()11041 InSequence::InSequence() {
11042   if (internal::g_gmock_implicit_sequence.get() == NULL) {
11043     internal::g_gmock_implicit_sequence.set(new Sequence);
11044     sequence_created_ = true;
11045   } else {
11046     sequence_created_ = false;
11047   }
11048 }
11049 
11050 // Deletes the implicit sequence if it was created by the constructor
11051 // of this object.
~InSequence()11052 InSequence::~InSequence() {
11053   if (sequence_created_) {
11054     delete internal::g_gmock_implicit_sequence.get();
11055     internal::g_gmock_implicit_sequence.set(NULL);
11056   }
11057 }
11058 
11059 }  // namespace testing
11060 // Copyright 2008, Google Inc.
11061 // All rights reserved.
11062 //
11063 // Redistribution and use in source and binary forms, with or without
11064 // modification, are permitted provided that the following conditions are
11065 // met:
11066 //
11067 //     * Redistributions of source code must retain the above copyright
11068 // notice, this list of conditions and the following disclaimer.
11069 //     * Redistributions in binary form must reproduce the above
11070 // copyright notice, this list of conditions and the following disclaimer
11071 // in the documentation and/or other materials provided with the
11072 // distribution.
11073 //     * Neither the name of Google Inc. nor the names of its
11074 // contributors may be used to endorse or promote products derived from
11075 // this software without specific prior written permission.
11076 //
11077 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
11078 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
11079 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
11080 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
11081 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
11082 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
11083 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
11084 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
11085 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
11086 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
11087 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
11088 //
11089 // Author: wan@google.com (Zhanyong Wan)
11090 
11091 namespace testing {
11092 
11093 // TODO(wan@google.com): support using environment variables to
11094 // control the flag values, like what Google Test does.
11095 
11096 GMOCK_DEFINE_bool_(catch_leaked_mocks, true,
11097                    "true iff Google Mock should report leaked mock objects "
11098                    "as failures.");
11099 
11100 GMOCK_DEFINE_string_(verbose, internal::kWarningVerbosity,
11101                      "Controls how verbose Google Mock's output is."
11102                      "  Valid values:\n"
11103                      "  info    - prints all messages.\n"
11104                      "  warning - prints warnings and errors.\n"
11105                      "  error   - prints errors only.");
11106 
11107 namespace internal {
11108 
11109 // Parses a string as a command line flag.  The string should have the
11110 // format "--gmock_flag=value".  When def_optional is true, the
11111 // "=value" part can be omitted.
11112 //
11113 // Returns the value of the flag, or NULL if the parsing failed.
ParseGoogleMockFlagValue(const char * str,const char * flag,bool def_optional)11114 static const char* ParseGoogleMockFlagValue(const char* str, const char* flag,
11115                                             bool def_optional) {
11116   // str and flag must not be NULL.
11117   if (str == NULL || flag == NULL) return NULL;
11118 
11119   // The flag must start with "--gmock_".
11120   const std::string flag_str = std::string("--gmock_") + flag;
11121   const size_t flag_len = flag_str.length();
11122   if (strncmp(str, flag_str.c_str(), flag_len) != 0) return NULL;
11123 
11124   // Skips the flag name.
11125   const char* flag_end = str + flag_len;
11126 
11127   // When def_optional is true, it's OK to not have a "=value" part.
11128   if (def_optional && (flag_end[0] == '\0')) {
11129     return flag_end;
11130   }
11131 
11132   // If def_optional is true and there are more characters after the
11133   // flag name, or if def_optional is false, there must be a '=' after
11134   // the flag name.
11135   if (flag_end[0] != '=') return NULL;
11136 
11137   // Returns the string after "=".
11138   return flag_end + 1;
11139 }
11140 
11141 // Parses a string for a Google Mock bool flag, in the form of
11142 // "--gmock_flag=value".
11143 //
11144 // On success, stores the value of the flag in *value, and returns
11145 // true.  On failure, returns false without changing *value.
ParseGoogleMockBoolFlag(const char * str,const char * flag,bool * value)11146 static bool ParseGoogleMockBoolFlag(const char* str, const char* flag,
11147                                     bool* value) {
11148   // Gets the value of the flag as a string.
11149   const char* const value_str = ParseGoogleMockFlagValue(str, flag, true);
11150 
11151   // Aborts if the parsing failed.
11152   if (value_str == NULL) return false;
11153 
11154   // Converts the string value to a bool.
11155   *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F');
11156   return true;
11157 }
11158 
11159 // Parses a string for a Google Mock string flag, in the form of
11160 // "--gmock_flag=value".
11161 //
11162 // On success, stores the value of the flag in *value, and returns
11163 // true.  On failure, returns false without changing *value.
ParseGoogleMockStringFlag(const char * str,const char * flag,std::string * value)11164 static bool ParseGoogleMockStringFlag(const char* str, const char* flag,
11165                                       std::string* value) {
11166   // Gets the value of the flag as a string.
11167   const char* const value_str = ParseGoogleMockFlagValue(str, flag, false);
11168 
11169   // Aborts if the parsing failed.
11170   if (value_str == NULL) return false;
11171 
11172   // Sets *value to the value of the flag.
11173   *value = value_str;
11174   return true;
11175 }
11176 
11177 // The internal implementation of InitGoogleMock().
11178 //
11179 // The type parameter CharType can be instantiated to either char or
11180 // wchar_t.
11181 template <typename CharType>
InitGoogleMockImpl(int * argc,CharType ** argv)11182 void InitGoogleMockImpl(int* argc, CharType** argv) {
11183   // Makes sure Google Test is initialized.  InitGoogleTest() is
11184   // idempotent, so it's fine if the user has already called it.
11185   InitGoogleTest(argc, argv);
11186   if (*argc <= 0) return;
11187 
11188   for (int i = 1; i != *argc; i++) {
11189     const std::string arg_string = StreamableToString(argv[i]);
11190     const char* const arg = arg_string.c_str();
11191 
11192     // Do we see a Google Mock flag?
11193     if (ParseGoogleMockBoolFlag(arg, "catch_leaked_mocks",
11194                                 &GMOCK_FLAG(catch_leaked_mocks)) ||
11195         ParseGoogleMockStringFlag(arg, "verbose", &GMOCK_FLAG(verbose))) {
11196       // Yes.  Shift the remainder of the argv list left by one.  Note
11197       // that argv has (*argc + 1) elements, the last one always being
11198       // NULL.  The following loop moves the trailing NULL element as
11199       // well.
11200       for (int j = i; j != *argc; j++) {
11201         argv[j] = argv[j + 1];
11202       }
11203 
11204       // Decrements the argument count.
11205       (*argc)--;
11206 
11207       // We also need to decrement the iterator as we just removed
11208       // an element.
11209       i--;
11210     }
11211   }
11212 }
11213 
11214 }  // namespace internal
11215 
11216 // Initializes Google Mock.  This must be called before running the
11217 // tests.  In particular, it parses a command line for the flags that
11218 // Google Mock recognizes.  Whenever a Google Mock flag is seen, it is
11219 // removed from argv, and *argc is decremented.
11220 //
11221 // No value is returned.  Instead, the Google Mock flag variables are
11222 // updated.
11223 //
11224 // Since Google Test is needed for Google Mock to work, this function
11225 // also initializes Google Test and parses its flags, if that hasn't
11226 // been done.
InitGoogleMock(int * argc,char ** argv)11227 GTEST_API_ void InitGoogleMock(int* argc, char** argv) {
11228   internal::InitGoogleMockImpl(argc, argv);
11229 }
11230 
11231 // This overloaded version can be used in Windows programs compiled in
11232 // UNICODE mode.
InitGoogleMock(int * argc,wchar_t ** argv)11233 GTEST_API_ void InitGoogleMock(int* argc, wchar_t** argv) {
11234   internal::InitGoogleMockImpl(argc, argv);
11235 }
11236 
11237 }  // namespace testing
11238