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/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 
113 namespace testing {
114 
115 // This helper class can be used to mock out Google Test failure reporting
116 // so that we can test Google Test or code that builds on Google Test.
117 //
118 // An object of this class appends a TestPartResult object to the
119 // TestPartResultArray object given in the constructor whenever a Google Test
120 // failure is reported. It can either intercept only failures that are
121 // generated in the same thread that created this object or it can intercept
122 // all generated failures. The scope of this mock object can be controlled with
123 // the second argument to the two arguments constructor.
124 class GTEST_API_ ScopedFakeTestPartResultReporter
125     : public TestPartResultReporterInterface {
126  public:
127   // The two possible mocking modes of this object.
128   enum InterceptMode {
129     INTERCEPT_ONLY_CURRENT_THREAD,  // Intercepts only thread local failures.
130     INTERCEPT_ALL_THREADS           // Intercepts all failures.
131   };
132 
133   // The c'tor sets this object as the test part result reporter used
134   // by Google Test.  The 'result' parameter specifies where to report the
135   // results. This reporter will only catch failures generated in the current
136   // thread. DEPRECATED
137   explicit ScopedFakeTestPartResultReporter(TestPartResultArray* result);
138 
139   // Same as above, but you can choose the interception scope of this object.
140   ScopedFakeTestPartResultReporter(InterceptMode intercept_mode,
141                                    TestPartResultArray* result);
142 
143   // The d'tor restores the previous test part result reporter.
144   virtual ~ScopedFakeTestPartResultReporter();
145 
146   // Appends the TestPartResult object to the TestPartResultArray
147   // received in the constructor.
148   //
149   // This method is from the TestPartResultReporterInterface
150   // interface.
151   virtual void ReportTestPartResult(const TestPartResult& result);
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,
174                        const string& substr);
175   ~SingleFailureChecker();
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, (substr));\
220     {\
221       ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
222           ::testing::ScopedFakeTestPartResultReporter:: \
223           INTERCEPT_ONLY_CURRENT_THREAD, &gtest_failures);\
224       GTestExpectFatalFailureHelper::Execute();\
225     }\
226   } while (::testing::internal::AlwaysFalse())
227 
228 #define EXPECT_FATAL_FAILURE_ON_ALL_THREADS(statement, substr) \
229   do { \
230     class GTestExpectFatalFailureHelper {\
231      public:\
232       static void Execute() { statement; }\
233     };\
234     ::testing::TestPartResultArray gtest_failures;\
235     ::testing::internal::SingleFailureChecker gtest_checker(\
236         &gtest_failures, ::testing::TestPartResult::kFatalFailure, (substr));\
237     {\
238       ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
239           ::testing::ScopedFakeTestPartResultReporter:: \
240           INTERCEPT_ALL_THREADS, &gtest_failures);\
241       GTestExpectFatalFailureHelper::Execute();\
242     }\
243   } while (::testing::internal::AlwaysFalse())
244 
245 // A macro for testing Google Test assertions or code that's expected to
246 // generate Google Test non-fatal failures.  It asserts that the given
247 // statement will cause exactly one non-fatal Google Test failure with 'substr'
248 // being part of the failure message.
249 //
250 // There are two different versions of this macro. EXPECT_NONFATAL_FAILURE only
251 // affects and considers failures generated in the current thread and
252 // EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS does the same but for all threads.
253 //
254 // 'statement' is allowed to reference local variables and members of
255 // the current object.
256 //
257 // The verification of the assertion is done correctly even when the statement
258 // throws an exception or aborts the current function.
259 //
260 // Known restrictions:
261 //   - You cannot stream a failure message to this macro.
262 //
263 // Note that even though the implementations of the following two
264 // macros are much alike, we cannot refactor them to use a common
265 // helper macro, due to some peculiarity in how the preprocessor
266 // works.  If we do that, the code won't compile when the user gives
267 // EXPECT_NONFATAL_FAILURE() a statement that contains a macro that
268 // expands to code containing an unprotected comma.  The
269 // AcceptsMacroThatExpandsToUnprotectedComma test in gtest_unittest.cc
270 // catches that.
271 //
272 // For the same reason, we have to write
273 //   if (::testing::internal::AlwaysTrue()) { statement; }
274 // instead of
275 //   GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement)
276 // to avoid an MSVC warning on unreachable code.
277 #define EXPECT_NONFATAL_FAILURE(statement, substr) \
278   do {\
279     ::testing::TestPartResultArray gtest_failures;\
280     ::testing::internal::SingleFailureChecker gtest_checker(\
281         &gtest_failures, ::testing::TestPartResult::kNonFatalFailure, \
282         (substr));\
283     {\
284       ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
285           ::testing::ScopedFakeTestPartResultReporter:: \
286           INTERCEPT_ONLY_CURRENT_THREAD, &gtest_failures);\
287       if (::testing::internal::AlwaysTrue()) { statement; }\
288     }\
289   } while (::testing::internal::AlwaysFalse())
290 
291 #define EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(statement, substr) \
292   do {\
293     ::testing::TestPartResultArray gtest_failures;\
294     ::testing::internal::SingleFailureChecker gtest_checker(\
295         &gtest_failures, ::testing::TestPartResult::kNonFatalFailure, \
296         (substr));\
297     {\
298       ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
299           ::testing::ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, \
300           &gtest_failures);\
301       if (::testing::internal::AlwaysTrue()) { statement; }\
302     }\
303   } while (::testing::internal::AlwaysFalse())
304 
305 #endif  // GTEST_INCLUDE_GTEST_GTEST_SPI_H_
306 
307 #include <ctype.h>
308 #include <math.h>
309 #include <stdarg.h>
310 #include <stdio.h>
311 #include <stdlib.h>
312 #include <time.h>
313 #include <wchar.h>
314 #include <wctype.h>
315 
316 #include <algorithm>
317 #include <iomanip>
318 #include <limits>
319 #include <ostream>  // NOLINT
320 #include <sstream>
321 #include <vector>
322 
323 #if GTEST_OS_LINUX
324 
325 // TODO(kenton@google.com): Use autoconf to detect availability of
326 // gettimeofday().
327 # define GTEST_HAS_GETTIMEOFDAY_ 1
328 
329 # include <fcntl.h>  // NOLINT
330 # include <limits.h>  // NOLINT
331 # include <sched.h>  // NOLINT
332 // Declares vsnprintf().  This header is not available on Windows.
333 # include <strings.h>  // NOLINT
334 # include <sys/mman.h>  // NOLINT
335 # include <sys/time.h>  // NOLINT
336 # include <unistd.h>  // NOLINT
337 # include <string>
338 
339 #elif GTEST_OS_SYMBIAN
340 # define GTEST_HAS_GETTIMEOFDAY_ 1
341 # include <sys/time.h>  // NOLINT
342 
343 #elif GTEST_OS_ZOS
344 # define GTEST_HAS_GETTIMEOFDAY_ 1
345 # include <sys/time.h>  // NOLINT
346 
347 // On z/OS we additionally need strings.h for strcasecmp.
348 # include <strings.h>  // NOLINT
349 
350 #elif GTEST_OS_WINDOWS_MOBILE  // We are on Windows CE.
351 
352 # include <windows.h>  // NOLINT
353 
354 #elif GTEST_OS_WINDOWS  // We are on Windows proper.
355 
356 # include <io.h>  // NOLINT
357 # include <sys/timeb.h>  // NOLINT
358 # include <sys/types.h>  // NOLINT
359 # include <sys/stat.h>  // NOLINT
360 
361 # if GTEST_OS_WINDOWS_MINGW
362 // MinGW has gettimeofday() but not _ftime64().
363 // TODO(kenton@google.com): Use autoconf to detect availability of
364 //   gettimeofday().
365 // TODO(kenton@google.com): There are other ways to get the time on
366 //   Windows, like GetTickCount() or GetSystemTimeAsFileTime().  MinGW
367 //   supports these.  consider using them instead.
368 #  define GTEST_HAS_GETTIMEOFDAY_ 1
369 #  include <sys/time.h>  // NOLINT
370 # endif  // GTEST_OS_WINDOWS_MINGW
371 
372 // cpplint thinks that the header is already included, so we want to
373 // silence it.
374 # include <windows.h>  // NOLINT
375 
376 #else
377 
378 // Assume other platforms have gettimeofday().
379 // TODO(kenton@google.com): Use autoconf to detect availability of
380 //   gettimeofday().
381 # define GTEST_HAS_GETTIMEOFDAY_ 1
382 
383 // cpplint thinks that the header is already included, so we want to
384 // silence it.
385 # include <sys/time.h>  // NOLINT
386 # include <unistd.h>  // NOLINT
387 
388 #endif  // GTEST_OS_LINUX
389 
390 #if GTEST_HAS_EXCEPTIONS
391 # include <stdexcept>
392 #endif
393 
394 #if GTEST_CAN_STREAM_RESULTS_
395 # include <arpa/inet.h>  // NOLINT
396 # include <netdb.h>  // NOLINT
397 #endif
398 
399 // Indicates that this translation unit is part of Google Test's
400 // implementation.  It must come before gtest-internal-inl.h is
401 // included, or there will be a compiler error.  This trick is to
402 // prevent a user from accidentally including gtest-internal-inl.h in
403 // his code.
404 #define GTEST_IMPLEMENTATION_ 1
405 // Copyright 2005, Google Inc.
406 // All rights reserved.
407 //
408 // Redistribution and use in source and binary forms, with or without
409 // modification, are permitted provided that the following conditions are
410 // met:
411 //
412 //     * Redistributions of source code must retain the above copyright
413 // notice, this list of conditions and the following disclaimer.
414 //     * Redistributions in binary form must reproduce the above
415 // copyright notice, this list of conditions and the following disclaimer
416 // in the documentation and/or other materials provided with the
417 // distribution.
418 //     * Neither the name of Google Inc. nor the names of its
419 // contributors may be used to endorse or promote products derived from
420 // this software without specific prior written permission.
421 //
422 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
423 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
424 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
425 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
426 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
427 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
428 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
429 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
430 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
431 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
432 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
433 
434 // Utility functions and classes used by the Google C++ testing framework.
435 //
436 // Author: wan@google.com (Zhanyong Wan)
437 //
438 // This file contains purely Google Test's internal implementation.  Please
439 // DO NOT #INCLUDE IT IN A USER PROGRAM.
440 
441 #ifndef GTEST_SRC_GTEST_INTERNAL_INL_H_
442 #define GTEST_SRC_GTEST_INTERNAL_INL_H_
443 
444 // GTEST_IMPLEMENTATION_ is defined to 1 iff the current translation unit is
445 // part of Google Test's implementation; otherwise it's undefined.
446 #if !GTEST_IMPLEMENTATION_
447 // A user is trying to include this from his code - just say no.
448 # error "gtest-internal-inl.h is part of Google Test's internal implementation."
449 # error "It must not be included except by Google Test itself."
450 #endif  // GTEST_IMPLEMENTATION_
451 
452 #ifndef _WIN32_WCE
453 # include <errno.h>
454 #endif  // !_WIN32_WCE
455 #include <stddef.h>
456 #include <stdlib.h>  // For strtoll/_strtoul64/malloc/free.
457 #include <string.h>  // For memmove.
458 
459 #include <algorithm>
460 #include <string>
461 #include <vector>
462 
463 
464 #if GTEST_CAN_STREAM_RESULTS_
465 # include <arpa/inet.h>  // NOLINT
466 # include <netdb.h>  // NOLINT
467 #endif
468 
469 #if GTEST_OS_WINDOWS
470 # include <windows.h>  // NOLINT
471 #endif  // GTEST_OS_WINDOWS
472 
473 
474 namespace testing {
475 
476 // Declares the flags.
477 //
478 // We don't want the users to modify this flag in the code, but want
479 // Google Test's own unit tests to be able to access it. Therefore we
480 // declare it here as opposed to in gtest.h.
481 GTEST_DECLARE_bool_(death_test_use_fork);
482 
483 namespace internal {
484 
485 // The value of GetTestTypeId() as seen from within the Google Test
486 // library.  This is solely for testing GetTestTypeId().
487 GTEST_API_ extern const TypeId kTestTypeIdInGoogleTest;
488 
489 // Names of the flags (needed for parsing Google Test flags).
490 const char kAlsoRunDisabledTestsFlag[] = "also_run_disabled_tests";
491 const char kBreakOnFailureFlag[] = "break_on_failure";
492 const char kCatchExceptionsFlag[] = "catch_exceptions";
493 const char kColorFlag[] = "color";
494 const char kFilterFlag[] = "filter";
495 const char kListTestsFlag[] = "list_tests";
496 const char kOutputFlag[] = "output";
497 const char kPrintTimeFlag[] = "print_time";
498 const char kRandomSeedFlag[] = "random_seed";
499 const char kRepeatFlag[] = "repeat";
500 const char kShuffleFlag[] = "shuffle";
501 const char kStackTraceDepthFlag[] = "stack_trace_depth";
502 const char kStreamResultToFlag[] = "stream_result_to";
503 const char kThrowOnFailureFlag[] = "throw_on_failure";
504 
505 // A valid random seed must be in [1, kMaxRandomSeed].
506 const int kMaxRandomSeed = 99999;
507 
508 // g_help_flag is true iff the --help flag or an equivalent form is
509 // specified on the command line.
510 GTEST_API_ extern bool g_help_flag;
511 
512 // Returns the current time in milliseconds.
513 GTEST_API_ TimeInMillis GetTimeInMillis();
514 
515 // Returns true iff Google Test should use colors in the output.
516 GTEST_API_ bool ShouldUseColor(bool stdout_is_tty);
517 
518 // Formats the given time in milliseconds as seconds.
519 GTEST_API_ std::string FormatTimeInMillisAsSeconds(TimeInMillis ms);
520 
521 // Converts the given time in milliseconds to a date string in the ISO 8601
522 // format, without the timezone information.  N.B.: due to the use the
523 // non-reentrant localtime() function, this function is not thread safe.  Do
524 // not use it in any code that can be called from multiple threads.
525 GTEST_API_ std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms);
526 
527 // Parses a string for an Int32 flag, in the form of "--flag=value".
528 //
529 // On success, stores the value of the flag in *value, and returns
530 // true.  On failure, returns false without changing *value.
531 GTEST_API_ bool ParseInt32Flag(
532     const char* str, const char* flag, Int32* value);
533 
534 // Returns a random seed in range [1, kMaxRandomSeed] based on the
535 // given --gtest_random_seed flag value.
GetRandomSeedFromFlag(Int32 random_seed_flag)536 inline int GetRandomSeedFromFlag(Int32 random_seed_flag) {
537   const unsigned int raw_seed = (random_seed_flag == 0) ?
538       static_cast<unsigned int>(GetTimeInMillis()) :
539       static_cast<unsigned int>(random_seed_flag);
540 
541   // Normalizes the actual seed to range [1, kMaxRandomSeed] such that
542   // it's easy to type.
543   const int normalized_seed =
544       static_cast<int>((raw_seed - 1U) %
545                        static_cast<unsigned int>(kMaxRandomSeed)) + 1;
546   return normalized_seed;
547 }
548 
549 // Returns the first valid random seed after 'seed'.  The behavior is
550 // undefined if 'seed' is invalid.  The seed after kMaxRandomSeed is
551 // considered to be 1.
GetNextRandomSeed(int seed)552 inline int GetNextRandomSeed(int seed) {
553   GTEST_CHECK_(1 <= seed && seed <= kMaxRandomSeed)
554       << "Invalid random seed " << seed << " - must be in [1, "
555       << kMaxRandomSeed << "].";
556   const int next_seed = seed + 1;
557   return (next_seed > kMaxRandomSeed) ? 1 : next_seed;
558 }
559 
560 // This class saves the values of all Google Test flags in its c'tor, and
561 // restores them in its d'tor.
562 class GTestFlagSaver {
563  public:
564   // The c'tor.
GTestFlagSaver()565   GTestFlagSaver() {
566     also_run_disabled_tests_ = GTEST_FLAG(also_run_disabled_tests);
567     break_on_failure_ = GTEST_FLAG(break_on_failure);
568     catch_exceptions_ = GTEST_FLAG(catch_exceptions);
569     color_ = GTEST_FLAG(color);
570     death_test_style_ = GTEST_FLAG(death_test_style);
571     death_test_use_fork_ = GTEST_FLAG(death_test_use_fork);
572     filter_ = GTEST_FLAG(filter);
573     internal_run_death_test_ = GTEST_FLAG(internal_run_death_test);
574     list_tests_ = GTEST_FLAG(list_tests);
575     output_ = GTEST_FLAG(output);
576     print_time_ = GTEST_FLAG(print_time);
577     random_seed_ = GTEST_FLAG(random_seed);
578     repeat_ = GTEST_FLAG(repeat);
579     shuffle_ = GTEST_FLAG(shuffle);
580     stack_trace_depth_ = GTEST_FLAG(stack_trace_depth);
581     stream_result_to_ = GTEST_FLAG(stream_result_to);
582     throw_on_failure_ = GTEST_FLAG(throw_on_failure);
583   }
584 
585   // The d'tor is not virtual.  DO NOT INHERIT FROM THIS CLASS.
~GTestFlagSaver()586   ~GTestFlagSaver() {
587     GTEST_FLAG(also_run_disabled_tests) = also_run_disabled_tests_;
588     GTEST_FLAG(break_on_failure) = break_on_failure_;
589     GTEST_FLAG(catch_exceptions) = catch_exceptions_;
590     GTEST_FLAG(color) = color_;
591     GTEST_FLAG(death_test_style) = death_test_style_;
592     GTEST_FLAG(death_test_use_fork) = death_test_use_fork_;
593     GTEST_FLAG(filter) = filter_;
594     GTEST_FLAG(internal_run_death_test) = internal_run_death_test_;
595     GTEST_FLAG(list_tests) = list_tests_;
596     GTEST_FLAG(output) = output_;
597     GTEST_FLAG(print_time) = print_time_;
598     GTEST_FLAG(random_seed) = random_seed_;
599     GTEST_FLAG(repeat) = repeat_;
600     GTEST_FLAG(shuffle) = shuffle_;
601     GTEST_FLAG(stack_trace_depth) = stack_trace_depth_;
602     GTEST_FLAG(stream_result_to) = stream_result_to_;
603     GTEST_FLAG(throw_on_failure) = throw_on_failure_;
604   }
605 
606  private:
607   // Fields for saving the original values of flags.
608   bool also_run_disabled_tests_;
609   bool break_on_failure_;
610   bool catch_exceptions_;
611   std::string color_;
612   std::string death_test_style_;
613   bool death_test_use_fork_;
614   std::string filter_;
615   std::string internal_run_death_test_;
616   bool list_tests_;
617   std::string output_;
618   bool print_time_;
619   internal::Int32 random_seed_;
620   internal::Int32 repeat_;
621   bool shuffle_;
622   internal::Int32 stack_trace_depth_;
623   std::string stream_result_to_;
624   bool throw_on_failure_;
625 } GTEST_ATTRIBUTE_UNUSED_;
626 
627 // Converts a Unicode code point to a narrow string in UTF-8 encoding.
628 // code_point parameter is of type UInt32 because wchar_t may not be
629 // wide enough to contain a code point.
630 // If the code_point is not a valid Unicode code point
631 // (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted
632 // to "(Invalid Unicode 0xXXXXXXXX)".
633 GTEST_API_ std::string CodePointToUtf8(UInt32 code_point);
634 
635 // Converts a wide string to a narrow string in UTF-8 encoding.
636 // The wide string is assumed to have the following encoding:
637 //   UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS)
638 //   UTF-32 if sizeof(wchar_t) == 4 (on Linux)
639 // Parameter str points to a null-terminated wide string.
640 // Parameter num_chars may additionally limit the number
641 // of wchar_t characters processed. -1 is used when the entire string
642 // should be processed.
643 // If the string contains code points that are not valid Unicode code points
644 // (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
645 // as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
646 // and contains invalid UTF-16 surrogate pairs, values in those pairs
647 // will be encoded as individual Unicode characters from Basic Normal Plane.
648 GTEST_API_ std::string WideStringToUtf8(const wchar_t* str, int num_chars);
649 
650 // Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
651 // if the variable is present. If a file already exists at this location, this
652 // function will write over it. If the variable is present, but the file cannot
653 // be created, prints an error and exits.
654 void WriteToShardStatusFileIfNeeded();
655 
656 // Checks whether sharding is enabled by examining the relevant
657 // environment variable values. If the variables are present,
658 // but inconsistent (e.g., shard_index >= total_shards), prints
659 // an error and exits. If in_subprocess_for_death_test, sharding is
660 // disabled because it must only be applied to the original test
661 // process. Otherwise, we could filter out death tests we intended to execute.
662 GTEST_API_ bool ShouldShard(const char* total_shards_str,
663                             const char* shard_index_str,
664                             bool in_subprocess_for_death_test);
665 
666 // Parses the environment variable var as an Int32. If it is unset,
667 // returns default_val. If it is not an Int32, prints an error and
668 // and aborts.
669 GTEST_API_ Int32 Int32FromEnvOrDie(const char* env_var, Int32 default_val);
670 
671 // Given the total number of shards, the shard index, and the test id,
672 // returns true iff the test should be run on this shard. The test id is
673 // some arbitrary but unique non-negative integer assigned to each test
674 // method. Assumes that 0 <= shard_index < total_shards.
675 GTEST_API_ bool ShouldRunTestOnShard(
676     int total_shards, int shard_index, int test_id);
677 
678 // STL container utilities.
679 
680 // Returns the number of elements in the given container that satisfy
681 // the given predicate.
682 template <class Container, typename Predicate>
CountIf(const Container & c,Predicate predicate)683 inline int CountIf(const Container& c, Predicate predicate) {
684   // Implemented as an explicit loop since std::count_if() in libCstd on
685   // Solaris has a non-standard signature.
686   int count = 0;
687   for (typename Container::const_iterator it = c.begin(); it != c.end(); ++it) {
688     if (predicate(*it))
689       ++count;
690   }
691   return count;
692 }
693 
694 // Applies a function/functor to each element in the container.
695 template <class Container, typename Functor>
ForEach(const Container & c,Functor functor)696 void ForEach(const Container& c, Functor functor) {
697   std::for_each(c.begin(), c.end(), functor);
698 }
699 
700 // Returns the i-th element of the vector, or default_value if i is not
701 // in range [0, v.size()).
702 template <typename E>
GetElementOr(const std::vector<E> & v,int i,E default_value)703 inline E GetElementOr(const std::vector<E>& v, int i, E default_value) {
704   return (i < 0 || i >= static_cast<int>(v.size())) ? default_value : v[i];
705 }
706 
707 // Performs an in-place shuffle of a range of the vector's elements.
708 // 'begin' and 'end' are element indices as an STL-style range;
709 // i.e. [begin, end) are shuffled, where 'end' == size() means to
710 // shuffle to the end of the vector.
711 template <typename E>
ShuffleRange(internal::Random * random,int begin,int end,std::vector<E> * v)712 void ShuffleRange(internal::Random* random, int begin, int end,
713                   std::vector<E>* v) {
714   const int size = static_cast<int>(v->size());
715   GTEST_CHECK_(0 <= begin && begin <= size)
716       << "Invalid shuffle range start " << begin << ": must be in range [0, "
717       << size << "].";
718   GTEST_CHECK_(begin <= end && end <= size)
719       << "Invalid shuffle range finish " << end << ": must be in range ["
720       << begin << ", " << size << "].";
721 
722   // Fisher-Yates shuffle, from
723   // http://en.wikipedia.org/wiki/Fisher-Yates_shuffle
724   for (int range_width = end - begin; range_width >= 2; range_width--) {
725     const int last_in_range = begin + range_width - 1;
726     const int selected = begin + random->Generate(range_width);
727     std::swap((*v)[selected], (*v)[last_in_range]);
728   }
729 }
730 
731 // Performs an in-place shuffle of the vector's elements.
732 template <typename E>
Shuffle(internal::Random * random,std::vector<E> * v)733 inline void Shuffle(internal::Random* random, std::vector<E>* v) {
734   ShuffleRange(random, 0, static_cast<int>(v->size()), v);
735 }
736 
737 // A function for deleting an object.  Handy for being used as a
738 // functor.
739 template <typename T>
Delete(T * x)740 static void Delete(T* x) {
741   delete x;
742 }
743 
744 // A predicate that checks the key of a TestProperty against a known key.
745 //
746 // TestPropertyKeyIs is copyable.
747 class TestPropertyKeyIs {
748  public:
749   // Constructor.
750   //
751   // TestPropertyKeyIs has NO default constructor.
TestPropertyKeyIs(const std::string & key)752   explicit TestPropertyKeyIs(const std::string& key) : key_(key) {}
753 
754   // Returns true iff the test name of test property matches on key_.
operator ()(const TestProperty & test_property) const755   bool operator()(const TestProperty& test_property) const {
756     return test_property.key() == key_;
757   }
758 
759  private:
760   std::string key_;
761 };
762 
763 // Class UnitTestOptions.
764 //
765 // This class contains functions for processing options the user
766 // specifies when running the tests.  It has only static members.
767 //
768 // In most cases, the user can specify an option using either an
769 // environment variable or a command line flag.  E.g. you can set the
770 // test filter using either GTEST_FILTER or --gtest_filter.  If both
771 // the variable and the flag are present, the latter overrides the
772 // former.
773 class GTEST_API_ UnitTestOptions {
774  public:
775   // Functions for processing the gtest_output flag.
776 
777   // Returns the output format, or "" for normal printed output.
778   static std::string GetOutputFormat();
779 
780   // Returns the absolute path of the requested output file, or the
781   // default (test_detail.xml in the original working directory) if
782   // none was explicitly specified.
783   static std::string GetAbsolutePathToOutputFile();
784 
785   // Functions for processing the gtest_filter flag.
786 
787   // Returns true iff the wildcard pattern matches the string.  The
788   // first ':' or '\0' character in pattern marks the end of it.
789   //
790   // This recursive algorithm isn't very efficient, but is clear and
791   // works well enough for matching test names, which are short.
792   static bool PatternMatchesString(const char *pattern, const char *str);
793 
794   // Returns true iff the user-specified filter matches the test case
795   // name and the test name.
796   static bool FilterMatchesTest(const std::string &test_case_name,
797                                 const std::string &test_name);
798 
799 #if GTEST_OS_WINDOWS
800   // Function for supporting the gtest_catch_exception flag.
801 
802   // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
803   // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
804   // This function is useful as an __except condition.
805   static int GTestShouldProcessSEH(DWORD exception_code);
806 #endif  // GTEST_OS_WINDOWS
807 
808   // Returns true if "name" matches the ':' separated list of glob-style
809   // filters in "filter".
810   static bool MatchesFilter(const std::string& name, const char* filter);
811 };
812 
813 // Returns the current application's name, removing directory path if that
814 // is present.  Used by UnitTestOptions::GetOutputFile.
815 GTEST_API_ FilePath GetCurrentExecutableName();
816 
817 // The role interface for getting the OS stack trace as a string.
818 class OsStackTraceGetterInterface {
819  public:
OsStackTraceGetterInterface()820   OsStackTraceGetterInterface() {}
~OsStackTraceGetterInterface()821   virtual ~OsStackTraceGetterInterface() {}
822 
823   // Returns the current OS stack trace as an std::string.  Parameters:
824   //
825   //   max_depth  - the maximum number of stack frames to be included
826   //                in the trace.
827   //   skip_count - the number of top frames to be skipped; doesn't count
828   //                against max_depth.
829   virtual string CurrentStackTrace(int max_depth, int skip_count) = 0;
830 
831   // UponLeavingGTest() should be called immediately before Google Test calls
832   // user code. It saves some information about the current stack that
833   // CurrentStackTrace() will use to find and hide Google Test stack frames.
834   virtual void UponLeavingGTest() = 0;
835 
836  private:
837   GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetterInterface);
838 };
839 
840 // A working implementation of the OsStackTraceGetterInterface interface.
841 class OsStackTraceGetter : public OsStackTraceGetterInterface {
842  public:
OsStackTraceGetter()843   OsStackTraceGetter() : caller_frame_(NULL) {}
844 
845   virtual string CurrentStackTrace(int max_depth, int skip_count)
846       GTEST_LOCK_EXCLUDED_(mutex_);
847 
848   virtual void UponLeavingGTest() GTEST_LOCK_EXCLUDED_(mutex_);
849 
850   // This string is inserted in place of stack frames that are part of
851   // Google Test's implementation.
852   static const char* const kElidedFramesMarker;
853 
854  private:
855   Mutex mutex_;  // protects all internal state
856 
857   // We save the stack frame below the frame that calls user code.
858   // We do this because the address of the frame immediately below
859   // the user code changes between the call to UponLeavingGTest()
860   // and any calls to CurrentStackTrace() from within the user code.
861   void* caller_frame_;
862 
863   GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetter);
864 };
865 
866 // Information about a Google Test trace point.
867 struct TraceInfo {
868   const char* file;
869   int line;
870   std::string message;
871 };
872 
873 // This is the default global test part result reporter used in UnitTestImpl.
874 // This class should only be used by UnitTestImpl.
875 class DefaultGlobalTestPartResultReporter
876   : public TestPartResultReporterInterface {
877  public:
878   explicit DefaultGlobalTestPartResultReporter(UnitTestImpl* unit_test);
879   // Implements the TestPartResultReporterInterface. Reports the test part
880   // result in the current test.
881   virtual void ReportTestPartResult(const TestPartResult& result);
882 
883  private:
884   UnitTestImpl* const unit_test_;
885 
886   GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultGlobalTestPartResultReporter);
887 };
888 
889 // This is the default per thread test part result reporter used in
890 // UnitTestImpl. This class should only be used by UnitTestImpl.
891 class DefaultPerThreadTestPartResultReporter
892     : public TestPartResultReporterInterface {
893  public:
894   explicit DefaultPerThreadTestPartResultReporter(UnitTestImpl* unit_test);
895   // Implements the TestPartResultReporterInterface. The implementation just
896   // delegates to the current global test part result reporter of *unit_test_.
897   virtual void ReportTestPartResult(const TestPartResult& result);
898 
899  private:
900   UnitTestImpl* const unit_test_;
901 
902   GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultPerThreadTestPartResultReporter);
903 };
904 
905 // The private implementation of the UnitTest class.  We don't protect
906 // the methods under a mutex, as this class is not accessible by a
907 // user and the UnitTest class that delegates work to this class does
908 // proper locking.
909 class GTEST_API_ UnitTestImpl {
910  public:
911   explicit UnitTestImpl(UnitTest* parent);
912   virtual ~UnitTestImpl();
913 
914   // There are two different ways to register your own TestPartResultReporter.
915   // You can register your own reporter to listen either only for test results
916   // from the current thread or for results from all threads.
917   // By default, each per-thread test result reporter just passes a new
918   // TestPartResult to the global test result reporter, which registers the
919   // test part result for the currently running test.
920 
921   // Returns the global test part result reporter.
922   TestPartResultReporterInterface* GetGlobalTestPartResultReporter();
923 
924   // Sets the global test part result reporter.
925   void SetGlobalTestPartResultReporter(
926       TestPartResultReporterInterface* reporter);
927 
928   // Returns the test part result reporter for the current thread.
929   TestPartResultReporterInterface* GetTestPartResultReporterForCurrentThread();
930 
931   // Sets the test part result reporter for the current thread.
932   void SetTestPartResultReporterForCurrentThread(
933       TestPartResultReporterInterface* reporter);
934 
935   // Gets the number of successful test cases.
936   int successful_test_case_count() const;
937 
938   // Gets the number of failed test cases.
939   int failed_test_case_count() const;
940 
941   // Gets the number of all test cases.
942   int total_test_case_count() const;
943 
944   // Gets the number of all test cases that contain at least one test
945   // that should run.
946   int test_case_to_run_count() const;
947 
948   // Gets the number of successful tests.
949   int successful_test_count() const;
950 
951   // Gets the number of failed tests.
952   int failed_test_count() const;
953 
954   // Gets the number of disabled tests that will be reported in the XML report.
955   int reportable_disabled_test_count() const;
956 
957   // Gets the number of disabled tests.
958   int disabled_test_count() const;
959 
960   // Gets the number of tests to be printed in the XML report.
961   int reportable_test_count() const;
962 
963   // Gets the number of all tests.
964   int total_test_count() const;
965 
966   // Gets the number of tests that should run.
967   int test_to_run_count() const;
968 
969   // Gets the time of the test program start, in ms from the start of the
970   // UNIX epoch.
start_timestamp() const971   TimeInMillis start_timestamp() const { return start_timestamp_; }
972 
973   // Gets the elapsed time, in milliseconds.
elapsed_time() const974   TimeInMillis elapsed_time() const { return elapsed_time_; }
975 
976   // Returns true iff the unit test passed (i.e. all test cases passed).
Passed() const977   bool Passed() const { return !Failed(); }
978 
979   // Returns true iff the unit test failed (i.e. some test case failed
980   // or something outside of all tests failed).
Failed() const981   bool Failed() const {
982     return failed_test_case_count() > 0 || ad_hoc_test_result()->Failed();
983   }
984 
985   // Gets the i-th test case among all the test cases. i can range from 0 to
986   // total_test_case_count() - 1. If i is not in that range, returns NULL.
GetTestCase(int i) const987   const TestCase* GetTestCase(int i) const {
988     const int index = GetElementOr(test_case_indices_, i, -1);
989     return index < 0 ? NULL : test_cases_[i];
990   }
991 
992   // Gets the i-th test case among all the test cases. i can range from 0 to
993   // total_test_case_count() - 1. If i is not in that range, returns NULL.
GetMutableTestCase(int i)994   TestCase* GetMutableTestCase(int i) {
995     const int index = GetElementOr(test_case_indices_, i, -1);
996     return index < 0 ? NULL : test_cases_[index];
997   }
998 
999   // Provides access to the event listener list.
listeners()1000   TestEventListeners* listeners() { return &listeners_; }
1001 
1002   // Returns the TestResult for the test that's currently running, or
1003   // the TestResult for the ad hoc test if no test is running.
1004   TestResult* current_test_result();
1005 
1006   // Returns the TestResult for the ad hoc test.
ad_hoc_test_result() const1007   const TestResult* ad_hoc_test_result() const { return &ad_hoc_test_result_; }
1008 
1009   // Sets the OS stack trace getter.
1010   //
1011   // Does nothing if the input and the current OS stack trace getter
1012   // are the same; otherwise, deletes the old getter and makes the
1013   // input the current getter.
1014   void set_os_stack_trace_getter(OsStackTraceGetterInterface* getter);
1015 
1016   // Returns the current OS stack trace getter if it is not NULL;
1017   // otherwise, creates an OsStackTraceGetter, makes it the current
1018   // getter, and returns it.
1019   OsStackTraceGetterInterface* os_stack_trace_getter();
1020 
1021   // Returns the current OS stack trace as an std::string.
1022   //
1023   // The maximum number of stack frames to be included is specified by
1024   // the gtest_stack_trace_depth flag.  The skip_count parameter
1025   // specifies the number of top frames to be skipped, which doesn't
1026   // count against the number of frames to be included.
1027   //
1028   // For example, if Foo() calls Bar(), which in turn calls
1029   // CurrentOsStackTraceExceptTop(1), Foo() will be included in the
1030   // trace but Bar() and CurrentOsStackTraceExceptTop() won't.
1031   std::string CurrentOsStackTraceExceptTop(int skip_count) GTEST_NO_INLINE_;
1032 
1033   // Finds and returns a TestCase with the given name.  If one doesn't
1034   // exist, creates one and returns it.
1035   //
1036   // Arguments:
1037   //
1038   //   test_case_name: name of the test case
1039   //   type_param:     the name of the test's type parameter, or NULL if
1040   //                   this is not a typed or a type-parameterized test.
1041   //   set_up_tc:      pointer to the function that sets up the test case
1042   //   tear_down_tc:   pointer to the function that tears down the test case
1043   TestCase* GetTestCase(const char* test_case_name,
1044                         const char* type_param,
1045                         Test::SetUpTestCaseFunc set_up_tc,
1046                         Test::TearDownTestCaseFunc tear_down_tc);
1047 
1048   // Adds a TestInfo to the unit test.
1049   //
1050   // Arguments:
1051   //
1052   //   set_up_tc:    pointer to the function that sets up the test case
1053   //   tear_down_tc: pointer to the function that tears down the test case
1054   //   test_info:    the TestInfo object
AddTestInfo(Test::SetUpTestCaseFunc set_up_tc,Test::TearDownTestCaseFunc tear_down_tc,TestInfo * test_info)1055   void AddTestInfo(Test::SetUpTestCaseFunc set_up_tc,
1056                    Test::TearDownTestCaseFunc tear_down_tc,
1057                    TestInfo* test_info) {
1058     // In order to support thread-safe death tests, we need to
1059     // remember the original working directory when the test program
1060     // was first invoked.  We cannot do this in RUN_ALL_TESTS(), as
1061     // the user may have changed the current directory before calling
1062     // RUN_ALL_TESTS().  Therefore we capture the current directory in
1063     // AddTestInfo(), which is called to register a TEST or TEST_F
1064     // before main() is reached.
1065     if (original_working_dir_.IsEmpty()) {
1066       original_working_dir_.Set(FilePath::GetCurrentDir());
1067       GTEST_CHECK_(!original_working_dir_.IsEmpty())
1068           << "Failed to get the current working directory.";
1069     }
1070 
1071     GetTestCase(test_info->test_case_name(),
1072                 test_info->type_param(),
1073                 set_up_tc,
1074                 tear_down_tc)->AddTestInfo(test_info);
1075   }
1076 
1077 #if GTEST_HAS_PARAM_TEST
1078   // Returns ParameterizedTestCaseRegistry object used to keep track of
1079   // value-parameterized tests and instantiate and register them.
parameterized_test_registry()1080   internal::ParameterizedTestCaseRegistry& parameterized_test_registry() {
1081     return parameterized_test_registry_;
1082   }
1083 #endif  // GTEST_HAS_PARAM_TEST
1084 
1085   // Sets the TestCase object for the test that's currently running.
set_current_test_case(TestCase * a_current_test_case)1086   void set_current_test_case(TestCase* a_current_test_case) {
1087     current_test_case_ = a_current_test_case;
1088   }
1089 
1090   // Sets the TestInfo object for the test that's currently running.  If
1091   // current_test_info is NULL, the assertion results will be stored in
1092   // ad_hoc_test_result_.
set_current_test_info(TestInfo * a_current_test_info)1093   void set_current_test_info(TestInfo* a_current_test_info) {
1094     current_test_info_ = a_current_test_info;
1095   }
1096 
1097   // Registers all parameterized tests defined using TEST_P and
1098   // INSTANTIATE_TEST_CASE_P, creating regular tests for each test/parameter
1099   // combination. This method can be called more then once; it has guards
1100   // protecting from registering the tests more then once.  If
1101   // value-parameterized tests are disabled, RegisterParameterizedTests is
1102   // present but does nothing.
1103   void RegisterParameterizedTests();
1104 
1105   // Runs all tests in this UnitTest object, prints the result, and
1106   // returns true if all tests are successful.  If any exception is
1107   // thrown during a test, this test is considered to be failed, but
1108   // the rest of the tests will still be run.
1109   bool RunAllTests();
1110 
1111   // Clears the results of all tests, except the ad hoc tests.
ClearNonAdHocTestResult()1112   void ClearNonAdHocTestResult() {
1113     ForEach(test_cases_, TestCase::ClearTestCaseResult);
1114   }
1115 
1116   // Clears the results of ad-hoc test assertions.
ClearAdHocTestResult()1117   void ClearAdHocTestResult() {
1118     ad_hoc_test_result_.Clear();
1119   }
1120 
1121   // Adds a TestProperty to the current TestResult object when invoked in a
1122   // context of a test or a test case, or to the global property set. If the
1123   // result already contains a property with the same key, the value will be
1124   // updated.
1125   void RecordProperty(const TestProperty& test_property);
1126 
1127   enum ReactionToSharding {
1128     HONOR_SHARDING_PROTOCOL,
1129     IGNORE_SHARDING_PROTOCOL
1130   };
1131 
1132   // Matches the full name of each test against the user-specified
1133   // filter to decide whether the test should run, then records the
1134   // result in each TestCase and TestInfo object.
1135   // If shard_tests == HONOR_SHARDING_PROTOCOL, further filters tests
1136   // based on sharding variables in the environment.
1137   // Returns the number of tests that should run.
1138   int FilterTests(ReactionToSharding shard_tests);
1139 
1140   // Prints the names of the tests matching the user-specified filter flag.
1141   void ListTestsMatchingFilter();
1142 
current_test_case() const1143   const TestCase* current_test_case() const { return current_test_case_; }
current_test_info()1144   TestInfo* current_test_info() { return current_test_info_; }
current_test_info() const1145   const TestInfo* current_test_info() const { return current_test_info_; }
1146 
1147   // Returns the vector of environments that need to be set-up/torn-down
1148   // before/after the tests are run.
environments()1149   std::vector<Environment*>& environments() { return environments_; }
1150 
1151   // Getters for the per-thread Google Test trace stack.
gtest_trace_stack()1152   std::vector<TraceInfo>& gtest_trace_stack() {
1153     return *(gtest_trace_stack_.pointer());
1154   }
gtest_trace_stack() const1155   const std::vector<TraceInfo>& gtest_trace_stack() const {
1156     return gtest_trace_stack_.get();
1157   }
1158 
1159 #if GTEST_HAS_DEATH_TEST
InitDeathTestSubprocessControlInfo()1160   void InitDeathTestSubprocessControlInfo() {
1161     internal_run_death_test_flag_.reset(ParseInternalRunDeathTestFlag());
1162   }
1163   // Returns a pointer to the parsed --gtest_internal_run_death_test
1164   // flag, or NULL if that flag was not specified.
1165   // This information is useful only in a death test child process.
1166   // Must not be called before a call to InitGoogleTest.
internal_run_death_test_flag() const1167   const InternalRunDeathTestFlag* internal_run_death_test_flag() const {
1168     return internal_run_death_test_flag_.get();
1169   }
1170 
1171   // Returns a pointer to the current death test factory.
death_test_factory()1172   internal::DeathTestFactory* death_test_factory() {
1173     return death_test_factory_.get();
1174   }
1175 
1176   void SuppressTestEventsIfInSubprocess();
1177 
1178   friend class ReplaceDeathTestFactory;
1179 #endif  // GTEST_HAS_DEATH_TEST
1180 
1181   // Initializes the event listener performing XML output as specified by
1182   // UnitTestOptions. Must not be called before InitGoogleTest.
1183   void ConfigureXmlOutput();
1184 
1185 #if GTEST_CAN_STREAM_RESULTS_
1186   // Initializes the event listener for streaming test results to a socket.
1187   // Must not be called before InitGoogleTest.
1188   void ConfigureStreamingOutput();
1189 #endif
1190 
1191   // Performs initialization dependent upon flag values obtained in
1192   // ParseGoogleTestFlagsOnly.  Is called from InitGoogleTest after the call to
1193   // ParseGoogleTestFlagsOnly.  In case a user neglects to call InitGoogleTest
1194   // this function is also called from RunAllTests.  Since this function can be
1195   // called more than once, it has to be idempotent.
1196   void PostFlagParsingInit();
1197 
1198   // Gets the random seed used at the start of the current test iteration.
random_seed() const1199   int random_seed() const { return random_seed_; }
1200 
1201   // Gets the random number generator.
random()1202   internal::Random* random() { return &random_; }
1203 
1204   // Shuffles all test cases, and the tests within each test case,
1205   // making sure that death tests are still run first.
1206   void ShuffleTests();
1207 
1208   // Restores the test cases and tests to their order before the first shuffle.
1209   void UnshuffleTests();
1210 
1211   // Returns the value of GTEST_FLAG(catch_exceptions) at the moment
1212   // UnitTest::Run() starts.
catch_exceptions() const1213   bool catch_exceptions() const { return catch_exceptions_; }
1214 
1215  private:
1216   friend class ::testing::UnitTest;
1217 
1218   // Used by UnitTest::Run() to capture the state of
1219   // GTEST_FLAG(catch_exceptions) at the moment it starts.
set_catch_exceptions(bool value)1220   void set_catch_exceptions(bool value) { catch_exceptions_ = value; }
1221 
1222   // The UnitTest object that owns this implementation object.
1223   UnitTest* const parent_;
1224 
1225   // The working directory when the first TEST() or TEST_F() was
1226   // executed.
1227   internal::FilePath original_working_dir_;
1228 
1229   // The default test part result reporters.
1230   DefaultGlobalTestPartResultReporter default_global_test_part_result_reporter_;
1231   DefaultPerThreadTestPartResultReporter
1232       default_per_thread_test_part_result_reporter_;
1233 
1234   // Points to (but doesn't own) the global test part result reporter.
1235   TestPartResultReporterInterface* global_test_part_result_repoter_;
1236 
1237   // Protects read and write access to global_test_part_result_reporter_.
1238   internal::Mutex global_test_part_result_reporter_mutex_;
1239 
1240   // Points to (but doesn't own) the per-thread test part result reporter.
1241   internal::ThreadLocal<TestPartResultReporterInterface*>
1242       per_thread_test_part_result_reporter_;
1243 
1244   // The vector of environments that need to be set-up/torn-down
1245   // before/after the tests are run.
1246   std::vector<Environment*> environments_;
1247 
1248   // The vector of TestCases in their original order.  It owns the
1249   // elements in the vector.
1250   std::vector<TestCase*> test_cases_;
1251 
1252   // Provides a level of indirection for the test case list to allow
1253   // easy shuffling and restoring the test case order.  The i-th
1254   // element of this vector is the index of the i-th test case in the
1255   // shuffled order.
1256   std::vector<int> test_case_indices_;
1257 
1258 #if GTEST_HAS_PARAM_TEST
1259   // ParameterizedTestRegistry object used to register value-parameterized
1260   // tests.
1261   internal::ParameterizedTestCaseRegistry parameterized_test_registry_;
1262 
1263   // Indicates whether RegisterParameterizedTests() has been called already.
1264   bool parameterized_tests_registered_;
1265 #endif  // GTEST_HAS_PARAM_TEST
1266 
1267   // Index of the last death test case registered.  Initially -1.
1268   int last_death_test_case_;
1269 
1270   // This points to the TestCase for the currently running test.  It
1271   // changes as Google Test goes through one test case after another.
1272   // When no test is running, this is set to NULL and Google Test
1273   // stores assertion results in ad_hoc_test_result_.  Initially NULL.
1274   TestCase* current_test_case_;
1275 
1276   // This points to the TestInfo for the currently running test.  It
1277   // changes as Google Test goes through one test after another.  When
1278   // no test is running, this is set to NULL and Google Test stores
1279   // assertion results in ad_hoc_test_result_.  Initially NULL.
1280   TestInfo* current_test_info_;
1281 
1282   // Normally, a user only writes assertions inside a TEST or TEST_F,
1283   // or inside a function called by a TEST or TEST_F.  Since Google
1284   // Test keeps track of which test is current running, it can
1285   // associate such an assertion with the test it belongs to.
1286   //
1287   // If an assertion is encountered when no TEST or TEST_F is running,
1288   // Google Test attributes the assertion result to an imaginary "ad hoc"
1289   // test, and records the result in ad_hoc_test_result_.
1290   TestResult ad_hoc_test_result_;
1291 
1292   // The list of event listeners that can be used to track events inside
1293   // Google Test.
1294   TestEventListeners listeners_;
1295 
1296   // The OS stack trace getter.  Will be deleted when the UnitTest
1297   // object is destructed.  By default, an OsStackTraceGetter is used,
1298   // but the user can set this field to use a custom getter if that is
1299   // desired.
1300   OsStackTraceGetterInterface* os_stack_trace_getter_;
1301 
1302   // True iff PostFlagParsingInit() has been called.
1303   bool post_flag_parse_init_performed_;
1304 
1305   // The random number seed used at the beginning of the test run.
1306   int random_seed_;
1307 
1308   // Our random number generator.
1309   internal::Random random_;
1310 
1311   // The time of the test program start, in ms from the start of the
1312   // UNIX epoch.
1313   TimeInMillis start_timestamp_;
1314 
1315   // How long the test took to run, in milliseconds.
1316   TimeInMillis elapsed_time_;
1317 
1318 #if GTEST_HAS_DEATH_TEST
1319   // The decomposed components of the gtest_internal_run_death_test flag,
1320   // parsed when RUN_ALL_TESTS is called.
1321   internal::scoped_ptr<InternalRunDeathTestFlag> internal_run_death_test_flag_;
1322   internal::scoped_ptr<internal::DeathTestFactory> death_test_factory_;
1323 #endif  // GTEST_HAS_DEATH_TEST
1324 
1325   // A per-thread stack of traces created by the SCOPED_TRACE() macro.
1326   internal::ThreadLocal<std::vector<TraceInfo> > gtest_trace_stack_;
1327 
1328   // The value of GTEST_FLAG(catch_exceptions) at the moment RunAllTests()
1329   // starts.
1330   bool catch_exceptions_;
1331 
1332   GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTestImpl);
1333 };  // class UnitTestImpl
1334 
1335 // Convenience function for accessing the global UnitTest
1336 // implementation object.
GetUnitTestImpl()1337 inline UnitTestImpl* GetUnitTestImpl() {
1338   return UnitTest::GetInstance()->impl();
1339 }
1340 
1341 #if GTEST_USES_SIMPLE_RE
1342 
1343 // Internal helper functions for implementing the simple regular
1344 // expression matcher.
1345 GTEST_API_ bool IsInSet(char ch, const char* str);
1346 GTEST_API_ bool IsAsciiDigit(char ch);
1347 GTEST_API_ bool IsAsciiPunct(char ch);
1348 GTEST_API_ bool IsRepeat(char ch);
1349 GTEST_API_ bool IsAsciiWhiteSpace(char ch);
1350 GTEST_API_ bool IsAsciiWordChar(char ch);
1351 GTEST_API_ bool IsValidEscape(char ch);
1352 GTEST_API_ bool AtomMatchesChar(bool escaped, char pattern, char ch);
1353 GTEST_API_ bool ValidateRegex(const char* regex);
1354 GTEST_API_ bool MatchRegexAtHead(const char* regex, const char* str);
1355 GTEST_API_ bool MatchRepetitionAndRegexAtHead(
1356     bool escaped, char ch, char repeat, const char* regex, const char* str);
1357 GTEST_API_ bool MatchRegexAnywhere(const char* regex, const char* str);
1358 
1359 #endif  // GTEST_USES_SIMPLE_RE
1360 
1361 // Parses the command line for Google Test flags, without initializing
1362 // other parts of Google Test.
1363 GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, char** argv);
1364 GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv);
1365 
1366 #if GTEST_HAS_DEATH_TEST
1367 
1368 // Returns the message describing the last system error, regardless of the
1369 // platform.
1370 GTEST_API_ std::string GetLastErrnoDescription();
1371 
1372 # if GTEST_OS_WINDOWS
1373 // Provides leak-safe Windows kernel handle ownership.
1374 class AutoHandle {
1375  public:
AutoHandle()1376   AutoHandle() : handle_(INVALID_HANDLE_VALUE) {}
AutoHandle(HANDLE handle)1377   explicit AutoHandle(HANDLE handle) : handle_(handle) {}
1378 
~AutoHandle()1379   ~AutoHandle() { Reset(); }
1380 
Get() const1381   HANDLE Get() const { return handle_; }
Reset()1382   void Reset() { Reset(INVALID_HANDLE_VALUE); }
Reset(HANDLE handle)1383   void Reset(HANDLE handle) {
1384     if (handle != handle_) {
1385       if (handle_ != INVALID_HANDLE_VALUE)
1386         ::CloseHandle(handle_);
1387       handle_ = handle;
1388     }
1389   }
1390 
1391  private:
1392   HANDLE handle_;
1393 
1394   GTEST_DISALLOW_COPY_AND_ASSIGN_(AutoHandle);
1395 };
1396 # endif  // GTEST_OS_WINDOWS
1397 
1398 // Attempts to parse a string into a positive integer pointed to by the
1399 // number parameter.  Returns true if that is possible.
1400 // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we can use
1401 // it here.
1402 template <typename Integer>
ParseNaturalNumber(const::std::string & str,Integer * number)1403 bool ParseNaturalNumber(const ::std::string& str, Integer* number) {
1404   // Fail fast if the given string does not begin with a digit;
1405   // this bypasses strtoXXX's "optional leading whitespace and plus
1406   // or minus sign" semantics, which are undesirable here.
1407   if (str.empty() || !IsDigit(str[0])) {
1408     return false;
1409   }
1410   errno = 0;
1411 
1412   char* end;
1413   // BiggestConvertible is the largest integer type that system-provided
1414   // string-to-number conversion routines can return.
1415 
1416 # if GTEST_OS_WINDOWS && !defined(__GNUC__)
1417 
1418   // MSVC and C++ Builder define __int64 instead of the standard long long.
1419   typedef unsigned __int64 BiggestConvertible;
1420   const BiggestConvertible parsed = _strtoui64(str.c_str(), &end, 10);
1421 
1422 # else
1423 
1424   typedef unsigned long long BiggestConvertible;  // NOLINT
1425   const BiggestConvertible parsed = strtoull(str.c_str(), &end, 10);
1426 
1427 # endif  // GTEST_OS_WINDOWS && !defined(__GNUC__)
1428 
1429   const bool parse_success = *end == '\0' && errno == 0;
1430 
1431   // TODO(vladl@google.com): Convert this to compile time assertion when it is
1432   // available.
1433   GTEST_CHECK_(sizeof(Integer) <= sizeof(parsed));
1434 
1435   const Integer result = static_cast<Integer>(parsed);
1436   if (parse_success && static_cast<BiggestConvertible>(result) == parsed) {
1437     *number = result;
1438     return true;
1439   }
1440   return false;
1441 }
1442 #endif  // GTEST_HAS_DEATH_TEST
1443 
1444 // TestResult contains some private methods that should be hidden from
1445 // Google Test user but are required for testing. This class allow our tests
1446 // to access them.
1447 //
1448 // This class is supplied only for the purpose of testing Google Test's own
1449 // constructs. Do not use it in user tests, either directly or indirectly.
1450 class TestResultAccessor {
1451  public:
RecordProperty(TestResult * test_result,const std::string & xml_element,const TestProperty & property)1452   static void RecordProperty(TestResult* test_result,
1453                              const std::string& xml_element,
1454                              const TestProperty& property) {
1455     test_result->RecordProperty(xml_element, property);
1456   }
1457 
ClearTestPartResults(TestResult * test_result)1458   static void ClearTestPartResults(TestResult* test_result) {
1459     test_result->ClearTestPartResults();
1460   }
1461 
test_part_results(const TestResult & test_result)1462   static const std::vector<testing::TestPartResult>& test_part_results(
1463       const TestResult& test_result) {
1464     return test_result.test_part_results();
1465   }
1466 };
1467 
1468 #if GTEST_CAN_STREAM_RESULTS_
1469 
1470 // Streams test results to the given port on the given host machine.
1471 class StreamingListener : public EmptyTestEventListener {
1472  public:
1473   // Abstract base class for writing strings to a socket.
1474   class AbstractSocketWriter {
1475    public:
~AbstractSocketWriter()1476     virtual ~AbstractSocketWriter() {}
1477 
1478     // Sends a string to the socket.
1479     virtual void Send(const string& message) = 0;
1480 
1481     // Closes the socket.
CloseConnection()1482     virtual void CloseConnection() {}
1483 
1484     // Sends a string and a newline to the socket.
SendLn(const string & message)1485     void SendLn(const string& message) {
1486       Send(message + "\n");
1487     }
1488   };
1489 
1490   // Concrete class for actually writing strings to a socket.
1491   class SocketWriter : public AbstractSocketWriter {
1492    public:
SocketWriter(const string & host,const string & port)1493     SocketWriter(const string& host, const string& port)
1494         : sockfd_(-1), host_name_(host), port_num_(port) {
1495       MakeConnection();
1496     }
1497 
~SocketWriter()1498     virtual ~SocketWriter() {
1499       if (sockfd_ != -1)
1500         CloseConnection();
1501     }
1502 
1503     // Sends a string to the socket.
Send(const string & message)1504     virtual void Send(const string& message) {
1505       GTEST_CHECK_(sockfd_ != -1)
1506           << "Send() can be called only when there is a connection.";
1507 
1508       const int len = static_cast<int>(message.length());
1509       if (write(sockfd_, message.c_str(), len) != len) {
1510         GTEST_LOG_(WARNING)
1511             << "stream_result_to: failed to stream to "
1512             << host_name_ << ":" << port_num_;
1513       }
1514     }
1515 
1516    private:
1517     // Creates a client socket and connects to the server.
1518     void MakeConnection();
1519 
1520     // Closes the socket.
CloseConnection()1521     void CloseConnection() {
1522       GTEST_CHECK_(sockfd_ != -1)
1523           << "CloseConnection() can be called only when there is a connection.";
1524 
1525       close(sockfd_);
1526       sockfd_ = -1;
1527     }
1528 
1529     int sockfd_;  // socket file descriptor
1530     const string host_name_;
1531     const string port_num_;
1532 
1533     GTEST_DISALLOW_COPY_AND_ASSIGN_(SocketWriter);
1534   };  // class SocketWriter
1535 
1536   // Escapes '=', '&', '%', and '\n' characters in str as "%xx".
1537   static string UrlEncode(const char* str);
1538 
StreamingListener(const string & host,const string & port)1539   StreamingListener(const string& host, const string& port)
1540       : socket_writer_(new SocketWriter(host, port)) { Start(); }
1541 
StreamingListener(AbstractSocketWriter * socket_writer)1542   explicit StreamingListener(AbstractSocketWriter* socket_writer)
1543       : socket_writer_(socket_writer) { Start(); }
1544 
OnTestProgramStart(const UnitTest &)1545   void OnTestProgramStart(const UnitTest& /* unit_test */) {
1546     SendLn("event=TestProgramStart");
1547   }
1548 
OnTestProgramEnd(const UnitTest & unit_test)1549   void OnTestProgramEnd(const UnitTest& unit_test) {
1550     // Note that Google Test current only report elapsed time for each
1551     // test iteration, not for the entire test program.
1552     SendLn("event=TestProgramEnd&passed=" + FormatBool(unit_test.Passed()));
1553 
1554     // Notify the streaming server to stop.
1555     socket_writer_->CloseConnection();
1556   }
1557 
OnTestIterationStart(const UnitTest &,int iteration)1558   void OnTestIterationStart(const UnitTest& /* unit_test */, int iteration) {
1559     SendLn("event=TestIterationStart&iteration=" +
1560            StreamableToString(iteration));
1561   }
1562 
OnTestIterationEnd(const UnitTest & unit_test,int)1563   void OnTestIterationEnd(const UnitTest& unit_test, int /* iteration */) {
1564     SendLn("event=TestIterationEnd&passed=" +
1565            FormatBool(unit_test.Passed()) + "&elapsed_time=" +
1566            StreamableToString(unit_test.elapsed_time()) + "ms");
1567   }
1568 
OnTestCaseStart(const TestCase & test_case)1569   void OnTestCaseStart(const TestCase& test_case) {
1570     SendLn(std::string("event=TestCaseStart&name=") + test_case.name());
1571   }
1572 
OnTestCaseEnd(const TestCase & test_case)1573   void OnTestCaseEnd(const TestCase& test_case) {
1574     SendLn("event=TestCaseEnd&passed=" + FormatBool(test_case.Passed())
1575            + "&elapsed_time=" + StreamableToString(test_case.elapsed_time())
1576            + "ms");
1577   }
1578 
OnTestStart(const TestInfo & test_info)1579   void OnTestStart(const TestInfo& test_info) {
1580     SendLn(std::string("event=TestStart&name=") + test_info.name());
1581   }
1582 
OnTestEnd(const TestInfo & test_info)1583   void OnTestEnd(const TestInfo& test_info) {
1584     SendLn("event=TestEnd&passed=" +
1585            FormatBool((test_info.result())->Passed()) +
1586            "&elapsed_time=" +
1587            StreamableToString((test_info.result())->elapsed_time()) + "ms");
1588   }
1589 
OnTestPartResult(const TestPartResult & test_part_result)1590   void OnTestPartResult(const TestPartResult& test_part_result) {
1591     const char* file_name = test_part_result.file_name();
1592     if (file_name == NULL)
1593       file_name = "";
1594     SendLn("event=TestPartResult&file=" + UrlEncode(file_name) +
1595            "&line=" + StreamableToString(test_part_result.line_number()) +
1596            "&message=" + UrlEncode(test_part_result.message()));
1597   }
1598 
1599  private:
1600   // Sends the given message and a newline to the socket.
SendLn(const string & message)1601   void SendLn(const string& message) { socket_writer_->SendLn(message); }
1602 
1603   // Called at the start of streaming to notify the receiver what
1604   // protocol we are using.
Start()1605   void Start() { SendLn("gtest_streaming_protocol_version=1.0"); }
1606 
FormatBool(bool value)1607   string FormatBool(bool value) { return value ? "1" : "0"; }
1608 
1609   const scoped_ptr<AbstractSocketWriter> socket_writer_;
1610 
1611   GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamingListener);
1612 };  // class StreamingListener
1613 
1614 #endif  // GTEST_CAN_STREAM_RESULTS_
1615 
1616 }  // namespace internal
1617 }  // namespace testing
1618 
1619 #endif  // GTEST_SRC_GTEST_INTERNAL_INL_H_
1620 #undef GTEST_IMPLEMENTATION_
1621 
1622 #if GTEST_OS_WINDOWS
1623 # define vsnprintf _vsnprintf
1624 #endif  // GTEST_OS_WINDOWS
1625 
1626 namespace testing {
1627 
1628 using internal::CountIf;
1629 using internal::ForEach;
1630 using internal::GetElementOr;
1631 using internal::Shuffle;
1632 
1633 // Constants.
1634 
1635 // A test whose test case name or test name matches this filter is
1636 // disabled and not run.
1637 static const char kDisableTestFilter[] = "DISABLED_*:*/DISABLED_*";
1638 
1639 // A test case whose name matches this filter is considered a death
1640 // test case and will be run before test cases whose name doesn't
1641 // match this filter.
1642 static const char kDeathTestCaseFilter[] = "*DeathTest:*DeathTest/*";
1643 
1644 // A test filter that matches everything.
1645 static const char kUniversalFilter[] = "*";
1646 
1647 // The default output file for XML output.
1648 static const char kDefaultOutputFile[] = "test_detail.xml";
1649 
1650 // The environment variable name for the test shard index.
1651 static const char kTestShardIndex[] = "GTEST_SHARD_INDEX";
1652 // The environment variable name for the total number of test shards.
1653 static const char kTestTotalShards[] = "GTEST_TOTAL_SHARDS";
1654 // The environment variable name for the test shard status file.
1655 static const char kTestShardStatusFile[] = "GTEST_SHARD_STATUS_FILE";
1656 
1657 namespace internal {
1658 
1659 // The text used in failure messages to indicate the start of the
1660 // stack trace.
1661 const char kStackTraceMarker[] = "\nStack trace:\n";
1662 
1663 // g_help_flag is true iff the --help flag or an equivalent form is
1664 // specified on the command line.
1665 bool g_help_flag = false;
1666 
1667 }  // namespace internal
1668 
GetDefaultFilter()1669 static const char* GetDefaultFilter() {
1670   return kUniversalFilter;
1671 }
1672 
1673 GTEST_DEFINE_bool_(
1674     also_run_disabled_tests,
1675     internal::BoolFromGTestEnv("also_run_disabled_tests", false),
1676     "Run disabled tests too, in addition to the tests normally being run.");
1677 
1678 GTEST_DEFINE_bool_(
1679     break_on_failure,
1680     internal::BoolFromGTestEnv("break_on_failure", false),
1681     "True iff a failed assertion should be a debugger break-point.");
1682 
1683 GTEST_DEFINE_bool_(
1684     catch_exceptions,
1685     internal::BoolFromGTestEnv("catch_exceptions", true),
1686     "True iff " GTEST_NAME_
1687     " should catch exceptions and treat them as test failures.");
1688 
1689 GTEST_DEFINE_string_(
1690     color,
1691     internal::StringFromGTestEnv("color", "auto"),
1692     "Whether to use colors in the output.  Valid values: yes, no, "
1693     "and auto.  'auto' means to use colors if the output is "
1694     "being sent to a terminal and the TERM environment variable "
1695     "is set to a terminal type that supports colors.");
1696 
1697 GTEST_DEFINE_string_(
1698     filter,
1699     internal::StringFromGTestEnv("filter", GetDefaultFilter()),
1700     "A colon-separated list of glob (not regex) patterns "
1701     "for filtering the tests to run, optionally followed by a "
1702     "'-' and a : separated list of negative patterns (tests to "
1703     "exclude).  A test is run if it matches one of the positive "
1704     "patterns and does not match any of the negative patterns.");
1705 
1706 GTEST_DEFINE_bool_(list_tests, false,
1707                    "List all tests without running them.");
1708 
1709 GTEST_DEFINE_string_(
1710     output,
1711     internal::StringFromGTestEnv("output", ""),
1712     "A format (currently must be \"xml\"), optionally followed "
1713     "by a colon and an output file name or directory. A directory "
1714     "is indicated by a trailing pathname separator. "
1715     "Examples: \"xml:filename.xml\", \"xml::directoryname/\". "
1716     "If a directory is specified, output files will be created "
1717     "within that directory, with file-names based on the test "
1718     "executable's name and, if necessary, made unique by adding "
1719     "digits.");
1720 
1721 GTEST_DEFINE_bool_(
1722     print_time,
1723     internal::BoolFromGTestEnv("print_time", true),
1724     "True iff " GTEST_NAME_
1725     " should display elapsed time in text output.");
1726 
1727 GTEST_DEFINE_int32_(
1728     random_seed,
1729     internal::Int32FromGTestEnv("random_seed", 0),
1730     "Random number seed to use when shuffling test orders.  Must be in range "
1731     "[1, 99999], or 0 to use a seed based on the current time.");
1732 
1733 GTEST_DEFINE_int32_(
1734     repeat,
1735     internal::Int32FromGTestEnv("repeat", 1),
1736     "How many times to repeat each test.  Specify a negative number "
1737     "for repeating forever.  Useful for shaking out flaky tests.");
1738 
1739 GTEST_DEFINE_bool_(
1740     show_internal_stack_frames, false,
1741     "True iff " GTEST_NAME_ " should include internal stack frames when "
1742     "printing test failure stack traces.");
1743 
1744 GTEST_DEFINE_bool_(
1745     shuffle,
1746     internal::BoolFromGTestEnv("shuffle", false),
1747     "True iff " GTEST_NAME_
1748     " should randomize tests' order on every run.");
1749 
1750 GTEST_DEFINE_int32_(
1751     stack_trace_depth,
1752     internal::Int32FromGTestEnv("stack_trace_depth", kMaxStackTraceDepth),
1753     "The maximum number of stack frames to print when an "
1754     "assertion fails.  The valid range is 0 through 100, inclusive.");
1755 
1756 GTEST_DEFINE_string_(
1757     stream_result_to,
1758     internal::StringFromGTestEnv("stream_result_to", ""),
1759     "This flag specifies the host name and the port number on which to stream "
1760     "test results. Example: \"localhost:555\". The flag is effective only on "
1761     "Linux.");
1762 
1763 GTEST_DEFINE_bool_(
1764     throw_on_failure,
1765     internal::BoolFromGTestEnv("throw_on_failure", false),
1766     "When this flag is specified, a failed assertion will throw an exception "
1767     "if exceptions are enabled or exit the program with a non-zero code "
1768     "otherwise.");
1769 
1770 namespace internal {
1771 
1772 // Generates a random number from [0, range), using a Linear
1773 // Congruential Generator (LCG).  Crashes if 'range' is 0 or greater
1774 // than kMaxRange.
Generate(UInt32 range)1775 UInt32 Random::Generate(UInt32 range) {
1776   // These constants are the same as are used in glibc's rand(3).
1777   state_ = (1103515245U*state_ + 12345U) % kMaxRange;
1778 
1779   GTEST_CHECK_(range > 0)
1780       << "Cannot generate a number in the range [0, 0).";
1781   GTEST_CHECK_(range <= kMaxRange)
1782       << "Generation of a number in [0, " << range << ") was requested, "
1783       << "but this can only generate numbers in [0, " << kMaxRange << ").";
1784 
1785   // Converting via modulus introduces a bit of downward bias, but
1786   // it's simple, and a linear congruential generator isn't too good
1787   // to begin with.
1788   return state_ % range;
1789 }
1790 
1791 // GTestIsInitialized() returns true iff the user has initialized
1792 // Google Test.  Useful for catching the user mistake of not initializing
1793 // Google Test before calling RUN_ALL_TESTS().
1794 //
1795 // A user must call testing::InitGoogleTest() to initialize Google
1796 // Test.  g_init_gtest_count is set to the number of times
1797 // InitGoogleTest() has been called.  We don't protect this variable
1798 // under a mutex as it is only accessed in the main thread.
1799 GTEST_API_ int g_init_gtest_count = 0;
GTestIsInitialized()1800 static bool GTestIsInitialized() { return g_init_gtest_count != 0; }
1801 
1802 // Iterates over a vector of TestCases, keeping a running sum of the
1803 // results of calling a given int-returning method on each.
1804 // Returns the sum.
SumOverTestCaseList(const std::vector<TestCase * > & case_list,int (TestCase::* method)()const)1805 static int SumOverTestCaseList(const std::vector<TestCase*>& case_list,
1806                                int (TestCase::*method)() const) {
1807   int sum = 0;
1808   for (size_t i = 0; i < case_list.size(); i++) {
1809     sum += (case_list[i]->*method)();
1810   }
1811   return sum;
1812 }
1813 
1814 // Returns true iff the test case passed.
TestCasePassed(const TestCase * test_case)1815 static bool TestCasePassed(const TestCase* test_case) {
1816   return test_case->should_run() && test_case->Passed();
1817 }
1818 
1819 // Returns true iff the test case failed.
TestCaseFailed(const TestCase * test_case)1820 static bool TestCaseFailed(const TestCase* test_case) {
1821   return test_case->should_run() && test_case->Failed();
1822 }
1823 
1824 // Returns true iff test_case contains at least one test that should
1825 // run.
ShouldRunTestCase(const TestCase * test_case)1826 static bool ShouldRunTestCase(const TestCase* test_case) {
1827   return test_case->should_run();
1828 }
1829 
1830 // AssertHelper constructor.
AssertHelper(TestPartResult::Type type,const char * file,int line,const char * message)1831 AssertHelper::AssertHelper(TestPartResult::Type type,
1832                            const char* file,
1833                            int line,
1834                            const char* message)
1835     : data_(new AssertHelperData(type, file, line, message)) {
1836 }
1837 
~AssertHelper()1838 AssertHelper::~AssertHelper() {
1839   delete data_;
1840 }
1841 
1842 // Message assignment, for assertion streaming support.
operator =(const Message & message) const1843 void AssertHelper::operator=(const Message& message) const {
1844   UnitTest::GetInstance()->
1845     AddTestPartResult(data_->type, data_->file, data_->line,
1846                       AppendUserMessage(data_->message, message),
1847                       UnitTest::GetInstance()->impl()
1848                       ->CurrentOsStackTraceExceptTop(1)
1849                       // Skips the stack frame for this function itself.
1850                       );  // NOLINT
1851 }
1852 
1853 // Mutex for linked pointers.
1854 GTEST_API_ GTEST_DEFINE_STATIC_MUTEX_(g_linked_ptr_mutex);
1855 
1856 // Application pathname gotten in InitGoogleTest.
1857 std::string g_executable_path;
1858 
1859 // Returns the current application's name, removing directory path if that
1860 // is present.
GetCurrentExecutableName()1861 FilePath GetCurrentExecutableName() {
1862   FilePath result;
1863 
1864 #if GTEST_OS_WINDOWS
1865   result.Set(FilePath(g_executable_path).RemoveExtension("exe"));
1866 #else
1867   result.Set(FilePath(g_executable_path));
1868 #endif  // GTEST_OS_WINDOWS
1869 
1870   return result.RemoveDirectoryName();
1871 }
1872 
1873 // Functions for processing the gtest_output flag.
1874 
1875 // Returns the output format, or "" for normal printed output.
GetOutputFormat()1876 std::string UnitTestOptions::GetOutputFormat() {
1877   const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
1878   if (gtest_output_flag == NULL) return std::string("");
1879 
1880   const char* const colon = strchr(gtest_output_flag, ':');
1881   return (colon == NULL) ?
1882       std::string(gtest_output_flag) :
1883       std::string(gtest_output_flag, colon - gtest_output_flag);
1884 }
1885 
1886 // Returns the name of the requested output file, or the default if none
1887 // was explicitly specified.
GetAbsolutePathToOutputFile()1888 std::string UnitTestOptions::GetAbsolutePathToOutputFile() {
1889   const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
1890   if (gtest_output_flag == NULL)
1891     return "";
1892 
1893   const char* const colon = strchr(gtest_output_flag, ':');
1894   if (colon == NULL)
1895     return internal::FilePath::ConcatPaths(
1896         internal::FilePath(
1897             UnitTest::GetInstance()->original_working_dir()),
1898         internal::FilePath(kDefaultOutputFile)).string();
1899 
1900   internal::FilePath output_name(colon + 1);
1901   if (!output_name.IsAbsolutePath())
1902     // TODO(wan@google.com): on Windows \some\path is not an absolute
1903     // path (as its meaning depends on the current drive), yet the
1904     // following logic for turning it into an absolute path is wrong.
1905     // Fix it.
1906     output_name = internal::FilePath::ConcatPaths(
1907         internal::FilePath(UnitTest::GetInstance()->original_working_dir()),
1908         internal::FilePath(colon + 1));
1909 
1910   if (!output_name.IsDirectory())
1911     return output_name.string();
1912 
1913   internal::FilePath result(internal::FilePath::GenerateUniqueFileName(
1914       output_name, internal::GetCurrentExecutableName(),
1915       GetOutputFormat().c_str()));
1916   return result.string();
1917 }
1918 
1919 // Returns true iff the wildcard pattern matches the string.  The
1920 // first ':' or '\0' character in pattern marks the end of it.
1921 //
1922 // This recursive algorithm isn't very efficient, but is clear and
1923 // works well enough for matching test names, which are short.
PatternMatchesString(const char * pattern,const char * str)1924 bool UnitTestOptions::PatternMatchesString(const char *pattern,
1925                                            const char *str) {
1926   switch (*pattern) {
1927     case '\0':
1928     case ':':  // Either ':' or '\0' marks the end of the pattern.
1929       return *str == '\0';
1930     case '?':  // Matches any single character.
1931       return *str != '\0' && PatternMatchesString(pattern + 1, str + 1);
1932     case '*':  // Matches any string (possibly empty) of characters.
1933       return (*str != '\0' && PatternMatchesString(pattern, str + 1)) ||
1934           PatternMatchesString(pattern + 1, str);
1935     default:  // Non-special character.  Matches itself.
1936       return *pattern == *str &&
1937           PatternMatchesString(pattern + 1, str + 1);
1938   }
1939 }
1940 
MatchesFilter(const std::string & name,const char * filter)1941 bool UnitTestOptions::MatchesFilter(
1942     const std::string& name, const char* filter) {
1943   const char *cur_pattern = filter;
1944   for (;;) {
1945     if (PatternMatchesString(cur_pattern, name.c_str())) {
1946       return true;
1947     }
1948 
1949     // Finds the next pattern in the filter.
1950     cur_pattern = strchr(cur_pattern, ':');
1951 
1952     // Returns if no more pattern can be found.
1953     if (cur_pattern == NULL) {
1954       return false;
1955     }
1956 
1957     // Skips the pattern separater (the ':' character).
1958     cur_pattern++;
1959   }
1960 }
1961 
1962 // Returns true iff the user-specified filter matches the test case
1963 // name and the test name.
FilterMatchesTest(const std::string & test_case_name,const std::string & test_name)1964 bool UnitTestOptions::FilterMatchesTest(const std::string &test_case_name,
1965                                         const std::string &test_name) {
1966   const std::string& full_name = test_case_name + "." + test_name.c_str();
1967 
1968   // Split --gtest_filter at '-', if there is one, to separate into
1969   // positive filter and negative filter portions
1970   const char* const p = GTEST_FLAG(filter).c_str();
1971   const char* const dash = strchr(p, '-');
1972   std::string positive;
1973   std::string negative;
1974   if (dash == NULL) {
1975     positive = GTEST_FLAG(filter).c_str();  // Whole string is a positive filter
1976     negative = "";
1977   } else {
1978     positive = std::string(p, dash);   // Everything up to the dash
1979     negative = std::string(dash + 1);  // Everything after the dash
1980     if (positive.empty()) {
1981       // Treat '-test1' as the same as '*-test1'
1982       positive = kUniversalFilter;
1983     }
1984   }
1985 
1986   // A filter is a colon-separated list of patterns.  It matches a
1987   // test if any pattern in it matches the test.
1988   return (MatchesFilter(full_name, positive.c_str()) &&
1989           !MatchesFilter(full_name, negative.c_str()));
1990 }
1991 
1992 #if GTEST_HAS_SEH
1993 // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
1994 // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
1995 // This function is useful as an __except condition.
GTestShouldProcessSEH(DWORD exception_code)1996 int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) {
1997   // Google Test should handle a SEH exception if:
1998   //   1. the user wants it to, AND
1999   //   2. this is not a breakpoint exception, AND
2000   //   3. this is not a C++ exception (VC++ implements them via SEH,
2001   //      apparently).
2002   //
2003   // SEH exception code for C++ exceptions.
2004   // (see http://support.microsoft.com/kb/185294 for more information).
2005   const DWORD kCxxExceptionCode = 0xe06d7363;
2006 
2007   bool should_handle = true;
2008 
2009   if (!GTEST_FLAG(catch_exceptions))
2010     should_handle = false;
2011   else if (exception_code == EXCEPTION_BREAKPOINT)
2012     should_handle = false;
2013   else if (exception_code == kCxxExceptionCode)
2014     should_handle = false;
2015 
2016   return should_handle ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH;
2017 }
2018 #endif  // GTEST_HAS_SEH
2019 
2020 }  // namespace internal
2021 
2022 // The c'tor sets this object as the test part result reporter used by
2023 // Google Test.  The 'result' parameter specifies where to report the
2024 // results. Intercepts only failures from the current thread.
ScopedFakeTestPartResultReporter(TestPartResultArray * result)2025 ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
2026     TestPartResultArray* result)
2027     : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD),
2028       result_(result) {
2029   Init();
2030 }
2031 
2032 // The c'tor sets this object as the test part result reporter used by
2033 // Google Test.  The 'result' parameter specifies where to report the
2034 // results.
ScopedFakeTestPartResultReporter(InterceptMode intercept_mode,TestPartResultArray * result)2035 ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
2036     InterceptMode intercept_mode, TestPartResultArray* result)
2037     : intercept_mode_(intercept_mode),
2038       result_(result) {
2039   Init();
2040 }
2041 
Init()2042 void ScopedFakeTestPartResultReporter::Init() {
2043   internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
2044   if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
2045     old_reporter_ = impl->GetGlobalTestPartResultReporter();
2046     impl->SetGlobalTestPartResultReporter(this);
2047   } else {
2048     old_reporter_ = impl->GetTestPartResultReporterForCurrentThread();
2049     impl->SetTestPartResultReporterForCurrentThread(this);
2050   }
2051 }
2052 
2053 // The d'tor restores the test part result reporter used by Google Test
2054 // before.
~ScopedFakeTestPartResultReporter()2055 ScopedFakeTestPartResultReporter::~ScopedFakeTestPartResultReporter() {
2056   internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
2057   if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
2058     impl->SetGlobalTestPartResultReporter(old_reporter_);
2059   } else {
2060     impl->SetTestPartResultReporterForCurrentThread(old_reporter_);
2061   }
2062 }
2063 
2064 // Increments the test part result count and remembers the result.
2065 // This method is from the TestPartResultReporterInterface interface.
ReportTestPartResult(const TestPartResult & result)2066 void ScopedFakeTestPartResultReporter::ReportTestPartResult(
2067     const TestPartResult& result) {
2068   result_->Append(result);
2069 }
2070 
2071 namespace internal {
2072 
2073 // Returns the type ID of ::testing::Test.  We should always call this
2074 // instead of GetTypeId< ::testing::Test>() to get the type ID of
2075 // testing::Test.  This is to work around a suspected linker bug when
2076 // using Google Test as a framework on Mac OS X.  The bug causes
2077 // GetTypeId< ::testing::Test>() to return different values depending
2078 // on whether the call is from the Google Test framework itself or
2079 // from user test code.  GetTestTypeId() is guaranteed to always
2080 // return the same value, as it always calls GetTypeId<>() from the
2081 // gtest.cc, which is within the Google Test framework.
GetTestTypeId()2082 TypeId GetTestTypeId() {
2083   return GetTypeId<Test>();
2084 }
2085 
2086 // The value of GetTestTypeId() as seen from within the Google Test
2087 // library.  This is solely for testing GetTestTypeId().
2088 extern const TypeId kTestTypeIdInGoogleTest = GetTestTypeId();
2089 
2090 // This predicate-formatter checks that 'results' contains a test part
2091 // failure of the given type and that the failure message contains the
2092 // given substring.
HasOneFailure(const char *,const char *,const char *,const TestPartResultArray & results,TestPartResult::Type type,const string & substr)2093 AssertionResult HasOneFailure(const char* /* results_expr */,
2094                               const char* /* type_expr */,
2095                               const char* /* substr_expr */,
2096                               const TestPartResultArray& results,
2097                               TestPartResult::Type type,
2098                               const string& substr) {
2099   const std::string expected(type == TestPartResult::kFatalFailure ?
2100                         "1 fatal failure" :
2101                         "1 non-fatal failure");
2102   Message msg;
2103   if (results.size() != 1) {
2104     msg << "Expected: " << expected << "\n"
2105         << "  Actual: " << results.size() << " failures";
2106     for (int i = 0; i < results.size(); i++) {
2107       msg << "\n" << results.GetTestPartResult(i);
2108     }
2109     return AssertionFailure() << msg;
2110   }
2111 
2112   const TestPartResult& r = results.GetTestPartResult(0);
2113   if (r.type() != type) {
2114     return AssertionFailure() << "Expected: " << expected << "\n"
2115                               << "  Actual:\n"
2116                               << r;
2117   }
2118 
2119   if (strstr(r.message(), substr.c_str()) == NULL) {
2120     return AssertionFailure() << "Expected: " << expected << " containing \""
2121                               << substr << "\"\n"
2122                               << "  Actual:\n"
2123                               << r;
2124   }
2125 
2126   return AssertionSuccess();
2127 }
2128 
2129 // The constructor of SingleFailureChecker remembers where to look up
2130 // test part results, what type of failure we expect, and what
2131 // substring the failure message should contain.
SingleFailureChecker(const TestPartResultArray * results,TestPartResult::Type type,const string & substr)2132 SingleFailureChecker:: SingleFailureChecker(
2133     const TestPartResultArray* results,
2134     TestPartResult::Type type,
2135     const string& substr)
2136     : results_(results),
2137       type_(type),
2138       substr_(substr) {}
2139 
2140 // The destructor of SingleFailureChecker verifies that the given
2141 // TestPartResultArray contains exactly one failure that has the given
2142 // type and contains the given substring.  If that's not the case, a
2143 // non-fatal failure will be generated.
~SingleFailureChecker()2144 SingleFailureChecker::~SingleFailureChecker() {
2145   EXPECT_PRED_FORMAT3(HasOneFailure, *results_, type_, substr_);
2146 }
2147 
DefaultGlobalTestPartResultReporter(UnitTestImpl * unit_test)2148 DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter(
2149     UnitTestImpl* unit_test) : unit_test_(unit_test) {}
2150 
ReportTestPartResult(const TestPartResult & result)2151 void DefaultGlobalTestPartResultReporter::ReportTestPartResult(
2152     const TestPartResult& result) {
2153   unit_test_->current_test_result()->AddTestPartResult(result);
2154   unit_test_->listeners()->repeater()->OnTestPartResult(result);
2155 }
2156 
DefaultPerThreadTestPartResultReporter(UnitTestImpl * unit_test)2157 DefaultPerThreadTestPartResultReporter::DefaultPerThreadTestPartResultReporter(
2158     UnitTestImpl* unit_test) : unit_test_(unit_test) {}
2159 
ReportTestPartResult(const TestPartResult & result)2160 void DefaultPerThreadTestPartResultReporter::ReportTestPartResult(
2161     const TestPartResult& result) {
2162   unit_test_->GetGlobalTestPartResultReporter()->ReportTestPartResult(result);
2163 }
2164 
2165 // Returns the global test part result reporter.
2166 TestPartResultReporterInterface*
GetGlobalTestPartResultReporter()2167 UnitTestImpl::GetGlobalTestPartResultReporter() {
2168   internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
2169   return global_test_part_result_repoter_;
2170 }
2171 
2172 // Sets the global test part result reporter.
SetGlobalTestPartResultReporter(TestPartResultReporterInterface * reporter)2173 void UnitTestImpl::SetGlobalTestPartResultReporter(
2174     TestPartResultReporterInterface* reporter) {
2175   internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
2176   global_test_part_result_repoter_ = reporter;
2177 }
2178 
2179 // Returns the test part result reporter for the current thread.
2180 TestPartResultReporterInterface*
GetTestPartResultReporterForCurrentThread()2181 UnitTestImpl::GetTestPartResultReporterForCurrentThread() {
2182   return per_thread_test_part_result_reporter_.get();
2183 }
2184 
2185 // Sets the test part result reporter for the current thread.
SetTestPartResultReporterForCurrentThread(TestPartResultReporterInterface * reporter)2186 void UnitTestImpl::SetTestPartResultReporterForCurrentThread(
2187     TestPartResultReporterInterface* reporter) {
2188   per_thread_test_part_result_reporter_.set(reporter);
2189 }
2190 
2191 // Gets the number of successful test cases.
successful_test_case_count() const2192 int UnitTestImpl::successful_test_case_count() const {
2193   return CountIf(test_cases_, TestCasePassed);
2194 }
2195 
2196 // Gets the number of failed test cases.
failed_test_case_count() const2197 int UnitTestImpl::failed_test_case_count() const {
2198   return CountIf(test_cases_, TestCaseFailed);
2199 }
2200 
2201 // Gets the number of all test cases.
total_test_case_count() const2202 int UnitTestImpl::total_test_case_count() const {
2203   return static_cast<int>(test_cases_.size());
2204 }
2205 
2206 // Gets the number of all test cases that contain at least one test
2207 // that should run.
test_case_to_run_count() const2208 int UnitTestImpl::test_case_to_run_count() const {
2209   return CountIf(test_cases_, ShouldRunTestCase);
2210 }
2211 
2212 // Gets the number of successful tests.
successful_test_count() const2213 int UnitTestImpl::successful_test_count() const {
2214   return SumOverTestCaseList(test_cases_, &TestCase::successful_test_count);
2215 }
2216 
2217 // Gets the number of failed tests.
failed_test_count() const2218 int UnitTestImpl::failed_test_count() const {
2219   return SumOverTestCaseList(test_cases_, &TestCase::failed_test_count);
2220 }
2221 
2222 // Gets the number of disabled tests that will be reported in the XML report.
reportable_disabled_test_count() const2223 int UnitTestImpl::reportable_disabled_test_count() const {
2224   return SumOverTestCaseList(test_cases_,
2225                              &TestCase::reportable_disabled_test_count);
2226 }
2227 
2228 // Gets the number of disabled tests.
disabled_test_count() const2229 int UnitTestImpl::disabled_test_count() const {
2230   return SumOverTestCaseList(test_cases_, &TestCase::disabled_test_count);
2231 }
2232 
2233 // Gets the number of tests to be printed in the XML report.
reportable_test_count() const2234 int UnitTestImpl::reportable_test_count() const {
2235   return SumOverTestCaseList(test_cases_, &TestCase::reportable_test_count);
2236 }
2237 
2238 // Gets the number of all tests.
total_test_count() const2239 int UnitTestImpl::total_test_count() const {
2240   return SumOverTestCaseList(test_cases_, &TestCase::total_test_count);
2241 }
2242 
2243 // Gets the number of tests that should run.
test_to_run_count() const2244 int UnitTestImpl::test_to_run_count() const {
2245   return SumOverTestCaseList(test_cases_, &TestCase::test_to_run_count);
2246 }
2247 
2248 // Returns the current OS stack trace as an std::string.
2249 //
2250 // The maximum number of stack frames to be included is specified by
2251 // the gtest_stack_trace_depth flag.  The skip_count parameter
2252 // specifies the number of top frames to be skipped, which doesn't
2253 // count against the number of frames to be included.
2254 //
2255 // For example, if Foo() calls Bar(), which in turn calls
2256 // CurrentOsStackTraceExceptTop(1), Foo() will be included in the
2257 // trace but Bar() and CurrentOsStackTraceExceptTop() won't.
CurrentOsStackTraceExceptTop(int skip_count)2258 std::string UnitTestImpl::CurrentOsStackTraceExceptTop(int skip_count) {
2259   (void)skip_count;
2260   return "";
2261 }
2262 
2263 // Returns the current time in milliseconds.
GetTimeInMillis()2264 TimeInMillis GetTimeInMillis() {
2265 #if GTEST_OS_WINDOWS_MOBILE || defined(__BORLANDC__)
2266   // Difference between 1970-01-01 and 1601-01-01 in milliseconds.
2267   // http://analogous.blogspot.com/2005/04/epoch.html
2268   const TimeInMillis kJavaEpochToWinFileTimeDelta =
2269     static_cast<TimeInMillis>(116444736UL) * 100000UL;
2270   const DWORD kTenthMicrosInMilliSecond = 10000;
2271 
2272   SYSTEMTIME now_systime;
2273   FILETIME now_filetime;
2274   ULARGE_INTEGER now_int64;
2275   // TODO(kenton@google.com): Shouldn't this just use
2276   //   GetSystemTimeAsFileTime()?
2277   GetSystemTime(&now_systime);
2278   if (SystemTimeToFileTime(&now_systime, &now_filetime)) {
2279     now_int64.LowPart = now_filetime.dwLowDateTime;
2280     now_int64.HighPart = now_filetime.dwHighDateTime;
2281     now_int64.QuadPart = (now_int64.QuadPart / kTenthMicrosInMilliSecond) -
2282       kJavaEpochToWinFileTimeDelta;
2283     return now_int64.QuadPart;
2284   }
2285   return 0;
2286 #elif GTEST_OS_WINDOWS && !GTEST_HAS_GETTIMEOFDAY_
2287   __timeb64 now;
2288 
2289 # ifdef _MSC_VER
2290 
2291   // MSVC 8 deprecates _ftime64(), so we want to suppress warning 4996
2292   // (deprecated function) there.
2293   // TODO(kenton@google.com): Use GetTickCount()?  Or use
2294   //   SystemTimeToFileTime()
2295 #  pragma warning(push)          // Saves the current warning state.
2296 #  pragma warning(disable:4996)  // Temporarily disables warning 4996.
2297   _ftime64(&now);
2298 #  pragma warning(pop)           // Restores the warning state.
2299 # else
2300 
2301   _ftime64(&now);
2302 
2303 # endif  // _MSC_VER
2304 
2305   return static_cast<TimeInMillis>(now.time) * 1000 + now.millitm;
2306 #elif GTEST_HAS_GETTIMEOFDAY_
2307   struct timeval now;
2308   gettimeofday(&now, NULL);
2309   return static_cast<TimeInMillis>(now.tv_sec) * 1000 + now.tv_usec / 1000;
2310 #else
2311 # error "Don't know how to get the current time on your system."
2312 #endif
2313 }
2314 
2315 // Utilities
2316 
2317 // class String.
2318 
2319 #if GTEST_OS_WINDOWS_MOBILE
2320 // Creates a UTF-16 wide string from the given ANSI string, allocating
2321 // memory using new. The caller is responsible for deleting the return
2322 // value using delete[]. Returns the wide string, or NULL if the
2323 // input is NULL.
AnsiToUtf16(const char * ansi)2324 LPCWSTR String::AnsiToUtf16(const char* ansi) {
2325   if (!ansi) return NULL;
2326   const int length = strlen(ansi);
2327   const int unicode_length =
2328       MultiByteToWideChar(CP_ACP, 0, ansi, length,
2329                           NULL, 0);
2330   WCHAR* unicode = new WCHAR[unicode_length + 1];
2331   MultiByteToWideChar(CP_ACP, 0, ansi, length,
2332                       unicode, unicode_length);
2333   unicode[unicode_length] = 0;
2334   return unicode;
2335 }
2336 
2337 // Creates an ANSI string from the given wide string, allocating
2338 // memory using new. The caller is responsible for deleting the return
2339 // value using delete[]. Returns the ANSI string, or NULL if the
2340 // input is NULL.
Utf16ToAnsi(LPCWSTR utf16_str)2341 const char* String::Utf16ToAnsi(LPCWSTR utf16_str)  {
2342   if (!utf16_str) return NULL;
2343   const int ansi_length =
2344       WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
2345                           NULL, 0, NULL, NULL);
2346   char* ansi = new char[ansi_length + 1];
2347   WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
2348                       ansi, ansi_length, NULL, NULL);
2349   ansi[ansi_length] = 0;
2350   return ansi;
2351 }
2352 
2353 #endif  // GTEST_OS_WINDOWS_MOBILE
2354 
2355 // Compares two C strings.  Returns true iff they have the same content.
2356 //
2357 // Unlike strcmp(), this function can handle NULL argument(s).  A NULL
2358 // C string is considered different to any non-NULL C string,
2359 // including the empty string.
CStringEquals(const char * lhs,const char * rhs)2360 bool String::CStringEquals(const char * lhs, const char * rhs) {
2361   if ( lhs == NULL ) return rhs == NULL;
2362 
2363   if ( rhs == NULL ) return false;
2364 
2365   return strcmp(lhs, rhs) == 0;
2366 }
2367 
2368 #if GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
2369 
2370 // Converts an array of wide chars to a narrow string using the UTF-8
2371 // encoding, and streams the result to the given Message object.
StreamWideCharsToMessage(const wchar_t * wstr,size_t length,Message * msg)2372 static void StreamWideCharsToMessage(const wchar_t* wstr, size_t length,
2373                                      Message* msg) {
2374   for (size_t i = 0; i != length; ) {  // NOLINT
2375     if (wstr[i] != L'\0') {
2376       *msg << WideStringToUtf8(wstr + i, static_cast<int>(length - i));
2377       while (i != length && wstr[i] != L'\0')
2378         i++;
2379     } else {
2380       *msg << '\0';
2381       i++;
2382     }
2383   }
2384 }
2385 
2386 #endif  // GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
2387 
2388 }  // namespace internal
2389 
2390 // Constructs an empty Message.
2391 // We allocate the stringstream separately because otherwise each use of
2392 // ASSERT/EXPECT in a procedure adds over 200 bytes to the procedure's
2393 // stack frame leading to huge stack frames in some cases; gcc does not reuse
2394 // the stack space.
Message()2395 Message::Message() : ss_(new ::std::stringstream) {
2396   // By default, we want there to be enough precision when printing
2397   // a double to a Message.
2398   *ss_ << std::setprecision(std::numeric_limits<double>::digits10 + 2);
2399 }
2400 
2401 // These two overloads allow streaming a wide C string to a Message
2402 // using the UTF-8 encoding.
operator <<(const wchar_t * wide_c_str)2403 Message& Message::operator <<(const wchar_t* wide_c_str) {
2404   return *this << internal::String::ShowWideCString(wide_c_str);
2405 }
operator <<(wchar_t * wide_c_str)2406 Message& Message::operator <<(wchar_t* wide_c_str) {
2407   return *this << internal::String::ShowWideCString(wide_c_str);
2408 }
2409 
2410 #if GTEST_HAS_STD_WSTRING
2411 // Converts the given wide string to a narrow string using the UTF-8
2412 // encoding, and streams the result to this Message object.
operator <<(const::std::wstring & wstr)2413 Message& Message::operator <<(const ::std::wstring& wstr) {
2414   internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
2415   return *this;
2416 }
2417 #endif  // GTEST_HAS_STD_WSTRING
2418 
2419 #if GTEST_HAS_GLOBAL_WSTRING
2420 // Converts the given wide string to a narrow string using the UTF-8
2421 // encoding, and streams the result to this Message object.
operator <<(const::wstring & wstr)2422 Message& Message::operator <<(const ::wstring& wstr) {
2423   internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
2424   return *this;
2425 }
2426 #endif  // GTEST_HAS_GLOBAL_WSTRING
2427 
2428 // Gets the text streamed to this object so far as an std::string.
2429 // Each '\0' character in the buffer is replaced with "\\0".
GetString() const2430 std::string Message::GetString() const {
2431   return internal::StringStreamToString(ss_.get());
2432 }
2433 
2434 // AssertionResult constructors.
2435 // Used in EXPECT_TRUE/FALSE(assertion_result).
AssertionResult(const AssertionResult & other)2436 AssertionResult::AssertionResult(const AssertionResult& other)
2437     : success_(other.success_),
2438       message_(other.message_.get() != NULL ?
2439                new ::std::string(*other.message_) :
2440                static_cast< ::std::string*>(NULL)) {
2441 }
2442 
2443 // Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE.
operator !() const2444 AssertionResult AssertionResult::operator!() const {
2445   AssertionResult negation(!success_);
2446   if (message_.get() != NULL)
2447     negation << *message_;
2448   return negation;
2449 }
2450 
2451 // Makes a successful assertion result.
AssertionSuccess()2452 AssertionResult AssertionSuccess() {
2453   return AssertionResult(true);
2454 }
2455 
2456 // Makes a failed assertion result.
AssertionFailure()2457 AssertionResult AssertionFailure() {
2458   return AssertionResult(false);
2459 }
2460 
2461 // Makes a failed assertion result with the given failure message.
2462 // Deprecated; use AssertionFailure() << message.
AssertionFailure(const Message & message)2463 AssertionResult AssertionFailure(const Message& message) {
2464   return AssertionFailure() << message;
2465 }
2466 
2467 namespace internal {
2468 
2469 // Constructs and returns the message for an equality assertion
2470 // (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure.
2471 //
2472 // The first four parameters are the expressions used in the assertion
2473 // and their values, as strings.  For example, for ASSERT_EQ(foo, bar)
2474 // where foo is 5 and bar is 6, we have:
2475 //
2476 //   expected_expression: "foo"
2477 //   actual_expression:   "bar"
2478 //   expected_value:      "5"
2479 //   actual_value:        "6"
2480 //
2481 // The ignoring_case parameter is true iff the assertion is a
2482 // *_STRCASEEQ*.  When it's true, the string " (ignoring case)" will
2483 // 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)2484 AssertionResult EqFailure(const char* expected_expression,
2485                           const char* actual_expression,
2486                           const std::string& expected_value,
2487                           const std::string& actual_value,
2488                           bool ignoring_case) {
2489   Message msg;
2490   msg << "Value of: " << actual_expression;
2491   if (actual_value != actual_expression) {
2492     msg << "\n  Actual: " << actual_value;
2493   }
2494 
2495   msg << "\nExpected: " << expected_expression;
2496   if (ignoring_case) {
2497     msg << " (ignoring case)";
2498   }
2499   if (expected_value != expected_expression) {
2500     msg << "\nWhich is: " << expected_value;
2501   }
2502 
2503   return AssertionFailure() << msg;
2504 }
2505 
2506 // 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)2507 std::string GetBoolAssertionFailureMessage(
2508     const AssertionResult& assertion_result,
2509     const char* expression_text,
2510     const char* actual_predicate_value,
2511     const char* expected_predicate_value) {
2512   const char* actual_message = assertion_result.message();
2513   Message msg;
2514   msg << "Value of: " << expression_text
2515       << "\n  Actual: " << actual_predicate_value;
2516   if (actual_message[0] != '\0')
2517     msg << " (" << actual_message << ")";
2518   msg << "\nExpected: " << expected_predicate_value;
2519   return msg.GetString();
2520 }
2521 
2522 // 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)2523 AssertionResult DoubleNearPredFormat(const char* expr1,
2524                                      const char* expr2,
2525                                      const char* abs_error_expr,
2526                                      double val1,
2527                                      double val2,
2528                                      double abs_error) {
2529   const double diff = fabs(val1 - val2);
2530   if (diff <= abs_error) return AssertionSuccess();
2531 
2532   // TODO(wan): do not print the value of an expression if it's
2533   // already a literal.
2534   return AssertionFailure()
2535       << "The difference between " << expr1 << " and " << expr2
2536       << " is " << diff << ", which exceeds " << abs_error_expr << ", where\n"
2537       << expr1 << " evaluates to " << val1 << ",\n"
2538       << expr2 << " evaluates to " << val2 << ", and\n"
2539       << abs_error_expr << " evaluates to " << abs_error << ".";
2540 }
2541 
2542 
2543 // Helper template for implementing FloatLE() and DoubleLE().
2544 template <typename RawType>
FloatingPointLE(const char * expr1,const char * expr2,RawType val1,RawType val2)2545 AssertionResult FloatingPointLE(const char* expr1,
2546                                 const char* expr2,
2547                                 RawType val1,
2548                                 RawType val2) {
2549   // Returns success if val1 is less than val2,
2550   if (val1 < val2) {
2551     return AssertionSuccess();
2552   }
2553 
2554   // or if val1 is almost equal to val2.
2555   const FloatingPoint<RawType> lhs(val1), rhs(val2);
2556   if (lhs.AlmostEquals(rhs)) {
2557     return AssertionSuccess();
2558   }
2559 
2560   // Note that the above two checks will both fail if either val1 or
2561   // val2 is NaN, as the IEEE floating-point standard requires that
2562   // any predicate involving a NaN must return false.
2563 
2564   ::std::stringstream val1_ss;
2565   val1_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
2566           << val1;
2567 
2568   ::std::stringstream val2_ss;
2569   val2_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
2570           << val2;
2571 
2572   return AssertionFailure()
2573       << "Expected: (" << expr1 << ") <= (" << expr2 << ")\n"
2574       << "  Actual: " << StringStreamToString(&val1_ss) << " vs "
2575       << StringStreamToString(&val2_ss);
2576 }
2577 
2578 }  // namespace internal
2579 
2580 // Asserts that val1 is less than, or almost equal to, val2.  Fails
2581 // otherwise.  In particular, it fails if either val1 or val2 is NaN.
FloatLE(const char * expr1,const char * expr2,float val1,float val2)2582 AssertionResult FloatLE(const char* expr1, const char* expr2,
2583                         float val1, float val2) {
2584   return internal::FloatingPointLE<float>(expr1, expr2, val1, val2);
2585 }
2586 
2587 // Asserts that val1 is less than, or almost equal to, val2.  Fails
2588 // otherwise.  In particular, it fails if either val1 or val2 is NaN.
DoubleLE(const char * expr1,const char * expr2,double val1,double val2)2589 AssertionResult DoubleLE(const char* expr1, const char* expr2,
2590                          double val1, double val2) {
2591   return internal::FloatingPointLE<double>(expr1, expr2, val1, val2);
2592 }
2593 
2594 namespace internal {
2595 
2596 // The helper function for {ASSERT|EXPECT}_EQ with int or enum
2597 // arguments.
CmpHelperEQ(const char * expected_expression,const char * actual_expression,BiggestInt expected,BiggestInt actual)2598 AssertionResult CmpHelperEQ(const char* expected_expression,
2599                             const char* actual_expression,
2600                             BiggestInt expected,
2601                             BiggestInt actual) {
2602   if (expected == actual) {
2603     return AssertionSuccess();
2604   }
2605 
2606   return EqFailure(expected_expression,
2607                    actual_expression,
2608                    FormatForComparisonFailureMessage(expected, actual),
2609                    FormatForComparisonFailureMessage(actual, expected),
2610                    false);
2611 }
2612 
2613 // A macro for implementing the helper functions needed to implement
2614 // ASSERT_?? and EXPECT_?? with integer or enum arguments.  It is here
2615 // just to avoid copy-and-paste of similar code.
2616 #define GTEST_IMPL_CMP_HELPER_(op_name, op)\
2617 AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \
2618                                    BiggestInt val1, BiggestInt val2) {\
2619   if (val1 op val2) {\
2620     return AssertionSuccess();\
2621   } else {\
2622     return AssertionFailure() \
2623         << "Expected: (" << expr1 << ") " #op " (" << expr2\
2624         << "), actual: " << FormatForComparisonFailureMessage(val1, val2)\
2625         << " vs " << FormatForComparisonFailureMessage(val2, val1);\
2626   }\
2627 }
2628 
2629 // Implements the helper function for {ASSERT|EXPECT}_NE with int or
2630 // enum arguments.
2631 GTEST_IMPL_CMP_HELPER_(NE, !=)
2632 // Implements the helper function for {ASSERT|EXPECT}_LE with int or
2633 // enum arguments.
2634 GTEST_IMPL_CMP_HELPER_(LE, <=)
2635 // Implements the helper function for {ASSERT|EXPECT}_LT with int or
2636 // enum arguments.
2637 GTEST_IMPL_CMP_HELPER_(LT, < )
2638 // Implements the helper function for {ASSERT|EXPECT}_GE with int or
2639 // enum arguments.
2640 GTEST_IMPL_CMP_HELPER_(GE, >=)
2641 // Implements the helper function for {ASSERT|EXPECT}_GT with int or
2642 // enum arguments.
2643 GTEST_IMPL_CMP_HELPER_(GT, > )
2644 
2645 #undef GTEST_IMPL_CMP_HELPER_
2646 
2647 // The helper function for {ASSERT|EXPECT}_STREQ.
CmpHelperSTREQ(const char * expected_expression,const char * actual_expression,const char * expected,const char * actual)2648 AssertionResult CmpHelperSTREQ(const char* expected_expression,
2649                                const char* actual_expression,
2650                                const char* expected,
2651                                const char* actual) {
2652   if (String::CStringEquals(expected, actual)) {
2653     return AssertionSuccess();
2654   }
2655 
2656   return EqFailure(expected_expression,
2657                    actual_expression,
2658                    PrintToString(expected),
2659                    PrintToString(actual),
2660                    false);
2661 }
2662 
2663 // The helper function for {ASSERT|EXPECT}_STRCASEEQ.
CmpHelperSTRCASEEQ(const char * expected_expression,const char * actual_expression,const char * expected,const char * actual)2664 AssertionResult CmpHelperSTRCASEEQ(const char* expected_expression,
2665                                    const char* actual_expression,
2666                                    const char* expected,
2667                                    const char* actual) {
2668   if (String::CaseInsensitiveCStringEquals(expected, actual)) {
2669     return AssertionSuccess();
2670   }
2671 
2672   return EqFailure(expected_expression,
2673                    actual_expression,
2674                    PrintToString(expected),
2675                    PrintToString(actual),
2676                    true);
2677 }
2678 
2679 // The helper function for {ASSERT|EXPECT}_STRNE.
CmpHelperSTRNE(const char * s1_expression,const char * s2_expression,const char * s1,const char * s2)2680 AssertionResult CmpHelperSTRNE(const char* s1_expression,
2681                                const char* s2_expression,
2682                                const char* s1,
2683                                const char* s2) {
2684   if (!String::CStringEquals(s1, s2)) {
2685     return AssertionSuccess();
2686   } else {
2687     return AssertionFailure() << "Expected: (" << s1_expression << ") != ("
2688                               << s2_expression << "), actual: \""
2689                               << s1 << "\" vs \"" << s2 << "\"";
2690   }
2691 }
2692 
2693 // The helper function for {ASSERT|EXPECT}_STRCASENE.
CmpHelperSTRCASENE(const char * s1_expression,const char * s2_expression,const char * s1,const char * s2)2694 AssertionResult CmpHelperSTRCASENE(const char* s1_expression,
2695                                    const char* s2_expression,
2696                                    const char* s1,
2697                                    const char* s2) {
2698   if (!String::CaseInsensitiveCStringEquals(s1, s2)) {
2699     return AssertionSuccess();
2700   } else {
2701     return AssertionFailure()
2702         << "Expected: (" << s1_expression << ") != ("
2703         << s2_expression << ") (ignoring case), actual: \""
2704         << s1 << "\" vs \"" << s2 << "\"";
2705   }
2706 }
2707 
2708 }  // namespace internal
2709 
2710 namespace {
2711 
2712 // Helper functions for implementing IsSubString() and IsNotSubstring().
2713 
2714 // This group of overloaded functions return true iff needle is a
2715 // substring of haystack.  NULL is considered a substring of itself
2716 // only.
2717 
IsSubstringPred(const char * needle,const char * haystack)2718 bool IsSubstringPred(const char* needle, const char* haystack) {
2719   if (needle == NULL || haystack == NULL)
2720     return needle == haystack;
2721 
2722   return strstr(haystack, needle) != NULL;
2723 }
2724 
IsSubstringPred(const wchar_t * needle,const wchar_t * haystack)2725 bool IsSubstringPred(const wchar_t* needle, const wchar_t* haystack) {
2726   if (needle == NULL || haystack == NULL)
2727     return needle == haystack;
2728 
2729   return wcsstr(haystack, needle) != NULL;
2730 }
2731 
2732 // StringType here can be either ::std::string or ::std::wstring.
2733 template <typename StringType>
IsSubstringPred(const StringType & needle,const StringType & haystack)2734 bool IsSubstringPred(const StringType& needle,
2735                      const StringType& haystack) {
2736   return haystack.find(needle) != StringType::npos;
2737 }
2738 
2739 // This function implements either IsSubstring() or IsNotSubstring(),
2740 // depending on the value of the expected_to_be_substring parameter.
2741 // StringType here can be const char*, const wchar_t*, ::std::string,
2742 // or ::std::wstring.
2743 template <typename StringType>
IsSubstringImpl(bool expected_to_be_substring,const char * needle_expr,const char * haystack_expr,const StringType & needle,const StringType & haystack)2744 AssertionResult IsSubstringImpl(
2745     bool expected_to_be_substring,
2746     const char* needle_expr, const char* haystack_expr,
2747     const StringType& needle, const StringType& haystack) {
2748   if (IsSubstringPred(needle, haystack) == expected_to_be_substring)
2749     return AssertionSuccess();
2750 
2751   const bool is_wide_string = sizeof(needle[0]) > 1;
2752   const char* const begin_string_quote = is_wide_string ? "L\"" : "\"";
2753   return AssertionFailure()
2754       << "Value of: " << needle_expr << "\n"
2755       << "  Actual: " << begin_string_quote << needle << "\"\n"
2756       << "Expected: " << (expected_to_be_substring ? "" : "not ")
2757       << "a substring of " << haystack_expr << "\n"
2758       << "Which is: " << begin_string_quote << haystack << "\"";
2759 }
2760 
2761 }  // namespace
2762 
2763 // IsSubstring() and IsNotSubstring() check whether needle is a
2764 // substring of haystack (NULL is considered a substring of itself
2765 // only), and return an appropriate error message when they fail.
2766 
IsSubstring(const char * needle_expr,const char * haystack_expr,const char * needle,const char * haystack)2767 AssertionResult IsSubstring(
2768     const char* needle_expr, const char* haystack_expr,
2769     const char* needle, const char* haystack) {
2770   return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
2771 }
2772 
IsSubstring(const char * needle_expr,const char * haystack_expr,const wchar_t * needle,const wchar_t * haystack)2773 AssertionResult IsSubstring(
2774     const char* needle_expr, const char* haystack_expr,
2775     const wchar_t* needle, const wchar_t* haystack) {
2776   return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
2777 }
2778 
IsNotSubstring(const char * needle_expr,const char * haystack_expr,const char * needle,const char * haystack)2779 AssertionResult IsNotSubstring(
2780     const char* needle_expr, const char* haystack_expr,
2781     const char* needle, const char* haystack) {
2782   return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
2783 }
2784 
IsNotSubstring(const char * needle_expr,const char * haystack_expr,const wchar_t * needle,const wchar_t * haystack)2785 AssertionResult IsNotSubstring(
2786     const char* needle_expr, const char* haystack_expr,
2787     const wchar_t* needle, const wchar_t* haystack) {
2788   return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
2789 }
2790 
IsSubstring(const char * needle_expr,const char * haystack_expr,const::std::string & needle,const::std::string & haystack)2791 AssertionResult IsSubstring(
2792     const char* needle_expr, const char* haystack_expr,
2793     const ::std::string& needle, const ::std::string& haystack) {
2794   return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
2795 }
2796 
IsNotSubstring(const char * needle_expr,const char * haystack_expr,const::std::string & needle,const::std::string & haystack)2797 AssertionResult IsNotSubstring(
2798     const char* needle_expr, const char* haystack_expr,
2799     const ::std::string& needle, const ::std::string& haystack) {
2800   return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
2801 }
2802 
2803 #if GTEST_HAS_STD_WSTRING
IsSubstring(const char * needle_expr,const char * haystack_expr,const::std::wstring & needle,const::std::wstring & haystack)2804 AssertionResult IsSubstring(
2805     const char* needle_expr, const char* haystack_expr,
2806     const ::std::wstring& needle, const ::std::wstring& haystack) {
2807   return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
2808 }
2809 
IsNotSubstring(const char * needle_expr,const char * haystack_expr,const::std::wstring & needle,const::std::wstring & haystack)2810 AssertionResult IsNotSubstring(
2811     const char* needle_expr, const char* haystack_expr,
2812     const ::std::wstring& needle, const ::std::wstring& haystack) {
2813   return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
2814 }
2815 #endif  // GTEST_HAS_STD_WSTRING
2816 
2817 namespace internal {
2818 
2819 #if GTEST_OS_WINDOWS
2820 
2821 namespace {
2822 
2823 // Helper function for IsHRESULT{SuccessFailure} predicates
HRESULTFailureHelper(const char * expr,const char * expected,long hr)2824 AssertionResult HRESULTFailureHelper(const char* expr,
2825                                      const char* expected,
2826                                      long hr) {  // NOLINT
2827 # if GTEST_OS_WINDOWS_MOBILE
2828 
2829   // Windows CE doesn't support FormatMessage.
2830   const char error_text[] = "";
2831 
2832 # else
2833 
2834   // Looks up the human-readable system message for the HRESULT code
2835   // and since we're not passing any params to FormatMessage, we don't
2836   // want inserts expanded.
2837   const DWORD kFlags = FORMAT_MESSAGE_FROM_SYSTEM |
2838                        FORMAT_MESSAGE_IGNORE_INSERTS;
2839   const DWORD kBufSize = 4096;
2840   // Gets the system's human readable message string for this HRESULT.
2841   char error_text[kBufSize] = { '\0' };
2842   DWORD message_length = ::FormatMessageA(kFlags,
2843                                           0,  // no source, we're asking system
2844                                           hr,  // the error
2845                                           0,  // no line width restrictions
2846                                           error_text,  // output buffer
2847                                           kBufSize,  // buf size
2848                                           NULL);  // no arguments for inserts
2849   // Trims tailing white space (FormatMessage leaves a trailing CR-LF)
2850   for (; message_length && IsSpace(error_text[message_length - 1]);
2851           --message_length) {
2852     error_text[message_length - 1] = '\0';
2853   }
2854 
2855 # endif  // GTEST_OS_WINDOWS_MOBILE
2856 
2857   const std::string error_hex("0x" + String::FormatHexInt(hr));
2858   return ::testing::AssertionFailure()
2859       << "Expected: " << expr << " " << expected << ".\n"
2860       << "  Actual: " << error_hex << " " << error_text << "\n";
2861 }
2862 
2863 }  // namespace
2864 
IsHRESULTSuccess(const char * expr,long hr)2865 AssertionResult IsHRESULTSuccess(const char* expr, long hr) {  // NOLINT
2866   if (SUCCEEDED(hr)) {
2867     return AssertionSuccess();
2868   }
2869   return HRESULTFailureHelper(expr, "succeeds", hr);
2870 }
2871 
IsHRESULTFailure(const char * expr,long hr)2872 AssertionResult IsHRESULTFailure(const char* expr, long hr) {  // NOLINT
2873   if (FAILED(hr)) {
2874     return AssertionSuccess();
2875   }
2876   return HRESULTFailureHelper(expr, "fails", hr);
2877 }
2878 
2879 #endif  // GTEST_OS_WINDOWS
2880 
2881 // Utility functions for encoding Unicode text (wide strings) in
2882 // UTF-8.
2883 
2884 // A Unicode code-point can have upto 21 bits, and is encoded in UTF-8
2885 // like this:
2886 //
2887 // Code-point length   Encoding
2888 //   0 -  7 bits       0xxxxxxx
2889 //   8 - 11 bits       110xxxxx 10xxxxxx
2890 //  12 - 16 bits       1110xxxx 10xxxxxx 10xxxxxx
2891 //  17 - 21 bits       11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
2892 
2893 // The maximum code-point a one-byte UTF-8 sequence can represent.
2894 const UInt32 kMaxCodePoint1 = (static_cast<UInt32>(1) <<  7) - 1;
2895 
2896 // The maximum code-point a two-byte UTF-8 sequence can represent.
2897 const UInt32 kMaxCodePoint2 = (static_cast<UInt32>(1) << (5 + 6)) - 1;
2898 
2899 // The maximum code-point a three-byte UTF-8 sequence can represent.
2900 const UInt32 kMaxCodePoint3 = (static_cast<UInt32>(1) << (4 + 2*6)) - 1;
2901 
2902 // The maximum code-point a four-byte UTF-8 sequence can represent.
2903 const UInt32 kMaxCodePoint4 = (static_cast<UInt32>(1) << (3 + 3*6)) - 1;
2904 
2905 // Chops off the n lowest bits from a bit pattern.  Returns the n
2906 // lowest bits.  As a side effect, the original bit pattern will be
2907 // shifted to the right by n bits.
ChopLowBits(UInt32 * bits,int n)2908 inline UInt32 ChopLowBits(UInt32* bits, int n) {
2909   const UInt32 low_bits = *bits & ((static_cast<UInt32>(1) << n) - 1);
2910   *bits >>= n;
2911   return low_bits;
2912 }
2913 
2914 // Converts a Unicode code point to a narrow string in UTF-8 encoding.
2915 // code_point parameter is of type UInt32 because wchar_t may not be
2916 // wide enough to contain a code point.
2917 // If the code_point is not a valid Unicode code point
2918 // (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted
2919 // to "(Invalid Unicode 0xXXXXXXXX)".
CodePointToUtf8(UInt32 code_point)2920 std::string CodePointToUtf8(UInt32 code_point) {
2921   if (code_point > kMaxCodePoint4) {
2922     return "(Invalid Unicode 0x" + String::FormatHexInt(code_point) + ")";
2923   }
2924 
2925   char str[5];  // Big enough for the largest valid code point.
2926   if (code_point <= kMaxCodePoint1) {
2927     str[1] = '\0';
2928     str[0] = static_cast<char>(code_point);                          // 0xxxxxxx
2929   } else if (code_point <= kMaxCodePoint2) {
2930     str[2] = '\0';
2931     str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx
2932     str[0] = static_cast<char>(0xC0 | code_point);                   // 110xxxxx
2933   } else if (code_point <= kMaxCodePoint3) {
2934     str[3] = '\0';
2935     str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx
2936     str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx
2937     str[0] = static_cast<char>(0xE0 | code_point);                   // 1110xxxx
2938   } else {  // code_point <= kMaxCodePoint4
2939     str[4] = '\0';
2940     str[3] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx
2941     str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx
2942     str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx
2943     str[0] = static_cast<char>(0xF0 | code_point);                   // 11110xxx
2944   }
2945   return str;
2946 }
2947 
2948 // The following two functions only make sense if the the system
2949 // uses UTF-16 for wide string encoding. All supported systems
2950 // with 16 bit wchar_t (Windows, Cygwin, Symbian OS) do use UTF-16.
2951 
2952 // Determines if the arguments constitute UTF-16 surrogate pair
2953 // and thus should be combined into a single Unicode code point
2954 // using CreateCodePointFromUtf16SurrogatePair.
IsUtf16SurrogatePair(wchar_t first,wchar_t second)2955 inline bool IsUtf16SurrogatePair(wchar_t first, wchar_t second) {
2956   return sizeof(wchar_t) == 2 &&
2957       (first & 0xFC00) == 0xD800 && (second & 0xFC00) == 0xDC00;
2958 }
2959 
2960 // Creates a Unicode code point from UTF16 surrogate pair.
CreateCodePointFromUtf16SurrogatePair(wchar_t first,wchar_t second)2961 inline UInt32 CreateCodePointFromUtf16SurrogatePair(wchar_t first,
2962                                                     wchar_t second) {
2963   const UInt32 mask = (1 << 10) - 1;
2964   return (sizeof(wchar_t) == 2) ?
2965       (((first & mask) << 10) | (second & mask)) + 0x10000 :
2966       // This function should not be called when the condition is
2967       // false, but we provide a sensible default in case it is.
2968       static_cast<UInt32>(first);
2969 }
2970 
2971 // Converts a wide string to a narrow string in UTF-8 encoding.
2972 // The wide string is assumed to have the following encoding:
2973 //   UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS)
2974 //   UTF-32 if sizeof(wchar_t) == 4 (on Linux)
2975 // Parameter str points to a null-terminated wide string.
2976 // Parameter num_chars may additionally limit the number
2977 // of wchar_t characters processed. -1 is used when the entire string
2978 // should be processed.
2979 // If the string contains code points that are not valid Unicode code points
2980 // (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
2981 // as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
2982 // and contains invalid UTF-16 surrogate pairs, values in those pairs
2983 // will be encoded as individual Unicode characters from Basic Normal Plane.
WideStringToUtf8(const wchar_t * str,int num_chars)2984 std::string WideStringToUtf8(const wchar_t* str, int num_chars) {
2985   if (num_chars == -1)
2986     num_chars = static_cast<int>(wcslen(str));
2987 
2988   ::std::stringstream stream;
2989   for (int i = 0; i < num_chars; ++i) {
2990     UInt32 unicode_code_point;
2991 
2992     if (str[i] == L'\0') {
2993       break;
2994     } else if (i + 1 < num_chars && IsUtf16SurrogatePair(str[i], str[i + 1])) {
2995       unicode_code_point = CreateCodePointFromUtf16SurrogatePair(str[i],
2996                                                                  str[i + 1]);
2997       i++;
2998     } else {
2999       unicode_code_point = static_cast<UInt32>(str[i]);
3000     }
3001 
3002     stream << CodePointToUtf8(unicode_code_point);
3003   }
3004   return StringStreamToString(&stream);
3005 }
3006 
3007 // Converts a wide C string to an std::string using the UTF-8 encoding.
3008 // NULL will be converted to "(null)".
ShowWideCString(const wchar_t * wide_c_str)3009 std::string String::ShowWideCString(const wchar_t * wide_c_str) {
3010   if (wide_c_str == NULL)  return "(null)";
3011 
3012   return internal::WideStringToUtf8(wide_c_str, -1);
3013 }
3014 
3015 // Compares two wide C strings.  Returns true iff they have the same
3016 // content.
3017 //
3018 // Unlike wcscmp(), this function can handle NULL argument(s).  A NULL
3019 // C string is considered different to any non-NULL C string,
3020 // including the empty string.
WideCStringEquals(const wchar_t * lhs,const wchar_t * rhs)3021 bool String::WideCStringEquals(const wchar_t * lhs, const wchar_t * rhs) {
3022   if (lhs == NULL) return rhs == NULL;
3023 
3024   if (rhs == NULL) return false;
3025 
3026   return wcscmp(lhs, rhs) == 0;
3027 }
3028 
3029 // Helper function for *_STREQ on wide strings.
CmpHelperSTREQ(const char * expected_expression,const char * actual_expression,const wchar_t * expected,const wchar_t * actual)3030 AssertionResult CmpHelperSTREQ(const char* expected_expression,
3031                                const char* actual_expression,
3032                                const wchar_t* expected,
3033                                const wchar_t* actual) {
3034   if (String::WideCStringEquals(expected, actual)) {
3035     return AssertionSuccess();
3036   }
3037 
3038   return EqFailure(expected_expression,
3039                    actual_expression,
3040                    PrintToString(expected),
3041                    PrintToString(actual),
3042                    false);
3043 }
3044 
3045 // Helper function for *_STRNE on wide strings.
CmpHelperSTRNE(const char * s1_expression,const char * s2_expression,const wchar_t * s1,const wchar_t * s2)3046 AssertionResult CmpHelperSTRNE(const char* s1_expression,
3047                                const char* s2_expression,
3048                                const wchar_t* s1,
3049                                const wchar_t* s2) {
3050   if (!String::WideCStringEquals(s1, s2)) {
3051     return AssertionSuccess();
3052   }
3053 
3054   return AssertionFailure() << "Expected: (" << s1_expression << ") != ("
3055                             << s2_expression << "), actual: "
3056                             << PrintToString(s1)
3057                             << " vs " << PrintToString(s2);
3058 }
3059 
3060 // Compares two C strings, ignoring case.  Returns true iff they have
3061 // the same content.
3062 //
3063 // Unlike strcasecmp(), this function can handle NULL argument(s).  A
3064 // NULL C string is considered different to any non-NULL C string,
3065 // including the empty string.
CaseInsensitiveCStringEquals(const char * lhs,const char * rhs)3066 bool String::CaseInsensitiveCStringEquals(const char * lhs, const char * rhs) {
3067   if (lhs == NULL)
3068     return rhs == NULL;
3069   if (rhs == NULL)
3070     return false;
3071   return posix::StrCaseCmp(lhs, rhs) == 0;
3072 }
3073 
3074   // Compares two wide C strings, ignoring case.  Returns true iff they
3075   // have the same content.
3076   //
3077   // Unlike wcscasecmp(), this function can handle NULL argument(s).
3078   // A NULL C string is considered different to any non-NULL wide C string,
3079   // including the empty string.
3080   // NB: The implementations on different platforms slightly differ.
3081   // On windows, this method uses _wcsicmp which compares according to LC_CTYPE
3082   // environment variable. On GNU platform this method uses wcscasecmp
3083   // which compares according to LC_CTYPE category of the current locale.
3084   // On MacOS X, it uses towlower, which also uses LC_CTYPE category of the
3085   // current locale.
CaseInsensitiveWideCStringEquals(const wchar_t * lhs,const wchar_t * rhs)3086 bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs,
3087                                               const wchar_t* rhs) {
3088   if (lhs == NULL) return rhs == NULL;
3089 
3090   if (rhs == NULL) return false;
3091 
3092 #if GTEST_OS_WINDOWS
3093   return _wcsicmp(lhs, rhs) == 0;
3094 #elif GTEST_OS_LINUX && !GTEST_OS_LINUX_ANDROID
3095   return wcscasecmp(lhs, rhs) == 0;
3096 #else
3097   // Android, Mac OS X and Cygwin don't define wcscasecmp.
3098   // Other unknown OSes may not define it either.
3099   wint_t left, right;
3100   do {
3101     left = towlower(*lhs++);
3102     right = towlower(*rhs++);
3103   } while (left && left == right);
3104   return left == right;
3105 #endif  // OS selector
3106 }
3107 
3108 // Returns true iff str ends with the given suffix, ignoring case.
3109 // Any string is considered to end with an empty suffix.
EndsWithCaseInsensitive(const std::string & str,const std::string & suffix)3110 bool String::EndsWithCaseInsensitive(
3111     const std::string& str, const std::string& suffix) {
3112   const size_t str_len = str.length();
3113   const size_t suffix_len = suffix.length();
3114   return (str_len >= suffix_len) &&
3115          CaseInsensitiveCStringEquals(str.c_str() + str_len - suffix_len,
3116                                       suffix.c_str());
3117 }
3118 
3119 // Formats an int value as "%02d".
FormatIntWidth2(int value)3120 std::string String::FormatIntWidth2(int value) {
3121   std::stringstream ss;
3122   ss << std::setfill('0') << std::setw(2) << value;
3123   return ss.str();
3124 }
3125 
3126 // Formats an int value as "%X".
FormatHexInt(int value)3127 std::string String::FormatHexInt(int value) {
3128   std::stringstream ss;
3129   ss << std::hex << std::uppercase << value;
3130   return ss.str();
3131 }
3132 
3133 // Formats a byte as "%02X".
FormatByte(unsigned char value)3134 std::string String::FormatByte(unsigned char value) {
3135   std::stringstream ss;
3136   ss << std::setfill('0') << std::setw(2) << std::hex << std::uppercase
3137      << static_cast<unsigned int>(value);
3138   return ss.str();
3139 }
3140 
3141 // Converts the buffer in a stringstream to an std::string, converting NUL
3142 // bytes to "\\0" along the way.
StringStreamToString(::std::stringstream * ss)3143 std::string StringStreamToString(::std::stringstream* ss) {
3144   const ::std::string& str = ss->str();
3145   const char* const start = str.c_str();
3146   const char* const end = start + str.length();
3147 
3148   std::string result;
3149   result.reserve(2 * (end - start));
3150   for (const char* ch = start; ch != end; ++ch) {
3151     if (*ch == '\0') {
3152       result += "\\0";  // Replaces NUL with "\\0";
3153     } else {
3154       result += *ch;
3155     }
3156   }
3157 
3158   return result;
3159 }
3160 
3161 // Appends the user-supplied message to the Google-Test-generated message.
AppendUserMessage(const std::string & gtest_msg,const Message & user_msg)3162 std::string AppendUserMessage(const std::string& gtest_msg,
3163                               const Message& user_msg) {
3164   // Appends the user message if it's non-empty.
3165   const std::string user_msg_string = user_msg.GetString();
3166   if (user_msg_string.empty()) {
3167     return gtest_msg;
3168   }
3169 
3170   return gtest_msg + "\n" + user_msg_string;
3171 }
3172 
3173 }  // namespace internal
3174 
3175 // class TestResult
3176 
3177 // Creates an empty TestResult.
TestResult()3178 TestResult::TestResult()
3179     : death_test_count_(0),
3180       elapsed_time_(0) {
3181 }
3182 
3183 // D'tor.
~TestResult()3184 TestResult::~TestResult() {
3185 }
3186 
3187 // Returns the i-th test part result among all the results. i can
3188 // range from 0 to total_part_count() - 1. If i is not in that range,
3189 // aborts the program.
GetTestPartResult(int i) const3190 const TestPartResult& TestResult::GetTestPartResult(int i) const {
3191   if (i < 0 || i >= total_part_count())
3192     internal::posix::Abort();
3193   return test_part_results_.at(i);
3194 }
3195 
3196 // Returns the i-th test property. i can range from 0 to
3197 // test_property_count() - 1. If i is not in that range, aborts the
3198 // program.
GetTestProperty(int i) const3199 const TestProperty& TestResult::GetTestProperty(int i) const {
3200   if (i < 0 || i >= test_property_count())
3201     internal::posix::Abort();
3202   return test_properties_.at(i);
3203 }
3204 
3205 // Clears the test part results.
ClearTestPartResults()3206 void TestResult::ClearTestPartResults() {
3207   test_part_results_.clear();
3208 }
3209 
3210 // Adds a test part result to the list.
AddTestPartResult(const TestPartResult & test_part_result)3211 void TestResult::AddTestPartResult(const TestPartResult& test_part_result) {
3212   test_part_results_.push_back(test_part_result);
3213 }
3214 
3215 // Adds a test property to the list. If a property with the same key as the
3216 // supplied property is already represented, the value of this test_property
3217 // replaces the old value for that key.
RecordProperty(const std::string & xml_element,const TestProperty & test_property)3218 void TestResult::RecordProperty(const std::string& xml_element,
3219                                 const TestProperty& test_property) {
3220   if (!ValidateTestProperty(xml_element, test_property)) {
3221     return;
3222   }
3223   internal::MutexLock lock(&test_properites_mutex_);
3224   const std::vector<TestProperty>::iterator property_with_matching_key =
3225       std::find_if(test_properties_.begin(), test_properties_.end(),
3226                    internal::TestPropertyKeyIs(test_property.key()));
3227   if (property_with_matching_key == test_properties_.end()) {
3228     test_properties_.push_back(test_property);
3229     return;
3230   }
3231   property_with_matching_key->SetValue(test_property.value());
3232 }
3233 
3234 // The list of reserved attributes used in the <testsuites> element of XML
3235 // output.
3236 static const char* const kReservedTestSuitesAttributes[] = {
3237   "disabled",
3238   "errors",
3239   "failures",
3240   "name",
3241   "random_seed",
3242   "tests",
3243   "time",
3244   "timestamp"
3245 };
3246 
3247 // The list of reserved attributes used in the <testsuite> element of XML
3248 // output.
3249 static const char* const kReservedTestSuiteAttributes[] = {
3250   "disabled",
3251   "errors",
3252   "failures",
3253   "name",
3254   "tests",
3255   "time"
3256 };
3257 
3258 // The list of reserved attributes used in the <testcase> element of XML output.
3259 static const char* const kReservedTestCaseAttributes[] = {
3260   "classname",
3261   "name",
3262   "status",
3263   "time",
3264   "type_param",
3265   "value_param"
3266 };
3267 
3268 template <int kSize>
ArrayAsVector(const char * const (& array)[kSize])3269 std::vector<std::string> ArrayAsVector(const char* const (&array)[kSize]) {
3270   return std::vector<std::string>(array, array + kSize);
3271 }
3272 
GetReservedAttributesForElement(const std::string & xml_element)3273 static std::vector<std::string> GetReservedAttributesForElement(
3274     const std::string& xml_element) {
3275   if (xml_element == "testsuites") {
3276     return ArrayAsVector(kReservedTestSuitesAttributes);
3277   } else if (xml_element == "testsuite") {
3278     return ArrayAsVector(kReservedTestSuiteAttributes);
3279   } else if (xml_element == "testcase") {
3280     return ArrayAsVector(kReservedTestCaseAttributes);
3281   } else {
3282     GTEST_CHECK_(false) << "Unrecognized xml_element provided: " << xml_element;
3283   }
3284   // This code is unreachable but some compilers may not realizes that.
3285   return std::vector<std::string>();
3286 }
3287 
FormatWordList(const std::vector<std::string> & words)3288 static std::string FormatWordList(const std::vector<std::string>& words) {
3289   Message word_list;
3290   for (size_t i = 0; i < words.size(); ++i) {
3291     if (i > 0 && words.size() > 2) {
3292       word_list << ", ";
3293     }
3294     if (i == words.size() - 1) {
3295       word_list << "and ";
3296     }
3297     word_list << "'" << words[i] << "'";
3298   }
3299   return word_list.GetString();
3300 }
3301 
ValidateTestPropertyName(const std::string & property_name,const std::vector<std::string> & reserved_names)3302 bool ValidateTestPropertyName(const std::string& property_name,
3303                               const std::vector<std::string>& reserved_names) {
3304   if (std::find(reserved_names.begin(), reserved_names.end(), property_name) !=
3305           reserved_names.end()) {
3306     ADD_FAILURE() << "Reserved key used in RecordProperty(): " << property_name
3307                   << " (" << FormatWordList(reserved_names)
3308                   << " are reserved by " << GTEST_NAME_ << ")";
3309     return false;
3310   }
3311   return true;
3312 }
3313 
3314 // Adds a failure if the key is a reserved attribute of the element named
3315 // xml_element.  Returns true if the property is valid.
ValidateTestProperty(const std::string & xml_element,const TestProperty & test_property)3316 bool TestResult::ValidateTestProperty(const std::string& xml_element,
3317                                       const TestProperty& test_property) {
3318   return ValidateTestPropertyName(test_property.key(),
3319                                   GetReservedAttributesForElement(xml_element));
3320 }
3321 
3322 // Clears the object.
Clear()3323 void TestResult::Clear() {
3324   test_part_results_.clear();
3325   test_properties_.clear();
3326   death_test_count_ = 0;
3327   elapsed_time_ = 0;
3328 }
3329 
3330 // Returns true iff the test failed.
Failed() const3331 bool TestResult::Failed() const {
3332   for (int i = 0; i < total_part_count(); ++i) {
3333     if (GetTestPartResult(i).failed())
3334       return true;
3335   }
3336   return false;
3337 }
3338 
3339 // Returns true iff the test part fatally failed.
TestPartFatallyFailed(const TestPartResult & result)3340 static bool TestPartFatallyFailed(const TestPartResult& result) {
3341   return result.fatally_failed();
3342 }
3343 
3344 // Returns true iff the test fatally failed.
HasFatalFailure() const3345 bool TestResult::HasFatalFailure() const {
3346   return CountIf(test_part_results_, TestPartFatallyFailed) > 0;
3347 }
3348 
3349 // Returns true iff the test part non-fatally failed.
TestPartNonfatallyFailed(const TestPartResult & result)3350 static bool TestPartNonfatallyFailed(const TestPartResult& result) {
3351   return result.nonfatally_failed();
3352 }
3353 
3354 // Returns true iff the test has a non-fatal failure.
HasNonfatalFailure() const3355 bool TestResult::HasNonfatalFailure() const {
3356   return CountIf(test_part_results_, TestPartNonfatallyFailed) > 0;
3357 }
3358 
3359 // Gets the number of all test parts.  This is the sum of the number
3360 // of successful test parts and the number of failed test parts.
total_part_count() const3361 int TestResult::total_part_count() const {
3362   return static_cast<int>(test_part_results_.size());
3363 }
3364 
3365 // Returns the number of the test properties.
test_property_count() const3366 int TestResult::test_property_count() const {
3367   return static_cast<int>(test_properties_.size());
3368 }
3369 
3370 // class Test
3371 
3372 // Creates a Test object.
3373 
3374 // The c'tor saves the values of all Google Test flags.
Test()3375 Test::Test()
3376     : gtest_flag_saver_(new internal::GTestFlagSaver) {
3377 }
3378 
3379 // The d'tor restores the values of all Google Test flags.
~Test()3380 Test::~Test() {
3381   delete gtest_flag_saver_;
3382 }
3383 
3384 // Sets up the test fixture.
3385 //
3386 // A sub-class may override this.
SetUp()3387 void Test::SetUp() {
3388 }
3389 
3390 // Tears down the test fixture.
3391 //
3392 // A sub-class may override this.
TearDown()3393 void Test::TearDown() {
3394 }
3395 
3396 // Allows user supplied key value pairs to be recorded for later output.
RecordProperty(const std::string & key,const std::string & value)3397 void Test::RecordProperty(const std::string& key, const std::string& value) {
3398   UnitTest::GetInstance()->RecordProperty(key, value);
3399 }
3400 
3401 // Allows user supplied key value pairs to be recorded for later output.
RecordProperty(const std::string & key,int value)3402 void Test::RecordProperty(const std::string& key, int value) {
3403   Message value_message;
3404   value_message << value;
3405   RecordProperty(key, value_message.GetString().c_str());
3406 }
3407 
3408 namespace internal {
3409 
ReportFailureInUnknownLocation(TestPartResult::Type result_type,const std::string & message)3410 void ReportFailureInUnknownLocation(TestPartResult::Type result_type,
3411                                     const std::string& message) {
3412   // This function is a friend of UnitTest and as such has access to
3413   // AddTestPartResult.
3414   UnitTest::GetInstance()->AddTestPartResult(
3415       result_type,
3416       NULL,  // No info about the source file where the exception occurred.
3417       -1,    // We have no info on which line caused the exception.
3418       message,
3419       "");   // No stack trace, either.
3420 }
3421 
3422 }  // namespace internal
3423 
3424 // Google Test requires all tests in the same test case to use the same test
3425 // fixture class.  This function checks if the current test has the
3426 // same fixture class as the first test in the current test case.  If
3427 // yes, it returns true; otherwise it generates a Google Test failure and
3428 // returns false.
HasSameFixtureClass()3429 bool Test::HasSameFixtureClass() {
3430   internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
3431   const TestCase* const test_case = impl->current_test_case();
3432 
3433   // Info about the first test in the current test case.
3434   const TestInfo* const first_test_info = test_case->test_info_list()[0];
3435   const internal::TypeId first_fixture_id = first_test_info->fixture_class_id_;
3436   const char* const first_test_name = first_test_info->name();
3437 
3438   // Info about the current test.
3439   const TestInfo* const this_test_info = impl->current_test_info();
3440   const internal::TypeId this_fixture_id = this_test_info->fixture_class_id_;
3441   const char* const this_test_name = this_test_info->name();
3442 
3443   if (this_fixture_id != first_fixture_id) {
3444     // Is the first test defined using TEST?
3445     const bool first_is_TEST = first_fixture_id == internal::GetTestTypeId();
3446     // Is this test defined using TEST?
3447     const bool this_is_TEST = this_fixture_id == internal::GetTestTypeId();
3448 
3449     if (first_is_TEST || this_is_TEST) {
3450       // The user mixed TEST and TEST_F in this test case - we'll tell
3451       // him/her how to fix it.
3452 
3453       // Gets the name of the TEST and the name of the TEST_F.  Note
3454       // that first_is_TEST and this_is_TEST cannot both be true, as
3455       // the fixture IDs are different for the two tests.
3456       const char* const TEST_name =
3457           first_is_TEST ? first_test_name : this_test_name;
3458       const char* const TEST_F_name =
3459           first_is_TEST ? this_test_name : first_test_name;
3460 
3461       ADD_FAILURE()
3462           << "All tests in the same test case must use the same test fixture\n"
3463           << "class, so mixing TEST_F and TEST in the same test case is\n"
3464           << "illegal.  In test case " << this_test_info->test_case_name()
3465           << ",\n"
3466           << "test " << TEST_F_name << " is defined using TEST_F but\n"
3467           << "test " << TEST_name << " is defined using TEST.  You probably\n"
3468           << "want to change the TEST to TEST_F or move it to another test\n"
3469           << "case.";
3470     } else {
3471       // The user defined two fixture classes with the same name in
3472       // two namespaces - we'll tell him/her how to fix it.
3473       ADD_FAILURE()
3474           << "All tests in the same test case must use the same test fixture\n"
3475           << "class.  However, in test case "
3476           << this_test_info->test_case_name() << ",\n"
3477           << "you defined test " << first_test_name
3478           << " and test " << this_test_name << "\n"
3479           << "using two different test fixture classes.  This can happen if\n"
3480           << "the two classes are from different namespaces or translation\n"
3481           << "units and have the same name.  You should probably rename one\n"
3482           << "of the classes to put the tests into different test cases.";
3483     }
3484     return false;
3485   }
3486 
3487   return true;
3488 }
3489 
3490 #if GTEST_HAS_SEH
3491 
3492 // Adds an "exception thrown" fatal failure to the current test.  This
3493 // function returns its result via an output parameter pointer because VC++
3494 // prohibits creation of objects with destructors on stack in functions
3495 // using __try (see error C2712).
FormatSehExceptionMessage(DWORD exception_code,const char * location)3496 static std::string* FormatSehExceptionMessage(DWORD exception_code,
3497                                               const char* location) {
3498   Message message;
3499   message << "SEH exception with code 0x" << std::setbase(16) <<
3500     exception_code << std::setbase(10) << " thrown in " << location << ".";
3501 
3502   return new std::string(message.GetString());
3503 }
3504 
3505 #endif  // GTEST_HAS_SEH
3506 
3507 namespace internal {
3508 
3509 #if GTEST_HAS_EXCEPTIONS
3510 
3511 // Adds an "exception thrown" fatal failure to the current test.
FormatCxxExceptionMessage(const char * description,const char * location)3512 static std::string FormatCxxExceptionMessage(const char* description,
3513                                              const char* location) {
3514   Message message;
3515   if (description != NULL) {
3516     message << "C++ exception with description \"" << description << "\"";
3517   } else {
3518     message << "Unknown C++ exception";
3519   }
3520   message << " thrown in " << location << ".";
3521 
3522   return message.GetString();
3523 }
3524 
3525 static std::string PrintTestPartResultToString(
3526     const TestPartResult& test_part_result);
3527 
GoogleTestFailureException(const TestPartResult & failure)3528 GoogleTestFailureException::GoogleTestFailureException(
3529     const TestPartResult& failure)
3530     : ::std::runtime_error(PrintTestPartResultToString(failure).c_str()) {}
3531 
3532 #endif  // GTEST_HAS_EXCEPTIONS
3533 
3534 // We put these helper functions in the internal namespace as IBM's xlC
3535 // compiler rejects the code if they were declared static.
3536 
3537 // Runs the given method and handles SEH exceptions it throws, when
3538 // SEH is supported; returns the 0-value for type Result in case of an
3539 // SEH exception.  (Microsoft compilers cannot handle SEH and C++
3540 // exceptions in the same function.  Therefore, we provide a separate
3541 // wrapper function for handling SEH exceptions.)
3542 template <class T, typename Result>
HandleSehExceptionsInMethodIfSupported(T * object,Result (T::* method)(),const char * location)3543 Result HandleSehExceptionsInMethodIfSupported(
3544     T* object, Result (T::*method)(), const char* location) {
3545 #if GTEST_HAS_SEH
3546   __try {
3547     return (object->*method)();
3548   } __except (internal::UnitTestOptions::GTestShouldProcessSEH(  // NOLINT
3549       GetExceptionCode())) {
3550     // We create the exception message on the heap because VC++ prohibits
3551     // creation of objects with destructors on stack in functions using __try
3552     // (see error C2712).
3553     std::string* exception_message = FormatSehExceptionMessage(
3554         GetExceptionCode(), location);
3555     internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure,
3556                                              *exception_message);
3557     delete exception_message;
3558     return static_cast<Result>(0);
3559   }
3560 #else
3561   (void)location;
3562   return (object->*method)();
3563 #endif  // GTEST_HAS_SEH
3564 }
3565 
3566 // Runs the given method and catches and reports C++ and/or SEH-style
3567 // exceptions, if they are supported; returns the 0-value for type
3568 // Result in case of an SEH exception.
3569 template <class T, typename Result>
HandleExceptionsInMethodIfSupported(T * object,Result (T::* method)(),const char * location)3570 Result HandleExceptionsInMethodIfSupported(
3571     T* object, Result (T::*method)(), const char* location) {
3572   // NOTE: The user code can affect the way in which Google Test handles
3573   // exceptions by setting GTEST_FLAG(catch_exceptions), but only before
3574   // RUN_ALL_TESTS() starts. It is technically possible to check the flag
3575   // after the exception is caught and either report or re-throw the
3576   // exception based on the flag's value:
3577   //
3578   // try {
3579   //   // Perform the test method.
3580   // } catch (...) {
3581   //   if (GTEST_FLAG(catch_exceptions))
3582   //     // Report the exception as failure.
3583   //   else
3584   //     throw;  // Re-throws the original exception.
3585   // }
3586   //
3587   // However, the purpose of this flag is to allow the program to drop into
3588   // the debugger when the exception is thrown. On most platforms, once the
3589   // control enters the catch block, the exception origin information is
3590   // lost and the debugger will stop the program at the point of the
3591   // re-throw in this function -- instead of at the point of the original
3592   // throw statement in the code under test.  For this reason, we perform
3593   // the check early, sacrificing the ability to affect Google Test's
3594   // exception handling in the method where the exception is thrown.
3595   if (internal::GetUnitTestImpl()->catch_exceptions()) {
3596 #if GTEST_HAS_EXCEPTIONS
3597     try {
3598       return HandleSehExceptionsInMethodIfSupported(object, method, location);
3599     } catch (const internal::GoogleTestFailureException&) {  // NOLINT
3600       // This exception type can only be thrown by a failed Google
3601       // Test assertion with the intention of letting another testing
3602       // framework catch it.  Therefore we just re-throw it.
3603       throw;
3604     } catch (const std::exception& e) {  // NOLINT
3605       internal::ReportFailureInUnknownLocation(
3606           TestPartResult::kFatalFailure,
3607           FormatCxxExceptionMessage(e.what(), location));
3608     } catch (...) {  // NOLINT
3609       internal::ReportFailureInUnknownLocation(
3610           TestPartResult::kFatalFailure,
3611           FormatCxxExceptionMessage(NULL, location));
3612     }
3613     return static_cast<Result>(0);
3614 #else
3615     return HandleSehExceptionsInMethodIfSupported(object, method, location);
3616 #endif  // GTEST_HAS_EXCEPTIONS
3617   } else {
3618     return (object->*method)();
3619   }
3620 }
3621 
3622 }  // namespace internal
3623 
3624 // Runs the test and updates the test result.
Run()3625 void Test::Run() {
3626   if (!HasSameFixtureClass()) return;
3627 
3628   internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
3629   impl->os_stack_trace_getter()->UponLeavingGTest();
3630   internal::HandleExceptionsInMethodIfSupported(this, &Test::SetUp, "SetUp()");
3631   // We will run the test only if SetUp() was successful.
3632   if (!HasFatalFailure()) {
3633     impl->os_stack_trace_getter()->UponLeavingGTest();
3634     internal::HandleExceptionsInMethodIfSupported(
3635         this, &Test::TestBody, "the test body");
3636   }
3637 
3638   // However, we want to clean up as much as possible.  Hence we will
3639   // always call TearDown(), even if SetUp() or the test body has
3640   // failed.
3641   impl->os_stack_trace_getter()->UponLeavingGTest();
3642   internal::HandleExceptionsInMethodIfSupported(
3643       this, &Test::TearDown, "TearDown()");
3644 }
3645 
3646 // Returns true iff the current test has a fatal failure.
HasFatalFailure()3647 bool Test::HasFatalFailure() {
3648   return internal::GetUnitTestImpl()->current_test_result()->HasFatalFailure();
3649 }
3650 
3651 // Returns true iff the current test has a non-fatal failure.
HasNonfatalFailure()3652 bool Test::HasNonfatalFailure() {
3653   return internal::GetUnitTestImpl()->current_test_result()->
3654       HasNonfatalFailure();
3655 }
3656 
3657 // class TestInfo
3658 
3659 // Constructs a TestInfo object. It assumes ownership of the test factory
3660 // 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)3661 TestInfo::TestInfo(const std::string& a_test_case_name,
3662                    const std::string& a_name,
3663                    const char* a_type_param,
3664                    const char* a_value_param,
3665                    internal::TypeId fixture_class_id,
3666                    internal::TestFactoryBase* factory)
3667     : test_case_name_(a_test_case_name),
3668       name_(a_name),
3669       type_param_(a_type_param ? new std::string(a_type_param) : NULL),
3670       value_param_(a_value_param ? new std::string(a_value_param) : NULL),
3671       fixture_class_id_(fixture_class_id),
3672       should_run_(false),
3673       is_disabled_(false),
3674       matches_filter_(false),
3675       factory_(factory),
3676       result_() {}
3677 
3678 // Destructs a TestInfo object.
~TestInfo()3679 TestInfo::~TestInfo() { delete factory_; }
3680 
3681 namespace internal {
3682 
3683 // Creates a new TestInfo object and registers it with Google Test;
3684 // returns the created object.
3685 //
3686 // Arguments:
3687 //
3688 //   test_case_name:   name of the test case
3689 //   name:             name of the test
3690 //   type_param:       the name of the test's type parameter, or NULL if
3691 //                     this is not a typed or a type-parameterized test.
3692 //   value_param:      text representation of the test's value parameter,
3693 //                     or NULL if this is not a value-parameterized test.
3694 //   fixture_class_id: ID of the test fixture class
3695 //   set_up_tc:        pointer to the function that sets up the test case
3696 //   tear_down_tc:     pointer to the function that tears down the test case
3697 //   factory:          pointer to the factory that creates a test object.
3698 //                     The newly created TestInfo instance will assume
3699 //                     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)3700 TestInfo* MakeAndRegisterTestInfo(
3701     const char* test_case_name,
3702     const char* name,
3703     const char* type_param,
3704     const char* value_param,
3705     TypeId fixture_class_id,
3706     SetUpTestCaseFunc set_up_tc,
3707     TearDownTestCaseFunc tear_down_tc,
3708     TestFactoryBase* factory) {
3709   TestInfo* const test_info =
3710       new TestInfo(test_case_name, name, type_param, value_param,
3711                    fixture_class_id, factory);
3712   GetUnitTestImpl()->AddTestInfo(set_up_tc, tear_down_tc, test_info);
3713   return test_info;
3714 }
3715 
3716 #if GTEST_HAS_PARAM_TEST
ReportInvalidTestCaseType(const char * test_case_name,const char * file,int line)3717 void ReportInvalidTestCaseType(const char* test_case_name,
3718                                const char* file, int line) {
3719   Message errors;
3720   errors
3721       << "Attempted redefinition of test case " << test_case_name << ".\n"
3722       << "All tests in the same test case must use the same test fixture\n"
3723       << "class.  However, in test case " << test_case_name << ", you tried\n"
3724       << "to define a test using a fixture class different from the one\n"
3725       << "used earlier. This can happen if the two fixture classes are\n"
3726       << "from different namespaces and have the same name. You should\n"
3727       << "probably rename one of the classes to put the tests into different\n"
3728       << "test cases.";
3729 
3730   fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(),
3731           errors.GetString().c_str());
3732 }
3733 #endif  // GTEST_HAS_PARAM_TEST
3734 
3735 }  // namespace internal
3736 
3737 namespace {
3738 
3739 // A predicate that checks the test name of a TestInfo against a known
3740 // value.
3741 //
3742 // This is used for implementation of the TestCase class only.  We put
3743 // it in the anonymous namespace to prevent polluting the outer
3744 // namespace.
3745 //
3746 // TestNameIs is copyable.
3747 
3748 //Commenting out this class since its not used and wherefor produces warnings
3749 // class TestNameIs {
3750 // public:
3751 //  // Constructor.
3752 //  //
3753 //  // TestNameIs has NO default constructor.
3754 //  explicit TestNameIs(const char* name)
3755 //      : name_(name) {}
3756 //
3757 //  // Returns true iff the test name of test_info matches name_.
3758 //  bool operator()(const TestInfo * test_info) const {
3759 //    return test_info && test_info->name() == name_;
3760 //  }
3761 //
3762 // private:
3763 //  std::string name_;
3764 //};
3765 
3766 }  // namespace
3767 
3768 namespace internal {
3769 
3770 // This method expands all parameterized tests registered with macros TEST_P
3771 // and INSTANTIATE_TEST_CASE_P into regular tests and registers those.
3772 // This will be done just once during the program runtime.
RegisterParameterizedTests()3773 void UnitTestImpl::RegisterParameterizedTests() {
3774 #if GTEST_HAS_PARAM_TEST
3775   if (!parameterized_tests_registered_) {
3776     parameterized_test_registry_.RegisterTests();
3777     parameterized_tests_registered_ = true;
3778   }
3779 #endif
3780 }
3781 
3782 }  // namespace internal
3783 
3784 // Creates the test object, runs it, records its result, and then
3785 // deletes it.
Run()3786 void TestInfo::Run() {
3787   if (!should_run_) return;
3788 
3789   // Tells UnitTest where to store test result.
3790   internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
3791   impl->set_current_test_info(this);
3792 
3793   TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
3794 
3795   // Notifies the unit test event listeners that a test is about to start.
3796   repeater->OnTestStart(*this);
3797 
3798   const TimeInMillis start = internal::GetTimeInMillis();
3799 
3800   impl->os_stack_trace_getter()->UponLeavingGTest();
3801 
3802   // Creates the test object.
3803   Test* const test = internal::HandleExceptionsInMethodIfSupported(
3804       factory_, &internal::TestFactoryBase::CreateTest,
3805       "the test fixture's constructor");
3806 
3807   // Runs the test only if the test object was created and its
3808   // constructor didn't generate a fatal failure.
3809   if ((test != NULL) && !Test::HasFatalFailure()) {
3810     // This doesn't throw as all user code that can throw are wrapped into
3811     // exception handling code.
3812     test->Run();
3813   }
3814 
3815   // Deletes the test object.
3816   impl->os_stack_trace_getter()->UponLeavingGTest();
3817   internal::HandleExceptionsInMethodIfSupported(
3818       test, &Test::DeleteSelf_, "the test fixture's destructor");
3819 
3820   result_.set_elapsed_time(internal::GetTimeInMillis() - start);
3821 
3822   // Notifies the unit test event listener that a test has just finished.
3823   repeater->OnTestEnd(*this);
3824 
3825   // Tells UnitTest to stop associating assertion results to this
3826   // test.
3827   impl->set_current_test_info(NULL);
3828 }
3829 
3830 // class TestCase
3831 
3832 // Gets the number of successful tests in this test case.
successful_test_count() const3833 int TestCase::successful_test_count() const {
3834   return CountIf(test_info_list_, TestPassed);
3835 }
3836 
3837 // Gets the number of failed tests in this test case.
failed_test_count() const3838 int TestCase::failed_test_count() const {
3839   return CountIf(test_info_list_, TestFailed);
3840 }
3841 
3842 // Gets the number of disabled tests that will be reported in the XML report.
reportable_disabled_test_count() const3843 int TestCase::reportable_disabled_test_count() const {
3844   return CountIf(test_info_list_, TestReportableDisabled);
3845 }
3846 
3847 // Gets the number of disabled tests in this test case.
disabled_test_count() const3848 int TestCase::disabled_test_count() const {
3849   return CountIf(test_info_list_, TestDisabled);
3850 }
3851 
3852 // Gets the number of tests to be printed in the XML report.
reportable_test_count() const3853 int TestCase::reportable_test_count() const {
3854   return CountIf(test_info_list_, TestReportable);
3855 }
3856 
3857 // Get the number of tests in this test case that should run.
test_to_run_count() const3858 int TestCase::test_to_run_count() const {
3859   return CountIf(test_info_list_, ShouldRunTest);
3860 }
3861 
3862 // Gets the number of all tests.
total_test_count() const3863 int TestCase::total_test_count() const {
3864   return static_cast<int>(test_info_list_.size());
3865 }
3866 
3867 // Creates a TestCase with the given name.
3868 //
3869 // Arguments:
3870 //
3871 //   name:         name of the test case
3872 //   a_type_param: the name of the test case's type parameter, or NULL if
3873 //                 this is not a typed or a type-parameterized test case.
3874 //   set_up_tc:    pointer to the function that sets up the test case
3875 //   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)3876 TestCase::TestCase(const char* a_name, const char* a_type_param,
3877                    Test::SetUpTestCaseFunc set_up_tc,
3878                    Test::TearDownTestCaseFunc tear_down_tc)
3879     : name_(a_name),
3880       type_param_(a_type_param ? new std::string(a_type_param) : NULL),
3881       set_up_tc_(set_up_tc),
3882       tear_down_tc_(tear_down_tc),
3883       should_run_(false),
3884       elapsed_time_(0) {
3885 }
3886 
3887 // Destructor of TestCase.
~TestCase()3888 TestCase::~TestCase() {
3889   // Deletes every Test in the collection.
3890   ForEach(test_info_list_, internal::Delete<TestInfo>);
3891 }
3892 
3893 // Returns the i-th test among all the tests. i can range from 0 to
3894 // total_test_count() - 1. If i is not in that range, returns NULL.
GetTestInfo(int i) const3895 const TestInfo* TestCase::GetTestInfo(int i) const {
3896   const int index = GetElementOr(test_indices_, i, -1);
3897   return index < 0 ? NULL : test_info_list_[index];
3898 }
3899 
3900 // Returns the i-th test among all the tests. i can range from 0 to
3901 // total_test_count() - 1. If i is not in that range, returns NULL.
GetMutableTestInfo(int i)3902 TestInfo* TestCase::GetMutableTestInfo(int i) {
3903   const int index = GetElementOr(test_indices_, i, -1);
3904   return index < 0 ? NULL : test_info_list_[index];
3905 }
3906 
3907 // Adds a test to this test case.  Will delete the test upon
3908 // destruction of the TestCase object.
AddTestInfo(TestInfo * test_info)3909 void TestCase::AddTestInfo(TestInfo * test_info) {
3910   test_info_list_.push_back(test_info);
3911   test_indices_.push_back(static_cast<int>(test_indices_.size()));
3912 }
3913 
3914 // Runs every test in this TestCase.
Run()3915 void TestCase::Run() {
3916   if (!should_run_) return;
3917 
3918   internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
3919   impl->set_current_test_case(this);
3920 
3921   TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
3922 
3923   repeater->OnTestCaseStart(*this);
3924   impl->os_stack_trace_getter()->UponLeavingGTest();
3925   internal::HandleExceptionsInMethodIfSupported(
3926       this, &TestCase::RunSetUpTestCase, "SetUpTestCase()");
3927 
3928   const internal::TimeInMillis start = internal::GetTimeInMillis();
3929   for (int i = 0; i < total_test_count(); i++) {
3930     GetMutableTestInfo(i)->Run();
3931   }
3932   elapsed_time_ = internal::GetTimeInMillis() - start;
3933 
3934   impl->os_stack_trace_getter()->UponLeavingGTest();
3935   internal::HandleExceptionsInMethodIfSupported(
3936       this, &TestCase::RunTearDownTestCase, "TearDownTestCase()");
3937 
3938   repeater->OnTestCaseEnd(*this);
3939   impl->set_current_test_case(NULL);
3940 }
3941 
3942 // Clears the results of all tests in this test case.
ClearResult()3943 void TestCase::ClearResult() {
3944   ad_hoc_test_result_.Clear();
3945   ForEach(test_info_list_, TestInfo::ClearTestResult);
3946 }
3947 
3948 // Shuffles the tests in this test case.
ShuffleTests(internal::Random * random)3949 void TestCase::ShuffleTests(internal::Random* random) {
3950   Shuffle(random, &test_indices_);
3951 }
3952 
3953 // Restores the test order to before the first shuffle.
UnshuffleTests()3954 void TestCase::UnshuffleTests() {
3955   for (size_t i = 0; i < test_indices_.size(); i++) {
3956     test_indices_[i] = static_cast<int>(i);
3957   }
3958 }
3959 
3960 // Formats a countable noun.  Depending on its quantity, either the
3961 // singular form or the plural form is used. e.g.
3962 //
3963 // FormatCountableNoun(1, "formula", "formuli") returns "1 formula".
3964 // FormatCountableNoun(5, "book", "books") returns "5 books".
FormatCountableNoun(int count,const char * singular_form,const char * plural_form)3965 static std::string FormatCountableNoun(int count,
3966                                        const char * singular_form,
3967                                        const char * plural_form) {
3968   return internal::StreamableToString(count) + " " +
3969       (count == 1 ? singular_form : plural_form);
3970 }
3971 
3972 // Formats the count of tests.
FormatTestCount(int test_count)3973 static std::string FormatTestCount(int test_count) {
3974   return FormatCountableNoun(test_count, "test", "tests");
3975 }
3976 
3977 // Formats the count of test cases.
FormatTestCaseCount(int test_case_count)3978 static std::string FormatTestCaseCount(int test_case_count) {
3979   return FormatCountableNoun(test_case_count, "test case", "test cases");
3980 }
3981 
3982 // Converts a TestPartResult::Type enum to human-friendly string
3983 // representation.  Both kNonFatalFailure and kFatalFailure are translated
3984 // to "Failure", as the user usually doesn't care about the difference
3985 // between the two when viewing the test result.
TestPartResultTypeToString(TestPartResult::Type type)3986 static const char * TestPartResultTypeToString(TestPartResult::Type type) {
3987   switch (type) {
3988     case TestPartResult::kSuccess:
3989       return "Success";
3990 
3991     case TestPartResult::kNonFatalFailure:
3992     case TestPartResult::kFatalFailure:
3993 #ifdef _MSC_VER
3994       return "error: ";
3995 #else
3996       return "Failure\n";
3997 #endif
3998     default:
3999       return "Unknown result type";
4000   }
4001 }
4002 
4003 namespace internal {
4004 
4005 // Prints a TestPartResult to an std::string.
PrintTestPartResultToString(const TestPartResult & test_part_result)4006 static std::string PrintTestPartResultToString(
4007     const TestPartResult& test_part_result) {
4008   return (Message()
4009           << internal::FormatFileLocation(test_part_result.file_name(),
4010                                           test_part_result.line_number())
4011           << " " << TestPartResultTypeToString(test_part_result.type())
4012           << test_part_result.message()).GetString();
4013 }
4014 
4015 // Prints a TestPartResult.
PrintTestPartResult(const TestPartResult & test_part_result)4016 static void PrintTestPartResult(const TestPartResult& test_part_result) {
4017   const std::string& result =
4018       PrintTestPartResultToString(test_part_result);
4019   printf("%s\n", result.c_str());
4020   fflush(stdout);
4021   // If the test program runs in Visual Studio or a debugger, the
4022   // following statements add the test part result message to the Output
4023   // window such that the user can double-click on it to jump to the
4024   // corresponding source code location; otherwise they do nothing.
4025 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
4026   // We don't call OutputDebugString*() on Windows Mobile, as printing
4027   // to stdout is done by OutputDebugString() there already - we don't
4028   // want the same message printed twice.
4029   ::OutputDebugStringA(result.c_str());
4030   ::OutputDebugStringA("\n");
4031 #endif
4032 }
4033 
4034 // class PrettyUnitTestResultPrinter
4035 
4036 enum GTestColor {
4037   COLOR_DEFAULT,
4038   COLOR_RED,
4039   COLOR_GREEN,
4040   COLOR_YELLOW
4041 };
4042 
4043 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
4044 
4045 // Returns the character attribute for the given color.
GetColorAttribute(GTestColor color)4046 WORD GetColorAttribute(GTestColor color) {
4047   switch (color) {
4048     case COLOR_RED:    return FOREGROUND_RED;
4049     case COLOR_GREEN:  return FOREGROUND_GREEN;
4050     case COLOR_YELLOW: return FOREGROUND_RED | FOREGROUND_GREEN;
4051     default:           return 0;
4052   }
4053 }
4054 
4055 #else
4056 
4057 // Returns the ANSI color code for the given color.  COLOR_DEFAULT is
4058 // an invalid input.
GetAnsiColorCode(GTestColor color)4059 const char* GetAnsiColorCode(GTestColor color) {
4060   switch (color) {
4061     case COLOR_RED:     return "1";
4062     case COLOR_GREEN:   return "2";
4063     case COLOR_YELLOW:  return "3";
4064     default:            return NULL;
4065   };
4066 }
4067 
4068 #endif  // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
4069 
4070 // Returns true iff Google Test should use colors in the output.
ShouldUseColor(bool stdout_is_tty)4071 bool ShouldUseColor(bool stdout_is_tty) {
4072   const char* const gtest_color = GTEST_FLAG(color).c_str();
4073 
4074   if (String::CaseInsensitiveCStringEquals(gtest_color, "auto")) {
4075 #if GTEST_OS_WINDOWS
4076     // On Windows the TERM variable is usually not set, but the
4077     // console there does support colors.
4078     return stdout_is_tty;
4079 #else
4080     // On non-Windows platforms, we rely on the TERM variable.
4081     const char* const term = posix::GetEnv("TERM");
4082     const bool term_supports_color =
4083         String::CStringEquals(term, "xterm") ||
4084         String::CStringEquals(term, "xterm-color") ||
4085         String::CStringEquals(term, "xterm-256color") ||
4086         String::CStringEquals(term, "screen") ||
4087         String::CStringEquals(term, "screen-256color") ||
4088         String::CStringEquals(term, "linux") ||
4089         String::CStringEquals(term, "cygwin");
4090     return stdout_is_tty && term_supports_color;
4091 #endif  // GTEST_OS_WINDOWS
4092   }
4093 
4094   return String::CaseInsensitiveCStringEquals(gtest_color, "yes") ||
4095       String::CaseInsensitiveCStringEquals(gtest_color, "true") ||
4096       String::CaseInsensitiveCStringEquals(gtest_color, "t") ||
4097       String::CStringEquals(gtest_color, "1");
4098   // We take "yes", "true", "t", and "1" as meaning "yes".  If the
4099   // value is neither one of these nor "auto", we treat it as "no" to
4100   // be conservative.
4101 }
4102 
4103 // Helpers for printing colored strings to stdout. Note that on Windows, we
4104 // cannot simply emit special characters and have the terminal change colors.
4105 // This routine must actually emit the characters rather than return a string
4106 // that would be colored when printed, as can be done on Linux.
ColoredPrintf(GTestColor color,const char * fmt,...)4107 void ColoredPrintf(GTestColor color, const char* fmt, ...) {
4108   va_list args;
4109   va_start(args, fmt);
4110 
4111 #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS || GTEST_OS_IOS
4112   const bool use_color = false;
4113 #else
4114   static const bool in_color_mode =
4115       ShouldUseColor(posix::IsATTY(posix::FileNo(stdout)) != 0);
4116   const bool use_color = in_color_mode && (color != COLOR_DEFAULT);
4117 #endif  // GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS
4118   // The '!= 0' comparison is necessary to satisfy MSVC 7.1.
4119 
4120   if (!use_color) {
4121     vprintf(fmt, args);
4122     va_end(args);
4123     return;
4124   }
4125 
4126 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
4127   const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
4128 
4129   // Gets the current text color.
4130   CONSOLE_SCREEN_BUFFER_INFO buffer_info;
4131   GetConsoleScreenBufferInfo(stdout_handle, &buffer_info);
4132   const WORD old_color_attrs = buffer_info.wAttributes;
4133 
4134   // We need to flush the stream buffers into the console before each
4135   // SetConsoleTextAttribute call lest it affect the text that is already
4136   // printed but has not yet reached the console.
4137   fflush(stdout);
4138   SetConsoleTextAttribute(stdout_handle,
4139                           GetColorAttribute(color) | FOREGROUND_INTENSITY);
4140   vprintf(fmt, args);
4141 
4142   fflush(stdout);
4143   // Restores the text color.
4144   SetConsoleTextAttribute(stdout_handle, old_color_attrs);
4145 #else
4146   printf("\033[0;3%sm", GetAnsiColorCode(color));
4147   vprintf(fmt, args);
4148   printf("\033[m");  // Resets the terminal to default.
4149 #endif  // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
4150   va_end(args);
4151 }
4152 
4153 // Text printed in Google Test's text output and --gunit_list_tests
4154 // output to label the type parameter and value parameter for a test.
4155 static const char kTypeParamLabel[] = "TypeParam";
4156 static const char kValueParamLabel[] = "GetParam()";
4157 
PrintFullTestCommentIfPresent(const TestInfo & test_info)4158 void PrintFullTestCommentIfPresent(const TestInfo& test_info) {
4159   const char* const type_param = test_info.type_param();
4160   const char* const value_param = test_info.value_param();
4161 
4162   if (type_param != NULL || value_param != NULL) {
4163     printf(", where ");
4164     if (type_param != NULL) {
4165       printf("%s = %s", kTypeParamLabel, type_param);
4166       if (value_param != NULL)
4167         printf(" and ");
4168     }
4169     if (value_param != NULL) {
4170       printf("%s = %s", kValueParamLabel, value_param);
4171     }
4172   }
4173 }
4174 
4175 // This class implements the TestEventListener interface.
4176 //
4177 // Class PrettyUnitTestResultPrinter is copyable.
4178 class PrettyUnitTestResultPrinter : public TestEventListener {
4179  public:
PrettyUnitTestResultPrinter()4180   PrettyUnitTestResultPrinter() {}
PrintTestName(const char * test_case,const char * test)4181   static void PrintTestName(const char * test_case, const char * test) {
4182     printf("%s.%s", test_case, test);
4183   }
4184 
4185   // The following methods override what's in the TestEventListener class.
OnTestProgramStart(const UnitTest &)4186   virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {}
4187   virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration);
4188   virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test);
OnEnvironmentsSetUpEnd(const UnitTest &)4189   virtual void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) {}
4190   virtual void OnTestCaseStart(const TestCase& test_case);
4191   virtual void OnTestStart(const TestInfo& test_info);
4192   virtual void OnTestPartResult(const TestPartResult& result);
4193   virtual void OnTestEnd(const TestInfo& test_info);
4194   virtual void OnTestCaseEnd(const TestCase& test_case);
4195   virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test);
OnEnvironmentsTearDownEnd(const UnitTest &)4196   virtual void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) {}
4197   virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
OnTestProgramEnd(const UnitTest &)4198   virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) {}
4199 
4200  private:
4201   static void PrintFailedTests(const UnitTest& unit_test);
4202 };
4203 
4204   // Fired before each iteration of tests starts.
OnTestIterationStart(const UnitTest & unit_test,int iteration)4205 void PrettyUnitTestResultPrinter::OnTestIterationStart(
4206     const UnitTest& unit_test, int iteration) {
4207   if (GTEST_FLAG(repeat) != 1)
4208     printf("\nRepeating all tests (iteration %d) . . .\n\n", iteration + 1);
4209 
4210   const char* const filter = GTEST_FLAG(filter).c_str();
4211 
4212   // Prints the filter if it's not *.  This reminds the user that some
4213   // tests may be skipped.
4214   if (!String::CStringEquals(filter, kUniversalFilter)) {
4215     ColoredPrintf(COLOR_YELLOW,
4216                   "Note: %s filter = %s\n", GTEST_NAME_, filter);
4217   }
4218 
4219   if (internal::ShouldShard(kTestTotalShards, kTestShardIndex, false)) {
4220     const Int32 shard_index = Int32FromEnvOrDie(kTestShardIndex, -1);
4221     ColoredPrintf(COLOR_YELLOW,
4222                   "Note: This is test shard %d of %s.\n",
4223                   static_cast<int>(shard_index) + 1,
4224                   internal::posix::GetEnv(kTestTotalShards));
4225   }
4226 
4227   if (GTEST_FLAG(shuffle)) {
4228     ColoredPrintf(COLOR_YELLOW,
4229                   "Note: Randomizing tests' orders with a seed of %d .\n",
4230                   unit_test.random_seed());
4231   }
4232 
4233   ColoredPrintf(COLOR_GREEN,  "[==========] ");
4234   printf("Running %s from %s.\n",
4235          FormatTestCount(unit_test.test_to_run_count()).c_str(),
4236          FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str());
4237   fflush(stdout);
4238 }
4239 
OnEnvironmentsSetUpStart(const UnitTest &)4240 void PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart(
4241     const UnitTest& /*unit_test*/) {
4242   ColoredPrintf(COLOR_GREEN,  "[----------] ");
4243   printf("Global test environment set-up.\n");
4244   fflush(stdout);
4245 }
4246 
OnTestCaseStart(const TestCase & test_case)4247 void PrettyUnitTestResultPrinter::OnTestCaseStart(const TestCase& test_case) {
4248   const std::string counts =
4249       FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
4250   ColoredPrintf(COLOR_GREEN, "[----------] ");
4251   printf("%s from %s", counts.c_str(), test_case.name());
4252   if (test_case.type_param() == NULL) {
4253     printf("\n");
4254   } else {
4255     printf(", where %s = %s\n", kTypeParamLabel, test_case.type_param());
4256   }
4257   fflush(stdout);
4258 }
4259 
OnTestStart(const TestInfo & test_info)4260 void PrettyUnitTestResultPrinter::OnTestStart(const TestInfo& test_info) {
4261   ColoredPrintf(COLOR_GREEN,  "[ RUN      ] ");
4262   PrintTestName(test_info.test_case_name(), test_info.name());
4263   printf("\n");
4264   fflush(stdout);
4265 }
4266 
4267 // Called after an assertion failure.
OnTestPartResult(const TestPartResult & result)4268 void PrettyUnitTestResultPrinter::OnTestPartResult(
4269     const TestPartResult& result) {
4270   // If the test part succeeded, we don't need to do anything.
4271   if (result.type() == TestPartResult::kSuccess)
4272     return;
4273 
4274   // Print failure message from the assertion (e.g. expected this and got that).
4275   PrintTestPartResult(result);
4276   fflush(stdout);
4277 }
4278 
OnTestEnd(const TestInfo & test_info)4279 void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) {
4280   if (test_info.result()->Passed()) {
4281     ColoredPrintf(COLOR_GREEN, "[       OK ] ");
4282   } else {
4283     ColoredPrintf(COLOR_RED, "[  FAILED  ] ");
4284   }
4285   PrintTestName(test_info.test_case_name(), test_info.name());
4286   if (test_info.result()->Failed())
4287     PrintFullTestCommentIfPresent(test_info);
4288 
4289   if (GTEST_FLAG(print_time)) {
4290     printf(" (%s ms)\n", internal::StreamableToString(
4291            test_info.result()->elapsed_time()).c_str());
4292   } else {
4293     printf("\n");
4294   }
4295   fflush(stdout);
4296 }
4297 
OnTestCaseEnd(const TestCase & test_case)4298 void PrettyUnitTestResultPrinter::OnTestCaseEnd(const TestCase& test_case) {
4299   if (!GTEST_FLAG(print_time)) return;
4300 
4301   const std::string counts =
4302       FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
4303   ColoredPrintf(COLOR_GREEN, "[----------] ");
4304   printf("%s from %s (%s ms total)\n\n",
4305          counts.c_str(), test_case.name(),
4306          internal::StreamableToString(test_case.elapsed_time()).c_str());
4307   fflush(stdout);
4308 }
4309 
OnEnvironmentsTearDownStart(const UnitTest &)4310 void PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart(
4311     const UnitTest& /*unit_test*/) {
4312   ColoredPrintf(COLOR_GREEN,  "[----------] ");
4313   printf("Global test environment tear-down\n");
4314   fflush(stdout);
4315 }
4316 
4317 // Internal helper for printing the list of failed tests.
PrintFailedTests(const UnitTest & unit_test)4318 void PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest& unit_test) {
4319   const int failed_test_count = unit_test.failed_test_count();
4320   if (failed_test_count == 0) {
4321     return;
4322   }
4323 
4324   for (int i = 0; i < unit_test.total_test_case_count(); ++i) {
4325     const TestCase& test_case = *unit_test.GetTestCase(i);
4326     if (!test_case.should_run() || (test_case.failed_test_count() == 0)) {
4327       continue;
4328     }
4329     for (int j = 0; j < test_case.total_test_count(); ++j) {
4330       const TestInfo& test_info = *test_case.GetTestInfo(j);
4331       if (!test_info.should_run() || test_info.result()->Passed()) {
4332         continue;
4333       }
4334       ColoredPrintf(COLOR_RED, "[  FAILED  ] ");
4335       printf("%s.%s", test_case.name(), test_info.name());
4336       PrintFullTestCommentIfPresent(test_info);
4337       printf("\n");
4338     }
4339   }
4340 }
4341 
OnTestIterationEnd(const UnitTest & unit_test,int)4342 void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
4343                                                      int /*iteration*/) {
4344   ColoredPrintf(COLOR_GREEN,  "[==========] ");
4345   printf("%s from %s ran.",
4346          FormatTestCount(unit_test.test_to_run_count()).c_str(),
4347          FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str());
4348   if (GTEST_FLAG(print_time)) {
4349     printf(" (%s ms total)",
4350            internal::StreamableToString(unit_test.elapsed_time()).c_str());
4351   }
4352   printf("\n");
4353   ColoredPrintf(COLOR_GREEN,  "[  PASSED  ] ");
4354   printf("%s.\n", FormatTestCount(unit_test.successful_test_count()).c_str());
4355 
4356   int num_failures = unit_test.failed_test_count();
4357   if (!unit_test.Passed()) {
4358     const int failed_test_count = unit_test.failed_test_count();
4359     ColoredPrintf(COLOR_RED,  "[  FAILED  ] ");
4360     printf("%s, listed below:\n", FormatTestCount(failed_test_count).c_str());
4361     PrintFailedTests(unit_test);
4362     printf("\n%2d FAILED %s\n", num_failures,
4363                         num_failures == 1 ? "TEST" : "TESTS");
4364   }
4365 
4366   int num_disabled = unit_test.reportable_disabled_test_count();
4367   if (num_disabled && !GTEST_FLAG(also_run_disabled_tests)) {
4368     if (!num_failures) {
4369       printf("\n");  // Add a spacer if no FAILURE banner is displayed.
4370     }
4371     ColoredPrintf(COLOR_YELLOW,
4372                   "  YOU HAVE %d DISABLED %s\n\n",
4373                   num_disabled,
4374                   num_disabled == 1 ? "TEST" : "TESTS");
4375   }
4376   // Ensure that Google Test output is printed before, e.g., heapchecker output.
4377   fflush(stdout);
4378 }
4379 
4380 // End PrettyUnitTestResultPrinter
4381 
4382 // class TestEventRepeater
4383 //
4384 // This class forwards events to other event listeners.
4385 class TestEventRepeater : public TestEventListener {
4386  public:
TestEventRepeater()4387   TestEventRepeater() : forwarding_enabled_(true) {}
4388   virtual ~TestEventRepeater();
4389   void Append(TestEventListener *listener);
4390   TestEventListener* Release(TestEventListener* listener);
4391 
4392   // Controls whether events will be forwarded to listeners_. Set to false
4393   // in death test child processes.
forwarding_enabled() const4394   bool forwarding_enabled() const { return forwarding_enabled_; }
set_forwarding_enabled(bool enable)4395   void set_forwarding_enabled(bool enable) { forwarding_enabled_ = enable; }
4396 
4397   virtual void OnTestProgramStart(const UnitTest& unit_test);
4398   virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration);
4399   virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test);
4400   virtual void OnEnvironmentsSetUpEnd(const UnitTest& unit_test);
4401   virtual void OnTestCaseStart(const TestCase& test_case);
4402   virtual void OnTestStart(const TestInfo& test_info);
4403   virtual void OnTestPartResult(const TestPartResult& result);
4404   virtual void OnTestEnd(const TestInfo& test_info);
4405   virtual void OnTestCaseEnd(const TestCase& test_case);
4406   virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test);
4407   virtual void OnEnvironmentsTearDownEnd(const UnitTest& unit_test);
4408   virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
4409   virtual void OnTestProgramEnd(const UnitTest& unit_test);
4410 
4411  private:
4412   // Controls whether events will be forwarded to listeners_. Set to false
4413   // in death test child processes.
4414   bool forwarding_enabled_;
4415   // The list of listeners that receive events.
4416   std::vector<TestEventListener*> listeners_;
4417 
4418   GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventRepeater);
4419 };
4420 
~TestEventRepeater()4421 TestEventRepeater::~TestEventRepeater() {
4422   ForEach(listeners_, Delete<TestEventListener>);
4423 }
4424 
Append(TestEventListener * listener)4425 void TestEventRepeater::Append(TestEventListener *listener) {
4426   listeners_.push_back(listener);
4427 }
4428 
4429 // TODO(vladl@google.com): Factor the search functionality into Vector::Find.
Release(TestEventListener * listener)4430 TestEventListener* TestEventRepeater::Release(TestEventListener *listener) {
4431   for (size_t i = 0; i < listeners_.size(); ++i) {
4432     if (listeners_[i] == listener) {
4433       listeners_.erase(listeners_.begin() + i);
4434       return listener;
4435     }
4436   }
4437 
4438   return NULL;
4439 }
4440 
4441 // Since most methods are very similar, use macros to reduce boilerplate.
4442 // This defines a member that forwards the call to all listeners.
4443 #define GTEST_REPEATER_METHOD_(Name, Type) \
4444 void TestEventRepeater::Name(const Type& parameter) { \
4445   if (forwarding_enabled_) { \
4446     for (size_t i = 0; i < listeners_.size(); i++) { \
4447       listeners_[i]->Name(parameter); \
4448     } \
4449   } \
4450 }
4451 // This defines a member that forwards the call to all listeners in reverse
4452 // order.
4453 #define GTEST_REVERSE_REPEATER_METHOD_(Name, Type) \
4454 void TestEventRepeater::Name(const Type& parameter) { \
4455   if (forwarding_enabled_) { \
4456     for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) { \
4457       listeners_[i]->Name(parameter); \
4458     } \
4459   } \
4460 }
4461 
GTEST_REPEATER_METHOD_(OnTestProgramStart,UnitTest)4462 GTEST_REPEATER_METHOD_(OnTestProgramStart, UnitTest)
4463 GTEST_REPEATER_METHOD_(OnEnvironmentsSetUpStart, UnitTest)
4464 GTEST_REPEATER_METHOD_(OnTestCaseStart, TestCase)
4465 GTEST_REPEATER_METHOD_(OnTestStart, TestInfo)
4466 GTEST_REPEATER_METHOD_(OnTestPartResult, TestPartResult)
4467 GTEST_REPEATER_METHOD_(OnEnvironmentsTearDownStart, UnitTest)
4468 GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsSetUpEnd, UnitTest)
4469 GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsTearDownEnd, UnitTest)
4470 GTEST_REVERSE_REPEATER_METHOD_(OnTestEnd, TestInfo)
4471 GTEST_REVERSE_REPEATER_METHOD_(OnTestCaseEnd, TestCase)
4472 GTEST_REVERSE_REPEATER_METHOD_(OnTestProgramEnd, UnitTest)
4473 
4474 #undef GTEST_REPEATER_METHOD_
4475 #undef GTEST_REVERSE_REPEATER_METHOD_
4476 
4477 void TestEventRepeater::OnTestIterationStart(const UnitTest& unit_test,
4478                                              int iteration) {
4479   if (forwarding_enabled_) {
4480     for (size_t i = 0; i < listeners_.size(); i++) {
4481       listeners_[i]->OnTestIterationStart(unit_test, iteration);
4482     }
4483   }
4484 }
4485 
OnTestIterationEnd(const UnitTest & unit_test,int iteration)4486 void TestEventRepeater::OnTestIterationEnd(const UnitTest& unit_test,
4487                                            int iteration) {
4488   if (forwarding_enabled_) {
4489     for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) {
4490       listeners_[i]->OnTestIterationEnd(unit_test, iteration);
4491     }
4492   }
4493 }
4494 
4495 // End TestEventRepeater
4496 
4497 // This class generates an XML output file.
4498 class XmlUnitTestResultPrinter : public EmptyTestEventListener {
4499  public:
4500   explicit XmlUnitTestResultPrinter(const char* output_file);
4501 
4502   virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
4503 
4504  private:
4505   // Is c a whitespace character that is normalized to a space character
4506   // when it appears in an XML attribute value?
IsNormalizableWhitespace(char c)4507   static bool IsNormalizableWhitespace(char c) {
4508     return c == 0x9 || c == 0xA || c == 0xD;
4509   }
4510 
4511   // May c appear in a well-formed XML document?
IsValidXmlCharacter(char c)4512   static bool IsValidXmlCharacter(char c) {
4513     return IsNormalizableWhitespace(c) || c >= 0x20;
4514   }
4515 
4516   // Returns an XML-escaped copy of the input string str.  If
4517   // is_attribute is true, the text is meant to appear as an attribute
4518   // value, and normalizable whitespace is preserved by replacing it
4519   // with character references.
4520   static std::string EscapeXml(const std::string& str, bool is_attribute);
4521 
4522   // Returns the given string with all characters invalid in XML removed.
4523   static std::string RemoveInvalidXmlCharacters(const std::string& str);
4524 
4525   // Convenience wrapper around EscapeXml when str is an attribute value.
EscapeXmlAttribute(const std::string & str)4526   static std::string EscapeXmlAttribute(const std::string& str) {
4527     return EscapeXml(str, true);
4528   }
4529 
4530   // Convenience wrapper around EscapeXml when str is not an attribute value.
EscapeXmlText(const char * str)4531   static std::string EscapeXmlText(const char* str) {
4532     return EscapeXml(str, false);
4533   }
4534 
4535   // Verifies that the given attribute belongs to the given element and
4536   // streams the attribute as XML.
4537   static void OutputXmlAttribute(std::ostream* stream,
4538                                  const std::string& element_name,
4539                                  const std::string& name,
4540                                  const std::string& value);
4541 
4542   // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
4543   static void OutputXmlCDataSection(::std::ostream* stream, const char* data);
4544 
4545   // Streams an XML representation of a TestInfo object.
4546   static void OutputXmlTestInfo(::std::ostream* stream,
4547                                 const char* test_case_name,
4548                                 const TestInfo& test_info);
4549 
4550   // Prints an XML representation of a TestCase object
4551   static void PrintXmlTestCase(::std::ostream* stream,
4552                                const TestCase& test_case);
4553 
4554   // Prints an XML summary of unit_test to output stream out.
4555   static void PrintXmlUnitTest(::std::ostream* stream,
4556                                const UnitTest& unit_test);
4557 
4558   // Produces a string representing the test properties in a result as space
4559   // delimited XML attributes based on the property key="value" pairs.
4560   // When the std::string is not empty, it includes a space at the beginning,
4561   // to delimit this attribute from prior attributes.
4562   static std::string TestPropertiesAsXmlAttributes(const TestResult& result);
4563 
4564   // The output file.
4565   const std::string output_file_;
4566 
4567   GTEST_DISALLOW_COPY_AND_ASSIGN_(XmlUnitTestResultPrinter);
4568 };
4569 
4570 // Creates a new XmlUnitTestResultPrinter.
XmlUnitTestResultPrinter(const char * output_file)4571 XmlUnitTestResultPrinter::XmlUnitTestResultPrinter(const char* output_file)
4572     : output_file_(output_file) {
4573   if (output_file_.c_str() == NULL || output_file_.empty()) {
4574     fprintf(stderr, "XML output file may not be null\n");
4575     fflush(stderr);
4576     exit(EXIT_FAILURE);
4577   }
4578 }
4579 
4580 // Called after the unit test ends.
OnTestIterationEnd(const UnitTest & unit_test,int)4581 void XmlUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
4582                                                   int /*iteration*/) {
4583   FILE* xmlout = NULL;
4584   FilePath output_file(output_file_);
4585   FilePath output_dir(output_file.RemoveFileName());
4586 
4587   if (output_dir.CreateDirectoriesRecursively()) {
4588     xmlout = posix::FOpen(output_file_.c_str(), "w");
4589   }
4590   if (xmlout == NULL) {
4591     // TODO(wan): report the reason of the failure.
4592     //
4593     // We don't do it for now as:
4594     //
4595     //   1. There is no urgent need for it.
4596     //   2. It's a bit involved to make the errno variable thread-safe on
4597     //      all three operating systems (Linux, Windows, and Mac OS).
4598     //   3. To interpret the meaning of errno in a thread-safe way,
4599     //      we need the strerror_r() function, which is not available on
4600     //      Windows.
4601     fprintf(stderr,
4602             "Unable to open file \"%s\"\n",
4603             output_file_.c_str());
4604     fflush(stderr);
4605     exit(EXIT_FAILURE);
4606   }
4607   std::stringstream stream;
4608   PrintXmlUnitTest(&stream, unit_test);
4609   fprintf(xmlout, "%s", StringStreamToString(&stream).c_str());
4610   fclose(xmlout);
4611 }
4612 
4613 // Returns an XML-escaped copy of the input string str.  If is_attribute
4614 // is true, the text is meant to appear as an attribute value, and
4615 // normalizable whitespace is preserved by replacing it with character
4616 // references.
4617 //
4618 // Invalid XML characters in str, if any, are stripped from the output.
4619 // It is expected that most, if not all, of the text processed by this
4620 // module will consist of ordinary English text.
4621 // If this module is ever modified to produce version 1.1 XML output,
4622 // most invalid characters can be retained using character references.
4623 // TODO(wan): It might be nice to have a minimally invasive, human-readable
4624 // escaping scheme for invalid characters, rather than dropping them.
EscapeXml(const std::string & str,bool is_attribute)4625 std::string XmlUnitTestResultPrinter::EscapeXml(
4626     const std::string& str, bool is_attribute) {
4627   Message m;
4628 
4629   for (size_t i = 0; i < str.size(); ++i) {
4630     const char ch = str[i];
4631     switch (ch) {
4632       case '<':
4633         m << "&lt;";
4634         break;
4635       case '>':
4636         m << "&gt;";
4637         break;
4638       case '&':
4639         m << "&amp;";
4640         break;
4641       case '\'':
4642         if (is_attribute)
4643           m << "&apos;";
4644         else
4645           m << '\'';
4646         break;
4647       case '"':
4648         if (is_attribute)
4649           m << "&quot;";
4650         else
4651           m << '"';
4652         break;
4653       default:
4654         if (IsValidXmlCharacter(ch)) {
4655           if (is_attribute && IsNormalizableWhitespace(ch))
4656             m << "&#x" << String::FormatByte(static_cast<unsigned char>(ch))
4657               << ";";
4658           else
4659             m << ch;
4660         }
4661         break;
4662     }
4663   }
4664 
4665   return m.GetString();
4666 }
4667 
4668 // Returns the given string with all characters invalid in XML removed.
4669 // Currently invalid characters are dropped from the string. An
4670 // alternative is to replace them with certain characters such as . or ?.
RemoveInvalidXmlCharacters(const std::string & str)4671 std::string XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters(
4672     const std::string& str) {
4673   std::string output;
4674   output.reserve(str.size());
4675   for (std::string::const_iterator it = str.begin(); it != str.end(); ++it)
4676     if (IsValidXmlCharacter(*it))
4677       output.push_back(*it);
4678 
4679   return output;
4680 }
4681 
4682 // The following routines generate an XML representation of a UnitTest
4683 // object.
4684 //
4685 // This is how Google Test concepts map to the DTD:
4686 //
4687 // <testsuites name="AllTests">        <-- corresponds to a UnitTest object
4688 //   <testsuite name="testcase-name">  <-- corresponds to a TestCase object
4689 //     <testcase name="test-name">     <-- corresponds to a TestInfo object
4690 //       <failure message="...">...</failure>
4691 //       <failure message="...">...</failure>
4692 //       <failure message="...">...</failure>
4693 //                                     <-- individual assertion failures
4694 //     </testcase>
4695 //   </testsuite>
4696 // </testsuites>
4697 
4698 // Formats the given time in milliseconds as seconds.
FormatTimeInMillisAsSeconds(TimeInMillis ms)4699 std::string FormatTimeInMillisAsSeconds(TimeInMillis ms) {
4700   ::std::stringstream ss;
4701   ss << ms/1000.0;
4702   return ss.str();
4703 }
4704 
4705 // Converts the given epoch time in milliseconds to a date string in the ISO
4706 // 8601 format, without the timezone information.
FormatEpochTimeInMillisAsIso8601(TimeInMillis ms)4707 std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms) {
4708   // Using non-reentrant version as localtime_r is not portable.
4709   time_t seconds = static_cast<time_t>(ms / 1000);
4710 #ifdef _MSC_VER
4711 # pragma warning(push)          // Saves the current warning state.
4712 # pragma warning(disable:4996)  // Temporarily disables warning 4996
4713                                 // (function or variable may be unsafe).
4714   const struct tm* const time_struct = localtime(&seconds);  // NOLINT
4715 # pragma warning(pop)           // Restores the warning state again.
4716 #else
4717   const struct tm* const time_struct = localtime(&seconds);  // NOLINT
4718 #endif
4719   if (time_struct == NULL)
4720     return "";  // Invalid ms value
4721 
4722   // YYYY-MM-DDThh:mm:ss
4723   return StreamableToString(time_struct->tm_year + 1900) + "-" +
4724       String::FormatIntWidth2(time_struct->tm_mon + 1) + "-" +
4725       String::FormatIntWidth2(time_struct->tm_mday) + "T" +
4726       String::FormatIntWidth2(time_struct->tm_hour) + ":" +
4727       String::FormatIntWidth2(time_struct->tm_min) + ":" +
4728       String::FormatIntWidth2(time_struct->tm_sec);
4729 }
4730 
4731 // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
OutputXmlCDataSection(::std::ostream * stream,const char * data)4732 void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream,
4733                                                      const char* data) {
4734   const char* segment = data;
4735   *stream << "<![CDATA[";
4736   for (;;) {
4737     const char* const next_segment = strstr(segment, "]]>");
4738     if (next_segment != NULL) {
4739       stream->write(
4740           segment, static_cast<std::streamsize>(next_segment - segment));
4741       *stream << "]]>]]&gt;<![CDATA[";
4742       segment = next_segment + strlen("]]>");
4743     } else {
4744       *stream << segment;
4745       break;
4746     }
4747   }
4748   *stream << "]]>";
4749 }
4750 
OutputXmlAttribute(std::ostream * stream,const std::string & element_name,const std::string & name,const std::string & value)4751 void XmlUnitTestResultPrinter::OutputXmlAttribute(
4752     std::ostream* stream,
4753     const std::string& element_name,
4754     const std::string& name,
4755     const std::string& value) {
4756   const std::vector<std::string>& allowed_names =
4757       GetReservedAttributesForElement(element_name);
4758 
4759   GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
4760                    allowed_names.end())
4761       << "Attribute " << name << " is not allowed for element <" << element_name
4762       << ">.";
4763 
4764   *stream << " " << name << "=\"" << EscapeXmlAttribute(value) << "\"";
4765 }
4766 
4767 // Prints an XML representation of a TestInfo object.
4768 // 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)4769 void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream,
4770                                                  const char* test_case_name,
4771                                                  const TestInfo& test_info) {
4772   const TestResult& result = *test_info.result();
4773   const std::string kTestcase = "testcase";
4774 
4775   *stream << "    <testcase";
4776   OutputXmlAttribute(stream, kTestcase, "name", test_info.name());
4777 
4778   if (test_info.value_param() != NULL) {
4779     OutputXmlAttribute(stream, kTestcase, "value_param",
4780                        test_info.value_param());
4781   }
4782   if (test_info.type_param() != NULL) {
4783     OutputXmlAttribute(stream, kTestcase, "type_param", test_info.type_param());
4784   }
4785 
4786   OutputXmlAttribute(stream, kTestcase, "status",
4787                      test_info.should_run() ? "run" : "notrun");
4788   OutputXmlAttribute(stream, kTestcase, "time",
4789                      FormatTimeInMillisAsSeconds(result.elapsed_time()));
4790   OutputXmlAttribute(stream, kTestcase, "classname", test_case_name);
4791   *stream << TestPropertiesAsXmlAttributes(result);
4792 
4793   int failures = 0;
4794   for (int i = 0; i < result.total_part_count(); ++i) {
4795     const TestPartResult& part = result.GetTestPartResult(i);
4796     if (part.failed()) {
4797       if (++failures == 1) {
4798         *stream << ">\n";
4799       }
4800       const string location = internal::FormatCompilerIndependentFileLocation(
4801           part.file_name(), part.line_number());
4802       const string summary = location + "\n" + part.summary();
4803       *stream << "      <failure message=\""
4804               << EscapeXmlAttribute(summary.c_str())
4805               << "\" type=\"\">";
4806       const string detail = location + "\n" + part.message();
4807       OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str());
4808       *stream << "</failure>\n";
4809     }
4810   }
4811 
4812   if (failures == 0)
4813     *stream << " />\n";
4814   else
4815     *stream << "    </testcase>\n";
4816 }
4817 
4818 // Prints an XML representation of a TestCase object
PrintXmlTestCase(std::ostream * stream,const TestCase & test_case)4819 void XmlUnitTestResultPrinter::PrintXmlTestCase(std::ostream* stream,
4820                                                 const TestCase& test_case) {
4821   const std::string kTestsuite = "testsuite";
4822   *stream << "  <" << kTestsuite;
4823   OutputXmlAttribute(stream, kTestsuite, "name", test_case.name());
4824   OutputXmlAttribute(stream, kTestsuite, "tests",
4825                      StreamableToString(test_case.reportable_test_count()));
4826   OutputXmlAttribute(stream, kTestsuite, "failures",
4827                      StreamableToString(test_case.failed_test_count()));
4828   OutputXmlAttribute(
4829       stream, kTestsuite, "disabled",
4830       StreamableToString(test_case.reportable_disabled_test_count()));
4831   OutputXmlAttribute(stream, kTestsuite, "errors", "0");
4832   OutputXmlAttribute(stream, kTestsuite, "time",
4833                      FormatTimeInMillisAsSeconds(test_case.elapsed_time()));
4834   *stream << TestPropertiesAsXmlAttributes(test_case.ad_hoc_test_result())
4835           << ">\n";
4836 
4837   for (int i = 0; i < test_case.total_test_count(); ++i) {
4838     if (test_case.GetTestInfo(i)->is_reportable())
4839       OutputXmlTestInfo(stream, test_case.name(), *test_case.GetTestInfo(i));
4840   }
4841   *stream << "  </" << kTestsuite << ">\n";
4842 }
4843 
4844 // Prints an XML summary of unit_test to output stream out.
PrintXmlUnitTest(std::ostream * stream,const UnitTest & unit_test)4845 void XmlUnitTestResultPrinter::PrintXmlUnitTest(std::ostream* stream,
4846                                                 const UnitTest& unit_test) {
4847   const std::string kTestsuites = "testsuites";
4848 
4849   *stream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
4850   *stream << "<" << kTestsuites;
4851 
4852   OutputXmlAttribute(stream, kTestsuites, "tests",
4853                      StreamableToString(unit_test.reportable_test_count()));
4854   OutputXmlAttribute(stream, kTestsuites, "failures",
4855                      StreamableToString(unit_test.failed_test_count()));
4856   OutputXmlAttribute(
4857       stream, kTestsuites, "disabled",
4858       StreamableToString(unit_test.reportable_disabled_test_count()));
4859   OutputXmlAttribute(stream, kTestsuites, "errors", "0");
4860   OutputXmlAttribute(
4861       stream, kTestsuites, "timestamp",
4862       FormatEpochTimeInMillisAsIso8601(unit_test.start_timestamp()));
4863   OutputXmlAttribute(stream, kTestsuites, "time",
4864                      FormatTimeInMillisAsSeconds(unit_test.elapsed_time()));
4865 
4866   if (GTEST_FLAG(shuffle)) {
4867     OutputXmlAttribute(stream, kTestsuites, "random_seed",
4868                        StreamableToString(unit_test.random_seed()));
4869   }
4870 
4871   *stream << TestPropertiesAsXmlAttributes(unit_test.ad_hoc_test_result());
4872 
4873   OutputXmlAttribute(stream, kTestsuites, "name", "AllTests");
4874   *stream << ">\n";
4875 
4876   for (int i = 0; i < unit_test.total_test_case_count(); ++i) {
4877     if (unit_test.GetTestCase(i)->reportable_test_count() > 0)
4878       PrintXmlTestCase(stream, *unit_test.GetTestCase(i));
4879   }
4880   *stream << "</" << kTestsuites << ">\n";
4881 }
4882 
4883 // Produces a string representing the test properties in a result as space
4884 // delimited XML attributes based on the property key="value" pairs.
TestPropertiesAsXmlAttributes(const TestResult & result)4885 std::string XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes(
4886     const TestResult& result) {
4887   Message attributes;
4888   for (int i = 0; i < result.test_property_count(); ++i) {
4889     const TestProperty& property = result.GetTestProperty(i);
4890     attributes << " " << property.key() << "="
4891         << "\"" << EscapeXmlAttribute(property.value()) << "\"";
4892   }
4893   return attributes.GetString();
4894 }
4895 
4896 // End XmlUnitTestResultPrinter
4897 
4898 #if GTEST_CAN_STREAM_RESULTS_
4899 
4900 // Checks if str contains '=', '&', '%' or '\n' characters. If yes,
4901 // replaces them by "%xx" where xx is their hexadecimal value. For
4902 // example, replaces "=" with "%3D".  This algorithm is O(strlen(str))
4903 // in both time and space -- important as the input str may contain an
4904 // arbitrarily long test failure message and stack trace.
UrlEncode(const char * str)4905 string StreamingListener::UrlEncode(const char* str) {
4906   string result;
4907   result.reserve(strlen(str) + 1);
4908   for (char ch = *str; ch != '\0'; ch = *++str) {
4909     switch (ch) {
4910       case '%':
4911       case '=':
4912       case '&':
4913       case '\n':
4914         result.append("%" + String::FormatByte(static_cast<unsigned char>(ch)));
4915         break;
4916       default:
4917         result.push_back(ch);
4918         break;
4919     }
4920   }
4921   return result;
4922 }
4923 
MakeConnection()4924 void StreamingListener::SocketWriter::MakeConnection() {
4925   GTEST_CHECK_(sockfd_ == -1)
4926       << "MakeConnection() can't be called when there is already a connection.";
4927 
4928   addrinfo hints;
4929   memset(&hints, 0, sizeof(hints));
4930   hints.ai_family = AF_UNSPEC;    // To allow both IPv4 and IPv6 addresses.
4931   hints.ai_socktype = SOCK_STREAM;
4932   addrinfo* servinfo = NULL;
4933 
4934   // Use the getaddrinfo() to get a linked list of IP addresses for
4935   // the given host name.
4936   const int error_num = getaddrinfo(
4937       host_name_.c_str(), port_num_.c_str(), &hints, &servinfo);
4938   if (error_num != 0) {
4939     GTEST_LOG_(WARNING) << "stream_result_to: getaddrinfo() failed: "
4940                         << gai_strerror(error_num);
4941   }
4942 
4943   // Loop through all the results and connect to the first we can.
4944   for (addrinfo* cur_addr = servinfo; sockfd_ == -1 && cur_addr != NULL;
4945        cur_addr = cur_addr->ai_next) {
4946     sockfd_ = socket(
4947         cur_addr->ai_family, cur_addr->ai_socktype, cur_addr->ai_protocol);
4948     if (sockfd_ != -1) {
4949       // Connect the client socket to the server socket.
4950       if (connect(sockfd_, cur_addr->ai_addr, cur_addr->ai_addrlen) == -1) {
4951         close(sockfd_);
4952         sockfd_ = -1;
4953       }
4954     }
4955   }
4956 
4957   freeaddrinfo(servinfo);  // all done with this structure
4958 
4959   if (sockfd_ == -1) {
4960     GTEST_LOG_(WARNING) << "stream_result_to: failed to connect to "
4961                         << host_name_ << ":" << port_num_;
4962   }
4963 }
4964 
4965 // End of class Streaming Listener
4966 #endif  // GTEST_CAN_STREAM_RESULTS__
4967 
4968 // Class ScopedTrace
4969 
4970 // Pushes the given source file location and message onto a per-thread
4971 // trace stack maintained by Google Test.
ScopedTrace(const char * file,int line,const Message & message)4972 ScopedTrace::ScopedTrace(const char* file, int line, const Message& message)
4973     GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) {
4974   TraceInfo trace;
4975   trace.file = file;
4976   trace.line = line;
4977   trace.message = message.GetString();
4978 
4979   UnitTest::GetInstance()->PushGTestTrace(trace);
4980 }
4981 
4982 // Pops the info pushed by the c'tor.
~ScopedTrace()4983 ScopedTrace::~ScopedTrace()
4984     GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) {
4985   UnitTest::GetInstance()->PopGTestTrace();
4986 }
4987 
4988 
4989 // class OsStackTraceGetter
4990 
4991 // Returns the current OS stack trace as an std::string.  Parameters:
4992 //
4993 //   max_depth  - the maximum number of stack frames to be included
4994 //                in the trace.
4995 //   skip_count - the number of top frames to be skipped; doesn't count
4996 //                against max_depth.
4997 //
CurrentStackTrace(int,int)4998 string OsStackTraceGetter::CurrentStackTrace(int /* max_depth */,
4999                                              int /* skip_count */)
5000     GTEST_LOCK_EXCLUDED_(mutex_) {
5001   return "";
5002 }
5003 
UponLeavingGTest()5004 void OsStackTraceGetter::UponLeavingGTest()
5005     GTEST_LOCK_EXCLUDED_(mutex_) {
5006 }
5007 
5008 const char* const
5009 OsStackTraceGetter::kElidedFramesMarker =
5010     "... " GTEST_NAME_ " internal frames ...";
5011 
5012 // A helper class that creates the premature-exit file in its
5013 // constructor and deletes the file in its destructor.
5014 class ScopedPrematureExitFile {
5015  public:
ScopedPrematureExitFile(const char * premature_exit_filepath)5016   explicit ScopedPrematureExitFile(const char* premature_exit_filepath)
5017       : premature_exit_filepath_(premature_exit_filepath) {
5018     // If a path to the premature-exit file is specified...
5019     if (premature_exit_filepath != NULL && *premature_exit_filepath != '\0') {
5020       // create the file with a single "0" character in it.  I/O
5021       // errors are ignored as there's nothing better we can do and we
5022       // don't want to fail the test because of this.
5023       FILE* pfile = posix::FOpen(premature_exit_filepath, "w");
5024       fwrite("0", 1, 1, pfile);
5025       fclose(pfile);
5026     }
5027   }
5028 
~ScopedPrematureExitFile()5029   ~ScopedPrematureExitFile() {
5030     if (premature_exit_filepath_ != NULL && *premature_exit_filepath_ != '\0') {
5031       remove(premature_exit_filepath_);
5032     }
5033   }
5034 
5035  private:
5036   const char* const premature_exit_filepath_;
5037 
5038   GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedPrematureExitFile);
5039 };
5040 
5041 }  // namespace internal
5042 
5043 // class TestEventListeners
5044 
TestEventListeners()5045 TestEventListeners::TestEventListeners()
5046     : repeater_(new internal::TestEventRepeater()),
5047       default_result_printer_(NULL),
5048       default_xml_generator_(NULL) {
5049 }
5050 
~TestEventListeners()5051 TestEventListeners::~TestEventListeners() { delete repeater_; }
5052 
5053 // Returns the standard listener responsible for the default console
5054 // output.  Can be removed from the listeners list to shut down default
5055 // console output.  Note that removing this object from the listener list
5056 // with Release transfers its ownership to the user.
Append(TestEventListener * listener)5057 void TestEventListeners::Append(TestEventListener* listener) {
5058   repeater_->Append(listener);
5059 }
5060 
5061 // Removes the given event listener from the list and returns it.  It then
5062 // becomes the caller's responsibility to delete the listener. Returns
5063 // NULL if the listener is not found in the list.
Release(TestEventListener * listener)5064 TestEventListener* TestEventListeners::Release(TestEventListener* listener) {
5065   if (listener == default_result_printer_)
5066     default_result_printer_ = NULL;
5067   else if (listener == default_xml_generator_)
5068     default_xml_generator_ = NULL;
5069   return repeater_->Release(listener);
5070 }
5071 
5072 // Returns repeater that broadcasts the TestEventListener events to all
5073 // subscribers.
repeater()5074 TestEventListener* TestEventListeners::repeater() { return repeater_; }
5075 
5076 // Sets the default_result_printer attribute to the provided listener.
5077 // The listener is also added to the listener list and previous
5078 // default_result_printer is removed from it and deleted. The listener can
5079 // also be NULL in which case it will not be added to the list. Does
5080 // nothing if the previous and the current listener objects are the same.
SetDefaultResultPrinter(TestEventListener * listener)5081 void TestEventListeners::SetDefaultResultPrinter(TestEventListener* listener) {
5082   if (default_result_printer_ != listener) {
5083     // It is an error to pass this method a listener that is already in the
5084     // list.
5085     delete Release(default_result_printer_);
5086     default_result_printer_ = listener;
5087     if (listener != NULL)
5088       Append(listener);
5089   }
5090 }
5091 
5092 // Sets the default_xml_generator attribute to the provided listener.  The
5093 // listener is also added to the listener list and previous
5094 // default_xml_generator is removed from it and deleted. The listener can
5095 // also be NULL in which case it will not be added to the list. Does
5096 // nothing if the previous and the current listener objects are the same.
SetDefaultXmlGenerator(TestEventListener * listener)5097 void TestEventListeners::SetDefaultXmlGenerator(TestEventListener* listener) {
5098   if (default_xml_generator_ != listener) {
5099     // It is an error to pass this method a listener that is already in the
5100     // list.
5101     delete Release(default_xml_generator_);
5102     default_xml_generator_ = listener;
5103     if (listener != NULL)
5104       Append(listener);
5105   }
5106 }
5107 
5108 // Controls whether events will be forwarded by the repeater to the
5109 // listeners in the list.
EventForwardingEnabled() const5110 bool TestEventListeners::EventForwardingEnabled() const {
5111   return repeater_->forwarding_enabled();
5112 }
5113 
SuppressEventForwarding()5114 void TestEventListeners::SuppressEventForwarding() {
5115   repeater_->set_forwarding_enabled(false);
5116 }
5117 
5118 // class UnitTest
5119 
5120 // Gets the singleton UnitTest object.  The first time this method is
5121 // called, a UnitTest object is constructed and returned.  Consecutive
5122 // calls will return the same object.
5123 //
5124 // We don't protect this under mutex_ as a user is not supposed to
5125 // call this before main() starts, from which point on the return
5126 // value will never change.
GetInstance()5127 UnitTest* UnitTest::GetInstance() {
5128   // When compiled with MSVC 7.1 in optimized mode, destroying the
5129   // UnitTest object upon exiting the program messes up the exit code,
5130   // causing successful tests to appear failed.  We have to use a
5131   // different implementation in this case to bypass the compiler bug.
5132   // This implementation makes the compiler happy, at the cost of
5133   // leaking the UnitTest object.
5134 
5135   // CodeGear C++Builder insists on a public destructor for the
5136   // default implementation.  Use this implementation to keep good OO
5137   // design with private destructor.
5138 
5139 #if (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)
5140   static UnitTest* const instance = new UnitTest;
5141   return instance;
5142 #else
5143   static UnitTest instance;
5144   return &instance;
5145 #endif  // (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)
5146 }
5147 
5148 // Gets the number of successful test cases.
successful_test_case_count() const5149 int UnitTest::successful_test_case_count() const {
5150   return impl()->successful_test_case_count();
5151 }
5152 
5153 // Gets the number of failed test cases.
failed_test_case_count() const5154 int UnitTest::failed_test_case_count() const {
5155   return impl()->failed_test_case_count();
5156 }
5157 
5158 // Gets the number of all test cases.
total_test_case_count() const5159 int UnitTest::total_test_case_count() const {
5160   return impl()->total_test_case_count();
5161 }
5162 
5163 // Gets the number of all test cases that contain at least one test
5164 // that should run.
test_case_to_run_count() const5165 int UnitTest::test_case_to_run_count() const {
5166   return impl()->test_case_to_run_count();
5167 }
5168 
5169 // Gets the number of successful tests.
successful_test_count() const5170 int UnitTest::successful_test_count() const {
5171   return impl()->successful_test_count();
5172 }
5173 
5174 // Gets the number of failed tests.
failed_test_count() const5175 int UnitTest::failed_test_count() const { return impl()->failed_test_count(); }
5176 
5177 // Gets the number of disabled tests that will be reported in the XML report.
reportable_disabled_test_count() const5178 int UnitTest::reportable_disabled_test_count() const {
5179   return impl()->reportable_disabled_test_count();
5180 }
5181 
5182 // Gets the number of disabled tests.
disabled_test_count() const5183 int UnitTest::disabled_test_count() const {
5184   return impl()->disabled_test_count();
5185 }
5186 
5187 // Gets the number of tests to be printed in the XML report.
reportable_test_count() const5188 int UnitTest::reportable_test_count() const {
5189   return impl()->reportable_test_count();
5190 }
5191 
5192 // Gets the number of all tests.
total_test_count() const5193 int UnitTest::total_test_count() const { return impl()->total_test_count(); }
5194 
5195 // Gets the number of tests that should run.
test_to_run_count() const5196 int UnitTest::test_to_run_count() const { return impl()->test_to_run_count(); }
5197 
5198 // Gets the time of the test program start, in ms from the start of the
5199 // UNIX epoch.
start_timestamp() const5200 internal::TimeInMillis UnitTest::start_timestamp() const {
5201     return impl()->start_timestamp();
5202 }
5203 
5204 // Gets the elapsed time, in milliseconds.
elapsed_time() const5205 internal::TimeInMillis UnitTest::elapsed_time() const {
5206   return impl()->elapsed_time();
5207 }
5208 
5209 // Returns true iff the unit test passed (i.e. all test cases passed).
Passed() const5210 bool UnitTest::Passed() const { return impl()->Passed(); }
5211 
5212 // Returns true iff the unit test failed (i.e. some test case failed
5213 // or something outside of all tests failed).
Failed() const5214 bool UnitTest::Failed() const { return impl()->Failed(); }
5215 
5216 // Gets the i-th test case among all the test cases. i can range from 0 to
5217 // total_test_case_count() - 1. If i is not in that range, returns NULL.
GetTestCase(int i) const5218 const TestCase* UnitTest::GetTestCase(int i) const {
5219   return impl()->GetTestCase(i);
5220 }
5221 
5222 // Returns the TestResult containing information on test failures and
5223 // properties logged outside of individual test cases.
ad_hoc_test_result() const5224 const TestResult& UnitTest::ad_hoc_test_result() const {
5225   return *impl()->ad_hoc_test_result();
5226 }
5227 
5228 // Gets the i-th test case among all the test cases. i can range from 0 to
5229 // total_test_case_count() - 1. If i is not in that range, returns NULL.
GetMutableTestCase(int i)5230 TestCase* UnitTest::GetMutableTestCase(int i) {
5231   return impl()->GetMutableTestCase(i);
5232 }
5233 
5234 // Returns the list of event listeners that can be used to track events
5235 // inside Google Test.
listeners()5236 TestEventListeners& UnitTest::listeners() {
5237   return *impl()->listeners();
5238 }
5239 
5240 // Registers and returns a global test environment.  When a test
5241 // program is run, all global test environments will be set-up in the
5242 // order they were registered.  After all tests in the program have
5243 // finished, all global test environments will be torn-down in the
5244 // *reverse* order they were registered.
5245 //
5246 // The UnitTest object takes ownership of the given environment.
5247 //
5248 // We don't protect this under mutex_, as we only support calling it
5249 // from the main thread.
AddEnvironment(Environment * env)5250 Environment* UnitTest::AddEnvironment(Environment* env) {
5251   if (env == NULL) {
5252     return NULL;
5253   }
5254 
5255   impl_->environments().push_back(env);
5256   return env;
5257 }
5258 
5259 // Adds a TestPartResult to the current TestResult object.  All Google Test
5260 // assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) eventually call
5261 // this to report their results.  The user code should use the
5262 // 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)5263 void UnitTest::AddTestPartResult(
5264     TestPartResult::Type result_type,
5265     const char* file_name,
5266     int line_number,
5267     const std::string& message,
5268     const std::string& os_stack_trace) GTEST_LOCK_EXCLUDED_(mutex_) {
5269   Message msg;
5270   msg << message;
5271 
5272   internal::MutexLock lock(&mutex_);
5273   if (impl_->gtest_trace_stack().size() > 0) {
5274     msg << "\n" << GTEST_NAME_ << " trace:";
5275 
5276     for (int i = static_cast<int>(impl_->gtest_trace_stack().size());
5277          i > 0; --i) {
5278       const internal::TraceInfo& trace = impl_->gtest_trace_stack()[i - 1];
5279       msg << "\n" << internal::FormatFileLocation(trace.file, trace.line)
5280           << " " << trace.message;
5281     }
5282   }
5283 
5284   if (os_stack_trace.c_str() != NULL && !os_stack_trace.empty()) {
5285     msg << internal::kStackTraceMarker << os_stack_trace;
5286   }
5287 
5288   const TestPartResult result =
5289     TestPartResult(result_type, file_name, line_number,
5290                    msg.GetString().c_str());
5291   impl_->GetTestPartResultReporterForCurrentThread()->
5292       ReportTestPartResult(result);
5293 
5294   if (result_type != TestPartResult::kSuccess) {
5295     // gtest_break_on_failure takes precedence over
5296     // gtest_throw_on_failure.  This allows a user to set the latter
5297     // in the code (perhaps in order to use Google Test assertions
5298     // with another testing framework) and specify the former on the
5299     // command line for debugging.
5300     if (GTEST_FLAG(break_on_failure)) {
5301 #if GTEST_OS_WINDOWS
5302       // Using DebugBreak on Windows allows gtest to still break into a debugger
5303       // when a failure happens and both the --gtest_break_on_failure and
5304       // the --gtest_catch_exceptions flags are specified.
5305       DebugBreak();
5306 #else
5307       // Dereference NULL through a volatile pointer to prevent the compiler
5308       // from removing. We use this rather than abort() or __builtin_trap() for
5309       // portability: Symbian doesn't implement abort() well, and some debuggers
5310       // don't correctly trap abort().
5311       *static_cast<volatile int*>(NULL) = 1;
5312 #endif  // GTEST_OS_WINDOWS
5313     } else if (GTEST_FLAG(throw_on_failure)) {
5314 #if GTEST_HAS_EXCEPTIONS
5315       throw internal::GoogleTestFailureException(result);
5316 #else
5317       // We cannot call abort() as it generates a pop-up in debug mode
5318       // that cannot be suppressed in VC 7.1 or below.
5319       exit(1);
5320 #endif
5321     }
5322   }
5323 }
5324 
5325 // Adds a TestProperty to the current TestResult object when invoked from
5326 // inside a test, to current TestCase's ad_hoc_test_result_ when invoked
5327 // from SetUpTestCase or TearDownTestCase, or to the global property set
5328 // when invoked elsewhere.  If the result already contains a property with
5329 // the same key, the value will be updated.
RecordProperty(const std::string & key,const std::string & value)5330 void UnitTest::RecordProperty(const std::string& key,
5331                               const std::string& value) {
5332   impl_->RecordProperty(TestProperty(key, value));
5333 }
5334 
5335 // Runs all tests in this UnitTest object and prints the result.
5336 // Returns 0 if successful, or 1 otherwise.
5337 //
5338 // We don't protect this under mutex_, as we only support calling it
5339 // from the main thread.
Run()5340 int UnitTest::Run() {
5341   const bool in_death_test_child_process =
5342       internal::GTEST_FLAG(internal_run_death_test).length() > 0;
5343 
5344   // Google Test implements this protocol for catching that a test
5345   // program exits before returning control to Google Test:
5346   //
5347   //   1. Upon start, Google Test creates a file whose absolute path
5348   //      is specified by the environment variable
5349   //      TEST_PREMATURE_EXIT_FILE.
5350   //   2. When Google Test has finished its work, it deletes the file.
5351   //
5352   // This allows a test runner to set TEST_PREMATURE_EXIT_FILE before
5353   // running a Google-Test-based test program and check the existence
5354   // of the file at the end of the test execution to see if it has
5355   // exited prematurely.
5356 
5357   // If we are in the child process of a death test, don't
5358   // create/delete the premature exit file, as doing so is unnecessary
5359   // and will confuse the parent process.  Otherwise, create/delete
5360   // the file upon entering/leaving this function.  If the program
5361   // somehow exits before this function has a chance to return, the
5362   // premature-exit file will be left undeleted, causing a test runner
5363   // that understands the premature-exit-file protocol to report the
5364   // test as having failed.
5365   const internal::ScopedPrematureExitFile premature_exit_file(
5366       in_death_test_child_process ?
5367       NULL : internal::posix::GetEnv("TEST_PREMATURE_EXIT_FILE"));
5368 
5369   // Captures the value of GTEST_FLAG(catch_exceptions).  This value will be
5370   // used for the duration of the program.
5371   impl()->set_catch_exceptions(GTEST_FLAG(catch_exceptions));
5372 
5373 #if GTEST_HAS_SEH
5374   // Either the user wants Google Test to catch exceptions thrown by the
5375   // tests or this is executing in the context of death test child
5376   // process. In either case the user does not want to see pop-up dialogs
5377   // about crashes - they are expected.
5378   if (impl()->catch_exceptions() || in_death_test_child_process) {
5379 # if !GTEST_OS_WINDOWS_MOBILE
5380     // SetErrorMode doesn't exist on CE.
5381     SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT |
5382                  SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);
5383 # endif  // !GTEST_OS_WINDOWS_MOBILE
5384 
5385 # if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE
5386     // Death test children can be terminated with _abort().  On Windows,
5387     // _abort() can show a dialog with a warning message.  This forces the
5388     // abort message to go to stderr instead.
5389     _set_error_mode(_OUT_TO_STDERR);
5390 # endif
5391 
5392 # if _MSC_VER >= 1400 && !GTEST_OS_WINDOWS_MOBILE
5393     // In the debug version, Visual Studio pops up a separate dialog
5394     // offering a choice to debug the aborted program. We need to suppress
5395     // this dialog or it will pop up for every EXPECT/ASSERT_DEATH statement
5396     // executed. Google Test will notify the user of any unexpected
5397     // failure via stderr.
5398     //
5399     // VC++ doesn't define _set_abort_behavior() prior to the version 8.0.
5400     // Users of prior VC versions shall suffer the agony and pain of
5401     // clicking through the countless debug dialogs.
5402     // TODO(vladl@google.com): find a way to suppress the abort dialog() in the
5403     // debug mode when compiled with VC 7.1 or lower.
5404     if (!GTEST_FLAG(break_on_failure))
5405       _set_abort_behavior(
5406           0x0,                                    // Clear the following flags:
5407           _WRITE_ABORT_MSG | _CALL_REPORTFAULT);  // pop-up window, core dump.
5408 # endif
5409   }
5410 #endif  // GTEST_HAS_SEH
5411 
5412   return internal::HandleExceptionsInMethodIfSupported(
5413       impl(),
5414       &internal::UnitTestImpl::RunAllTests,
5415       "auxiliary test code (environments or event listeners)") ? 0 : 1;
5416 }
5417 
5418 // Returns the working directory when the first TEST() or TEST_F() was
5419 // executed.
original_working_dir() const5420 const char* UnitTest::original_working_dir() const {
5421   return impl_->original_working_dir_.c_str();
5422 }
5423 
5424 // Returns the TestCase object for the test that's currently running,
5425 // or NULL if no test is running.
current_test_case() const5426 const TestCase* UnitTest::current_test_case() const
5427     GTEST_LOCK_EXCLUDED_(mutex_) {
5428   internal::MutexLock lock(&mutex_);
5429   return impl_->current_test_case();
5430 }
5431 
5432 // Returns the TestInfo object for the test that's currently running,
5433 // or NULL if no test is running.
current_test_info() const5434 const TestInfo* UnitTest::current_test_info() const
5435     GTEST_LOCK_EXCLUDED_(mutex_) {
5436   internal::MutexLock lock(&mutex_);
5437   return impl_->current_test_info();
5438 }
5439 
5440 // Returns the random seed used at the start of the current test run.
random_seed() const5441 int UnitTest::random_seed() const { return impl_->random_seed(); }
5442 
5443 #if GTEST_HAS_PARAM_TEST
5444 // Returns ParameterizedTestCaseRegistry object used to keep track of
5445 // value-parameterized tests and instantiate and register them.
5446 internal::ParameterizedTestCaseRegistry&
parameterized_test_registry()5447     UnitTest::parameterized_test_registry()
5448         GTEST_LOCK_EXCLUDED_(mutex_) {
5449   return impl_->parameterized_test_registry();
5450 }
5451 #endif  // GTEST_HAS_PARAM_TEST
5452 
5453 // Creates an empty UnitTest.
UnitTest()5454 UnitTest::UnitTest() {
5455   impl_ = new internal::UnitTestImpl(this);
5456 }
5457 
5458 // Destructor of UnitTest.
~UnitTest()5459 UnitTest::~UnitTest() {
5460   delete impl_;
5461 }
5462 
5463 // Pushes a trace defined by SCOPED_TRACE() on to the per-thread
5464 // Google Test trace stack.
PushGTestTrace(const internal::TraceInfo & trace)5465 void UnitTest::PushGTestTrace(const internal::TraceInfo& trace)
5466     GTEST_LOCK_EXCLUDED_(mutex_) {
5467   internal::MutexLock lock(&mutex_);
5468   impl_->gtest_trace_stack().push_back(trace);
5469 }
5470 
5471 // Pops a trace from the per-thread Google Test trace stack.
PopGTestTrace()5472 void UnitTest::PopGTestTrace()
5473     GTEST_LOCK_EXCLUDED_(mutex_) {
5474   internal::MutexLock lock(&mutex_);
5475   impl_->gtest_trace_stack().pop_back();
5476 }
5477 
5478 namespace internal {
5479 
UnitTestImpl(UnitTest * parent)5480 UnitTestImpl::UnitTestImpl(UnitTest* parent)
5481     : parent_(parent),
5482 #ifdef _MSC_VER
5483 # pragma warning(push)                    // Saves the current warning state.
5484 # pragma warning(disable:4355)            // Temporarily disables warning 4355
5485                                          // (using this in initializer).
5486       default_global_test_part_result_reporter_(this),
5487       default_per_thread_test_part_result_reporter_(this),
5488 # pragma warning(pop)                     // Restores the warning state again.
5489 #else
5490       default_global_test_part_result_reporter_(this),
5491       default_per_thread_test_part_result_reporter_(this),
5492 #endif  // _MSC_VER
5493       global_test_part_result_repoter_(
5494           &default_global_test_part_result_reporter_),
5495       per_thread_test_part_result_reporter_(
5496           &default_per_thread_test_part_result_reporter_),
5497 #if GTEST_HAS_PARAM_TEST
5498       parameterized_test_registry_(),
5499       parameterized_tests_registered_(false),
5500 #endif  // GTEST_HAS_PARAM_TEST
5501       last_death_test_case_(-1),
5502       current_test_case_(NULL),
5503       current_test_info_(NULL),
5504       ad_hoc_test_result_(),
5505       os_stack_trace_getter_(NULL),
5506       post_flag_parse_init_performed_(false),
5507       random_seed_(0),  // Will be overridden by the flag before first use.
5508       random_(0),  // Will be reseeded before first use.
5509       start_timestamp_(0),
5510       elapsed_time_(0),
5511 #if GTEST_HAS_DEATH_TEST
5512       death_test_factory_(new DefaultDeathTestFactory),
5513 #endif
5514       // Will be overridden by the flag before first use.
5515       catch_exceptions_(false) {
5516   listeners()->SetDefaultResultPrinter(new PrettyUnitTestResultPrinter);
5517 }
5518 
~UnitTestImpl()5519 UnitTestImpl::~UnitTestImpl() {
5520   // Deletes every TestCase.
5521   ForEach(test_cases_, internal::Delete<TestCase>);
5522 
5523   // Deletes every Environment.
5524   ForEach(environments_, internal::Delete<Environment>);
5525 
5526   delete os_stack_trace_getter_;
5527 }
5528 
5529 // Adds a TestProperty to the current TestResult object when invoked in a
5530 // context of a test, to current test case's ad_hoc_test_result when invoke
5531 // from SetUpTestCase/TearDownTestCase, or to the global property set
5532 // otherwise.  If the result already contains a property with the same key,
5533 // the value will be updated.
RecordProperty(const TestProperty & test_property)5534 void UnitTestImpl::RecordProperty(const TestProperty& test_property) {
5535   std::string xml_element;
5536   TestResult* test_result;  // TestResult appropriate for property recording.
5537 
5538   if (current_test_info_ != NULL) {
5539     xml_element = "testcase";
5540     test_result = &(current_test_info_->result_);
5541   } else if (current_test_case_ != NULL) {
5542     xml_element = "testsuite";
5543     test_result = &(current_test_case_->ad_hoc_test_result_);
5544   } else {
5545     xml_element = "testsuites";
5546     test_result = &ad_hoc_test_result_;
5547   }
5548   test_result->RecordProperty(xml_element, test_property);
5549 }
5550 
5551 #if GTEST_HAS_DEATH_TEST
5552 // Disables event forwarding if the control is currently in a death test
5553 // subprocess. Must not be called before InitGoogleTest.
SuppressTestEventsIfInSubprocess()5554 void UnitTestImpl::SuppressTestEventsIfInSubprocess() {
5555   if (internal_run_death_test_flag_.get() != NULL)
5556     listeners()->SuppressEventForwarding();
5557 }
5558 #endif  // GTEST_HAS_DEATH_TEST
5559 
5560 // Initializes event listeners performing XML output as specified by
5561 // UnitTestOptions. Must not be called before InitGoogleTest.
ConfigureXmlOutput()5562 void UnitTestImpl::ConfigureXmlOutput() {
5563   const std::string& output_format = UnitTestOptions::GetOutputFormat();
5564   if (output_format == "xml") {
5565     listeners()->SetDefaultXmlGenerator(new XmlUnitTestResultPrinter(
5566         UnitTestOptions::GetAbsolutePathToOutputFile().c_str()));
5567   } else if (output_format != "") {
5568     printf("WARNING: unrecognized output format \"%s\" ignored.\n",
5569            output_format.c_str());
5570     fflush(stdout);
5571   }
5572 }
5573 
5574 #if GTEST_CAN_STREAM_RESULTS_
5575 // Initializes event listeners for streaming test results in string form.
5576 // Must not be called before InitGoogleTest.
ConfigureStreamingOutput()5577 void UnitTestImpl::ConfigureStreamingOutput() {
5578   const std::string& target = GTEST_FLAG(stream_result_to);
5579   if (!target.empty()) {
5580     const size_t pos = target.find(':');
5581     if (pos != std::string::npos) {
5582       listeners()->Append(new StreamingListener(target.substr(0, pos),
5583                                                 target.substr(pos+1)));
5584     } else {
5585       printf("WARNING: unrecognized streaming target \"%s\" ignored.\n",
5586              target.c_str());
5587       fflush(stdout);
5588     }
5589   }
5590 }
5591 #endif  // GTEST_CAN_STREAM_RESULTS_
5592 
5593 // Performs initialization dependent upon flag values obtained in
5594 // ParseGoogleTestFlagsOnly.  Is called from InitGoogleTest after the call to
5595 // ParseGoogleTestFlagsOnly.  In case a user neglects to call InitGoogleTest
5596 // this function is also called from RunAllTests.  Since this function can be
5597 // called more than once, it has to be idempotent.
PostFlagParsingInit()5598 void UnitTestImpl::PostFlagParsingInit() {
5599   // Ensures that this function does not execute more than once.
5600   if (!post_flag_parse_init_performed_) {
5601     post_flag_parse_init_performed_ = true;
5602 
5603 #if GTEST_HAS_DEATH_TEST
5604     InitDeathTestSubprocessControlInfo();
5605     SuppressTestEventsIfInSubprocess();
5606 #endif  // GTEST_HAS_DEATH_TEST
5607 
5608     // Registers parameterized tests. This makes parameterized tests
5609     // available to the UnitTest reflection API without running
5610     // RUN_ALL_TESTS.
5611     RegisterParameterizedTests();
5612 
5613     // Configures listeners for XML output. This makes it possible for users
5614     // to shut down the default XML output before invoking RUN_ALL_TESTS.
5615     ConfigureXmlOutput();
5616 
5617 #if GTEST_CAN_STREAM_RESULTS_
5618     // Configures listeners for streaming test results to the specified server.
5619     ConfigureStreamingOutput();
5620 #endif  // GTEST_CAN_STREAM_RESULTS_
5621   }
5622 }
5623 
5624 // A predicate that checks the name of a TestCase against a known
5625 // value.
5626 //
5627 // This is used for implementation of the UnitTest class only.  We put
5628 // it in the anonymous namespace to prevent polluting the outer
5629 // namespace.
5630 //
5631 // TestCaseNameIs is copyable.
5632 class TestCaseNameIs {
5633  public:
5634   // Constructor.
TestCaseNameIs(const std::string & name)5635   explicit TestCaseNameIs(const std::string& name)
5636       : name_(name) {}
5637 
5638   // Returns true iff the name of test_case matches name_.
operator ()(const TestCase * test_case) const5639   bool operator()(const TestCase* test_case) const {
5640     return test_case != NULL && strcmp(test_case->name(), name_.c_str()) == 0;
5641   }
5642 
5643  private:
5644   std::string name_;
5645 };
5646 
5647 // Finds and returns a TestCase with the given name.  If one doesn't
5648 // exist, creates one and returns it.  It's the CALLER'S
5649 // RESPONSIBILITY to ensure that this function is only called WHEN THE
5650 // TESTS ARE NOT SHUFFLED.
5651 //
5652 // Arguments:
5653 //
5654 //   test_case_name: name of the test case
5655 //   type_param:     the name of the test case's type parameter, or NULL if
5656 //                   this is not a typed or a type-parameterized test case.
5657 //   set_up_tc:      pointer to the function that sets up the test case
5658 //   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)5659 TestCase* UnitTestImpl::GetTestCase(const char* test_case_name,
5660                                     const char* type_param,
5661                                     Test::SetUpTestCaseFunc set_up_tc,
5662                                     Test::TearDownTestCaseFunc tear_down_tc) {
5663   // Can we find a TestCase with the given name?
5664   const std::vector<TestCase*>::const_iterator test_case =
5665       std::find_if(test_cases_.begin(), test_cases_.end(),
5666                    TestCaseNameIs(test_case_name));
5667 
5668   if (test_case != test_cases_.end())
5669     return *test_case;
5670 
5671   // No.  Let's create one.
5672   TestCase* const new_test_case =
5673       new TestCase(test_case_name, type_param, set_up_tc, tear_down_tc);
5674 
5675   // Is this a death test case?
5676   if (internal::UnitTestOptions::MatchesFilter(test_case_name,
5677                                                kDeathTestCaseFilter)) {
5678     // Yes.  Inserts the test case after the last death test case
5679     // defined so far.  This only works when the test cases haven't
5680     // been shuffled.  Otherwise we may end up running a death test
5681     // after a non-death test.
5682     ++last_death_test_case_;
5683     test_cases_.insert(test_cases_.begin() + last_death_test_case_,
5684                        new_test_case);
5685   } else {
5686     // No.  Appends to the end of the list.
5687     test_cases_.push_back(new_test_case);
5688   }
5689 
5690   test_case_indices_.push_back(static_cast<int>(test_case_indices_.size()));
5691   return new_test_case;
5692 }
5693 
5694 // Helpers for setting up / tearing down the given environment.  They
5695 // are for use in the ForEach() function.
SetUpEnvironment(Environment * env)5696 static void SetUpEnvironment(Environment* env) { env->SetUp(); }
TearDownEnvironment(Environment * env)5697 static void TearDownEnvironment(Environment* env) { env->TearDown(); }
5698 
5699 // Runs all tests in this UnitTest object, prints the result, and
5700 // returns true if all tests are successful.  If any exception is
5701 // thrown during a test, the test is considered to be failed, but the
5702 // rest of the tests will still be run.
5703 //
5704 // When parameterized tests are enabled, it expands and registers
5705 // parameterized tests first in RegisterParameterizedTests().
5706 // All other functions called from RunAllTests() may safely assume that
5707 // parameterized tests are ready to be counted and run.
RunAllTests()5708 bool UnitTestImpl::RunAllTests() {
5709   // Makes sure InitGoogleTest() was called.
5710   if (!GTestIsInitialized()) {
5711     printf("%s",
5712            "\nThis test program did NOT call ::testing::InitGoogleTest "
5713            "before calling RUN_ALL_TESTS().  Please fix it.\n");
5714     return false;
5715   }
5716 
5717   // Do not run any test if the --help flag was specified.
5718   if (g_help_flag)
5719     return true;
5720 
5721   // Repeats the call to the post-flag parsing initialization in case the
5722   // user didn't call InitGoogleTest.
5723   PostFlagParsingInit();
5724 
5725   // Even if sharding is not on, test runners may want to use the
5726   // GTEST_SHARD_STATUS_FILE to query whether the test supports the sharding
5727   // protocol.
5728   internal::WriteToShardStatusFileIfNeeded();
5729 
5730   // True iff we are in a subprocess for running a thread-safe-style
5731   // death test.
5732   bool in_subprocess_for_death_test = false;
5733 
5734 #if GTEST_HAS_DEATH_TEST
5735   in_subprocess_for_death_test = (internal_run_death_test_flag_.get() != NULL);
5736 #endif  // GTEST_HAS_DEATH_TEST
5737 
5738   const bool should_shard = ShouldShard(kTestTotalShards, kTestShardIndex,
5739                                         in_subprocess_for_death_test);
5740 
5741   // Compares the full test names with the filter to decide which
5742   // tests to run.
5743   const bool has_tests_to_run = FilterTests(should_shard
5744                                               ? HONOR_SHARDING_PROTOCOL
5745                                               : IGNORE_SHARDING_PROTOCOL) > 0;
5746 
5747   // Lists the tests and exits if the --gtest_list_tests flag was specified.
5748   if (GTEST_FLAG(list_tests)) {
5749     // This must be called *after* FilterTests() has been called.
5750     ListTestsMatchingFilter();
5751     return true;
5752   }
5753 
5754   random_seed_ = GTEST_FLAG(shuffle) ?
5755       GetRandomSeedFromFlag(GTEST_FLAG(random_seed)) : 0;
5756 
5757   // True iff at least one test has failed.
5758   bool failed = false;
5759 
5760   TestEventListener* repeater = listeners()->repeater();
5761 
5762   start_timestamp_ = GetTimeInMillis();
5763   repeater->OnTestProgramStart(*parent_);
5764 
5765   // How many times to repeat the tests?  We don't want to repeat them
5766   // when we are inside the subprocess of a death test.
5767   const int repeat = in_subprocess_for_death_test ? 1 : GTEST_FLAG(repeat);
5768   // Repeats forever if the repeat count is negative.
5769   const bool forever = repeat < 0;
5770   for (int i = 0; forever || i != repeat; i++) {
5771     // We want to preserve failures generated by ad-hoc test
5772     // assertions executed before RUN_ALL_TESTS().
5773     ClearNonAdHocTestResult();
5774 
5775     const TimeInMillis start = GetTimeInMillis();
5776 
5777     // Shuffles test cases and tests if requested.
5778     if (has_tests_to_run && GTEST_FLAG(shuffle)) {
5779       random()->Reseed(random_seed_);
5780       // This should be done before calling OnTestIterationStart(),
5781       // such that a test event listener can see the actual test order
5782       // in the event.
5783       ShuffleTests();
5784     }
5785 
5786     // Tells the unit test event listeners that the tests are about to start.
5787     repeater->OnTestIterationStart(*parent_, i);
5788 
5789     // Runs each test case if there is at least one test to run.
5790     if (has_tests_to_run) {
5791       // Sets up all environments beforehand.
5792       repeater->OnEnvironmentsSetUpStart(*parent_);
5793       ForEach(environments_, SetUpEnvironment);
5794       repeater->OnEnvironmentsSetUpEnd(*parent_);
5795 
5796       // Runs the tests only if there was no fatal failure during global
5797       // set-up.
5798       if (!Test::HasFatalFailure()) {
5799         for (int test_index = 0; test_index < total_test_case_count();
5800              test_index++) {
5801           GetMutableTestCase(test_index)->Run();
5802         }
5803       }
5804 
5805       // Tears down all environments in reverse order afterwards.
5806       repeater->OnEnvironmentsTearDownStart(*parent_);
5807       std::for_each(environments_.rbegin(), environments_.rend(),
5808                     TearDownEnvironment);
5809       repeater->OnEnvironmentsTearDownEnd(*parent_);
5810     }
5811 
5812     elapsed_time_ = GetTimeInMillis() - start;
5813 
5814     // Tells the unit test event listener that the tests have just finished.
5815     repeater->OnTestIterationEnd(*parent_, i);
5816 
5817     // Gets the result and clears it.
5818     if (!Passed()) {
5819       failed = true;
5820     }
5821 
5822     // Restores the original test order after the iteration.  This
5823     // allows the user to quickly repro a failure that happens in the
5824     // N-th iteration without repeating the first (N - 1) iterations.
5825     // This is not enclosed in "if (GTEST_FLAG(shuffle)) { ... }", in
5826     // case the user somehow changes the value of the flag somewhere
5827     // (it's always safe to unshuffle the tests).
5828     UnshuffleTests();
5829 
5830     if (GTEST_FLAG(shuffle)) {
5831       // Picks a new random seed for each iteration.
5832       random_seed_ = GetNextRandomSeed(random_seed_);
5833     }
5834   }
5835 
5836   repeater->OnTestProgramEnd(*parent_);
5837 
5838   return !failed;
5839 }
5840 
5841 // Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
5842 // if the variable is present. If a file already exists at this location, this
5843 // function will write over it. If the variable is present, but the file cannot
5844 // be created, prints an error and exits.
WriteToShardStatusFileIfNeeded()5845 void WriteToShardStatusFileIfNeeded() {
5846   const char* const test_shard_file = posix::GetEnv(kTestShardStatusFile);
5847   if (test_shard_file != NULL) {
5848     FILE* const file = posix::FOpen(test_shard_file, "w");
5849     if (file == NULL) {
5850       ColoredPrintf(COLOR_RED,
5851                     "Could not write to the test shard status file \"%s\" "
5852                     "specified by the %s environment variable.\n",
5853                     test_shard_file, kTestShardStatusFile);
5854       fflush(stdout);
5855       exit(EXIT_FAILURE);
5856     }
5857     fclose(file);
5858   }
5859 }
5860 
5861 // Checks whether sharding is enabled by examining the relevant
5862 // environment variable values. If the variables are present,
5863 // but inconsistent (i.e., shard_index >= total_shards), prints
5864 // an error and exits. If in_subprocess_for_death_test, sharding is
5865 // disabled because it must only be applied to the original test
5866 // 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)5867 bool ShouldShard(const char* total_shards_env,
5868                  const char* shard_index_env,
5869                  bool in_subprocess_for_death_test) {
5870   if (in_subprocess_for_death_test) {
5871     return false;
5872   }
5873 
5874   const Int32 total_shards = Int32FromEnvOrDie(total_shards_env, -1);
5875   const Int32 shard_index = Int32FromEnvOrDie(shard_index_env, -1);
5876 
5877   if (total_shards == -1 && shard_index == -1) {
5878     return false;
5879   } else if (total_shards == -1 && shard_index != -1) {
5880     const Message msg = Message()
5881       << "Invalid environment variables: you have "
5882       << kTestShardIndex << " = " << shard_index
5883       << ", but have left " << kTestTotalShards << " unset.\n";
5884     ColoredPrintf(COLOR_RED, msg.GetString().c_str());
5885     fflush(stdout);
5886     exit(EXIT_FAILURE);
5887   } else if (total_shards != -1 && shard_index == -1) {
5888     const Message msg = Message()
5889       << "Invalid environment variables: you have "
5890       << kTestTotalShards << " = " << total_shards
5891       << ", but have left " << kTestShardIndex << " unset.\n";
5892     ColoredPrintf(COLOR_RED, msg.GetString().c_str());
5893     fflush(stdout);
5894     exit(EXIT_FAILURE);
5895   } else if (shard_index < 0 || shard_index >= total_shards) {
5896     const Message msg = Message()
5897       << "Invalid environment variables: we require 0 <= "
5898       << kTestShardIndex << " < " << kTestTotalShards
5899       << ", but you have " << kTestShardIndex << "=" << shard_index
5900       << ", " << kTestTotalShards << "=" << total_shards << ".\n";
5901     ColoredPrintf(COLOR_RED, msg.GetString().c_str());
5902     fflush(stdout);
5903     exit(EXIT_FAILURE);
5904   }
5905 
5906   return total_shards > 1;
5907 }
5908 
5909 // Parses the environment variable var as an Int32. If it is unset,
5910 // returns default_val. If it is not an Int32, prints an error
5911 // and aborts.
Int32FromEnvOrDie(const char * var,Int32 default_val)5912 Int32 Int32FromEnvOrDie(const char* var, Int32 default_val) {
5913   const char* str_val = posix::GetEnv(var);
5914   if (str_val == NULL) {
5915     return default_val;
5916   }
5917 
5918   Int32 result;
5919   if (!ParseInt32(Message() << "The value of environment variable " << var,
5920                   str_val, &result)) {
5921     exit(EXIT_FAILURE);
5922   }
5923   return result;
5924 }
5925 
5926 // Given the total number of shards, the shard index, and the test id,
5927 // returns true iff the test should be run on this shard. The test id is
5928 // some arbitrary but unique non-negative integer assigned to each test
5929 // method. Assumes that 0 <= shard_index < total_shards.
ShouldRunTestOnShard(int total_shards,int shard_index,int test_id)5930 bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) {
5931   return (test_id % total_shards) == shard_index;
5932 }
5933 
5934 // Compares the name of each test with the user-specified filter to
5935 // decide whether the test should be run, then records the result in
5936 // each TestCase and TestInfo object.
5937 // If shard_tests == true, further filters tests based on sharding
5938 // variables in the environment - see
5939 // http://code.google.com/p/googletest/wiki/GoogleTestAdvancedGuide.
5940 // Returns the number of tests that should run.
FilterTests(ReactionToSharding shard_tests)5941 int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) {
5942   const Int32 total_shards = shard_tests == HONOR_SHARDING_PROTOCOL ?
5943       Int32FromEnvOrDie(kTestTotalShards, -1) : -1;
5944   const Int32 shard_index = shard_tests == HONOR_SHARDING_PROTOCOL ?
5945       Int32FromEnvOrDie(kTestShardIndex, -1) : -1;
5946 
5947   // num_runnable_tests are the number of tests that will
5948   // run across all shards (i.e., match filter and are not disabled).
5949   // num_selected_tests are the number of tests to be run on
5950   // this shard.
5951   int num_runnable_tests = 0;
5952   int num_selected_tests = 0;
5953   for (size_t i = 0; i < test_cases_.size(); i++) {
5954     TestCase* const test_case = test_cases_[i];
5955     const std::string &test_case_name = test_case->name();
5956     test_case->set_should_run(false);
5957 
5958     for (size_t j = 0; j < test_case->test_info_list().size(); j++) {
5959       TestInfo* const test_info = test_case->test_info_list()[j];
5960       const std::string test_name(test_info->name());
5961       // A test is disabled if test case name or test name matches
5962       // kDisableTestFilter.
5963       const bool is_disabled =
5964           internal::UnitTestOptions::MatchesFilter(test_case_name,
5965                                                    kDisableTestFilter) ||
5966           internal::UnitTestOptions::MatchesFilter(test_name,
5967                                                    kDisableTestFilter);
5968       test_info->is_disabled_ = is_disabled;
5969 
5970       const bool matches_filter =
5971           internal::UnitTestOptions::FilterMatchesTest(test_case_name,
5972                                                        test_name);
5973       test_info->matches_filter_ = matches_filter;
5974 
5975       const bool is_runnable =
5976           (GTEST_FLAG(also_run_disabled_tests) || !is_disabled) &&
5977           matches_filter;
5978 
5979       const bool is_selected = is_runnable &&
5980           (shard_tests == IGNORE_SHARDING_PROTOCOL ||
5981            ShouldRunTestOnShard(total_shards, shard_index,
5982                                 num_runnable_tests));
5983 
5984       num_runnable_tests += is_runnable;
5985       num_selected_tests += is_selected;
5986 
5987       test_info->should_run_ = is_selected;
5988       test_case->set_should_run(test_case->should_run() || is_selected);
5989     }
5990   }
5991   return num_selected_tests;
5992 }
5993 
5994 // Prints the given C-string on a single line by replacing all '\n'
5995 // characters with string "\\n".  If the output takes more than
5996 // max_length characters, only prints the first max_length characters
5997 // and "...".
PrintOnOneLine(const char * str,int max_length)5998 static void PrintOnOneLine(const char* str, int max_length) {
5999   if (str != NULL) {
6000     for (int i = 0; *str != '\0'; ++str) {
6001       if (i >= max_length) {
6002         printf("...");
6003         break;
6004       }
6005       if (*str == '\n') {
6006         printf("\\n");
6007         i += 2;
6008       } else {
6009         printf("%c", *str);
6010         ++i;
6011       }
6012     }
6013   }
6014 }
6015 
6016 // Prints the names of the tests matching the user-specified filter flag.
ListTestsMatchingFilter()6017 void UnitTestImpl::ListTestsMatchingFilter() {
6018   // Print at most this many characters for each type/value parameter.
6019   const int kMaxParamLength = 250;
6020 
6021   for (size_t i = 0; i < test_cases_.size(); i++) {
6022     const TestCase* const test_case = test_cases_[i];
6023     bool printed_test_case_name = false;
6024 
6025     for (size_t j = 0; j < test_case->test_info_list().size(); j++) {
6026       const TestInfo* const test_info =
6027           test_case->test_info_list()[j];
6028       if (test_info->matches_filter_) {
6029         if (!printed_test_case_name) {
6030           printed_test_case_name = true;
6031           printf("%s.", test_case->name());
6032           if (test_case->type_param() != NULL) {
6033             printf("  # %s = ", kTypeParamLabel);
6034             // We print the type parameter on a single line to make
6035             // the output easy to parse by a program.
6036             PrintOnOneLine(test_case->type_param(), kMaxParamLength);
6037           }
6038           printf("\n");
6039         }
6040         printf("  %s", test_info->name());
6041         if (test_info->value_param() != NULL) {
6042           printf("  # %s = ", kValueParamLabel);
6043           // We print the value parameter on a single line to make the
6044           // output easy to parse by a program.
6045           PrintOnOneLine(test_info->value_param(), kMaxParamLength);
6046         }
6047         printf("\n");
6048       }
6049     }
6050   }
6051   fflush(stdout);
6052 }
6053 
6054 // Sets the OS stack trace getter.
6055 //
6056 // Does nothing if the input and the current OS stack trace getter are
6057 // the same; otherwise, deletes the old getter and makes the input the
6058 // current getter.
set_os_stack_trace_getter(OsStackTraceGetterInterface * getter)6059 void UnitTestImpl::set_os_stack_trace_getter(
6060     OsStackTraceGetterInterface* getter) {
6061   if (os_stack_trace_getter_ != getter) {
6062     delete os_stack_trace_getter_;
6063     os_stack_trace_getter_ = getter;
6064   }
6065 }
6066 
6067 // Returns the current OS stack trace getter if it is not NULL;
6068 // otherwise, creates an OsStackTraceGetter, makes it the current
6069 // getter, and returns it.
os_stack_trace_getter()6070 OsStackTraceGetterInterface* UnitTestImpl::os_stack_trace_getter() {
6071   if (os_stack_trace_getter_ == NULL) {
6072     os_stack_trace_getter_ = new OsStackTraceGetter;
6073   }
6074 
6075   return os_stack_trace_getter_;
6076 }
6077 
6078 // Returns the TestResult for the test that's currently running, or
6079 // the TestResult for the ad hoc test if no test is running.
current_test_result()6080 TestResult* UnitTestImpl::current_test_result() {
6081   return current_test_info_ ?
6082       &(current_test_info_->result_) : &ad_hoc_test_result_;
6083 }
6084 
6085 // Shuffles all test cases, and the tests within each test case,
6086 // making sure that death tests are still run first.
ShuffleTests()6087 void UnitTestImpl::ShuffleTests() {
6088   // Shuffles the death test cases.
6089   ShuffleRange(random(), 0, last_death_test_case_ + 1, &test_case_indices_);
6090 
6091   // Shuffles the non-death test cases.
6092   ShuffleRange(random(), last_death_test_case_ + 1,
6093                static_cast<int>(test_cases_.size()), &test_case_indices_);
6094 
6095   // Shuffles the tests inside each test case.
6096   for (size_t i = 0; i < test_cases_.size(); i++) {
6097     test_cases_[i]->ShuffleTests(random());
6098   }
6099 }
6100 
6101 // Restores the test cases and tests to their order before the first shuffle.
UnshuffleTests()6102 void UnitTestImpl::UnshuffleTests() {
6103   for (size_t i = 0; i < test_cases_.size(); i++) {
6104     // Unshuffles the tests in each test case.
6105     test_cases_[i]->UnshuffleTests();
6106     // Resets the index of each test case.
6107     test_case_indices_[i] = static_cast<int>(i);
6108   }
6109 }
6110 
6111 // Returns the current OS stack trace as an std::string.
6112 //
6113 // The maximum number of stack frames to be included is specified by
6114 // the gtest_stack_trace_depth flag.  The skip_count parameter
6115 // specifies the number of top frames to be skipped, which doesn't
6116 // count against the number of frames to be included.
6117 //
6118 // For example, if Foo() calls Bar(), which in turn calls
6119 // GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in
6120 // the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.
GetCurrentOsStackTraceExceptTop(UnitTest *,int skip_count)6121 std::string GetCurrentOsStackTraceExceptTop(UnitTest* /*unit_test*/,
6122                                             int skip_count) {
6123   // We pass skip_count + 1 to skip this wrapper function in addition
6124   // to what the user really wants to skip.
6125   return GetUnitTestImpl()->CurrentOsStackTraceExceptTop(skip_count + 1);
6126 }
6127 
6128 // Used by the GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_ macro to
6129 // suppress unreachable code warnings.
6130 namespace {
6131 class ClassUniqueToAlwaysTrue {};
6132 }
6133 
IsTrue(bool condition)6134 bool IsTrue(bool condition) { return condition; }
6135 
AlwaysTrue()6136 bool AlwaysTrue() {
6137 #if GTEST_HAS_EXCEPTIONS
6138   // This condition is always false so AlwaysTrue() never actually throws,
6139   // but it makes the compiler think that it may throw.
6140   if (IsTrue(false))
6141     throw ClassUniqueToAlwaysTrue();
6142 #endif  // GTEST_HAS_EXCEPTIONS
6143   return true;
6144 }
6145 
6146 // If *pstr starts with the given prefix, modifies *pstr to be right
6147 // past the prefix and returns true; otherwise leaves *pstr unchanged
6148 // and returns false.  None of pstr, *pstr, and prefix can be NULL.
SkipPrefix(const char * prefix,const char ** pstr)6149 bool SkipPrefix(const char* prefix, const char** pstr) {
6150   const size_t prefix_len = strlen(prefix);
6151   if (strncmp(*pstr, prefix, prefix_len) == 0) {
6152     *pstr += prefix_len;
6153     return true;
6154   }
6155   return false;
6156 }
6157 
6158 // Parses a string as a command line flag.  The string should have
6159 // the format "--flag=value".  When def_optional is true, the "=value"
6160 // part can be omitted.
6161 //
6162 // Returns the value of the flag, or NULL if the parsing failed.
ParseFlagValue(const char * str,const char * flag,bool def_optional)6163 const char* ParseFlagValue(const char* str,
6164                            const char* flag,
6165                            bool def_optional) {
6166   // str and flag must not be NULL.
6167   if (str == NULL || flag == NULL) return NULL;
6168 
6169   // The flag must start with "--" followed by GTEST_FLAG_PREFIX_.
6170   const std::string flag_str = std::string("--") + GTEST_FLAG_PREFIX_ + flag;
6171   const size_t flag_len = flag_str.length();
6172   if (strncmp(str, flag_str.c_str(), flag_len) != 0) return NULL;
6173 
6174   // Skips the flag name.
6175   const char* flag_end = str + flag_len;
6176 
6177   // When def_optional is true, it's OK to not have a "=value" part.
6178   if (def_optional && (flag_end[0] == '\0')) {
6179     return flag_end;
6180   }
6181 
6182   // If def_optional is true and there are more characters after the
6183   // flag name, or if def_optional is false, there must be a '=' after
6184   // the flag name.
6185   if (flag_end[0] != '=') return NULL;
6186 
6187   // Returns the string after "=".
6188   return flag_end + 1;
6189 }
6190 
6191 // Parses a string for a bool flag, in the form of either
6192 // "--flag=value" or "--flag".
6193 //
6194 // In the former case, the value is taken as true as long as it does
6195 // not start with '0', 'f', or 'F'.
6196 //
6197 // In the latter case, the value is taken as true.
6198 //
6199 // On success, stores the value of the flag in *value, and returns
6200 // true.  On failure, returns false without changing *value.
ParseBoolFlag(const char * str,const char * flag,bool * value)6201 bool ParseBoolFlag(const char* str, const char* flag, bool* value) {
6202   // Gets the value of the flag as a string.
6203   const char* const value_str = ParseFlagValue(str, flag, true);
6204 
6205   // Aborts if the parsing failed.
6206   if (value_str == NULL) return false;
6207 
6208   // Converts the string value to a bool.
6209   *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F');
6210   return true;
6211 }
6212 
6213 // Parses a string for an Int32 flag, in the form of
6214 // "--flag=value".
6215 //
6216 // On success, stores the value of the flag in *value, and returns
6217 // true.  On failure, returns false without changing *value.
ParseInt32Flag(const char * str,const char * flag,Int32 * value)6218 bool ParseInt32Flag(const char* str, const char* flag, Int32* value) {
6219   // Gets the value of the flag as a string.
6220   const char* const value_str = ParseFlagValue(str, flag, false);
6221 
6222   // Aborts if the parsing failed.
6223   if (value_str == NULL) return false;
6224 
6225   // Sets *value to the value of the flag.
6226   return ParseInt32(Message() << "The value of flag --" << flag,
6227                     value_str, value);
6228 }
6229 
6230 // Parses a string for a string flag, in the form of
6231 // "--flag=value".
6232 //
6233 // On success, stores the value of the flag in *value, and returns
6234 // true.  On failure, returns false without changing *value.
ParseStringFlag(const char * str,const char * flag,std::string * value)6235 bool ParseStringFlag(const char* str, const char* flag, std::string* value) {
6236   // Gets the value of the flag as a string.
6237   const char* const value_str = ParseFlagValue(str, flag, false);
6238 
6239   // Aborts if the parsing failed.
6240   if (value_str == NULL) return false;
6241 
6242   // Sets *value to the value of the flag.
6243   *value = value_str;
6244   return true;
6245 }
6246 
6247 // Determines whether a string has a prefix that Google Test uses for its
6248 // flags, i.e., starts with GTEST_FLAG_PREFIX_ or GTEST_FLAG_PREFIX_DASH_.
6249 // If Google Test detects that a command line flag has its prefix but is not
6250 // recognized, it will print its help message. Flags starting with
6251 // GTEST_INTERNAL_PREFIX_ followed by "internal_" are considered Google Test
6252 // internal flags and do not trigger the help message.
HasGoogleTestFlagPrefix(const char * str)6253 static bool HasGoogleTestFlagPrefix(const char* str) {
6254   return (SkipPrefix("--", &str) ||
6255           SkipPrefix("-", &str) ||
6256           SkipPrefix("/", &str)) &&
6257          !SkipPrefix(GTEST_FLAG_PREFIX_ "internal_", &str) &&
6258          (SkipPrefix(GTEST_FLAG_PREFIX_, &str) ||
6259           SkipPrefix(GTEST_FLAG_PREFIX_DASH_, &str));
6260 }
6261 
6262 // Prints a string containing code-encoded text.  The following escape
6263 // sequences can be used in the string to control the text color:
6264 //
6265 //   @@    prints a single '@' character.
6266 //   @R    changes the color to red.
6267 //   @G    changes the color to green.
6268 //   @Y    changes the color to yellow.
6269 //   @D    changes to the default terminal text color.
6270 //
6271 // TODO(wan@google.com): Write tests for this once we add stdout
6272 // capturing to Google Test.
PrintColorEncoded(const char * str)6273 static void PrintColorEncoded(const char* str) {
6274   GTestColor color = COLOR_DEFAULT;  // The current color.
6275 
6276   // Conceptually, we split the string into segments divided by escape
6277   // sequences.  Then we print one segment at a time.  At the end of
6278   // each iteration, the str pointer advances to the beginning of the
6279   // next segment.
6280   for (;;) {
6281     const char* p = strchr(str, '@');
6282     if (p == NULL) {
6283       ColoredPrintf(color, "%s", str);
6284       return;
6285     }
6286 
6287     ColoredPrintf(color, "%s", std::string(str, p).c_str());
6288 
6289     const char ch = p[1];
6290     str = p + 2;
6291     if (ch == '@') {
6292       ColoredPrintf(color, "@");
6293     } else if (ch == 'D') {
6294       color = COLOR_DEFAULT;
6295     } else if (ch == 'R') {
6296       color = COLOR_RED;
6297     } else if (ch == 'G') {
6298       color = COLOR_GREEN;
6299     } else if (ch == 'Y') {
6300       color = COLOR_YELLOW;
6301     } else {
6302       --str;
6303     }
6304   }
6305 }
6306 
6307 static const char kColorEncodedHelpMessage[] =
6308 "This program contains tests written using " GTEST_NAME_ ". You can use the\n"
6309 "following command line flags to control its behavior:\n"
6310 "\n"
6311 "Test Selection:\n"
6312 "  @G--" GTEST_FLAG_PREFIX_ "list_tests@D\n"
6313 "      List the names of all tests instead of running them. The name of\n"
6314 "      TEST(Foo, Bar) is \"Foo.Bar\".\n"
6315 "  @G--" GTEST_FLAG_PREFIX_ "filter=@YPOSTIVE_PATTERNS"
6316     "[@G-@YNEGATIVE_PATTERNS]@D\n"
6317 "      Run only the tests whose name matches one of the positive patterns but\n"
6318 "      none of the negative patterns. '?' matches any single character; '*'\n"
6319 "      matches any substring; ':' separates two patterns.\n"
6320 "  @G--" GTEST_FLAG_PREFIX_ "also_run_disabled_tests@D\n"
6321 "      Run all disabled tests too.\n"
6322 "\n"
6323 "Test Execution:\n"
6324 "  @G--" GTEST_FLAG_PREFIX_ "repeat=@Y[COUNT]@D\n"
6325 "      Run the tests repeatedly; use a negative count to repeat forever.\n"
6326 "  @G--" GTEST_FLAG_PREFIX_ "shuffle@D\n"
6327 "      Randomize tests' orders on every iteration.\n"
6328 "  @G--" GTEST_FLAG_PREFIX_ "random_seed=@Y[NUMBER]@D\n"
6329 "      Random number seed to use for shuffling test orders (between 1 and\n"
6330 "      99999, or 0 to use a seed based on the current time).\n"
6331 "\n"
6332 "Test Output:\n"
6333 "  @G--" GTEST_FLAG_PREFIX_ "color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\n"
6334 "      Enable/disable colored output. The default is @Gauto@D.\n"
6335 "  -@G-" GTEST_FLAG_PREFIX_ "print_time=0@D\n"
6336 "      Don't print the elapsed time of each test.\n"
6337 "  @G--" GTEST_FLAG_PREFIX_ "output=xml@Y[@G:@YDIRECTORY_PATH@G"
6338     GTEST_PATH_SEP_ "@Y|@G:@YFILE_PATH]@D\n"
6339 "      Generate an XML report in the given directory or with the given file\n"
6340 "      name. @YFILE_PATH@D defaults to @Gtest_details.xml@D.\n"
6341 #if GTEST_CAN_STREAM_RESULTS_
6342 "  @G--" GTEST_FLAG_PREFIX_ "stream_result_to=@YHOST@G:@YPORT@D\n"
6343 "      Stream test results to the given server.\n"
6344 #endif  // GTEST_CAN_STREAM_RESULTS_
6345 "\n"
6346 "Assertion Behavior:\n"
6347 #if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
6348 "  @G--" GTEST_FLAG_PREFIX_ "death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n"
6349 "      Set the default death test style.\n"
6350 #endif  // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
6351 "  @G--" GTEST_FLAG_PREFIX_ "break_on_failure@D\n"
6352 "      Turn assertion failures into debugger break-points.\n"
6353 "  @G--" GTEST_FLAG_PREFIX_ "throw_on_failure@D\n"
6354 "      Turn assertion failures into C++ exceptions.\n"
6355 "  @G--" GTEST_FLAG_PREFIX_ "catch_exceptions=0@D\n"
6356 "      Do not report exceptions as test failures. Instead, allow them\n"
6357 "      to crash the program or throw a pop-up (on Windows).\n"
6358 "\n"
6359 "Except for @G--" GTEST_FLAG_PREFIX_ "list_tests@D, you can alternatively set "
6360     "the corresponding\n"
6361 "environment variable of a flag (all letters in upper-case). For example, to\n"
6362 "disable colored text output, you can either specify @G--" GTEST_FLAG_PREFIX_
6363     "color=no@D or set\n"
6364 "the @G" GTEST_FLAG_PREFIX_UPPER_ "COLOR@D environment variable to @Gno@D.\n"
6365 "\n"
6366 "For more information, please read the " GTEST_NAME_ " documentation at\n"
6367 "@G" GTEST_PROJECT_URL_ "@D. If you find a bug in " GTEST_NAME_ "\n"
6368 "(not one in your own code or tests), please report it to\n"
6369 "@G<" GTEST_DEV_EMAIL_ ">@D.\n";
6370 
6371 // Parses the command line for Google Test flags, without initializing
6372 // other parts of Google Test.  The type parameter CharType can be
6373 // instantiated to either char or wchar_t.
6374 template <typename CharType>
ParseGoogleTestFlagsOnlyImpl(int * argc,CharType ** argv)6375 void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) {
6376   for (int i = 1; i < *argc; i++) {
6377     const std::string arg_string = StreamableToString(argv[i]);
6378     const char* const arg = arg_string.c_str();
6379 
6380     using internal::ParseBoolFlag;
6381     using internal::ParseInt32Flag;
6382     using internal::ParseStringFlag;
6383 
6384     // Do we see a Google Test flag?
6385     if (ParseBoolFlag(arg, kAlsoRunDisabledTestsFlag,
6386                       &GTEST_FLAG(also_run_disabled_tests)) ||
6387         ParseBoolFlag(arg, kBreakOnFailureFlag,
6388                       &GTEST_FLAG(break_on_failure)) ||
6389         ParseBoolFlag(arg, kCatchExceptionsFlag,
6390                       &GTEST_FLAG(catch_exceptions)) ||
6391         ParseStringFlag(arg, kColorFlag, &GTEST_FLAG(color)) ||
6392         ParseStringFlag(arg, kDeathTestStyleFlag,
6393                         &GTEST_FLAG(death_test_style)) ||
6394         ParseBoolFlag(arg, kDeathTestUseFork,
6395                       &GTEST_FLAG(death_test_use_fork)) ||
6396         ParseStringFlag(arg, kFilterFlag, &GTEST_FLAG(filter)) ||
6397         ParseStringFlag(arg, kInternalRunDeathTestFlag,
6398                         &GTEST_FLAG(internal_run_death_test)) ||
6399         ParseBoolFlag(arg, kListTestsFlag, &GTEST_FLAG(list_tests)) ||
6400         ParseStringFlag(arg, kOutputFlag, &GTEST_FLAG(output)) ||
6401         ParseBoolFlag(arg, kPrintTimeFlag, &GTEST_FLAG(print_time)) ||
6402         ParseInt32Flag(arg, kRandomSeedFlag, &GTEST_FLAG(random_seed)) ||
6403         ParseInt32Flag(arg, kRepeatFlag, &GTEST_FLAG(repeat)) ||
6404         ParseBoolFlag(arg, kShuffleFlag, &GTEST_FLAG(shuffle)) ||
6405         ParseInt32Flag(arg, kStackTraceDepthFlag,
6406                        &GTEST_FLAG(stack_trace_depth)) ||
6407         ParseStringFlag(arg, kStreamResultToFlag,
6408                         &GTEST_FLAG(stream_result_to)) ||
6409         ParseBoolFlag(arg, kThrowOnFailureFlag,
6410                       &GTEST_FLAG(throw_on_failure))
6411         ) {
6412       // Yes.  Shift the remainder of the argv list left by one.  Note
6413       // that argv has (*argc + 1) elements, the last one always being
6414       // NULL.  The following loop moves the trailing NULL element as
6415       // well.
6416       for (int j = i; j != *argc; j++) {
6417         argv[j] = argv[j + 1];
6418       }
6419 
6420       // Decrements the argument count.
6421       (*argc)--;
6422 
6423       // We also need to decrement the iterator as we just removed
6424       // an element.
6425       i--;
6426     } else if (arg_string == "--help" || arg_string == "-h" ||
6427                arg_string == "-?" || arg_string == "/?" ||
6428                HasGoogleTestFlagPrefix(arg)) {
6429       // Both help flag and unrecognized Google Test flags (excluding
6430       // internal ones) trigger help display.
6431       g_help_flag = true;
6432     }
6433   }
6434 
6435   if (g_help_flag) {
6436     // We print the help here instead of in RUN_ALL_TESTS(), as the
6437     // latter may not be called at all if the user is using Google
6438     // Test with another testing framework.
6439     PrintColorEncoded(kColorEncodedHelpMessage);
6440   }
6441 }
6442 
6443 // Parses the command line for Google Test flags, without initializing
6444 // other parts of Google Test.
ParseGoogleTestFlagsOnly(int * argc,char ** argv)6445 void ParseGoogleTestFlagsOnly(int* argc, char** argv) {
6446   ParseGoogleTestFlagsOnlyImpl(argc, argv);
6447 }
ParseGoogleTestFlagsOnly(int * argc,wchar_t ** argv)6448 void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv) {
6449   ParseGoogleTestFlagsOnlyImpl(argc, argv);
6450 }
6451 
6452 // The internal implementation of InitGoogleTest().
6453 //
6454 // The type parameter CharType can be instantiated to either char or
6455 // wchar_t.
6456 template <typename CharType>
InitGoogleTestImpl(int * argc,CharType ** argv)6457 void InitGoogleTestImpl(int* argc, CharType** argv) {
6458   g_init_gtest_count++;
6459 
6460   // We don't want to run the initialization code twice.
6461   if (g_init_gtest_count != 1) return;
6462 
6463   if (*argc <= 0) return;
6464 
6465   internal::g_executable_path = internal::StreamableToString(argv[0]);
6466 
6467 #if GTEST_HAS_DEATH_TEST
6468 
6469   g_argvs.clear();
6470   for (int i = 0; i != *argc; i++) {
6471     g_argvs.push_back(StreamableToString(argv[i]));
6472   }
6473 
6474 #endif  // GTEST_HAS_DEATH_TEST
6475 
6476   ParseGoogleTestFlagsOnly(argc, argv);
6477   GetUnitTestImpl()->PostFlagParsingInit();
6478 }
6479 
6480 }  // namespace internal
6481 
6482 // Initializes Google Test.  This must be called before calling
6483 // RUN_ALL_TESTS().  In particular, it parses a command line for the
6484 // flags that Google Test recognizes.  Whenever a Google Test flag is
6485 // seen, it is removed from argv, and *argc is decremented.
6486 //
6487 // No value is returned.  Instead, the Google Test flag variables are
6488 // updated.
6489 //
6490 // Calling the function for the second time has no user-visible effect.
InitGoogleTest(int * argc,char ** argv)6491 void InitGoogleTest(int* argc, char** argv) {
6492   internal::InitGoogleTestImpl(argc, argv);
6493 }
6494 
6495 // This overloaded version can be used in Windows programs compiled in
6496 // UNICODE mode.
InitGoogleTest(int * argc,wchar_t ** argv)6497 void InitGoogleTest(int* argc, wchar_t** argv) {
6498   internal::InitGoogleTestImpl(argc, argv);
6499 }
6500 
6501 }  // namespace testing
6502 // Copyright 2005, Google Inc.
6503 // All rights reserved.
6504 //
6505 // Redistribution and use in source and binary forms, with or without
6506 // modification, are permitted provided that the following conditions are
6507 // met:
6508 //
6509 //     * Redistributions of source code must retain the above copyright
6510 // notice, this list of conditions and the following disclaimer.
6511 //     * Redistributions in binary form must reproduce the above
6512 // copyright notice, this list of conditions and the following disclaimer
6513 // in the documentation and/or other materials provided with the
6514 // distribution.
6515 //     * Neither the name of Google Inc. nor the names of its
6516 // contributors may be used to endorse or promote products derived from
6517 // this software without specific prior written permission.
6518 //
6519 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
6520 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
6521 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
6522 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
6523 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
6524 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
6525 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
6526 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
6527 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
6528 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
6529 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
6530 //
6531 // Author: wan@google.com (Zhanyong Wan), vladl@google.com (Vlad Losev)
6532 //
6533 // This file implements death tests.
6534 
6535 
6536 #if GTEST_HAS_DEATH_TEST
6537 
6538 # if GTEST_OS_MAC
6539 #  include <crt_externs.h>
6540 # endif  // GTEST_OS_MAC
6541 
6542 # include <errno.h>
6543 # include <fcntl.h>
6544 # include <limits.h>
6545 
6546 # if GTEST_OS_LINUX
6547 #  include <signal.h>
6548 # endif  // GTEST_OS_LINUX
6549 
6550 # include <stdarg.h>
6551 
6552 # if GTEST_OS_WINDOWS
6553 #  include <windows.h>
6554 # else
6555 #  include <sys/mman.h>
6556 #  include <sys/wait.h>
6557 # endif  // GTEST_OS_WINDOWS
6558 
6559 # if GTEST_OS_QNX
6560 #  include <spawn.h>
6561 # endif  // GTEST_OS_QNX
6562 
6563 #endif  // GTEST_HAS_DEATH_TEST
6564 
6565 
6566 // Indicates that this translation unit is part of Google Test's
6567 // implementation.  It must come before gtest-internal-inl.h is
6568 // included, or there will be a compiler error.  This trick is to
6569 // prevent a user from accidentally including gtest-internal-inl.h in
6570 // his code.
6571 #define GTEST_IMPLEMENTATION_ 1
6572 #undef GTEST_IMPLEMENTATION_
6573 
6574 namespace testing {
6575 
6576 // Constants.
6577 
6578 // The default death test style.
6579 static const char kDefaultDeathTestStyle[] = "fast";
6580 
6581 GTEST_DEFINE_string_(
6582     death_test_style,
6583     internal::StringFromGTestEnv("death_test_style", kDefaultDeathTestStyle),
6584     "Indicates how to run a death test in a forked child process: "
6585     "\"threadsafe\" (child process re-executes the test binary "
6586     "from the beginning, running only the specific death test) or "
6587     "\"fast\" (child process runs the death test immediately "
6588     "after forking).");
6589 
6590 GTEST_DEFINE_bool_(
6591     death_test_use_fork,
6592     internal::BoolFromGTestEnv("death_test_use_fork", false),
6593     "Instructs to use fork()/_exit() instead of clone() in death tests. "
6594     "Ignored and always uses fork() on POSIX systems where clone() is not "
6595     "implemented. Useful when running under valgrind or similar tools if "
6596     "those do not support clone(). Valgrind 3.3.1 will just fail if "
6597     "it sees an unsupported combination of clone() flags. "
6598     "It is not recommended to use this flag w/o valgrind though it will "
6599     "work in 99% of the cases. Once valgrind is fixed, this flag will "
6600     "most likely be removed.");
6601 
6602 namespace internal {
6603 GTEST_DEFINE_string_(
6604     internal_run_death_test, "",
6605     "Indicates the file, line number, temporal index of "
6606     "the single death test to run, and a file descriptor to "
6607     "which a success code may be sent, all separated by "
6608     "the '|' characters.  This flag is specified if and only if the current "
6609     "process is a sub-process launched for running a thread-safe "
6610     "death test.  FOR INTERNAL USE ONLY.");
6611 }  // namespace internal
6612 
6613 #if GTEST_HAS_DEATH_TEST
6614 
6615 namespace internal {
6616 
6617 // Valid only for fast death tests. Indicates the code is running in the
6618 // child process of a fast style death test.
6619 static bool g_in_fast_death_test_child = false;
6620 
6621 // Returns a Boolean value indicating whether the caller is currently
6622 // executing in the context of the death test child process.  Tools such as
6623 // Valgrind heap checkers may need this to modify their behavior in death
6624 // tests.  IMPORTANT: This is an internal utility.  Using it may break the
6625 // implementation of death tests.  User code MUST NOT use it.
InDeathTestChild()6626 bool InDeathTestChild() {
6627 # if GTEST_OS_WINDOWS
6628 
6629   // On Windows, death tests are thread-safe regardless of the value of the
6630   // death_test_style flag.
6631   return !GTEST_FLAG(internal_run_death_test).empty();
6632 
6633 # else
6634 
6635   if (GTEST_FLAG(death_test_style) == "threadsafe")
6636     return !GTEST_FLAG(internal_run_death_test).empty();
6637   else
6638     return g_in_fast_death_test_child;
6639 #endif
6640 }
6641 
6642 }  // namespace internal
6643 
6644 // ExitedWithCode constructor.
ExitedWithCode(int exit_code)6645 ExitedWithCode::ExitedWithCode(int exit_code) : exit_code_(exit_code) {
6646 }
6647 
6648 // ExitedWithCode function-call operator.
operator ()(int exit_status) const6649 bool ExitedWithCode::operator()(int exit_status) const {
6650 # if GTEST_OS_WINDOWS
6651 
6652   return exit_status == exit_code_;
6653 
6654 # else
6655 
6656   return WIFEXITED(exit_status) && WEXITSTATUS(exit_status) == exit_code_;
6657 
6658 # endif  // GTEST_OS_WINDOWS
6659 }
6660 
6661 # if !GTEST_OS_WINDOWS
6662 // KilledBySignal constructor.
KilledBySignal(int signum)6663 KilledBySignal::KilledBySignal(int signum) : signum_(signum) {
6664 }
6665 
6666 // KilledBySignal function-call operator.
operator ()(int exit_status) const6667 bool KilledBySignal::operator()(int exit_status) const {
6668   return WIFSIGNALED(exit_status) && WTERMSIG(exit_status) == signum_;
6669 }
6670 # endif  // !GTEST_OS_WINDOWS
6671 
6672 namespace internal {
6673 
6674 // Utilities needed for death tests.
6675 
6676 // Generates a textual description of a given exit code, in the format
6677 // specified by wait(2).
ExitSummary(int exit_code)6678 static std::string ExitSummary(int exit_code) {
6679   Message m;
6680 
6681 # if GTEST_OS_WINDOWS
6682 
6683   m << "Exited with exit status " << exit_code;
6684 
6685 # else
6686 
6687   if (WIFEXITED(exit_code)) {
6688     m << "Exited with exit status " << WEXITSTATUS(exit_code);
6689   } else if (WIFSIGNALED(exit_code)) {
6690     m << "Terminated by signal " << WTERMSIG(exit_code);
6691   }
6692 #  ifdef WCOREDUMP
6693   if (WCOREDUMP(exit_code)) {
6694     m << " (core dumped)";
6695   }
6696 #  endif
6697 # endif  // GTEST_OS_WINDOWS
6698 
6699   return m.GetString();
6700 }
6701 
6702 // Returns true if exit_status describes a process that was terminated
6703 // by a signal, or exited normally with a nonzero exit code.
ExitedUnsuccessfully(int exit_status)6704 bool ExitedUnsuccessfully(int exit_status) {
6705   return !ExitedWithCode(0)(exit_status);
6706 }
6707 
6708 # if !GTEST_OS_WINDOWS
6709 // Generates a textual failure message when a death test finds more than
6710 // one thread running, or cannot determine the number of threads, prior
6711 // to executing the given statement.  It is the responsibility of the
6712 // caller not to pass a thread_count of 1.
DeathTestThreadWarning(size_t thread_count)6713 static std::string DeathTestThreadWarning(size_t thread_count) {
6714   Message msg;
6715   msg << "Death tests use fork(), which is unsafe particularly"
6716       << " in a threaded context. For this test, " << GTEST_NAME_ << " ";
6717   if (thread_count == 0)
6718     msg << "couldn't detect the number of threads.";
6719   else
6720     msg << "detected " << thread_count << " threads.";
6721   return msg.GetString();
6722 }
6723 # endif  // !GTEST_OS_WINDOWS
6724 
6725 // Flag characters for reporting a death test that did not die.
6726 static const char kDeathTestLived = 'L';
6727 static const char kDeathTestReturned = 'R';
6728 static const char kDeathTestThrew = 'T';
6729 static const char kDeathTestInternalError = 'I';
6730 
6731 // An enumeration describing all of the possible ways that a death test can
6732 // conclude.  DIED means that the process died while executing the test
6733 // code; LIVED means that process lived beyond the end of the test code;
6734 // RETURNED means that the test statement attempted to execute a return
6735 // statement, which is not allowed; THREW means that the test statement
6736 // returned control by throwing an exception.  IN_PROGRESS means the test
6737 // has not yet concluded.
6738 // TODO(vladl@google.com): Unify names and possibly values for
6739 // AbortReason, DeathTestOutcome, and flag characters above.
6740 enum DeathTestOutcome { IN_PROGRESS, DIED, LIVED, RETURNED, THREW };
6741 
6742 // Routine for aborting the program which is safe to call from an
6743 // exec-style death test child process, in which case the error
6744 // message is propagated back to the parent process.  Otherwise, the
6745 // message is simply printed to stderr.  In either case, the program
6746 // then exits with status 1.
DeathTestAbort(const std::string & message)6747 void DeathTestAbort(const std::string& message) {
6748   // On a POSIX system, this function may be called from a threadsafe-style
6749   // death test child process, which operates on a very small stack.  Use
6750   // the heap for any additional non-minuscule memory requirements.
6751   const InternalRunDeathTestFlag* const flag =
6752       GetUnitTestImpl()->internal_run_death_test_flag();
6753   if (flag != NULL) {
6754     FILE* parent = posix::FDOpen(flag->write_fd(), "w");
6755     fputc(kDeathTestInternalError, parent);
6756     fprintf(parent, "%s", message.c_str());
6757     fflush(parent);
6758     _exit(1);
6759   } else {
6760     fprintf(stderr, "%s", message.c_str());
6761     fflush(stderr);
6762     posix::Abort();
6763   }
6764 }
6765 
6766 // A replacement for CHECK that calls DeathTestAbort if the assertion
6767 // fails.
6768 # define GTEST_DEATH_TEST_CHECK_(expression) \
6769   do { \
6770     if (!::testing::internal::IsTrue(expression)) { \
6771       DeathTestAbort( \
6772           ::std::string("CHECK failed: File ") + __FILE__ +  ", line " \
6773           + ::testing::internal::StreamableToString(__LINE__) + ": " \
6774           + #expression); \
6775     } \
6776   } while (::testing::internal::AlwaysFalse())
6777 
6778 // This macro is similar to GTEST_DEATH_TEST_CHECK_, but it is meant for
6779 // evaluating any system call that fulfills two conditions: it must return
6780 // -1 on failure, and set errno to EINTR when it is interrupted and
6781 // should be tried again.  The macro expands to a loop that repeatedly
6782 // evaluates the expression as long as it evaluates to -1 and sets
6783 // errno to EINTR.  If the expression evaluates to -1 but errno is
6784 // something other than EINTR, DeathTestAbort is called.
6785 # define GTEST_DEATH_TEST_CHECK_SYSCALL_(expression) \
6786   do { \
6787     int gtest_retval; \
6788     do { \
6789       gtest_retval = (expression); \
6790     } while (gtest_retval == -1 && errno == EINTR); \
6791     if (gtest_retval == -1) { \
6792       DeathTestAbort( \
6793           ::std::string("CHECK failed: File ") + __FILE__ + ", line " \
6794           + ::testing::internal::StreamableToString(__LINE__) + ": " \
6795           + #expression + " != -1"); \
6796     } \
6797   } while (::testing::internal::AlwaysFalse())
6798 
6799 // Returns the message describing the last system error in errno.
GetLastErrnoDescription()6800 std::string GetLastErrnoDescription() {
6801     return errno == 0 ? "" : posix::StrError(errno);
6802 }
6803 
6804 // This is called from a death test parent process to read a failure
6805 // message from the death test child process and log it with the FATAL
6806 // severity. On Windows, the message is read from a pipe handle. On other
6807 // platforms, it is read from a file descriptor.
FailFromInternalError(int fd)6808 static void FailFromInternalError(int fd) {
6809   Message error;
6810   char buffer[256];
6811   int num_read;
6812 
6813   do {
6814     while ((num_read = posix::Read(fd, buffer, 255)) > 0) {
6815       buffer[num_read] = '\0';
6816       error << buffer;
6817     }
6818   } while (num_read == -1 && errno == EINTR);
6819 
6820   if (num_read == 0) {
6821     GTEST_LOG_(FATAL) << error.GetString();
6822   } else {
6823     const int last_error = errno;
6824     GTEST_LOG_(FATAL) << "Error while reading death test internal: "
6825                       << GetLastErrnoDescription() << " [" << last_error << "]";
6826   }
6827 }
6828 
6829 // Death test constructor.  Increments the running death test count
6830 // for the current test.
DeathTest()6831 DeathTest::DeathTest() {
6832   TestInfo* const info = GetUnitTestImpl()->current_test_info();
6833   if (info == NULL) {
6834     DeathTestAbort("Cannot run a death test outside of a TEST or "
6835                    "TEST_F construct");
6836   }
6837 }
6838 
6839 // Creates and returns a death test by dispatching to the current
6840 // death test factory.
Create(const char * statement,const RE * regex,const char * file,int line,DeathTest ** test)6841 bool DeathTest::Create(const char* statement, const RE* regex,
6842                        const char* file, int line, DeathTest** test) {
6843   return GetUnitTestImpl()->death_test_factory()->Create(
6844       statement, regex, file, line, test);
6845 }
6846 
LastMessage()6847 const char* DeathTest::LastMessage() {
6848   return last_death_test_message_.c_str();
6849 }
6850 
set_last_death_test_message(const std::string & message)6851 void DeathTest::set_last_death_test_message(const std::string& message) {
6852   last_death_test_message_ = message;
6853 }
6854 
6855 std::string DeathTest::last_death_test_message_;
6856 
6857 // Provides cross platform implementation for some death functionality.
6858 class DeathTestImpl : public DeathTest {
6859  protected:
DeathTestImpl(const char * a_statement,const RE * a_regex)6860   DeathTestImpl(const char* a_statement, const RE* a_regex)
6861       : statement_(a_statement),
6862         regex_(a_regex),
6863         spawned_(false),
6864         status_(-1),
6865         outcome_(IN_PROGRESS),
6866         read_fd_(-1),
6867         write_fd_(-1) {}
6868 
6869   // read_fd_ is expected to be closed and cleared by a derived class.
~DeathTestImpl()6870   ~DeathTestImpl() { GTEST_DEATH_TEST_CHECK_(read_fd_ == -1); }
6871 
6872   void Abort(AbortReason reason);
6873   virtual bool Passed(bool status_ok);
6874 
statement() const6875   const char* statement() const { return statement_; }
regex() const6876   const RE* regex() const { return regex_; }
spawned() const6877   bool spawned() const { return spawned_; }
set_spawned(bool is_spawned)6878   void set_spawned(bool is_spawned) { spawned_ = is_spawned; }
status() const6879   int status() const { return status_; }
set_status(int a_status)6880   void set_status(int a_status) { status_ = a_status; }
outcome() const6881   DeathTestOutcome outcome() const { return outcome_; }
set_outcome(DeathTestOutcome an_outcome)6882   void set_outcome(DeathTestOutcome an_outcome) { outcome_ = an_outcome; }
read_fd() const6883   int read_fd() const { return read_fd_; }
set_read_fd(int fd)6884   void set_read_fd(int fd) { read_fd_ = fd; }
write_fd() const6885   int write_fd() const { return write_fd_; }
set_write_fd(int fd)6886   void set_write_fd(int fd) { write_fd_ = fd; }
6887 
6888   // Called in the parent process only. Reads the result code of the death
6889   // test child process via a pipe, interprets it to set the outcome_
6890   // member, and closes read_fd_.  Outputs diagnostics and terminates in
6891   // case of unexpected codes.
6892   void ReadAndInterpretStatusByte();
6893 
6894  private:
6895   // The textual content of the code this object is testing.  This class
6896   // doesn't own this string and should not attempt to delete it.
6897   const char* const statement_;
6898   // The regular expression which test output must match.  DeathTestImpl
6899   // doesn't own this object and should not attempt to delete it.
6900   const RE* const regex_;
6901   // True if the death test child process has been successfully spawned.
6902   bool spawned_;
6903   // The exit status of the child process.
6904   int status_;
6905   // How the death test concluded.
6906   DeathTestOutcome outcome_;
6907   // Descriptor to the read end of the pipe to the child process.  It is
6908   // always -1 in the child process.  The child keeps its write end of the
6909   // pipe in write_fd_.
6910   int read_fd_;
6911   // Descriptor to the child's write end of the pipe to the parent process.
6912   // It is always -1 in the parent process.  The parent keeps its end of the
6913   // pipe in read_fd_.
6914   int write_fd_;
6915 };
6916 
6917 // Called in the parent process only. Reads the result code of the death
6918 // test child process via a pipe, interprets it to set the outcome_
6919 // member, and closes read_fd_.  Outputs diagnostics and terminates in
6920 // case of unexpected codes.
ReadAndInterpretStatusByte()6921 void DeathTestImpl::ReadAndInterpretStatusByte() {
6922   char flag;
6923   int bytes_read;
6924 
6925   // The read() here blocks until data is available (signifying the
6926   // failure of the death test) or until the pipe is closed (signifying
6927   // its success), so it's okay to call this in the parent before
6928   // the child process has exited.
6929   do {
6930     bytes_read = posix::Read(read_fd(), &flag, 1);
6931   } while (bytes_read == -1 && errno == EINTR);
6932 
6933   if (bytes_read == 0) {
6934     set_outcome(DIED);
6935   } else if (bytes_read == 1) {
6936     switch (flag) {
6937       case kDeathTestReturned:
6938         set_outcome(RETURNED);
6939         break;
6940       case kDeathTestThrew:
6941         set_outcome(THREW);
6942         break;
6943       case kDeathTestLived:
6944         set_outcome(LIVED);
6945         break;
6946       case kDeathTestInternalError:
6947         FailFromInternalError(read_fd());  // Does not return.
6948         break;
6949       default:
6950         GTEST_LOG_(FATAL) << "Death test child process reported "
6951                           << "unexpected status byte ("
6952                           << static_cast<unsigned int>(flag) << ")";
6953     }
6954   } else {
6955     GTEST_LOG_(FATAL) << "Read from death test child process failed: "
6956                       << GetLastErrnoDescription();
6957   }
6958   GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Close(read_fd()));
6959   set_read_fd(-1);
6960 }
6961 
6962 // Signals that the death test code which should have exited, didn't.
6963 // Should be called only in a death test child process.
6964 // Writes a status byte to the child's status file descriptor, then
6965 // calls _exit(1).
Abort(AbortReason reason)6966 void DeathTestImpl::Abort(AbortReason reason) {
6967   // The parent process considers the death test to be a failure if
6968   // it finds any data in our pipe.  So, here we write a single flag byte
6969   // to the pipe, then exit.
6970   const char status_ch =
6971       reason == TEST_DID_NOT_DIE ? kDeathTestLived :
6972       reason == TEST_THREW_EXCEPTION ? kDeathTestThrew : kDeathTestReturned;
6973 
6974   GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Write(write_fd(), &status_ch, 1));
6975   // We are leaking the descriptor here because on some platforms (i.e.,
6976   // when built as Windows DLL), destructors of global objects will still
6977   // run after calling _exit(). On such systems, write_fd_ will be
6978   // indirectly closed from the destructor of UnitTestImpl, causing double
6979   // close if it is also closed here. On debug configurations, double close
6980   // may assert. As there are no in-process buffers to flush here, we are
6981   // relying on the OS to close the descriptor after the process terminates
6982   // when the destructors are not run.
6983   _exit(1);  // Exits w/o any normal exit hooks (we were supposed to crash)
6984 }
6985 
6986 // Returns an indented copy of stderr output for a death test.
6987 // This makes distinguishing death test output lines from regular log lines
6988 // much easier.
FormatDeathTestOutput(const::std::string & output)6989 static ::std::string FormatDeathTestOutput(const ::std::string& output) {
6990   ::std::string ret;
6991   for (size_t at = 0; ; ) {
6992     const size_t line_end = output.find('\n', at);
6993     ret += "[  DEATH   ] ";
6994     if (line_end == ::std::string::npos) {
6995       ret += output.substr(at);
6996       break;
6997     }
6998     ret += output.substr(at, line_end + 1 - at);
6999     at = line_end + 1;
7000   }
7001   return ret;
7002 }
7003 
7004 // Assesses the success or failure of a death test, using both private
7005 // members which have previously been set, and one argument:
7006 //
7007 // Private data members:
7008 //   outcome:  An enumeration describing how the death test
7009 //             concluded: DIED, LIVED, THREW, or RETURNED.  The death test
7010 //             fails in the latter three cases.
7011 //   status:   The exit status of the child process. On *nix, it is in the
7012 //             in the format specified by wait(2). On Windows, this is the
7013 //             value supplied to the ExitProcess() API or a numeric code
7014 //             of the exception that terminated the program.
7015 //   regex:    A regular expression object to be applied to
7016 //             the test's captured standard error output; the death test
7017 //             fails if it does not match.
7018 //
7019 // Argument:
7020 //   status_ok: true if exit_status is acceptable in the context of
7021 //              this particular death test, which fails if it is false
7022 //
7023 // Returns true iff all of the above conditions are met.  Otherwise, the
7024 // first failing condition, in the order given above, is the one that is
7025 // reported. Also sets the last death test message string.
Passed(bool status_ok)7026 bool DeathTestImpl::Passed(bool status_ok) {
7027   if (!spawned())
7028     return false;
7029 
7030   const std::string error_message = GetCapturedStderr();
7031 
7032   bool success = false;
7033   Message buffer;
7034 
7035   buffer << "Death test: " << statement() << "\n";
7036   switch (outcome()) {
7037     case LIVED:
7038       buffer << "    Result: failed to die.\n"
7039              << " Error msg:\n" << FormatDeathTestOutput(error_message);
7040       break;
7041     case THREW:
7042       buffer << "    Result: threw an exception.\n"
7043              << " Error msg:\n" << FormatDeathTestOutput(error_message);
7044       break;
7045     case RETURNED:
7046       buffer << "    Result: illegal return in test statement.\n"
7047              << " Error msg:\n" << FormatDeathTestOutput(error_message);
7048       break;
7049     case DIED:
7050       if (status_ok) {
7051         const bool matched = RE::PartialMatch(error_message.c_str(), *regex());
7052         if (matched) {
7053           success = true;
7054         } else {
7055           buffer << "    Result: died but not with expected error.\n"
7056                  << "  Expected: " << regex()->pattern() << "\n"
7057                  << "Actual msg:\n" << FormatDeathTestOutput(error_message);
7058         }
7059       } else {
7060         buffer << "    Result: died but not with expected exit code:\n"
7061                << "            " << ExitSummary(status()) << "\n"
7062                << "Actual msg:\n" << FormatDeathTestOutput(error_message);
7063       }
7064       break;
7065     case IN_PROGRESS:
7066     default:
7067       GTEST_LOG_(FATAL)
7068           << "DeathTest::Passed somehow called before conclusion of test";
7069   }
7070 
7071   DeathTest::set_last_death_test_message(buffer.GetString());
7072   return success;
7073 }
7074 
7075 # if GTEST_OS_WINDOWS
7076 // WindowsDeathTest implements death tests on Windows. Due to the
7077 // specifics of starting new processes on Windows, death tests there are
7078 // always threadsafe, and Google Test considers the
7079 // --gtest_death_test_style=fast setting to be equivalent to
7080 // --gtest_death_test_style=threadsafe there.
7081 //
7082 // A few implementation notes:  Like the Linux version, the Windows
7083 // implementation uses pipes for child-to-parent communication. But due to
7084 // the specifics of pipes on Windows, some extra steps are required:
7085 //
7086 // 1. The parent creates a communication pipe and stores handles to both
7087 //    ends of it.
7088 // 2. The parent starts the child and provides it with the information
7089 //    necessary to acquire the handle to the write end of the pipe.
7090 // 3. The child acquires the write end of the pipe and signals the parent
7091 //    using a Windows event.
7092 // 4. Now the parent can release the write end of the pipe on its side. If
7093 //    this is done before step 3, the object's reference count goes down to
7094 //    0 and it is destroyed, preventing the child from acquiring it. The
7095 //    parent now has to release it, or read operations on the read end of
7096 //    the pipe will not return when the child terminates.
7097 // 5. The parent reads child's output through the pipe (outcome code and
7098 //    any possible error messages) from the pipe, and its stderr and then
7099 //    determines whether to fail the test.
7100 //
7101 // Note: to distinguish Win32 API calls from the local method and function
7102 // calls, the former are explicitly resolved in the global namespace.
7103 //
7104 class WindowsDeathTest : public DeathTestImpl {
7105  public:
WindowsDeathTest(const char * a_statement,const RE * a_regex,const char * file,int line)7106   WindowsDeathTest(const char* a_statement,
7107                    const RE* a_regex,
7108                    const char* file,
7109                    int line)
7110       : DeathTestImpl(a_statement, a_regex), file_(file), line_(line) {}
7111 
7112   // All of these virtual functions are inherited from DeathTest.
7113   virtual int Wait();
7114   virtual TestRole AssumeRole();
7115 
7116  private:
7117   // The name of the file in which the death test is located.
7118   const char* const file_;
7119   // The line number on which the death test is located.
7120   const int line_;
7121   // Handle to the write end of the pipe to the child process.
7122   AutoHandle write_handle_;
7123   // Child process handle.
7124   AutoHandle child_handle_;
7125   // Event the child process uses to signal the parent that it has
7126   // acquired the handle to the write end of the pipe. After seeing this
7127   // event the parent can release its own handles to make sure its
7128   // ReadFile() calls return when the child terminates.
7129   AutoHandle event_handle_;
7130 };
7131 
7132 // Waits for the child in a death test to exit, returning its exit
7133 // status, or 0 if no child process exists.  As a side effect, sets the
7134 // outcome data member.
Wait()7135 int WindowsDeathTest::Wait() {
7136   if (!spawned())
7137     return 0;
7138 
7139   // Wait until the child either signals that it has acquired the write end
7140   // of the pipe or it dies.
7141   const HANDLE wait_handles[2] = { child_handle_.Get(), event_handle_.Get() };
7142   switch (::WaitForMultipleObjects(2,
7143                                    wait_handles,
7144                                    FALSE,  // Waits for any of the handles.
7145                                    INFINITE)) {
7146     case WAIT_OBJECT_0:
7147     case WAIT_OBJECT_0 + 1:
7148       break;
7149     default:
7150       GTEST_DEATH_TEST_CHECK_(false);  // Should not get here.
7151   }
7152 
7153   // The child has acquired the write end of the pipe or exited.
7154   // We release the handle on our side and continue.
7155   write_handle_.Reset();
7156   event_handle_.Reset();
7157 
7158   ReadAndInterpretStatusByte();
7159 
7160   // Waits for the child process to exit if it haven't already. This
7161   // returns immediately if the child has already exited, regardless of
7162   // whether previous calls to WaitForMultipleObjects synchronized on this
7163   // handle or not.
7164   GTEST_DEATH_TEST_CHECK_(
7165       WAIT_OBJECT_0 == ::WaitForSingleObject(child_handle_.Get(),
7166                                              INFINITE));
7167   DWORD status_code;
7168   GTEST_DEATH_TEST_CHECK_(
7169       ::GetExitCodeProcess(child_handle_.Get(), &status_code) != FALSE);
7170   child_handle_.Reset();
7171   set_status(static_cast<int>(status_code));
7172   return status();
7173 }
7174 
7175 // The AssumeRole process for a Windows death test.  It creates a child
7176 // process with the same executable as the current process to run the
7177 // death test.  The child process is given the --gtest_filter and
7178 // --gtest_internal_run_death_test flags such that it knows to run the
7179 // current death test only.
AssumeRole()7180 DeathTest::TestRole WindowsDeathTest::AssumeRole() {
7181   const UnitTestImpl* const impl = GetUnitTestImpl();
7182   const InternalRunDeathTestFlag* const flag =
7183       impl->internal_run_death_test_flag();
7184   const TestInfo* const info = impl->current_test_info();
7185   const int death_test_index = info->result()->death_test_count();
7186 
7187   if (flag != NULL) {
7188     // ParseInternalRunDeathTestFlag() has performed all the necessary
7189     // processing.
7190     set_write_fd(flag->write_fd());
7191     return EXECUTE_TEST;
7192   }
7193 
7194   // WindowsDeathTest uses an anonymous pipe to communicate results of
7195   // a death test.
7196   SECURITY_ATTRIBUTES handles_are_inheritable = {
7197     sizeof(SECURITY_ATTRIBUTES), NULL, TRUE };
7198   HANDLE read_handle, write_handle;
7199   GTEST_DEATH_TEST_CHECK_(
7200       ::CreatePipe(&read_handle, &write_handle, &handles_are_inheritable,
7201                    0)  // Default buffer size.
7202       != FALSE);
7203   set_read_fd(::_open_osfhandle(reinterpret_cast<intptr_t>(read_handle),
7204                                 O_RDONLY));
7205   write_handle_.Reset(write_handle);
7206   event_handle_.Reset(::CreateEvent(
7207       &handles_are_inheritable,
7208       TRUE,    // The event will automatically reset to non-signaled state.
7209       FALSE,   // The initial state is non-signalled.
7210       NULL));  // The even is unnamed.
7211   GTEST_DEATH_TEST_CHECK_(event_handle_.Get() != NULL);
7212   const std::string filter_flag =
7213       std::string("--") + GTEST_FLAG_PREFIX_ + kFilterFlag + "=" +
7214       info->test_case_name() + "." + info->name();
7215   const std::string internal_flag =
7216       std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag +
7217       "=" + file_ + "|" + StreamableToString(line_) + "|" +
7218       StreamableToString(death_test_index) + "|" +
7219       StreamableToString(static_cast<unsigned int>(::GetCurrentProcessId())) +
7220       // size_t has the same width as pointers on both 32-bit and 64-bit
7221       // Windows platforms.
7222       // See http://msdn.microsoft.com/en-us/library/tcxf1dw6.aspx.
7223       "|" + StreamableToString(reinterpret_cast<size_t>(write_handle)) +
7224       "|" + StreamableToString(reinterpret_cast<size_t>(event_handle_.Get()));
7225 
7226   char executable_path[_MAX_PATH + 1];  // NOLINT
7227   GTEST_DEATH_TEST_CHECK_(
7228       _MAX_PATH + 1 != ::GetModuleFileNameA(NULL,
7229                                             executable_path,
7230                                             _MAX_PATH));
7231 
7232   std::string command_line =
7233       std::string(::GetCommandLineA()) + " " + filter_flag + " \"" +
7234       internal_flag + "\"";
7235 
7236   DeathTest::set_last_death_test_message("");
7237 
7238   CaptureStderr();
7239   // Flush the log buffers since the log streams are shared with the child.
7240   FlushInfoLog();
7241 
7242   // The child process will share the standard handles with the parent.
7243   STARTUPINFOA startup_info;
7244   memset(&startup_info, 0, sizeof(STARTUPINFO));
7245   startup_info.dwFlags = STARTF_USESTDHANDLES;
7246   startup_info.hStdInput = ::GetStdHandle(STD_INPUT_HANDLE);
7247   startup_info.hStdOutput = ::GetStdHandle(STD_OUTPUT_HANDLE);
7248   startup_info.hStdError = ::GetStdHandle(STD_ERROR_HANDLE);
7249 
7250   PROCESS_INFORMATION process_info;
7251   GTEST_DEATH_TEST_CHECK_(::CreateProcessA(
7252       executable_path,
7253       const_cast<char*>(command_line.c_str()),
7254       NULL,   // Retuned process handle is not inheritable.
7255       NULL,   // Retuned thread handle is not inheritable.
7256       TRUE,   // Child inherits all inheritable handles (for write_handle_).
7257       0x0,    // Default creation flags.
7258       NULL,   // Inherit the parent's environment.
7259       UnitTest::GetInstance()->original_working_dir(),
7260       &startup_info,
7261       &process_info) != FALSE);
7262   child_handle_.Reset(process_info.hProcess);
7263   ::CloseHandle(process_info.hThread);
7264   set_spawned(true);
7265   return OVERSEE_TEST;
7266 }
7267 # else  // We are not on Windows.
7268 
7269 // ForkingDeathTest provides implementations for most of the abstract
7270 // methods of the DeathTest interface.  Only the AssumeRole method is
7271 // left undefined.
7272 class ForkingDeathTest : public DeathTestImpl {
7273  public:
7274   ForkingDeathTest(const char* statement, const RE* regex);
7275 
7276   // All of these virtual functions are inherited from DeathTest.
7277   virtual int Wait();
7278 
7279  protected:
set_child_pid(pid_t child_pid)7280   void set_child_pid(pid_t child_pid) { child_pid_ = child_pid; }
7281 
7282  private:
7283   // PID of child process during death test; 0 in the child process itself.
7284   pid_t child_pid_;
7285 };
7286 
7287 // Constructs a ForkingDeathTest.
ForkingDeathTest(const char * a_statement,const RE * a_regex)7288 ForkingDeathTest::ForkingDeathTest(const char* a_statement, const RE* a_regex)
7289     : DeathTestImpl(a_statement, a_regex),
7290       child_pid_(-1) {}
7291 
7292 // Waits for the child in a death test to exit, returning its exit
7293 // status, or 0 if no child process exists.  As a side effect, sets the
7294 // outcome data member.
Wait()7295 int ForkingDeathTest::Wait() {
7296   if (!spawned())
7297     return 0;
7298 
7299   ReadAndInterpretStatusByte();
7300 
7301   int status_value;
7302   GTEST_DEATH_TEST_CHECK_SYSCALL_(waitpid(child_pid_, &status_value, 0));
7303   set_status(status_value);
7304   return status_value;
7305 }
7306 
7307 // A concrete death test class that forks, then immediately runs the test
7308 // in the child process.
7309 class NoExecDeathTest : public ForkingDeathTest {
7310  public:
NoExecDeathTest(const char * a_statement,const RE * a_regex)7311   NoExecDeathTest(const char* a_statement, const RE* a_regex) :
7312       ForkingDeathTest(a_statement, a_regex) { }
7313   virtual TestRole AssumeRole();
7314 };
7315 
7316 // The AssumeRole process for a fork-and-run death test.  It implements a
7317 // straightforward fork, with a simple pipe to transmit the status byte.
AssumeRole()7318 DeathTest::TestRole NoExecDeathTest::AssumeRole() {
7319   const size_t thread_count = GetThreadCount();
7320   if (thread_count != 1) {
7321     GTEST_LOG_(WARNING) << DeathTestThreadWarning(thread_count);
7322   }
7323 
7324   int pipe_fd[2];
7325   GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
7326 
7327   DeathTest::set_last_death_test_message("");
7328   CaptureStderr();
7329   // When we fork the process below, the log file buffers are copied, but the
7330   // file descriptors are shared.  We flush all log files here so that closing
7331   // the file descriptors in the child process doesn't throw off the
7332   // synchronization between descriptors and buffers in the parent process.
7333   // This is as close to the fork as possible to avoid a race condition in case
7334   // there are multiple threads running before the death test, and another
7335   // thread writes to the log file.
7336   FlushInfoLog();
7337 
7338   const pid_t child_pid = fork();
7339   GTEST_DEATH_TEST_CHECK_(child_pid != -1);
7340   set_child_pid(child_pid);
7341   if (child_pid == 0) {
7342     GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[0]));
7343     set_write_fd(pipe_fd[1]);
7344     // Redirects all logging to stderr in the child process to prevent
7345     // concurrent writes to the log files.  We capture stderr in the parent
7346     // process and append the child process' output to a log.
7347     LogToStderr();
7348     // Event forwarding to the listeners of event listener API mush be shut
7349     // down in death test subprocesses.
7350     GetUnitTestImpl()->listeners()->SuppressEventForwarding();
7351     g_in_fast_death_test_child = true;
7352     return EXECUTE_TEST;
7353   } else {
7354     GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
7355     set_read_fd(pipe_fd[0]);
7356     set_spawned(true);
7357     return OVERSEE_TEST;
7358   }
7359 }
7360 
7361 // A concrete death test class that forks and re-executes the main
7362 // program from the beginning, with command-line flags set that cause
7363 // only this specific death test to be run.
7364 class ExecDeathTest : public ForkingDeathTest {
7365  public:
ExecDeathTest(const char * a_statement,const RE * a_regex,const char * file,int line)7366   ExecDeathTest(const char* a_statement, const RE* a_regex,
7367                 const char* file, int line) :
7368       ForkingDeathTest(a_statement, a_regex), file_(file), line_(line) { }
7369   virtual TestRole AssumeRole();
7370  private:
7371   static ::std::vector<testing::internal::string>
GetArgvsForDeathTestChildProcess()7372   GetArgvsForDeathTestChildProcess() {
7373     ::std::vector<testing::internal::string> args = GetInjectableArgvs();
7374     return args;
7375   }
7376   // The name of the file in which the death test is located.
7377   const char* const file_;
7378   // The line number on which the death test is located.
7379   const int line_;
7380 };
7381 
7382 // Utility class for accumulating command-line arguments.
7383 class Arguments {
7384  public:
Arguments()7385   Arguments() {
7386     args_.push_back(NULL);
7387   }
7388 
~Arguments()7389   ~Arguments() {
7390     for (std::vector<char*>::iterator i = args_.begin(); i != args_.end();
7391          ++i) {
7392       free(*i);
7393     }
7394   }
AddArgument(const char * argument)7395   void AddArgument(const char* argument) {
7396     args_.insert(args_.end() - 1, posix::StrDup(argument));
7397   }
7398 
7399   template <typename Str>
AddArguments(const::std::vector<Str> & arguments)7400   void AddArguments(const ::std::vector<Str>& arguments) {
7401     for (typename ::std::vector<Str>::const_iterator i = arguments.begin();
7402          i != arguments.end();
7403          ++i) {
7404       args_.insert(args_.end() - 1, posix::StrDup(i->c_str()));
7405     }
7406   }
Argv()7407   char* const* Argv() {
7408     return &args_[0];
7409   }
7410 
7411  private:
7412   std::vector<char*> args_;
7413 };
7414 
7415 // A struct that encompasses the arguments to the child process of a
7416 // threadsafe-style death test process.
7417 struct ExecDeathTestArgs {
7418   char* const* argv;  // Command-line arguments for the child's call to exec
7419   int close_fd;       // File descriptor to close; the read end of a pipe
7420 };
7421 
7422 #  if GTEST_OS_MAC
GetEnviron()7423 inline char** GetEnviron() {
7424   // When Google Test is built as a framework on MacOS X, the environ variable
7425   // is unavailable. Apple's documentation (man environ) recommends using
7426   // _NSGetEnviron() instead.
7427   return *_NSGetEnviron();
7428 }
7429 #  else
7430 // Some POSIX platforms expect you to declare environ. extern "C" makes
7431 // it reside in the global namespace.
7432 extern "C" char** environ;
GetEnviron()7433 inline char** GetEnviron() { return environ; }
7434 #  endif  // GTEST_OS_MAC
7435 
7436 #  if !GTEST_OS_QNX
7437 // The main function for a threadsafe-style death test child process.
7438 // This function is called in a clone()-ed process and thus must avoid
7439 // any potentially unsafe operations like malloc or libc functions.
ExecDeathTestChildMain(void * child_arg)7440 static int ExecDeathTestChildMain(void* child_arg) {
7441   ExecDeathTestArgs* const args = static_cast<ExecDeathTestArgs*>(child_arg);
7442   GTEST_DEATH_TEST_CHECK_SYSCALL_(close(args->close_fd));
7443 
7444   // We need to execute the test program in the same environment where
7445   // it was originally invoked.  Therefore we change to the original
7446   // working directory first.
7447   const char* const original_dir =
7448       UnitTest::GetInstance()->original_working_dir();
7449   // We can safely call chdir() as it's a direct system call.
7450   if (chdir(original_dir) != 0) {
7451     DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " +
7452                    GetLastErrnoDescription());
7453     return EXIT_FAILURE;
7454   }
7455 
7456   // We can safely call execve() as it's a direct system call.  We
7457   // cannot use execvp() as it's a libc function and thus potentially
7458   // unsafe.  Since execve() doesn't search the PATH, the user must
7459   // invoke the test program via a valid path that contains at least
7460   // one path separator.
7461   execve(args->argv[0], args->argv, GetEnviron());
7462   DeathTestAbort(std::string("execve(") + args->argv[0] + ", ...) in " +
7463                  original_dir + " failed: " +
7464                  GetLastErrnoDescription());
7465   return EXIT_FAILURE;
7466 }
7467 #  endif  // !GTEST_OS_QNX
7468 
7469 // Two utility routines that together determine the direction the stack
7470 // grows.
7471 // This could be accomplished more elegantly by a single recursive
7472 // function, but we want to guard against the unlikely possibility of
7473 // a smart compiler optimizing the recursion away.
7474 //
7475 // GTEST_NO_INLINE_ is required to prevent GCC 4.6 from inlining
7476 // StackLowerThanAddress into StackGrowsDown, which then doesn't give
7477 // correct answer.
7478 void StackLowerThanAddress(const void* ptr, bool* result) GTEST_NO_INLINE_;
StackLowerThanAddress(const void * ptr,bool * result)7479 void StackLowerThanAddress(const void* ptr, bool* result) {
7480   int dummy;
7481   *result = (&dummy < ptr);
7482 }
7483 
StackGrowsDown()7484 bool StackGrowsDown() {
7485   int dummy;
7486   bool result;
7487   StackLowerThanAddress(&dummy, &result);
7488   return result;
7489 }
7490 
7491 // Spawns a child process with the same executable as the current process in
7492 // a thread-safe manner and instructs it to run the death test.  The
7493 // implementation uses fork(2) + exec.  On systems where clone(2) is
7494 // available, it is used instead, being slightly more thread-safe.  On QNX,
7495 // fork supports only single-threaded environments, so this function uses
7496 // spawn(2) there instead.  The function dies with an error message if
7497 // anything goes wrong.
ExecDeathTestSpawnChild(char * const * argv,int close_fd)7498 static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) {
7499   ExecDeathTestArgs args = { argv, close_fd };
7500   pid_t child_pid = -1;
7501 
7502 #  if GTEST_OS_QNX
7503   // Obtains the current directory and sets it to be closed in the child
7504   // process.
7505   const int cwd_fd = open(".", O_RDONLY);
7506   GTEST_DEATH_TEST_CHECK_(cwd_fd != -1);
7507   GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(cwd_fd, F_SETFD, FD_CLOEXEC));
7508   // We need to execute the test program in the same environment where
7509   // it was originally invoked.  Therefore we change to the original
7510   // working directory first.
7511   const char* const original_dir =
7512       UnitTest::GetInstance()->original_working_dir();
7513   // We can safely call chdir() as it's a direct system call.
7514   if (chdir(original_dir) != 0) {
7515     DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " +
7516                    GetLastErrnoDescription());
7517     return EXIT_FAILURE;
7518   }
7519 
7520   int fd_flags;
7521   // Set close_fd to be closed after spawn.
7522   GTEST_DEATH_TEST_CHECK_SYSCALL_(fd_flags = fcntl(close_fd, F_GETFD));
7523   GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(close_fd, F_SETFD,
7524                                         fd_flags | FD_CLOEXEC));
7525   struct inheritance inherit = {0};
7526   // spawn is a system call.
7527   child_pid = spawn(args.argv[0], 0, NULL, &inherit, args.argv, GetEnviron());
7528   // Restores the current working directory.
7529   GTEST_DEATH_TEST_CHECK_(fchdir(cwd_fd) != -1);
7530   GTEST_DEATH_TEST_CHECK_SYSCALL_(close(cwd_fd));
7531 
7532 #  else   // GTEST_OS_QNX
7533 #   if GTEST_OS_LINUX
7534   // When a SIGPROF signal is received while fork() or clone() are executing,
7535   // the process may hang. To avoid this, we ignore SIGPROF here and re-enable
7536   // it after the call to fork()/clone() is complete.
7537   struct sigaction saved_sigprof_action;
7538   struct sigaction ignore_sigprof_action;
7539   memset(&ignore_sigprof_action, 0, sizeof(ignore_sigprof_action));
7540   sigemptyset(&ignore_sigprof_action.sa_mask);
7541   ignore_sigprof_action.sa_handler = SIG_IGN;
7542   GTEST_DEATH_TEST_CHECK_SYSCALL_(sigaction(
7543       SIGPROF, &ignore_sigprof_action, &saved_sigprof_action));
7544 #   endif  // GTEST_OS_LINUX
7545 
7546 #   if GTEST_HAS_CLONE
7547   const bool use_fork = GTEST_FLAG(death_test_use_fork);
7548 
7549   if (!use_fork) {
7550     static const bool stack_grows_down = StackGrowsDown();
7551     const size_t stack_size = getpagesize();
7552     // MMAP_ANONYMOUS is not defined on Mac, so we use MAP_ANON instead.
7553     void* const stack = mmap(NULL, stack_size, PROT_READ | PROT_WRITE,
7554                              MAP_ANON | MAP_PRIVATE, -1, 0);
7555     GTEST_DEATH_TEST_CHECK_(stack != MAP_FAILED);
7556 
7557     // Maximum stack alignment in bytes:  For a downward-growing stack, this
7558     // amount is subtracted from size of the stack space to get an address
7559     // that is within the stack space and is aligned on all systems we care
7560     // about.  As far as I know there is no ABI with stack alignment greater
7561     // than 64.  We assume stack and stack_size already have alignment of
7562     // kMaxStackAlignment.
7563     const size_t kMaxStackAlignment = 64;
7564     void* const stack_top =
7565         static_cast<char*>(stack) +
7566             (stack_grows_down ? stack_size - kMaxStackAlignment : 0);
7567     GTEST_DEATH_TEST_CHECK_(stack_size > kMaxStackAlignment &&
7568         reinterpret_cast<intptr_t>(stack_top) % kMaxStackAlignment == 0);
7569 
7570     child_pid = clone(&ExecDeathTestChildMain, stack_top, SIGCHLD, &args);
7571 
7572     GTEST_DEATH_TEST_CHECK_(munmap(stack, stack_size) != -1);
7573   }
7574 #   else
7575   const bool use_fork = true;
7576 #   endif  // GTEST_HAS_CLONE
7577 
7578   if (use_fork && (child_pid = fork()) == 0) {
7579       ExecDeathTestChildMain(&args);
7580       _exit(0);
7581   }
7582 #  endif  // GTEST_OS_QNX
7583 #  if GTEST_OS_LINUX
7584   GTEST_DEATH_TEST_CHECK_SYSCALL_(
7585       sigaction(SIGPROF, &saved_sigprof_action, NULL));
7586 #  endif  // GTEST_OS_LINUX
7587 
7588   GTEST_DEATH_TEST_CHECK_(child_pid != -1);
7589   return child_pid;
7590 }
7591 
7592 // The AssumeRole process for a fork-and-exec death test.  It re-executes the
7593 // main program from the beginning, setting the --gtest_filter
7594 // and --gtest_internal_run_death_test flags to cause only the current
7595 // death test to be re-run.
AssumeRole()7596 DeathTest::TestRole ExecDeathTest::AssumeRole() {
7597   const UnitTestImpl* const impl = GetUnitTestImpl();
7598   const InternalRunDeathTestFlag* const flag =
7599       impl->internal_run_death_test_flag();
7600   const TestInfo* const info = impl->current_test_info();
7601   const int death_test_index = info->result()->death_test_count();
7602 
7603   if (flag != NULL) {
7604     set_write_fd(flag->write_fd());
7605     return EXECUTE_TEST;
7606   }
7607 
7608   int pipe_fd[2];
7609   GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
7610   // Clear the close-on-exec flag on the write end of the pipe, lest
7611   // it be closed when the child process does an exec:
7612   GTEST_DEATH_TEST_CHECK_(fcntl(pipe_fd[1], F_SETFD, 0) != -1);
7613 
7614   const std::string filter_flag =
7615       std::string("--") + GTEST_FLAG_PREFIX_ + kFilterFlag + "="
7616       + info->test_case_name() + "." + info->name();
7617   const std::string internal_flag =
7618       std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag + "="
7619       + file_ + "|" + StreamableToString(line_) + "|"
7620       + StreamableToString(death_test_index) + "|"
7621       + StreamableToString(pipe_fd[1]);
7622   Arguments args;
7623   args.AddArguments(GetArgvsForDeathTestChildProcess());
7624   args.AddArgument(filter_flag.c_str());
7625   args.AddArgument(internal_flag.c_str());
7626 
7627   DeathTest::set_last_death_test_message("");
7628 
7629   CaptureStderr();
7630   // See the comment in NoExecDeathTest::AssumeRole for why the next line
7631   // is necessary.
7632   FlushInfoLog();
7633 
7634   const pid_t child_pid = ExecDeathTestSpawnChild(args.Argv(), pipe_fd[0]);
7635   GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
7636   set_child_pid(child_pid);
7637   set_read_fd(pipe_fd[0]);
7638   set_spawned(true);
7639   return OVERSEE_TEST;
7640 }
7641 
7642 # endif  // !GTEST_OS_WINDOWS
7643 
7644 // Creates a concrete DeathTest-derived class that depends on the
7645 // --gtest_death_test_style flag, and sets the pointer pointed to
7646 // by the "test" argument to its address.  If the test should be
7647 // skipped, sets that pointer to NULL.  Returns true, unless the
7648 // flag is set to an invalid value.
Create(const char * statement,const RE * regex,const char * file,int line,DeathTest ** test)7649 bool DefaultDeathTestFactory::Create(const char* statement, const RE* regex,
7650                                      const char* file, int line,
7651                                      DeathTest** test) {
7652   UnitTestImpl* const impl = GetUnitTestImpl();
7653   const InternalRunDeathTestFlag* const flag =
7654       impl->internal_run_death_test_flag();
7655   const int death_test_index = impl->current_test_info()
7656       ->increment_death_test_count();
7657 
7658   if (flag != NULL) {
7659     if (death_test_index > flag->index()) {
7660       DeathTest::set_last_death_test_message(
7661           "Death test count (" + StreamableToString(death_test_index)
7662           + ") somehow exceeded expected maximum ("
7663           + StreamableToString(flag->index()) + ")");
7664       return false;
7665     }
7666 
7667     if (!(flag->file() == file && flag->line() == line &&
7668           flag->index() == death_test_index)) {
7669       *test = NULL;
7670       return true;
7671     }
7672   }
7673 
7674 # if GTEST_OS_WINDOWS
7675 
7676   if (GTEST_FLAG(death_test_style) == "threadsafe" ||
7677       GTEST_FLAG(death_test_style) == "fast") {
7678     *test = new WindowsDeathTest(statement, regex, file, line);
7679   }
7680 
7681 # else
7682 
7683   if (GTEST_FLAG(death_test_style) == "threadsafe") {
7684     *test = new ExecDeathTest(statement, regex, file, line);
7685   } else if (GTEST_FLAG(death_test_style) == "fast") {
7686     *test = new NoExecDeathTest(statement, regex);
7687   }
7688 
7689 # endif  // GTEST_OS_WINDOWS
7690 
7691   else {  // NOLINT - this is more readable than unbalanced brackets inside #if.
7692     DeathTest::set_last_death_test_message(
7693         "Unknown death test style \"" + GTEST_FLAG(death_test_style)
7694         + "\" encountered");
7695     return false;
7696   }
7697 
7698   return true;
7699 }
7700 
7701 // Splits a given string on a given delimiter, populating a given
7702 // vector with the fields.  GTEST_HAS_DEATH_TEST implies that we have
7703 // ::std::string, so we can use it here.
SplitString(const::std::string & str,char delimiter,::std::vector<::std::string> * dest)7704 static void SplitString(const ::std::string& str, char delimiter,
7705                         ::std::vector< ::std::string>* dest) {
7706   ::std::vector< ::std::string> parsed;
7707   ::std::string::size_type pos = 0;
7708   while (::testing::internal::AlwaysTrue()) {
7709     const ::std::string::size_type colon = str.find(delimiter, pos);
7710     if (colon == ::std::string::npos) {
7711       parsed.push_back(str.substr(pos));
7712       break;
7713     } else {
7714       parsed.push_back(str.substr(pos, colon - pos));
7715       pos = colon + 1;
7716     }
7717   }
7718   dest->swap(parsed);
7719 }
7720 
7721 # if GTEST_OS_WINDOWS
7722 // Recreates the pipe and event handles from the provided parameters,
7723 // signals the event, and returns a file descriptor wrapped around the pipe
7724 // 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)7725 int GetStatusFileDescriptor(unsigned int parent_process_id,
7726                             size_t write_handle_as_size_t,
7727                             size_t event_handle_as_size_t) {
7728   AutoHandle parent_process_handle(::OpenProcess(PROCESS_DUP_HANDLE,
7729                                                    FALSE,  // Non-inheritable.
7730                                                    parent_process_id));
7731   if (parent_process_handle.Get() == INVALID_HANDLE_VALUE) {
7732     DeathTestAbort("Unable to open parent process " +
7733                    StreamableToString(parent_process_id));
7734   }
7735 
7736   // TODO(vladl@google.com): Replace the following check with a
7737   // compile-time assertion when available.
7738   GTEST_CHECK_(sizeof(HANDLE) <= sizeof(size_t));
7739 
7740   const HANDLE write_handle =
7741       reinterpret_cast<HANDLE>(write_handle_as_size_t);
7742   HANDLE dup_write_handle;
7743 
7744   // The newly initialized handle is accessible only in in the parent
7745   // process. To obtain one accessible within the child, we need to use
7746   // DuplicateHandle.
7747   if (!::DuplicateHandle(parent_process_handle.Get(), write_handle,
7748                          ::GetCurrentProcess(), &dup_write_handle,
7749                          0x0,    // Requested privileges ignored since
7750                                  // DUPLICATE_SAME_ACCESS is used.
7751                          FALSE,  // Request non-inheritable handler.
7752                          DUPLICATE_SAME_ACCESS)) {
7753     DeathTestAbort("Unable to duplicate the pipe handle " +
7754                    StreamableToString(write_handle_as_size_t) +
7755                    " from the parent process " +
7756                    StreamableToString(parent_process_id));
7757   }
7758 
7759   const HANDLE event_handle = reinterpret_cast<HANDLE>(event_handle_as_size_t);
7760   HANDLE dup_event_handle;
7761 
7762   if (!::DuplicateHandle(parent_process_handle.Get(), event_handle,
7763                          ::GetCurrentProcess(), &dup_event_handle,
7764                          0x0,
7765                          FALSE,
7766                          DUPLICATE_SAME_ACCESS)) {
7767     DeathTestAbort("Unable to duplicate the event handle " +
7768                    StreamableToString(event_handle_as_size_t) +
7769                    " from the parent process " +
7770                    StreamableToString(parent_process_id));
7771   }
7772 
7773   const int write_fd =
7774       ::_open_osfhandle(reinterpret_cast<intptr_t>(dup_write_handle), O_APPEND);
7775   if (write_fd == -1) {
7776     DeathTestAbort("Unable to convert pipe handle " +
7777                    StreamableToString(write_handle_as_size_t) +
7778                    " to a file descriptor");
7779   }
7780 
7781   // Signals the parent that the write end of the pipe has been acquired
7782   // so the parent can release its own write end.
7783   ::SetEvent(dup_event_handle);
7784 
7785   return write_fd;
7786 }
7787 # endif  // GTEST_OS_WINDOWS
7788 
7789 // Returns a newly created InternalRunDeathTestFlag object with fields
7790 // initialized from the GTEST_FLAG(internal_run_death_test) flag if
7791 // the flag is specified; otherwise returns NULL.
ParseInternalRunDeathTestFlag()7792 InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() {
7793   if (GTEST_FLAG(internal_run_death_test) == "") return NULL;
7794 
7795   // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we
7796   // can use it here.
7797   int line = -1;
7798   int index = -1;
7799   ::std::vector< ::std::string> fields;
7800   SplitString(GTEST_FLAG(internal_run_death_test).c_str(), '|', &fields);
7801   int write_fd = -1;
7802 
7803 # if GTEST_OS_WINDOWS
7804 
7805   unsigned int parent_process_id = 0;
7806   size_t write_handle_as_size_t = 0;
7807   size_t event_handle_as_size_t = 0;
7808 
7809   if (fields.size() != 6
7810       || !ParseNaturalNumber(fields[1], &line)
7811       || !ParseNaturalNumber(fields[2], &index)
7812       || !ParseNaturalNumber(fields[3], &parent_process_id)
7813       || !ParseNaturalNumber(fields[4], &write_handle_as_size_t)
7814       || !ParseNaturalNumber(fields[5], &event_handle_as_size_t)) {
7815     DeathTestAbort("Bad --gtest_internal_run_death_test flag: " +
7816                    GTEST_FLAG(internal_run_death_test));
7817   }
7818   write_fd = GetStatusFileDescriptor(parent_process_id,
7819                                      write_handle_as_size_t,
7820                                      event_handle_as_size_t);
7821 # else
7822 
7823   if (fields.size() != 4
7824       || !ParseNaturalNumber(fields[1], &line)
7825       || !ParseNaturalNumber(fields[2], &index)
7826       || !ParseNaturalNumber(fields[3], &write_fd)) {
7827     DeathTestAbort("Bad --gtest_internal_run_death_test flag: "
7828         + GTEST_FLAG(internal_run_death_test));
7829   }
7830 
7831 # endif  // GTEST_OS_WINDOWS
7832 
7833   return new InternalRunDeathTestFlag(fields[0], line, index, write_fd);
7834 }
7835 
7836 }  // namespace internal
7837 
7838 #endif  // GTEST_HAS_DEATH_TEST
7839 
7840 }  // namespace testing
7841 // Copyright 2008, Google Inc.
7842 // All rights reserved.
7843 //
7844 // Redistribution and use in source and binary forms, with or without
7845 // modification, are permitted provided that the following conditions are
7846 // met:
7847 //
7848 //     * Redistributions of source code must retain the above copyright
7849 // notice, this list of conditions and the following disclaimer.
7850 //     * Redistributions in binary form must reproduce the above
7851 // copyright notice, this list of conditions and the following disclaimer
7852 // in the documentation and/or other materials provided with the
7853 // distribution.
7854 //     * Neither the name of Google Inc. nor the names of its
7855 // contributors may be used to endorse or promote products derived from
7856 // this software without specific prior written permission.
7857 //
7858 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
7859 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
7860 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
7861 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
7862 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
7863 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
7864 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
7865 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
7866 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
7867 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
7868 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
7869 //
7870 // Authors: keith.ray@gmail.com (Keith Ray)
7871 
7872 
7873 #include <stdlib.h>
7874 
7875 #if GTEST_OS_WINDOWS_MOBILE
7876 # include <windows.h>
7877 #elif GTEST_OS_WINDOWS
7878 # include <direct.h>
7879 # include <io.h>
7880 #elif GTEST_OS_SYMBIAN
7881 // Symbian OpenC has PATH_MAX in sys/syslimits.h
7882 # include <sys/syslimits.h>
7883 #else
7884 # include <limits.h>
7885 # include <climits>  // Some Linux distributions define PATH_MAX here.
7886 #endif  // GTEST_OS_WINDOWS_MOBILE
7887 
7888 #if GTEST_OS_WINDOWS
7889 # define GTEST_PATH_MAX_ _MAX_PATH
7890 #elif defined(PATH_MAX)
7891 # define GTEST_PATH_MAX_ PATH_MAX
7892 #elif defined(_XOPEN_PATH_MAX)
7893 # define GTEST_PATH_MAX_ _XOPEN_PATH_MAX
7894 #else
7895 # define GTEST_PATH_MAX_ _POSIX_PATH_MAX
7896 #endif  // GTEST_OS_WINDOWS
7897 
7898 
7899 namespace testing {
7900 namespace internal {
7901 
7902 #if GTEST_OS_WINDOWS
7903 // On Windows, '\\' is the standard path separator, but many tools and the
7904 // Windows API also accept '/' as an alternate path separator. Unless otherwise
7905 // noted, a file path can contain either kind of path separators, or a mixture
7906 // of them.
7907 const char kPathSeparator = '\\';
7908 const char kAlternatePathSeparator = '/';
7909 //const char kPathSeparatorString[] = "\\";
7910 const char kAlternatePathSeparatorString[] = "/";
7911 # if GTEST_OS_WINDOWS_MOBILE
7912 // Windows CE doesn't have a current directory. You should not use
7913 // the current directory in tests on Windows CE, but this at least
7914 // provides a reasonable fallback.
7915 const char kCurrentDirectoryString[] = "\\";
7916 // Windows CE doesn't define INVALID_FILE_ATTRIBUTES
7917 const DWORD kInvalidFileAttributes = 0xffffffff;
7918 # else
7919 const char kCurrentDirectoryString[] = ".\\";
7920 # endif  // GTEST_OS_WINDOWS_MOBILE
7921 #else
7922 const char kPathSeparator = '/';
7923 //const char kPathSeparatorString[] = "/";
7924 const char kCurrentDirectoryString[] = "./";
7925 #endif  // GTEST_OS_WINDOWS
7926 
7927 // Returns whether the given character is a valid path separator.
IsPathSeparator(char c)7928 static bool IsPathSeparator(char c) {
7929 #if GTEST_HAS_ALT_PATH_SEP_
7930   return (c == kPathSeparator) || (c == kAlternatePathSeparator);
7931 #else
7932   return c == kPathSeparator;
7933 #endif
7934 }
7935 
7936 // Returns the current working directory, or "" if unsuccessful.
GetCurrentDir()7937 FilePath FilePath::GetCurrentDir() {
7938 #if GTEST_OS_WINDOWS_MOBILE
7939   // Windows CE doesn't have a current directory, so we just return
7940   // something reasonable.
7941   return FilePath(kCurrentDirectoryString);
7942 #elif GTEST_OS_WINDOWS
7943   char cwd[GTEST_PATH_MAX_ + 1] = { '\0' };
7944   return FilePath(_getcwd(cwd, sizeof(cwd)) == NULL ? "" : cwd);
7945 #else
7946   char cwd[GTEST_PATH_MAX_ + 1] = { '\0' };
7947   return FilePath(getcwd(cwd, sizeof(cwd)) == NULL ? "" : cwd);
7948 #endif  // GTEST_OS_WINDOWS_MOBILE
7949 }
7950 
7951 // Returns a copy of the FilePath with the case-insensitive extension removed.
7952 // Example: FilePath("dir/file.exe").RemoveExtension("EXE") returns
7953 // FilePath("dir/file"). If a case-insensitive extension is not
7954 // found, returns a copy of the original FilePath.
RemoveExtension(const char * extension) const7955 FilePath FilePath::RemoveExtension(const char* extension) const {
7956   const std::string dot_extension = std::string(".") + extension;
7957   if (String::EndsWithCaseInsensitive(pathname_, dot_extension)) {
7958     return FilePath(pathname_.substr(
7959         0, pathname_.length() - dot_extension.length()));
7960   }
7961   return *this;
7962 }
7963 
7964 // Returns a pointer to the last occurrence of a valid path separator in
7965 // the FilePath. On Windows, for example, both '/' and '\' are valid path
7966 // separators. Returns NULL if no path separator was found.
FindLastPathSeparator() const7967 const char* FilePath::FindLastPathSeparator() const {
7968   const char* const last_sep = strrchr(c_str(), kPathSeparator);
7969 #if GTEST_HAS_ALT_PATH_SEP_
7970   const char* const last_alt_sep = strrchr(c_str(), kAlternatePathSeparator);
7971   // Comparing two pointers of which only one is NULL is undefined.
7972   if (last_alt_sep != NULL &&
7973       (last_sep == NULL || last_alt_sep > last_sep)) {
7974     return last_alt_sep;
7975   }
7976 #endif
7977   return last_sep;
7978 }
7979 
7980 // Returns a copy of the FilePath with the directory part removed.
7981 // Example: FilePath("path/to/file").RemoveDirectoryName() returns
7982 // FilePath("file"). If there is no directory part ("just_a_file"), it returns
7983 // the FilePath unmodified. If there is no file part ("just_a_dir/") it
7984 // returns an empty FilePath ("").
7985 // On Windows platform, '\' is the path separator, otherwise it is '/'.
RemoveDirectoryName() const7986 FilePath FilePath::RemoveDirectoryName() const {
7987   const char* const last_sep = FindLastPathSeparator();
7988   return last_sep ? FilePath(last_sep + 1) : *this;
7989 }
7990 
7991 // RemoveFileName returns the directory path with the filename removed.
7992 // Example: FilePath("path/to/file").RemoveFileName() returns "path/to/".
7993 // If the FilePath is "a_file" or "/a_file", RemoveFileName returns
7994 // FilePath("./") or, on Windows, FilePath(".\\"). If the filepath does
7995 // not have a file, like "just/a/dir/", it returns the FilePath unmodified.
7996 // On Windows platform, '\' is the path separator, otherwise it is '/'.
RemoveFileName() const7997 FilePath FilePath::RemoveFileName() const {
7998   const char* const last_sep = FindLastPathSeparator();
7999   std::string dir;
8000   if (last_sep) {
8001     dir = std::string(c_str(), last_sep + 1 - c_str());
8002   } else {
8003     dir = kCurrentDirectoryString;
8004   }
8005   return FilePath(dir);
8006 }
8007 
8008 // Helper functions for naming files in a directory for xml output.
8009 
8010 // Given directory = "dir", base_name = "test", number = 0,
8011 // extension = "xml", returns "dir/test.xml". If number is greater
8012 // than zero (e.g., 12), returns "dir/test_12.xml".
8013 // On Windows platform, uses \ as the separator rather than /.
MakeFileName(const FilePath & directory,const FilePath & base_name,int number,const char * extension)8014 FilePath FilePath::MakeFileName(const FilePath& directory,
8015                                 const FilePath& base_name,
8016                                 int number,
8017                                 const char* extension) {
8018   std::string file;
8019   if (number == 0) {
8020     file = base_name.string() + "." + extension;
8021   } else {
8022     file = base_name.string() + "_" + StreamableToString(number)
8023         + "." + extension;
8024   }
8025   return ConcatPaths(directory, FilePath(file));
8026 }
8027 
8028 // Given directory = "dir", relative_path = "test.xml", returns "dir/test.xml".
8029 // On Windows, uses \ as the separator rather than /.
ConcatPaths(const FilePath & directory,const FilePath & relative_path)8030 FilePath FilePath::ConcatPaths(const FilePath& directory,
8031                                const FilePath& relative_path) {
8032   if (directory.IsEmpty())
8033     return relative_path;
8034   const FilePath dir(directory.RemoveTrailingPathSeparator());
8035   return FilePath(dir.string() + kPathSeparator + relative_path.string());
8036 }
8037 
8038 // Returns true if pathname describes something findable in the file-system,
8039 // either a file, directory, or whatever.
FileOrDirectoryExists() const8040 bool FilePath::FileOrDirectoryExists() const {
8041 #if GTEST_OS_WINDOWS_MOBILE
8042   LPCWSTR unicode = String::AnsiToUtf16(pathname_.c_str());
8043   const DWORD attributes = GetFileAttributes(unicode);
8044   delete [] unicode;
8045   return attributes != kInvalidFileAttributes;
8046 #else
8047   posix::StatStruct file_stat;
8048   return posix::Stat(pathname_.c_str(), &file_stat) == 0;
8049 #endif  // GTEST_OS_WINDOWS_MOBILE
8050 }
8051 
8052 // Returns true if pathname describes a directory in the file-system
8053 // that exists.
DirectoryExists() const8054 bool FilePath::DirectoryExists() const {
8055   bool result = false;
8056 #if GTEST_OS_WINDOWS
8057   // Don't strip off trailing separator if path is a root directory on
8058   // Windows (like "C:\\").
8059   const FilePath& path(IsRootDirectory() ? *this :
8060                                            RemoveTrailingPathSeparator());
8061 #else
8062   const FilePath& path(*this);
8063 #endif
8064 
8065 #if GTEST_OS_WINDOWS_MOBILE
8066   LPCWSTR unicode = String::AnsiToUtf16(path.c_str());
8067   const DWORD attributes = GetFileAttributes(unicode);
8068   delete [] unicode;
8069   if ((attributes != kInvalidFileAttributes) &&
8070       (attributes & FILE_ATTRIBUTE_DIRECTORY)) {
8071     result = true;
8072   }
8073 #else
8074   posix::StatStruct file_stat;
8075   result = posix::Stat(path.c_str(), &file_stat) == 0 &&
8076       posix::IsDir(file_stat);
8077 #endif  // GTEST_OS_WINDOWS_MOBILE
8078 
8079   return result;
8080 }
8081 
8082 // Returns true if pathname describes a root directory. (Windows has one
8083 // root directory per disk drive.)
IsRootDirectory() const8084 bool FilePath::IsRootDirectory() const {
8085 #if GTEST_OS_WINDOWS
8086   // TODO(wan@google.com): on Windows a network share like
8087   // \\server\share can be a root directory, although it cannot be the
8088   // current directory.  Handle this properly.
8089   return pathname_.length() == 3 && IsAbsolutePath();
8090 #else
8091   return pathname_.length() == 1 && IsPathSeparator(pathname_.c_str()[0]);
8092 #endif
8093 }
8094 
8095 // Returns true if pathname describes an absolute path.
IsAbsolutePath() const8096 bool FilePath::IsAbsolutePath() const {
8097   const char* const name = pathname_.c_str();
8098 #if GTEST_OS_WINDOWS
8099   return pathname_.length() >= 3 &&
8100      ((name[0] >= 'a' && name[0] <= 'z') ||
8101       (name[0] >= 'A' && name[0] <= 'Z')) &&
8102      name[1] == ':' &&
8103      IsPathSeparator(name[2]);
8104 #else
8105   return IsPathSeparator(name[0]);
8106 #endif
8107 }
8108 
8109 // Returns a pathname for a file that does not currently exist. The pathname
8110 // will be directory/base_name.extension or
8111 // directory/base_name_<number>.extension if directory/base_name.extension
8112 // already exists. The number will be incremented until a pathname is found
8113 // that does not already exist.
8114 // Examples: 'dir/foo_test.xml' or 'dir/foo_test_1.xml'.
8115 // There could be a race condition if two or more processes are calling this
8116 // function at the same time -- they could both pick the same filename.
GenerateUniqueFileName(const FilePath & directory,const FilePath & base_name,const char * extension)8117 FilePath FilePath::GenerateUniqueFileName(const FilePath& directory,
8118                                           const FilePath& base_name,
8119                                           const char* extension) {
8120   FilePath full_pathname;
8121   int number = 0;
8122   do {
8123     full_pathname.Set(MakeFileName(directory, base_name, number++, extension));
8124   } while (full_pathname.FileOrDirectoryExists());
8125   return full_pathname;
8126 }
8127 
8128 // Returns true if FilePath ends with a path separator, which indicates that
8129 // it is intended to represent a directory. Returns false otherwise.
8130 // This does NOT check that a directory (or file) actually exists.
IsDirectory() const8131 bool FilePath::IsDirectory() const {
8132   return !pathname_.empty() &&
8133          IsPathSeparator(pathname_.c_str()[pathname_.length() - 1]);
8134 }
8135 
8136 // Create directories so that path exists. Returns true if successful or if
8137 // the directories already exist; returns false if unable to create directories
8138 // for any reason.
CreateDirectoriesRecursively() const8139 bool FilePath::CreateDirectoriesRecursively() const {
8140   if (!this->IsDirectory()) {
8141     return false;
8142   }
8143 
8144   if (pathname_.length() == 0 || this->DirectoryExists()) {
8145     return true;
8146   }
8147 
8148   const FilePath parent(this->RemoveTrailingPathSeparator().RemoveFileName());
8149   return parent.CreateDirectoriesRecursively() && this->CreateFolder();
8150 }
8151 
8152 // Create the directory so that path exists. Returns true if successful or
8153 // if the directory already exists; returns false if unable to create the
8154 // directory for any reason, including if the parent directory does not
8155 // exist. Not named "CreateDirectory" because that's a macro on Windows.
CreateFolder() const8156 bool FilePath::CreateFolder() const {
8157 #if GTEST_OS_WINDOWS_MOBILE
8158   FilePath removed_sep(this->RemoveTrailingPathSeparator());
8159   LPCWSTR unicode = String::AnsiToUtf16(removed_sep.c_str());
8160   int result = CreateDirectory(unicode, NULL) ? 0 : -1;
8161   delete [] unicode;
8162 #elif GTEST_OS_WINDOWS
8163   int result = _mkdir(pathname_.c_str());
8164 #else
8165   int result = mkdir(pathname_.c_str(), 0777);
8166 #endif  // GTEST_OS_WINDOWS_MOBILE
8167 
8168   if (result == -1) {
8169     return this->DirectoryExists();  // An error is OK if the directory exists.
8170   }
8171   return true;  // No error.
8172 }
8173 
8174 // If input name has a trailing separator character, remove it and return the
8175 // name, otherwise return the name string unmodified.
8176 // On Windows platform, uses \ as the separator, other platforms use /.
RemoveTrailingPathSeparator() const8177 FilePath FilePath::RemoveTrailingPathSeparator() const {
8178   return IsDirectory()
8179       ? FilePath(pathname_.substr(0, pathname_.length() - 1))
8180       : *this;
8181 }
8182 
8183 // Removes any redundant separators that might be in the pathname.
8184 // For example, "bar///foo" becomes "bar/foo". Does not eliminate other
8185 // redundancies that might be in a pathname involving "." or "..".
8186 // TODO(wan@google.com): handle Windows network shares (e.g. \\server\share).
Normalize()8187 void FilePath::Normalize() {
8188   if (pathname_.c_str() == NULL) {
8189     pathname_ = "";
8190     return;
8191   }
8192   const char* src = pathname_.c_str();
8193   char* const dest = new char[pathname_.length() + 1];
8194   char* dest_ptr = dest;
8195   memset(dest_ptr, 0, pathname_.length() + 1);
8196 
8197   while (*src != '\0') {
8198     *dest_ptr = *src;
8199     if (!IsPathSeparator(*src)) {
8200       src++;
8201     } else {
8202 #if GTEST_HAS_ALT_PATH_SEP_
8203       if (*dest_ptr == kAlternatePathSeparator) {
8204         *dest_ptr = kPathSeparator;
8205       }
8206 #endif
8207       while (IsPathSeparator(*src))
8208         src++;
8209     }
8210     dest_ptr++;
8211   }
8212   *dest_ptr = '\0';
8213   pathname_ = dest;
8214   delete[] dest;
8215 }
8216 
8217 }  // namespace internal
8218 }  // namespace testing
8219 // Copyright 2008, Google Inc.
8220 // All rights reserved.
8221 //
8222 // Redistribution and use in source and binary forms, with or without
8223 // modification, are permitted provided that the following conditions are
8224 // met:
8225 //
8226 //     * Redistributions of source code must retain the above copyright
8227 // notice, this list of conditions and the following disclaimer.
8228 //     * Redistributions in binary form must reproduce the above
8229 // copyright notice, this list of conditions and the following disclaimer
8230 // in the documentation and/or other materials provided with the
8231 // distribution.
8232 //     * Neither the name of Google Inc. nor the names of its
8233 // contributors may be used to endorse or promote products derived from
8234 // this software without specific prior written permission.
8235 //
8236 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
8237 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
8238 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
8239 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
8240 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
8241 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
8242 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
8243 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
8244 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
8245 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
8246 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
8247 //
8248 // Author: wan@google.com (Zhanyong Wan)
8249 
8250 
8251 #include <limits.h>
8252 #include <stdlib.h>
8253 #include <stdio.h>
8254 #include <string.h>
8255 
8256 #if GTEST_OS_WINDOWS_MOBILE
8257 # include <windows.h>  // For TerminateProcess()
8258 #elif GTEST_OS_WINDOWS
8259 # include <io.h>
8260 # include <sys/stat.h>
8261 #else
8262 # include <unistd.h>
8263 #endif  // GTEST_OS_WINDOWS_MOBILE
8264 
8265 #if GTEST_OS_MAC
8266 # include <mach/mach_init.h>
8267 # include <mach/task.h>
8268 # include <mach/vm_map.h>
8269 #endif  // GTEST_OS_MAC
8270 
8271 #if GTEST_OS_QNX
8272 # include <devctl.h>
8273 # include <sys/procfs.h>
8274 #endif  // GTEST_OS_QNX
8275 
8276 
8277 // Indicates that this translation unit is part of Google Test's
8278 // implementation.  It must come before gtest-internal-inl.h is
8279 // included, or there will be a compiler error.  This trick is to
8280 // prevent a user from accidentally including gtest-internal-inl.h in
8281 // his code.
8282 #define GTEST_IMPLEMENTATION_ 1
8283 #undef GTEST_IMPLEMENTATION_
8284 
8285 namespace testing {
8286 namespace internal {
8287 
8288 #if defined(_MSC_VER) || defined(__BORLANDC__)
8289 // MSVC and C++Builder do not provide a definition of STDERR_FILENO.
8290 const int kStdOutFileno = 1;
8291 const int kStdErrFileno = 2;
8292 #else
8293 const int kStdOutFileno = STDOUT_FILENO;
8294 const int kStdErrFileno = STDERR_FILENO;
8295 #endif  // _MSC_VER
8296 
8297 #if GTEST_OS_MAC
8298 
8299 // Returns the number of threads running in the process, or 0 to indicate that
8300 // we cannot detect it.
GetThreadCount()8301 size_t GetThreadCount() {
8302   const task_t task = mach_task_self();
8303   mach_msg_type_number_t thread_count;
8304   thread_act_array_t thread_list;
8305   const kern_return_t status = task_threads(task, &thread_list, &thread_count);
8306   if (status == KERN_SUCCESS) {
8307     // task_threads allocates resources in thread_list and we need to free them
8308     // to avoid leaks.
8309     vm_deallocate(task,
8310                   reinterpret_cast<vm_address_t>(thread_list),
8311                   sizeof(thread_t) * thread_count);
8312     return static_cast<size_t>(thread_count);
8313   } else {
8314     return 0;
8315   }
8316 }
8317 
8318 #elif GTEST_OS_QNX
8319 
8320 // Returns the number of threads running in the process, or 0 to indicate that
8321 // we cannot detect it.
GetThreadCount()8322 size_t GetThreadCount() {
8323   const int fd = open("/proc/self/as", O_RDONLY);
8324   if (fd < 0) {
8325     return 0;
8326   }
8327   procfs_info process_info;
8328   const int status =
8329       devctl(fd, DCMD_PROC_INFO, &process_info, sizeof(process_info), NULL);
8330   close(fd);
8331   if (status == EOK) {
8332     return static_cast<size_t>(process_info.num_threads);
8333   } else {
8334     return 0;
8335   }
8336 }
8337 
8338 #else
8339 
GetThreadCount()8340 size_t GetThreadCount() {
8341   // There's no portable way to detect the number of threads, so we just
8342   // return 0 to indicate that we cannot detect it.
8343   return 0;
8344 }
8345 
8346 #endif  // GTEST_OS_MAC
8347 
8348 #if GTEST_USES_POSIX_RE
8349 
8350 // Implements RE.  Currently only needed for death tests.
8351 
~RE()8352 RE::~RE() {
8353   if (is_valid_) {
8354     // regfree'ing an invalid regex might crash because the content
8355     // of the regex is undefined. Since the regex's are essentially
8356     // the same, one cannot be valid (or invalid) without the other
8357     // being so too.
8358     regfree(&partial_regex_);
8359     regfree(&full_regex_);
8360   }
8361   free(const_cast<char*>(pattern_));
8362 }
8363 
8364 // Returns true iff regular expression re matches the entire str.
FullMatch(const char * str,const RE & re)8365 bool RE::FullMatch(const char* str, const RE& re) {
8366   if (!re.is_valid_) return false;
8367 
8368   regmatch_t match;
8369   return regexec(&re.full_regex_, str, 1, &match, 0) == 0;
8370 }
8371 
8372 // Returns true iff regular expression re matches a substring of str
8373 // (including str itself).
PartialMatch(const char * str,const RE & re)8374 bool RE::PartialMatch(const char* str, const RE& re) {
8375   if (!re.is_valid_) return false;
8376 
8377   regmatch_t match;
8378   return regexec(&re.partial_regex_, str, 1, &match, 0) == 0;
8379 }
8380 
8381 // Initializes an RE from its string representation.
Init(const char * regex)8382 void RE::Init(const char* regex) {
8383   pattern_ = posix::StrDup(regex);
8384 
8385   // Reserves enough bytes to hold the regular expression used for a
8386   // full match.
8387   const size_t full_regex_len = strlen(regex) + 10;
8388   char* const full_pattern = new char[full_regex_len];
8389 
8390   snprintf(full_pattern, full_regex_len, "^(%s)$", regex);
8391   is_valid_ = regcomp(&full_regex_, full_pattern, REG_EXTENDED) == 0;
8392   // We want to call regcomp(&partial_regex_, ...) even if the
8393   // previous expression returns false.  Otherwise partial_regex_ may
8394   // not be properly initialized can may cause trouble when it's
8395   // freed.
8396   //
8397   // Some implementation of POSIX regex (e.g. on at least some
8398   // versions of Cygwin) doesn't accept the empty string as a valid
8399   // regex.  We change it to an equivalent form "()" to be safe.
8400   if (is_valid_) {
8401     const char* const partial_regex = (*regex == '\0') ? "()" : regex;
8402     is_valid_ = regcomp(&partial_regex_, partial_regex, REG_EXTENDED) == 0;
8403   }
8404   EXPECT_TRUE(is_valid_)
8405       << "Regular expression \"" << regex
8406       << "\" is not a valid POSIX Extended regular expression.";
8407 
8408   delete[] full_pattern;
8409 }
8410 
8411 #elif GTEST_USES_SIMPLE_RE
8412 
8413 // Returns true iff ch appears anywhere in str (excluding the
8414 // terminating '\0' character).
IsInSet(char ch,const char * str)8415 bool IsInSet(char ch, const char* str) {
8416   return ch != '\0' && strchr(str, ch) != NULL;
8417 }
8418 
8419 // Returns true iff ch belongs to the given classification.  Unlike
8420 // similar functions in <ctype.h>, these aren't affected by the
8421 // current locale.
IsAsciiDigit(char ch)8422 bool IsAsciiDigit(char ch) { return '0' <= ch && ch <= '9'; }
IsAsciiPunct(char ch)8423 bool IsAsciiPunct(char ch) {
8424   return IsInSet(ch, "^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~");
8425 }
IsRepeat(char ch)8426 bool IsRepeat(char ch) { return IsInSet(ch, "?*+"); }
IsAsciiWhiteSpace(char ch)8427 bool IsAsciiWhiteSpace(char ch) { return IsInSet(ch, " \f\n\r\t\v"); }
IsAsciiWordChar(char ch)8428 bool IsAsciiWordChar(char ch) {
8429   return ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') ||
8430       ('0' <= ch && ch <= '9') || ch == '_';
8431 }
8432 
8433 // Returns true iff "\\c" is a supported escape sequence.
IsValidEscape(char c)8434 bool IsValidEscape(char c) {
8435   return (IsAsciiPunct(c) || IsInSet(c, "dDfnrsStvwW"));
8436 }
8437 
8438 // Returns true iff the given atom (specified by escaped and pattern)
8439 // matches ch.  The result is undefined if the atom is invalid.
AtomMatchesChar(bool escaped,char pattern_char,char ch)8440 bool AtomMatchesChar(bool escaped, char pattern_char, char ch) {
8441   if (escaped) {  // "\\p" where p is pattern_char.
8442     switch (pattern_char) {
8443       case 'd': return IsAsciiDigit(ch);
8444       case 'D': return !IsAsciiDigit(ch);
8445       case 'f': return ch == '\f';
8446       case 'n': return ch == '\n';
8447       case 'r': return ch == '\r';
8448       case 's': return IsAsciiWhiteSpace(ch);
8449       case 'S': return !IsAsciiWhiteSpace(ch);
8450       case 't': return ch == '\t';
8451       case 'v': return ch == '\v';
8452       case 'w': return IsAsciiWordChar(ch);
8453       case 'W': return !IsAsciiWordChar(ch);
8454     }
8455     return IsAsciiPunct(pattern_char) && pattern_char == ch;
8456   }
8457 
8458   return (pattern_char == '.' && ch != '\n') || pattern_char == ch;
8459 }
8460 
8461 // Helper function used by ValidateRegex() to format error messages.
FormatRegexSyntaxError(const char * regex,int index)8462 std::string FormatRegexSyntaxError(const char* regex, int index) {
8463   return (Message() << "Syntax error at index " << index
8464           << " in simple regular expression \"" << regex << "\": ").GetString();
8465 }
8466 
8467 // Generates non-fatal failures and returns false if regex is invalid;
8468 // otherwise returns true.
ValidateRegex(const char * regex)8469 bool ValidateRegex(const char* regex) {
8470   if (regex == NULL) {
8471     // TODO(wan@google.com): fix the source file location in the
8472     // assertion failures to match where the regex is used in user
8473     // code.
8474     ADD_FAILURE() << "NULL is not a valid simple regular expression.";
8475     return false;
8476   }
8477 
8478   bool is_valid = true;
8479 
8480   // True iff ?, *, or + can follow the previous atom.
8481   bool prev_repeatable = false;
8482   for (int i = 0; regex[i]; i++) {
8483     if (regex[i] == '\\') {  // An escape sequence
8484       i++;
8485       if (regex[i] == '\0') {
8486         ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
8487                       << "'\\' cannot appear at the end.";
8488         return false;
8489       }
8490 
8491       if (!IsValidEscape(regex[i])) {
8492         ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
8493                       << "invalid escape sequence \"\\" << regex[i] << "\".";
8494         is_valid = false;
8495       }
8496       prev_repeatable = true;
8497     } else {  // Not an escape sequence.
8498       const char ch = regex[i];
8499 
8500       if (ch == '^' && i > 0) {
8501         ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
8502                       << "'^' can only appear at the beginning.";
8503         is_valid = false;
8504       } else if (ch == '$' && regex[i + 1] != '\0') {
8505         ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
8506                       << "'$' can only appear at the end.";
8507         is_valid = false;
8508       } else if (IsInSet(ch, "()[]{}|")) {
8509         ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
8510                       << "'" << ch << "' is unsupported.";
8511         is_valid = false;
8512       } else if (IsRepeat(ch) && !prev_repeatable) {
8513         ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
8514                       << "'" << ch << "' can only follow a repeatable token.";
8515         is_valid = false;
8516       }
8517 
8518       prev_repeatable = !IsInSet(ch, "^$?*+");
8519     }
8520   }
8521 
8522   return is_valid;
8523 }
8524 
8525 // Matches a repeated regex atom followed by a valid simple regular
8526 // expression.  The regex atom is defined as c if escaped is false,
8527 // or \c otherwise.  repeat is the repetition meta character (?, *,
8528 // or +).  The behavior is undefined if str contains too many
8529 // characters to be indexable by size_t, in which case the test will
8530 // probably time out anyway.  We are fine with this limitation as
8531 // std::string has it too.
MatchRepetitionAndRegexAtHead(bool escaped,char c,char repeat,const char * regex,const char * str)8532 bool MatchRepetitionAndRegexAtHead(
8533     bool escaped, char c, char repeat, const char* regex,
8534     const char* str) {
8535   const size_t min_count = (repeat == '+') ? 1 : 0;
8536   const size_t max_count = (repeat == '?') ? 1 :
8537       static_cast<size_t>(-1) - 1;
8538   // We cannot call numeric_limits::max() as it conflicts with the
8539   // max() macro on Windows.
8540 
8541   for (size_t i = 0; i <= max_count; ++i) {
8542     // We know that the atom matches each of the first i characters in str.
8543     if (i >= min_count && MatchRegexAtHead(regex, str + i)) {
8544       // We have enough matches at the head, and the tail matches too.
8545       // Since we only care about *whether* the pattern matches str
8546       // (as opposed to *how* it matches), there is no need to find a
8547       // greedy match.
8548       return true;
8549     }
8550     if (str[i] == '\0' || !AtomMatchesChar(escaped, c, str[i]))
8551       return false;
8552   }
8553   return false;
8554 }
8555 
8556 // Returns true iff regex matches a prefix of str.  regex must be a
8557 // valid simple regular expression and not start with "^", or the
8558 // result is undefined.
MatchRegexAtHead(const char * regex,const char * str)8559 bool MatchRegexAtHead(const char* regex, const char* str) {
8560   if (*regex == '\0')  // An empty regex matches a prefix of anything.
8561     return true;
8562 
8563   // "$" only matches the end of a string.  Note that regex being
8564   // valid guarantees that there's nothing after "$" in it.
8565   if (*regex == '$')
8566     return *str == '\0';
8567 
8568   // Is the first thing in regex an escape sequence?
8569   const bool escaped = *regex == '\\';
8570   if (escaped)
8571     ++regex;
8572   if (IsRepeat(regex[1])) {
8573     // MatchRepetitionAndRegexAtHead() calls MatchRegexAtHead(), so
8574     // here's an indirect recursion.  It terminates as the regex gets
8575     // shorter in each recursion.
8576     return MatchRepetitionAndRegexAtHead(
8577         escaped, regex[0], regex[1], regex + 2, str);
8578   } else {
8579     // regex isn't empty, isn't "$", and doesn't start with a
8580     // repetition.  We match the first atom of regex with the first
8581     // character of str and recurse.
8582     return (*str != '\0') && AtomMatchesChar(escaped, *regex, *str) &&
8583         MatchRegexAtHead(regex + 1, str + 1);
8584   }
8585 }
8586 
8587 // Returns true iff regex matches any substring of str.  regex must be
8588 // a valid simple regular expression, or the result is undefined.
8589 //
8590 // The algorithm is recursive, but the recursion depth doesn't exceed
8591 // the regex length, so we won't need to worry about running out of
8592 // stack space normally.  In rare cases the time complexity can be
8593 // exponential with respect to the regex length + the string length,
8594 // but usually it's must faster (often close to linear).
MatchRegexAnywhere(const char * regex,const char * str)8595 bool MatchRegexAnywhere(const char* regex, const char* str) {
8596   if (regex == NULL || str == NULL)
8597     return false;
8598 
8599   if (*regex == '^')
8600     return MatchRegexAtHead(regex + 1, str);
8601 
8602   // A successful match can be anywhere in str.
8603   do {
8604     if (MatchRegexAtHead(regex, str))
8605       return true;
8606   } while (*str++ != '\0');
8607   return false;
8608 }
8609 
8610 // Implements the RE class.
8611 
~RE()8612 RE::~RE() {
8613   free(const_cast<char*>(pattern_));
8614   free(const_cast<char*>(full_pattern_));
8615 }
8616 
8617 // Returns true iff regular expression re matches the entire str.
FullMatch(const char * str,const RE & re)8618 bool RE::FullMatch(const char* str, const RE& re) {
8619   return re.is_valid_ && MatchRegexAnywhere(re.full_pattern_, str);
8620 }
8621 
8622 // Returns true iff regular expression re matches a substring of str
8623 // (including str itself).
PartialMatch(const char * str,const RE & re)8624 bool RE::PartialMatch(const char* str, const RE& re) {
8625   return re.is_valid_ && MatchRegexAnywhere(re.pattern_, str);
8626 }
8627 
8628 // Initializes an RE from its string representation.
Init(const char * regex)8629 void RE::Init(const char* regex) {
8630   pattern_ = full_pattern_ = NULL;
8631   if (regex != NULL) {
8632     pattern_ = posix::StrDup(regex);
8633   }
8634 
8635   is_valid_ = ValidateRegex(regex);
8636   if (!is_valid_) {
8637     // No need to calculate the full pattern when the regex is invalid.
8638     return;
8639   }
8640 
8641   const size_t len = strlen(regex);
8642   // Reserves enough bytes to hold the regular expression used for a
8643   // full match: we need space to prepend a '^', append a '$', and
8644   // terminate the string with '\0'.
8645   char* buffer = static_cast<char*>(malloc(len + 3));
8646   full_pattern_ = buffer;
8647 
8648   if (*regex != '^')
8649     *buffer++ = '^';  // Makes sure full_pattern_ starts with '^'.
8650 
8651   // We don't use snprintf or strncpy, as they trigger a warning when
8652   // compiled with VC++ 8.0.
8653   memcpy(buffer, regex, len);
8654   buffer += len;
8655 
8656   if (len == 0 || regex[len - 1] != '$')
8657     *buffer++ = '$';  // Makes sure full_pattern_ ends with '$'.
8658 
8659   *buffer = '\0';
8660 }
8661 
8662 #endif  // GTEST_USES_POSIX_RE
8663 
8664 const char kUnknownFile[] = "unknown file";
8665 
8666 // Formats a source file path and a line number as they would appear
8667 // in an error message from the compiler used to compile this code.
FormatFileLocation(const char * file,int line)8668 GTEST_API_ ::std::string FormatFileLocation(const char* file, int line) {
8669   const std::string file_name(file == NULL ? kUnknownFile : file);
8670 
8671   if (line < 0) {
8672     return file_name + ":";
8673   }
8674 #ifdef _MSC_VER
8675   return file_name + "(" + StreamableToString(line) + "):";
8676 #else
8677   return file_name + ":" + StreamableToString(line) + ":";
8678 #endif  // _MSC_VER
8679 }
8680 
8681 // Formats a file location for compiler-independent XML output.
8682 // Although this function is not platform dependent, we put it next to
8683 // FormatFileLocation in order to contrast the two functions.
8684 // Note that FormatCompilerIndependentFileLocation() does NOT append colon
8685 // to the file location it produces, unlike FormatFileLocation().
FormatCompilerIndependentFileLocation(const char * file,int line)8686 GTEST_API_ ::std::string FormatCompilerIndependentFileLocation(
8687     const char* file, int line) {
8688   const std::string file_name(file == NULL ? kUnknownFile : file);
8689 
8690   if (line < 0)
8691     return file_name;
8692   else
8693     return file_name + ":" + StreamableToString(line);
8694 }
8695 
8696 
GTestLog(GTestLogSeverity severity,const char * file,int line)8697 GTestLog::GTestLog(GTestLogSeverity severity, const char* file, int line)
8698     : severity_(severity) {
8699   const char* const marker =
8700       severity == GTEST_INFO ?    "[  INFO ]" :
8701       severity == GTEST_WARNING ? "[WARNING]" :
8702       severity == GTEST_ERROR ?   "[ ERROR ]" : "[ FATAL ]";
8703   GetStream() << ::std::endl << marker << " "
8704               << FormatFileLocation(file, line).c_str() << ": ";
8705 }
8706 
8707 // Flushes the buffers and, if severity is GTEST_FATAL, aborts the program.
~GTestLog()8708 GTestLog::~GTestLog() {
8709   GetStream() << ::std::endl;
8710   if (severity_ == GTEST_FATAL) {
8711     fflush(stderr);
8712     posix::Abort();
8713   }
8714 }
8715 // Disable Microsoft deprecation warnings for POSIX functions called from
8716 // this class (creat, dup, dup2, and close)
8717 #ifdef _MSC_VER
8718 # pragma warning(push)
8719 # pragma warning(disable: 4996)
8720 #endif  // _MSC_VER
8721 
8722 #if GTEST_HAS_STREAM_REDIRECTION
8723 
8724 // Object that captures an output stream (stdout/stderr).
8725 class CapturedStream {
8726  public:
8727   // The ctor redirects the stream to a temporary file.
CapturedStream(int fd)8728   explicit CapturedStream(int fd) : fd_(fd), uncaptured_fd_(dup(fd)) {
8729 # if GTEST_OS_WINDOWS
8730     char temp_dir_path[MAX_PATH + 1] = { '\0' };  // NOLINT
8731     char temp_file_path[MAX_PATH + 1] = { '\0' };  // NOLINT
8732 
8733     ::GetTempPathA(sizeof(temp_dir_path), temp_dir_path);
8734     const UINT success = ::GetTempFileNameA(temp_dir_path,
8735                                             "gtest_redir",
8736                                             0,  // Generate unique file name.
8737                                             temp_file_path);
8738     GTEST_CHECK_(success != 0)
8739         << "Unable to create a temporary file in " << temp_dir_path;
8740     const int captured_fd = creat(temp_file_path, _S_IREAD | _S_IWRITE);
8741     GTEST_CHECK_(captured_fd != -1) << "Unable to open temporary file "
8742                                     << temp_file_path;
8743     filename_ = temp_file_path;
8744 # else
8745     // There's no guarantee that a test has write access to the current
8746     // directory, so we create the temporary file in the /tmp directory
8747     // instead. We use /tmp on most systems, and /sdcard on Android.
8748     // That's because Android doesn't have /tmp.
8749 #  if GTEST_OS_LINUX_ANDROID
8750     // Note: Android applications are expected to call the framework's
8751     // Context.getExternalStorageDirectory() method through JNI to get
8752     // the location of the world-writable SD Card directory. However,
8753     // this requires a Context handle, which cannot be retrieved
8754     // globally from native code. Doing so also precludes running the
8755     // code as part of a regular standalone executable, which doesn't
8756     // run in a Dalvik process (e.g. when running it through 'adb shell').
8757     //
8758     // The location /sdcard is directly accessible from native code
8759     // and is the only location (unofficially) supported by the Android
8760     // team. It's generally a symlink to the real SD Card mount point
8761     // which can be /mnt/sdcard, /mnt/sdcard0, /system/media/sdcard, or
8762     // other OEM-customized locations. Never rely on these, and always
8763     // use /sdcard.
8764     char name_template[] = "/sdcard/gtest_captured_stream.XXXXXX";
8765 #  else
8766     char name_template[] = "/tmp/captured_stream.XXXXXX";
8767 #  endif  // GTEST_OS_LINUX_ANDROID
8768     const int captured_fd = mkstemp(name_template);
8769     filename_ = name_template;
8770 # endif  // GTEST_OS_WINDOWS
8771     fflush(NULL);
8772     dup2(captured_fd, fd_);
8773     close(captured_fd);
8774   }
8775 
~CapturedStream()8776   ~CapturedStream() {
8777     remove(filename_.c_str());
8778   }
8779 
GetCapturedString()8780   std::string GetCapturedString() {
8781     if (uncaptured_fd_ != -1) {
8782       // Restores the original stream.
8783       fflush(NULL);
8784       dup2(uncaptured_fd_, fd_);
8785       close(uncaptured_fd_);
8786       uncaptured_fd_ = -1;
8787     }
8788 
8789     FILE* const file = posix::FOpen(filename_.c_str(), "r");
8790     const std::string content = ReadEntireFile(file);
8791     posix::FClose(file);
8792     return content;
8793   }
8794 
8795  private:
8796   // Reads the entire content of a file as an std::string.
8797   static std::string ReadEntireFile(FILE* file);
8798 
8799   // Returns the size (in bytes) of a file.
8800   static size_t GetFileSize(FILE* file);
8801 
8802   const int fd_;  // A stream to capture.
8803   int uncaptured_fd_;
8804   // Name of the temporary file holding the stderr output.
8805   ::std::string filename_;
8806 
8807   GTEST_DISALLOW_COPY_AND_ASSIGN_(CapturedStream);
8808 };
8809 
8810 // Returns the size (in bytes) of a file.
GetFileSize(FILE * file)8811 size_t CapturedStream::GetFileSize(FILE* file) {
8812   fseek(file, 0, SEEK_END);
8813   return static_cast<size_t>(ftell(file));
8814 }
8815 
8816 // Reads the entire content of a file as a string.
ReadEntireFile(FILE * file)8817 std::string CapturedStream::ReadEntireFile(FILE* file) {
8818   const size_t file_size = GetFileSize(file);
8819   char* const buffer = new char[file_size];
8820 
8821   size_t bytes_last_read = 0;  // # of bytes read in the last fread()
8822   size_t bytes_read = 0;       // # of bytes read so far
8823 
8824   fseek(file, 0, SEEK_SET);
8825 
8826   // Keeps reading the file until we cannot read further or the
8827   // pre-determined file size is reached.
8828   do {
8829     bytes_last_read = fread(buffer+bytes_read, 1, file_size-bytes_read, file);
8830     bytes_read += bytes_last_read;
8831   } while (bytes_last_read > 0 && bytes_read < file_size);
8832 
8833   const std::string content(buffer, bytes_read);
8834   delete[] buffer;
8835 
8836   return content;
8837 }
8838 
8839 # ifdef _MSC_VER
8840 #  pragma warning(pop)
8841 # endif  // _MSC_VER
8842 
8843 static CapturedStream* g_captured_stderr = NULL;
8844 static CapturedStream* g_captured_stdout = NULL;
8845 
8846 // Starts capturing an output stream (stdout/stderr).
CaptureStream(int fd,const char * stream_name,CapturedStream ** stream)8847 void CaptureStream(int fd, const char* stream_name, CapturedStream** stream) {
8848   if (*stream != NULL) {
8849     GTEST_LOG_(FATAL) << "Only one " << stream_name
8850                       << " capturer can exist at a time.";
8851   }
8852   *stream = new CapturedStream(fd);
8853 }
8854 
8855 // Stops capturing the output stream and returns the captured string.
GetCapturedStream(CapturedStream ** captured_stream)8856 std::string GetCapturedStream(CapturedStream** captured_stream) {
8857   const std::string content = (*captured_stream)->GetCapturedString();
8858 
8859   delete *captured_stream;
8860   *captured_stream = NULL;
8861 
8862   return content;
8863 }
8864 
8865 // Starts capturing stdout.
CaptureStdout()8866 void CaptureStdout() {
8867   CaptureStream(kStdOutFileno, "stdout", &g_captured_stdout);
8868 }
8869 
8870 // Starts capturing stderr.
CaptureStderr()8871 void CaptureStderr() {
8872   CaptureStream(kStdErrFileno, "stderr", &g_captured_stderr);
8873 }
8874 
8875 // Stops capturing stdout and returns the captured string.
GetCapturedStdout()8876 std::string GetCapturedStdout() {
8877   return GetCapturedStream(&g_captured_stdout);
8878 }
8879 
8880 // Stops capturing stderr and returns the captured string.
GetCapturedStderr()8881 std::string GetCapturedStderr() {
8882   return GetCapturedStream(&g_captured_stderr);
8883 }
8884 
8885 #endif  // GTEST_HAS_STREAM_REDIRECTION
8886 
8887 #if GTEST_HAS_DEATH_TEST
8888 
8889 // A copy of all command line arguments.  Set by InitGoogleTest().
8890 ::std::vector<testing::internal::string> g_argvs;
8891 
8892 static const ::std::vector<testing::internal::string>* g_injected_test_argvs =
8893                                         NULL;  // Owned.
8894 
SetInjectableArgvs(const::std::vector<testing::internal::string> * argvs)8895 void SetInjectableArgvs(const ::std::vector<testing::internal::string>* argvs) {
8896   if (g_injected_test_argvs != argvs)
8897     delete g_injected_test_argvs;
8898   g_injected_test_argvs = argvs;
8899 }
8900 
GetInjectableArgvs()8901 const ::std::vector<testing::internal::string>& GetInjectableArgvs() {
8902   if (g_injected_test_argvs != NULL) {
8903     return *g_injected_test_argvs;
8904   }
8905   return g_argvs;
8906 }
8907 #endif  // GTEST_HAS_DEATH_TEST
8908 
8909 #if GTEST_OS_WINDOWS_MOBILE
8910 namespace posix {
Abort()8911 void Abort() {
8912   DebugBreak();
8913   TerminateProcess(GetCurrentProcess(), 1);
8914 }
8915 }  // namespace posix
8916 #endif  // GTEST_OS_WINDOWS_MOBILE
8917 
8918 // Returns the name of the environment variable corresponding to the
8919 // given flag.  For example, FlagToEnvVar("foo") will return
8920 // "GTEST_FOO" in the open-source version.
FlagToEnvVar(const char * flag)8921 static std::string FlagToEnvVar(const char* flag) {
8922   const std::string full_flag =
8923       (Message() << GTEST_FLAG_PREFIX_ << flag).GetString();
8924 
8925   Message env_var;
8926   for (size_t i = 0; i != full_flag.length(); i++) {
8927     env_var << ToUpper(full_flag.c_str()[i]);
8928   }
8929 
8930   return env_var.GetString();
8931 }
8932 
8933 // Parses 'str' for a 32-bit signed integer.  If successful, writes
8934 // the result to *value and returns true; otherwise leaves *value
8935 // unchanged and returns false.
ParseInt32(const Message & src_text,const char * str,Int32 * value)8936 bool ParseInt32(const Message& src_text, const char* str, Int32* value) {
8937   // Parses the environment variable as a decimal integer.
8938   char* end = NULL;
8939   const long long_value = strtol(str, &end, 10);  // NOLINT
8940 
8941   // Has strtol() consumed all characters in the string?
8942   if (*end != '\0') {
8943     // No - an invalid character was encountered.
8944     Message msg;
8945     msg << "WARNING: " << src_text
8946         << " is expected to be a 32-bit integer, but actually"
8947         << " has value \"" << str << "\".\n";
8948     printf("%s", msg.GetString().c_str());
8949     fflush(stdout);
8950     return false;
8951   }
8952 
8953   // Is the parsed value in the range of an Int32?
8954   const Int32 result = static_cast<Int32>(long_value);
8955   if (long_value == LONG_MAX || long_value == LONG_MIN ||
8956       // The parsed value overflows as a long.  (strtol() returns
8957       // LONG_MAX or LONG_MIN when the input overflows.)
8958       result != long_value
8959       // The parsed value overflows as an Int32.
8960       ) {
8961     Message msg;
8962     msg << "WARNING: " << src_text
8963         << " is expected to be a 32-bit integer, but actually"
8964         << " has value " << str << ", which overflows.\n";
8965     printf("%s", msg.GetString().c_str());
8966     fflush(stdout);
8967     return false;
8968   }
8969 
8970   *value = result;
8971   return true;
8972 }
8973 
8974 // Reads and returns the Boolean environment variable corresponding to
8975 // the given flag; if it's not set, returns default_value.
8976 //
8977 // The value is considered true iff it's not "0".
BoolFromGTestEnv(const char * flag,bool default_value)8978 bool BoolFromGTestEnv(const char* flag, bool default_value) {
8979   const std::string env_var = FlagToEnvVar(flag);
8980   const char* const string_value = posix::GetEnv(env_var.c_str());
8981   return string_value == NULL ?
8982       default_value : strcmp(string_value, "0") != 0;
8983 }
8984 
8985 // Reads and returns a 32-bit integer stored in the environment
8986 // variable corresponding to the given flag; if it isn't set or
8987 // doesn't represent a valid 32-bit integer, returns default_value.
Int32FromGTestEnv(const char * flag,Int32 default_value)8988 Int32 Int32FromGTestEnv(const char* flag, Int32 default_value) {
8989   const std::string env_var = FlagToEnvVar(flag);
8990   const char* const string_value = posix::GetEnv(env_var.c_str());
8991   if (string_value == NULL) {
8992     // The environment variable is not set.
8993     return default_value;
8994   }
8995 
8996   Int32 result = default_value;
8997   if (!ParseInt32(Message() << "Environment variable " << env_var,
8998                   string_value, &result)) {
8999     printf("The default value %s is used.\n",
9000            (Message() << default_value).GetString().c_str());
9001     fflush(stdout);
9002     return default_value;
9003   }
9004 
9005   return result;
9006 }
9007 
9008 // Reads and returns the string environment variable corresponding to
9009 // the given flag; if it's not set, returns default_value.
StringFromGTestEnv(const char * flag,const char * default_value)9010 const char* StringFromGTestEnv(const char* flag, const char* default_value) {
9011   const std::string env_var = FlagToEnvVar(flag);
9012   const char* const value = posix::GetEnv(env_var.c_str());
9013   return value == NULL ? default_value : value;
9014 }
9015 
9016 }  // namespace internal
9017 }  // namespace testing
9018 // Copyright 2007, Google Inc.
9019 // All rights reserved.
9020 //
9021 // Redistribution and use in source and binary forms, with or without
9022 // modification, are permitted provided that the following conditions are
9023 // met:
9024 //
9025 //     * Redistributions of source code must retain the above copyright
9026 // notice, this list of conditions and the following disclaimer.
9027 //     * Redistributions in binary form must reproduce the above
9028 // copyright notice, this list of conditions and the following disclaimer
9029 // in the documentation and/or other materials provided with the
9030 // distribution.
9031 //     * Neither the name of Google Inc. nor the names of its
9032 // contributors may be used to endorse or promote products derived from
9033 // this software without specific prior written permission.
9034 //
9035 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
9036 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
9037 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
9038 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9039 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
9040 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9041 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
9042 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
9043 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
9044 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
9045 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
9046 //
9047 // Author: wan@google.com (Zhanyong Wan)
9048 
9049 // Google Test - The Google C++ Testing Framework
9050 //
9051 // This file implements a universal value printer that can print a
9052 // value of any type T:
9053 //
9054 //   void ::testing::internal::UniversalPrinter<T>::Print(value, ostream_ptr);
9055 //
9056 // It uses the << operator when possible, and prints the bytes in the
9057 // object otherwise.  A user can override its behavior for a class
9058 // type Foo by defining either operator<<(::std::ostream&, const Foo&)
9059 // or void PrintTo(const Foo&, ::std::ostream*) in the namespace that
9060 // defines Foo.
9061 
9062 #include <ctype.h>
9063 #include <stdio.h>
9064 #include <ostream>  // NOLINT
9065 #include <string>
9066 
9067 namespace testing {
9068 
9069 namespace {
9070 
9071 using ::std::ostream;
9072 
9073 // Prints a segment of bytes in the given object.
PrintByteSegmentInObjectTo(const unsigned char * obj_bytes,size_t start,size_t count,ostream * os)9074 void PrintByteSegmentInObjectTo(const unsigned char* obj_bytes, size_t start,
9075                                 size_t count, ostream* os) {
9076   char text[5] = "";
9077   for (size_t i = 0; i != count; i++) {
9078     const size_t j = start + i;
9079     if (i != 0) {
9080       // Organizes the bytes into groups of 2 for easy parsing by
9081       // human.
9082       if ((j % 2) == 0)
9083         *os << ' ';
9084       else
9085         *os << '-';
9086     }
9087     GTEST_SNPRINTF_(text, sizeof(text), "%02X", obj_bytes[j]);
9088     *os << text;
9089   }
9090 }
9091 
9092 // Prints the bytes in the given value to the given ostream.
PrintBytesInObjectToImpl(const unsigned char * obj_bytes,size_t count,ostream * os)9093 void PrintBytesInObjectToImpl(const unsigned char* obj_bytes, size_t count,
9094                               ostream* os) {
9095   // Tells the user how big the object is.
9096   *os << count << "-byte object <";
9097 
9098   const size_t kThreshold = 132;
9099   const size_t kChunkSize = 64;
9100   // If the object size is bigger than kThreshold, we'll have to omit
9101   // some details by printing only the first and the last kChunkSize
9102   // bytes.
9103   // TODO(wan): let the user control the threshold using a flag.
9104   if (count < kThreshold) {
9105     PrintByteSegmentInObjectTo(obj_bytes, 0, count, os);
9106   } else {
9107     PrintByteSegmentInObjectTo(obj_bytes, 0, kChunkSize, os);
9108     *os << " ... ";
9109     // Rounds up to 2-byte boundary.
9110     const size_t resume_pos = (count - kChunkSize + 1)/2*2;
9111     PrintByteSegmentInObjectTo(obj_bytes, resume_pos, count - resume_pos, os);
9112   }
9113   *os << ">";
9114 }
9115 
9116 }  // namespace
9117 
9118 namespace internal2 {
9119 
9120 // Delegates to PrintBytesInObjectToImpl() to print the bytes in the
9121 // given object.  The delegation simplifies the implementation, which
9122 // uses the << operator and thus is easier done outside of the
9123 // ::testing::internal namespace, which contains a << operator that
9124 // sometimes conflicts with the one in STL.
PrintBytesInObjectTo(const unsigned char * obj_bytes,size_t count,ostream * os)9125 void PrintBytesInObjectTo(const unsigned char* obj_bytes, size_t count,
9126                           ostream* os) {
9127   PrintBytesInObjectToImpl(obj_bytes, count, os);
9128 }
9129 
9130 }  // namespace internal2
9131 
9132 namespace internal {
9133 
9134 // Depending on the value of a char (or wchar_t), we print it in one
9135 // of three formats:
9136 //   - as is if it's a printable ASCII (e.g. 'a', '2', ' '),
9137 //   - as a hexidecimal escape sequence (e.g. '\x7F'), or
9138 //   - as a special escape sequence (e.g. '\r', '\n').
9139 enum CharFormat {
9140   kAsIs,
9141   kHexEscape,
9142   kSpecialEscape
9143 };
9144 
9145 // Returns true if c is a printable ASCII character.  We test the
9146 // value of c directly instead of calling isprint(), which is buggy on
9147 // Windows Mobile.
IsPrintableAscii(wchar_t c)9148 inline bool IsPrintableAscii(wchar_t c) {
9149   return 0x20 <= c && c <= 0x7E;
9150 }
9151 
9152 // Prints a wide or narrow char c as a character literal without the
9153 // quotes, escaping it when necessary; returns how c was formatted.
9154 // The template argument UnsignedChar is the unsigned version of Char,
9155 // which is the type of c.
9156 template <typename UnsignedChar, typename Char>
PrintAsCharLiteralTo(Char c,ostream * os)9157 static CharFormat PrintAsCharLiteralTo(Char c, ostream* os) {
9158   switch (static_cast<wchar_t>(c)) {
9159     case L'\0':
9160       *os << "\\0";
9161       break;
9162     case L'\'':
9163       *os << "\\'";
9164       break;
9165     case L'\\':
9166       *os << "\\\\";
9167       break;
9168     case L'\a':
9169       *os << "\\a";
9170       break;
9171     case L'\b':
9172       *os << "\\b";
9173       break;
9174     case L'\f':
9175       *os << "\\f";
9176       break;
9177     case L'\n':
9178       *os << "\\n";
9179       break;
9180     case L'\r':
9181       *os << "\\r";
9182       break;
9183     case L'\t':
9184       *os << "\\t";
9185       break;
9186     case L'\v':
9187       *os << "\\v";
9188       break;
9189     default:
9190       if (IsPrintableAscii(c)) {
9191         *os << static_cast<char>(c);
9192         return kAsIs;
9193       } else {
9194         *os << "\\x" + String::FormatHexInt(static_cast<UnsignedChar>(c));
9195         return kHexEscape;
9196       }
9197   }
9198   return kSpecialEscape;
9199 }
9200 
9201 // Prints a wchar_t c as if it's part of a string literal, escaping it when
9202 // necessary; returns how c was formatted.
PrintAsStringLiteralTo(wchar_t c,ostream * os)9203 static CharFormat PrintAsStringLiteralTo(wchar_t c, ostream* os) {
9204   switch (c) {
9205     case L'\'':
9206       *os << "'";
9207       return kAsIs;
9208     case L'"':
9209       *os << "\\\"";
9210       return kSpecialEscape;
9211     default:
9212       return PrintAsCharLiteralTo<wchar_t>(c, os);
9213   }
9214 }
9215 
9216 // Prints a char c as if it's part of a string literal, escaping it when
9217 // necessary; returns how c was formatted.
PrintAsStringLiteralTo(char c,ostream * os)9218 static CharFormat PrintAsStringLiteralTo(char c, ostream* os) {
9219   return PrintAsStringLiteralTo(
9220       static_cast<wchar_t>(static_cast<unsigned char>(c)), os);
9221 }
9222 
9223 // Prints a wide or narrow character c and its code.  '\0' is printed
9224 // as "'\\0'", other unprintable characters are also properly escaped
9225 // using the standard C++ escape sequence.  The template argument
9226 // UnsignedChar is the unsigned version of Char, which is the type of c.
9227 template <typename UnsignedChar, typename Char>
PrintCharAndCodeTo(Char c,ostream * os)9228 void PrintCharAndCodeTo(Char c, ostream* os) {
9229   // First, print c as a literal in the most readable form we can find.
9230   *os << ((sizeof(c) > 1) ? "L'" : "'");
9231   const CharFormat format = PrintAsCharLiteralTo<UnsignedChar>(c, os);
9232   *os << "'";
9233 
9234   // To aid user debugging, we also print c's code in decimal, unless
9235   // it's 0 (in which case c was printed as '\\0', making the code
9236   // obvious).
9237   if (c == 0)
9238     return;
9239   *os << " (" << static_cast<int>(c);
9240 
9241   // For more convenience, we print c's code again in hexidecimal,
9242   // unless c was already printed in the form '\x##' or the code is in
9243   // [1, 9].
9244   if (format == kHexEscape || (1 <= c && c <= 9)) {
9245     // Do nothing.
9246   } else {
9247     *os << ", 0x" << String::FormatHexInt(static_cast<UnsignedChar>(c));
9248   }
9249   *os << ")";
9250 }
9251 
PrintTo(unsigned char c,::std::ostream * os)9252 void PrintTo(unsigned char c, ::std::ostream* os) {
9253   PrintCharAndCodeTo<unsigned char>(c, os);
9254 }
PrintTo(signed char c,::std::ostream * os)9255 void PrintTo(signed char c, ::std::ostream* os) {
9256   PrintCharAndCodeTo<unsigned char>(c, os);
9257 }
9258 
9259 // Prints a wchar_t as a symbol if it is printable or as its internal
9260 // code otherwise and also as its code.  L'\0' is printed as "L'\\0'".
PrintTo(wchar_t wc,ostream * os)9261 void PrintTo(wchar_t wc, ostream* os) {
9262   PrintCharAndCodeTo<wchar_t>(wc, os);
9263 }
9264 
9265 // Prints the given array of characters to the ostream.  CharType must be either
9266 // char or wchar_t.
9267 // The array starts at begin, the length is len, it may include '\0' characters
9268 // and may not be NUL-terminated.
9269 template <typename CharType>
PrintCharsAsStringTo(const CharType * begin,size_t len,ostream * os)9270 static void PrintCharsAsStringTo(
9271     const CharType* begin, size_t len, ostream* os) {
9272   const char* const kQuoteBegin = sizeof(CharType) == 1 ? "\"" : "L\"";
9273   *os << kQuoteBegin;
9274   bool is_previous_hex = false;
9275   for (size_t index = 0; index < len; ++index) {
9276     const CharType cur = begin[index];
9277     if (is_previous_hex && IsXDigit(cur)) {
9278       // Previous character is of '\x..' form and this character can be
9279       // interpreted as another hexadecimal digit in its number. Break string to
9280       // disambiguate.
9281       *os << "\" " << kQuoteBegin;
9282     }
9283     is_previous_hex = PrintAsStringLiteralTo(cur, os) == kHexEscape;
9284   }
9285   *os << "\"";
9286 }
9287 
9288 // Prints a (const) char/wchar_t array of 'len' elements, starting at address
9289 // 'begin'.  CharType must be either char or wchar_t.
9290 template <typename CharType>
UniversalPrintCharArray(const CharType * begin,size_t len,ostream * os)9291 static void UniversalPrintCharArray(
9292     const CharType* begin, size_t len, ostream* os) {
9293   // The code
9294   //   const char kFoo[] = "foo";
9295   // generates an array of 4, not 3, elements, with the last one being '\0'.
9296   //
9297   // Therefore when printing a char array, we don't print the last element if
9298   // it's '\0', such that the output matches the string literal as it's
9299   // written in the source code.
9300   if (len > 0 && begin[len - 1] == '\0') {
9301     PrintCharsAsStringTo(begin, len - 1, os);
9302     return;
9303   }
9304 
9305   // If, however, the last element in the array is not '\0', e.g.
9306   //    const char kFoo[] = { 'f', 'o', 'o' };
9307   // we must print the entire array.  We also print a message to indicate
9308   // that the array is not NUL-terminated.
9309   PrintCharsAsStringTo(begin, len, os);
9310   *os << " (no terminating NUL)";
9311 }
9312 
9313 // Prints a (const) char array of 'len' elements, starting at address 'begin'.
UniversalPrintArray(const char * begin,size_t len,ostream * os)9314 void UniversalPrintArray(const char* begin, size_t len, ostream* os) {
9315   UniversalPrintCharArray(begin, len, os);
9316 }
9317 
9318 // Prints a (const) wchar_t array of 'len' elements, starting at address
9319 // 'begin'.
UniversalPrintArray(const wchar_t * begin,size_t len,ostream * os)9320 void UniversalPrintArray(const wchar_t* begin, size_t len, ostream* os) {
9321   UniversalPrintCharArray(begin, len, os);
9322 }
9323 
9324 // Prints the given C string to the ostream.
PrintTo(const char * s,ostream * os)9325 void PrintTo(const char* s, ostream* os) {
9326   if (s == NULL) {
9327     *os << "NULL";
9328   } else {
9329     *os << ImplicitCast_<const void*>(s) << " pointing to ";
9330     PrintCharsAsStringTo(s, strlen(s), os);
9331   }
9332 }
9333 
9334 // MSVC compiler can be configured to define whar_t as a typedef
9335 // of unsigned short. Defining an overload for const wchar_t* in that case
9336 // would cause pointers to unsigned shorts be printed as wide strings,
9337 // possibly accessing more memory than intended and causing invalid
9338 // memory accesses. MSVC defines _NATIVE_WCHAR_T_DEFINED symbol when
9339 // wchar_t is implemented as a native type.
9340 #if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED)
9341 // Prints the given wide C string to the ostream.
PrintTo(const wchar_t * s,ostream * os)9342 void PrintTo(const wchar_t* s, ostream* os) {
9343   if (s == NULL) {
9344     *os << "NULL";
9345   } else {
9346     *os << ImplicitCast_<const void*>(s) << " pointing to ";
9347     PrintCharsAsStringTo(s, wcslen(s), os);
9348   }
9349 }
9350 #endif  // wchar_t is native
9351 
9352 // Prints a ::string object.
9353 #if GTEST_HAS_GLOBAL_STRING
PrintStringTo(const::string & s,ostream * os)9354 void PrintStringTo(const ::string& s, ostream* os) {
9355   PrintCharsAsStringTo(s.data(), s.size(), os);
9356 }
9357 #endif  // GTEST_HAS_GLOBAL_STRING
9358 
PrintStringTo(const::std::string & s,ostream * os)9359 void PrintStringTo(const ::std::string& s, ostream* os) {
9360   PrintCharsAsStringTo(s.data(), s.size(), os);
9361 }
9362 
9363 // Prints a ::wstring object.
9364 #if GTEST_HAS_GLOBAL_WSTRING
PrintWideStringTo(const::wstring & s,ostream * os)9365 void PrintWideStringTo(const ::wstring& s, ostream* os) {
9366   PrintCharsAsStringTo(s.data(), s.size(), os);
9367 }
9368 #endif  // GTEST_HAS_GLOBAL_WSTRING
9369 
9370 #if GTEST_HAS_STD_WSTRING
PrintWideStringTo(const::std::wstring & s,ostream * os)9371 void PrintWideStringTo(const ::std::wstring& s, ostream* os) {
9372   PrintCharsAsStringTo(s.data(), s.size(), os);
9373 }
9374 #endif  // GTEST_HAS_STD_WSTRING
9375 
9376 }  // namespace internal
9377 
9378 }  // namespace testing
9379 // Copyright 2008, Google Inc.
9380 // All rights reserved.
9381 //
9382 // Redistribution and use in source and binary forms, with or without
9383 // modification, are permitted provided that the following conditions are
9384 // met:
9385 //
9386 //     * Redistributions of source code must retain the above copyright
9387 // notice, this list of conditions and the following disclaimer.
9388 //     * Redistributions in binary form must reproduce the above
9389 // copyright notice, this list of conditions and the following disclaimer
9390 // in the documentation and/or other materials provided with the
9391 // distribution.
9392 //     * Neither the name of Google Inc. nor the names of its
9393 // contributors may be used to endorse or promote products derived from
9394 // this software without specific prior written permission.
9395 //
9396 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
9397 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
9398 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
9399 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9400 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
9401 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9402 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
9403 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
9404 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
9405 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
9406 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
9407 //
9408 // Author: mheule@google.com (Markus Heule)
9409 //
9410 // The Google C++ Testing Framework (Google Test)
9411 
9412 
9413 // Indicates that this translation unit is part of Google Test's
9414 // implementation.  It must come before gtest-internal-inl.h is
9415 // included, or there will be a compiler error.  This trick is to
9416 // prevent a user from accidentally including gtest-internal-inl.h in
9417 // his code.
9418 #define GTEST_IMPLEMENTATION_ 1
9419 #undef GTEST_IMPLEMENTATION_
9420 
9421 namespace testing {
9422 
9423 using internal::GetUnitTestImpl;
9424 
9425 // Gets the summary of the failure message by omitting the stack trace
9426 // in it.
ExtractSummary(const char * message)9427 std::string TestPartResult::ExtractSummary(const char* message) {
9428   const char* const stack_trace = strstr(message, internal::kStackTraceMarker);
9429   return stack_trace == NULL ? message :
9430       std::string(message, stack_trace);
9431 }
9432 
9433 // Prints a TestPartResult object.
operator <<(std::ostream & os,const TestPartResult & result)9434 std::ostream& operator<<(std::ostream& os, const TestPartResult& result) {
9435   return os
9436       << result.file_name() << ":" << result.line_number() << ": "
9437       << (result.type() == TestPartResult::kSuccess ? "Success" :
9438           result.type() == TestPartResult::kFatalFailure ? "Fatal failure" :
9439           "Non-fatal failure") << ":\n"
9440       << result.message() << std::endl;
9441 }
9442 
9443 // Appends a TestPartResult to the array.
Append(const TestPartResult & result)9444 void TestPartResultArray::Append(const TestPartResult& result) {
9445   array_.push_back(result);
9446 }
9447 
9448 // Returns the TestPartResult at the given index (0-based).
GetTestPartResult(int index) const9449 const TestPartResult& TestPartResultArray::GetTestPartResult(int index) const {
9450   if (index < 0 || index >= size()) {
9451     printf("\nInvalid index (%d) into TestPartResultArray.\n", index);
9452     internal::posix::Abort();
9453   }
9454 
9455   return array_[index];
9456 }
9457 
9458 // Returns the number of TestPartResult objects in the array.
size() const9459 int TestPartResultArray::size() const {
9460   return static_cast<int>(array_.size());
9461 }
9462 
9463 namespace internal {
9464 
HasNewFatalFailureHelper()9465 HasNewFatalFailureHelper::HasNewFatalFailureHelper()
9466     : has_new_fatal_failure_(false),
9467       original_reporter_(GetUnitTestImpl()->
9468                          GetTestPartResultReporterForCurrentThread()) {
9469   GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(this);
9470 }
9471 
~HasNewFatalFailureHelper()9472 HasNewFatalFailureHelper::~HasNewFatalFailureHelper() {
9473   GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(
9474       original_reporter_);
9475 }
9476 
ReportTestPartResult(const TestPartResult & result)9477 void HasNewFatalFailureHelper::ReportTestPartResult(
9478     const TestPartResult& result) {
9479   if (result.fatally_failed())
9480     has_new_fatal_failure_ = true;
9481   original_reporter_->ReportTestPartResult(result);
9482 }
9483 
9484 }  // namespace internal
9485 
9486 }  // namespace testing
9487 // Copyright 2008 Google Inc.
9488 // All Rights Reserved.
9489 //
9490 // Redistribution and use in source and binary forms, with or without
9491 // modification, are permitted provided that the following conditions are
9492 // met:
9493 //
9494 //     * Redistributions of source code must retain the above copyright
9495 // notice, this list of conditions and the following disclaimer.
9496 //     * Redistributions in binary form must reproduce the above
9497 // copyright notice, this list of conditions and the following disclaimer
9498 // in the documentation and/or other materials provided with the
9499 // distribution.
9500 //     * Neither the name of Google Inc. nor the names of its
9501 // contributors may be used to endorse or promote products derived from
9502 // this software without specific prior written permission.
9503 //
9504 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
9505 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
9506 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
9507 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9508 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
9509 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9510 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
9511 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
9512 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
9513 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
9514 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
9515 //
9516 // Author: wan@google.com (Zhanyong Wan)
9517 
9518 
9519 namespace testing {
9520 namespace internal {
9521 
9522 #if GTEST_HAS_TYPED_TEST_P
9523 
9524 // Skips to the first non-space char in str. Returns an empty string if str
9525 // contains only whitespace characters.
SkipSpaces(const char * str)9526 static const char* SkipSpaces(const char* str) {
9527   while (IsSpace(*str))
9528     str++;
9529   return str;
9530 }
9531 
9532 // Verifies that registered_tests match the test names in
9533 // defined_test_names_; returns registered_tests if successful, or
9534 // aborts the program otherwise.
VerifyRegisteredTestNames(const char * file,int line,const char * registered_tests)9535 const char* TypedTestCasePState::VerifyRegisteredTestNames(
9536     const char* file, int line, const char* registered_tests) {
9537   typedef ::std::set<const char*>::const_iterator DefinedTestIter;
9538   registered_ = true;
9539 
9540   // Skip initial whitespace in registered_tests since some
9541   // preprocessors prefix stringizied literals with whitespace.
9542   registered_tests = SkipSpaces(registered_tests);
9543 
9544   Message errors;
9545   ::std::set<std::string> tests;
9546   for (const char* names = registered_tests; names != NULL;
9547        names = SkipComma(names)) {
9548     const std::string name = GetPrefixUntilComma(names);
9549     if (tests.count(name) != 0) {
9550       errors << "Test " << name << " is listed more than once.\n";
9551       continue;
9552     }
9553 
9554     bool found = false;
9555     for (DefinedTestIter it = defined_test_names_.begin();
9556          it != defined_test_names_.end();
9557          ++it) {
9558       if (name == *it) {
9559         found = true;
9560         break;
9561       }
9562     }
9563 
9564     if (found) {
9565       tests.insert(name);
9566     } else {
9567       errors << "No test named " << name
9568              << " can be found in this test case.\n";
9569     }
9570   }
9571 
9572   for (DefinedTestIter it = defined_test_names_.begin();
9573        it != defined_test_names_.end();
9574        ++it) {
9575     if (tests.count(*it) == 0) {
9576       errors << "You forgot to list test " << *it << ".\n";
9577     }
9578   }
9579 
9580   const std::string& errors_str = errors.GetString();
9581   if (errors_str != "") {
9582     fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(),
9583             errors_str.c_str());
9584     fflush(stderr);
9585     posix::Abort();
9586   }
9587 
9588   return registered_tests;
9589 }
9590 
9591 #endif  // GTEST_HAS_TYPED_TEST_P
9592 
9593 }  // namespace internal
9594 }  // namespace testing
9595