gtest-all.cc
Go to the documentation of this file.
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.
126  public:
127  // The two possible mocking modes of this object.
129  INTERCEPT_ONLY_CURRENT_THREAD, // Intercepts only thread local failures.
130  INTERCEPT_ALL_THREADS // Intercepts all failures.
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
138 
139  // Same as above, but you can choose the interception scope of this object.
141  TestPartResultArray* result);
142 
143  // The d'tor restores the previous test part result reporter.
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 
158 
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.
170  public:
171  // The constructor remembers the arguments.
174  const string& substr);
176  private:
179  const string substr_;
180 
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().
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.
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.
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.
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.
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.
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.
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.
563  public:
564  // The c'tor.
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.
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.
621  bool shuffle_;
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)".
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.
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.
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>
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>
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>
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>
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>
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>
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.
748  public:
749  // Constructor.
750  //
751  // TestPropertyKeyIs has NO default constructor.
752  explicit TestPropertyKeyIs(const std::string& key) : key_(key) {}
753 
754  // Returns true iff the test name of test property matches on key_.
755  bool operator()(const TestProperty& test_property) const {
756  return test_property.key() == key_;
757  }
758 
759  private:
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.
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.
816 
817 // The role interface for getting the OS stack trace as a string.
819  public:
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:
838 };
839 
840 // A working implementation of the OsStackTraceGetterInterface interface.
842  public:
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.
862 
864 };
865 
866 // Information about a Google Test trace point.
867 struct TraceInfo {
868  const char* file;
869  int line;
871 };
872 
873 // This is the default global test part result reporter used in UnitTestImpl.
874 // This class should only be used by UnitTestImpl.
877  public:
879  // Implements the TestPartResultReporterInterface. Reports the test part
880  // result in the current test.
881  virtual void ReportTestPartResult(const TestPartResult& result);
882 
883  private:
885 
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.
893  public:
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:
901 
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.
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 repoter 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 repoter 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(
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(
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.
971  TimeInMillis start_timestamp() const { return start_timestamp_; }
972 
973  // Gets the elapsed time, in milliseconds.
974  TimeInMillis elapsed_time() const { return elapsed_time_; }
975 
976  // Returns true iff the unit test passed (i.e. all test cases passed).
977  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).
981  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.
987  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.
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.
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.
1007  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
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.
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.
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_.
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.
1113  ForEach(test_cases_, TestCase::ClearTestCaseResult);
1114  }
1115 
1116  // Clears the results of ad-hoc test assertions.
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 
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 
1143  const TestCase* current_test_case() const { return current_test_case_; }
1144  TestInfo* current_test_info() { return current_test_info_; }
1145  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.
1149  std::vector<Environment*>& environments() { return environments_; }
1150 
1151  // Getters for the per-thread Google Test trace stack.
1152  std::vector<TraceInfo>& gtest_trace_stack() {
1153  return *(gtest_trace_stack_.pointer());
1154  }
1155  const std::vector<TraceInfo>& gtest_trace_stack() const {
1156  return gtest_trace_stack_.get();
1157  }
1158 
1159 #if GTEST_HAS_DEATH_TEST
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.
1167  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.
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.
1199  int random_seed() const { return random_seed_; }
1200 
1201  // Gets the random number generator.
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.
1213  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.
1220  void set_catch_exceptions(bool value) { catch_exceptions_ = value; }
1221 
1222  // The UnitTest object that owns this implementation object.
1224 
1225  // The working directory when the first TEST() or TEST_F() was
1226  // executed.
1228 
1229  // The default test part result reporters.
1233 
1234  // Points to (but doesn't own) the global test part result reporter.
1236 
1237  // Protects read and write access to global_test_part_result_reporter_.
1239 
1240  // Points to (but doesn't own) the 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.
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.
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.
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_.
1291 
1292  // The list of event listeners that can be used to track events inside
1293  // Google Test.
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.
1301 
1302  // True iff PostFlagParsingInit() has been called.
1304 
1305  // The random number seed used at the beginning of the test run.
1307 
1308  // Our random number generator.
1310 
1311  // The time of the test program start, in ms from the start of the
1312  // UNIX epoch.
1314 
1315  // How long the test took to run, in milliseconds.
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_;
1323 #endif // GTEST_HAS_DEATH_TEST
1324 
1325  // A per-thread stack of traces created by the SCOPED_TRACE() macro.
1327 
1328  // The value of GTEST_FLAG(catch_exceptions) at the moment RunAllTests()
1329  // starts.
1331 
1333 }; // class UnitTestImpl
1334 
1335 // Convenience function for accessing the global UnitTest
1336 // implementation object.
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:
1376  AutoHandle() : handle_(INVALID_HANDLE_VALUE) {}
1377  explicit AutoHandle(HANDLE handle) : handle_(handle) {}
1378 
1379  ~AutoHandle() { Reset(); }
1380 
1381  HANDLE Get() const { return handle_; }
1382  void Reset() { Reset(INVALID_HANDLE_VALUE); }
1383  void Reset(HANDLE handle) {
1384  if (handle != handle_) {
1385  if (handle_ != INVALID_HANDLE_VALUE)
1386  ::CloseHandle(handle_);
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>
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.
1451  public:
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 
1458  static void ClearTestPartResults(TestResult* test_result) {
1459  test_result->ClearTestPartResults();
1460  }
1461 
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:
1476  virtual ~AbstractSocketWriter() {}
1477 
1478  // Sends a string to the socket.
1479  virtual void Send(const string& message) = 0;
1480 
1481  // Closes the socket.
1482  virtual void CloseConnection() {}
1483 
1484  // Sends a string and a newline to the socket.
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:
1493  SocketWriter(const string& host, const string& port)
1494  : sockfd_(-1), host_name_(host), port_num_(port) {
1495  MakeConnection();
1496  }
1497 
1498  virtual ~SocketWriter() {
1499  if (sockfd_ != -1)
1500  CloseConnection();
1501  }
1502 
1503  // Sends a string to the socket.
1504  virtual void Send(const string& message) {
1505  GTEST_CHECK_(sockfd_ != -1)
1506  << "Send() can be called only when there is a connection.";
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.
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 
1539  StreamingListener(const string& host, const string& port)
1540  : socket_writer_(new SocketWriter(host, port)) { Start(); }
1541 
1542  explicit StreamingListener(AbstractSocketWriter* socket_writer)
1543  : socket_writer_(socket_writer) { Start(); }
1544 
1545  void OnTestProgramStart(const UnitTest& /* unit_test */) {
1546  SendLn("event=TestProgramStart");
1547  }
1548 
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 
1558  void OnTestIterationStart(const UnitTest& /* unit_test */, int iteration) {
1559  SendLn("event=TestIterationStart&iteration=" +
1560  StreamableToString(iteration));
1561  }
1562 
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 
1569  void OnTestCaseStart(const TestCase& test_case) {
1570  SendLn(std::string("event=TestCaseStart&name=") + test_case.name());
1571  }
1572 
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 
1579  void OnTestStart(const TestInfo& test_info) {
1580  SendLn(std::string("event=TestStart&name=") + test_info.name());
1581  }
1582 
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 
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.
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.
1605  void Start() { SendLn("gtest_streaming_protocol_version=1.0"); }
1606 
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;
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 
1669 static const char* GetDefaultFilter() {
1670  return kUniversalFilter;
1671 }
1672 
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 
1679  break_on_failure,
1680  internal::BoolFromGTestEnv("break_on_failure", false),
1681  "True iff a failed assertion should be a debugger break-point.");
1682 
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 
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 
1698  filter,
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 
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 
1722  print_time,
1723  internal::BoolFromGTestEnv("print_time", true),
1724  "True iff " GTEST_NAME_
1725  " should display elapsed time in text output.");
1726 
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 
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 
1740  show_internal_stack_frames, false,
1741  "True iff " GTEST_NAME_ " should include internal stack frames when "
1742  "printing test failure stack traces.");
1743 
1745  shuffle,
1746  internal::BoolFromGTestEnv("shuffle", false),
1747  "True iff " GTEST_NAME_
1748  " should randomize tests' order on every run.");
1749 
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 
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 
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.
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.
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.
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.
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.
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.
1826 static bool ShouldRunTestCase(const TestCase* test_case) {
1827  return test_case->should_run();
1828 }
1829 
1830 // AssertHelper constructor.
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 
1839  delete data_;
1840 }
1841 
1842 // Message assignment, for assertion streaming support.
1843 void AssertHelper::operator=(const Message& message) const {
1845  AddTestPartResult(data_->type, data_->file, data_->line,
1846  AppendUserMessage(data_->message, message),
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.
1858 
1859 // Returns the current application's name, removing directory path if that
1860 // is present.
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.
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.
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)
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 
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.
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 
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.
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.
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.
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.
2036  InterceptMode intercept_mode, TestPartResultArray* result)
2037  : intercept_mode_(intercept_mode),
2038  result_(result) {
2039  Init();
2040 }
2041 
2046  impl->SetGlobalTestPartResultReporter(this);
2047  } else {
2050  }
2051 }
2052 
2053 // The d'tor restores the test part result reporter used by Google Test
2054 // before.
2059  } else {
2061  }
2062 }
2063 
2064 // Increments the test part result count and remembers the result.
2065 // This method is from the TestPartResultReporterInterface interface.
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.
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().
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.
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.
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.
2146 }
2147 
2149  UnitTestImpl* unit_test) : unit_test_(unit_test) {}
2150 
2152  const TestPartResult& result) {
2155 }
2156 
2158  UnitTestImpl* unit_test) : unit_test_(unit_test) {}
2159 
2161  const TestPartResult& result) {
2163 }
2164 
2165 // Returns the global test part result reporter.
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.
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.
2182  return per_thread_test_part_result_reporter_.get();
2183 }
2184 
2185 // Sets the test part result reporter for the current thread.
2187  TestPartResultReporterInterface* reporter) {
2188  per_thread_test_part_result_reporter_.set(reporter);
2189 }
2190 
2191 // Gets the number of successful test cases.
2193  return CountIf(test_cases_, TestCasePassed);
2194 }
2195 
2196 // Gets the number of failed test cases.
2198  return CountIf(test_cases_, TestCaseFailed);
2199 }
2200 
2201 // Gets the number of all test cases.
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.
2209  return CountIf(test_cases_, ShouldRunTestCase);
2210 }
2211 
2212 // Gets the number of successful tests.
2215 }
2216 
2217 // Gets the number of failed tests.
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.
2224  return SumOverTestCaseList(test_cases_,
2226 }
2227 
2228 // Gets the number of disabled tests.
2230  return SumOverTestCaseList(test_cases_, &TestCase::disabled_test_count);
2231 }
2232 
2233 // Gets the number of tests to be printed in the XML report.
2236 }
2237 
2238 // Gets the number of all tests.
2240  return SumOverTestCaseList(test_cases_, &TestCase::total_test_count);
2241 }
2242 
2243 // Gets the number of tests that should run.
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.
2259  (void)skip_count;
2260  return "";
2261 }
2262 
2263 // Returns the current time in milliseconds.
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;
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.
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.
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.
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.
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.
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.
2403 Message& Message::operator <<(const wchar_t* wide_c_str) {
2404  return *this << internal::String::ShowWideCString(wide_c_str);
2405 }
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.
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.
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".
2432 }
2433 
2434 // AssertionResult constructors.
2435 // Used in EXPECT_TRUE/FALSE(assertion_result).
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.
2445  AssertionResult negation(!success_);
2446  if (message_.get() != NULL)
2447  negation << *message_;
2448  return negation;
2449 }
2450 
2451 // Makes a successful assertion result.
2453  return AssertionResult(true);
2454 }
2455 
2456 // Makes a failed assertion result.
2458  return AssertionResult(false);
2459 }
2460 
2461 // Makes a failed assertion result with the given failure message.
2462 // Deprecated; use AssertionFailure() << 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.
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.
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.
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>
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.
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.
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.
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.
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.
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.
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.
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 
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 
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>
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>
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 
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 
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 
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 
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 
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 
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
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 
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
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));
2859  << "Expected: " << expr << " " << expected << ".\n"
2860  << " Actual: " << error_hex << " " << error_text << "\n";
2861 }
2862 
2863 } // namespace
2864 
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 
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.
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)".
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.
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.
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.
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)".
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.
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.
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.
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.
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.
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.
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".
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".
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".
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.
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.
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.
3179  : death_test_count_(0),
3180  elapsed_time_(0) {
3181 }
3182 
3183 // D'tor.
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.
3191  if (i < 0 || i >= total_part_count())
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.
3200  if (i < 0 || i >= test_property_count())
3202  return test_properties_.at(i);
3203 }
3204 
3205 // Clears the test part results.
3207  test_part_results_.clear();
3208 }
3209 
3210 // Adds a test part result to the list.
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.
3218 void TestResult::RecordProperty(const std::string& xml_element,
3219  const TestProperty& test_property) {
3220  if (!ValidateTestProperty(xml_element, test_property)) {
3221  return;
3222  }
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>
3269 std::vector<std::string> ArrayAsVector(const char* const (&array)[kSize]) {
3270  return std::vector<std::string>(array, array + kSize);
3271 }
3272 
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 
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 
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.
3317  const TestProperty& test_property) {
3318  return ValidateTestPropertyName(test_property.key(),
3319  GetReservedAttributesForElement(xml_element));
3320 }
3321 
3322 // Clears the object.
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.
3331 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.
3340 static bool TestPartFatallyFailed(const TestPartResult& result) {
3341  return result.fatally_failed();
3342 }
3343 
3344 // Returns true iff the test fatally failed.
3347 }
3348 
3349 // Returns true iff the test part non-fatally failed.
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.
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.
3362  return static_cast<int>(test_part_results_.size());
3363 }
3364 
3365 // Returns the number of the test properties.
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.
3376  : gtest_flag_saver_(new internal::GTestFlagSaver) {
3377 }
3378 
3379 // The d'tor restores the values of all Google Test flags.
3381  delete gtest_flag_saver_;
3382 }
3383 
3384 // Sets up the test fixture.
3385 //
3386 // A sub-class may override this.
3387 void Test::SetUp() {
3388 }
3389 
3390 // Tears down the test fixture.
3391 //
3392 // A sub-class may override this.
3394 }
3395 
3396 // Allows user supplied key value pairs to be recorded for later output.
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.
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 
3411  const std::string& message) {
3412  // This function is a friend of UnitTest and as such has access to
3413  // 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.
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).
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.
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 
3526  const TestPartResult& test_part_result);
3527 
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>
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);
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>
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
3607  FormatCxxExceptionMessage(e.what(), location));
3608  } catch (...) { // NOLINT
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.
3625 void Test::Run() {
3626  if (!HasSameFixtureClass()) return;
3627 
3631  // We will run the test only if SetUp() was successful.
3632  if (!HasFatalFailure()) {
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.
3643  this, &Test::TearDown, "TearDown()");
3644 }
3645 
3646 // Returns true iff the current test has a fatal failure.
3649 }
3650 
3651 // Returns true iff the current test has a non-fatal failure.
3655 }
3656 
3657 // class TestInfo
3658 
3659 // Constructs a TestInfo object. It assumes ownership of the test factory
3660 // object.
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.
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.
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
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 class TestNameIs {
3748  public:
3749  // Constructor.
3750  //
3751  // TestNameIs has NO default constructor.
3752  explicit TestNameIs(const char* name)
3753  : name_(name) {}
3754 
3755  // Returns true iff the test name of test_info matches name_.
3756  bool operator()(const TestInfo * test_info) const {
3757  return test_info && test_info->name() == name_;
3758  }
3759 
3760  private:
3762 };
3763 
3764 } // namespace
3765 
3766 namespace internal {
3767 
3768 // This method expands all parameterized tests registered with macros TEST_P
3769 // and INSTANTIATE_TEST_CASE_P into regular tests and registers those.
3770 // This will be done just once during the program runtime.
3771 void UnitTestImpl::RegisterParameterizedTests() {
3772 #if GTEST_HAS_PARAM_TEST
3773  if (!parameterized_tests_registered_) {
3774  parameterized_test_registry_.RegisterTests();
3775  parameterized_tests_registered_ = true;
3776  }
3777 #endif
3778 }
3779 
3780 } // namespace internal
3781 
3782 // Creates the test object, runs it, records its result, and then
3783 // deletes it.
3785  if (!should_run_) return;
3786 
3787  // Tells UnitTest where to store test result.
3789  impl->set_current_test_info(this);
3790 
3792 
3793  // Notifies the unit test event listeners that a test is about to start.
3794  repeater->OnTestStart(*this);
3795 
3797 
3799 
3800  // Creates the test object.
3803  "the test fixture's constructor");
3804 
3805  // Runs the test only if the test object was created and its
3806  // constructor didn't generate a fatal failure.
3807  if ((test != NULL) && !Test::HasFatalFailure()) {
3808  // This doesn't throw as all user code that can throw are wrapped into
3809  // exception handling code.
3810  test->Run();
3811  }
3812 
3813  // Deletes the test object.
3816  test, &Test::DeleteSelf_, "the test fixture's destructor");
3817 
3819 
3820  // Notifies the unit test event listener that a test has just finished.
3821  repeater->OnTestEnd(*this);
3822 
3823  // Tells UnitTest to stop associating assertion results to this
3824  // test.
3825  impl->set_current_test_info(NULL);
3826 }
3827 
3828 // class TestCase
3829 
3830 // Gets the number of successful tests in this test case.
3832  return CountIf(test_info_list_, TestPassed);
3833 }
3834 
3835 // Gets the number of failed tests in this test case.
3837  return CountIf(test_info_list_, TestFailed);
3838 }
3839 
3840 // Gets the number of disabled tests that will be reported in the XML report.
3842  return CountIf(test_info_list_, TestReportableDisabled);
3843 }
3844 
3845 // Gets the number of disabled tests in this test case.
3847  return CountIf(test_info_list_, TestDisabled);
3848 }
3849 
3850 // Gets the number of tests to be printed in the XML report.
3852  return CountIf(test_info_list_, TestReportable);
3853 }
3854 
3855 // Get the number of tests in this test case that should run.
3857  return CountIf(test_info_list_, ShouldRunTest);
3858 }
3859 
3860 // Gets the number of all tests.
3862  return static_cast<int>(test_info_list_.size());
3863 }
3864 
3865 // Creates a TestCase with the given name.
3866 //
3867 // Arguments:
3868 //
3869 // name: name of the test case
3870 // a_type_param: the name of the test case's type parameter, or NULL if
3871 // this is not a typed or a type-parameterized test case.
3872 // set_up_tc: pointer to the function that sets up the test case
3873 // tear_down_tc: pointer to the function that tears down the test case
3874 TestCase::TestCase(const char* a_name, const char* a_type_param,
3875  Test::SetUpTestCaseFunc set_up_tc,
3876  Test::TearDownTestCaseFunc tear_down_tc)
3877  : name_(a_name),
3878  type_param_(a_type_param ? new std::string(a_type_param) : NULL),
3879  set_up_tc_(set_up_tc),
3880  tear_down_tc_(tear_down_tc),
3881  should_run_(false),
3882  elapsed_time_(0) {
3883 }
3884 
3885 // Destructor of TestCase.
3887  // Deletes every Test in the collection.
3888  ForEach(test_info_list_, internal::Delete<TestInfo>);
3889 }
3890 
3891 // Returns the i-th test among all the tests. i can range from 0 to
3892 // total_test_count() - 1. If i is not in that range, returns NULL.
3893 const TestInfo* TestCase::GetTestInfo(int i) const {
3894  const int index = GetElementOr(test_indices_, i, -1);
3895  return index < 0 ? NULL : test_info_list_[index];
3896 }
3897 
3898 // Returns the i-th test among all the tests. i can range from 0 to
3899 // total_test_count() - 1. If i is not in that range, returns NULL.
3901  const int index = GetElementOr(test_indices_, i, -1);
3902  return index < 0 ? NULL : test_info_list_[index];
3903 }
3904 
3905 // Adds a test to this test case. Will delete the test upon
3906 // destruction of the TestCase object.
3907 void TestCase::AddTestInfo(TestInfo * test_info) {
3908  test_info_list_.push_back(test_info);
3909  test_indices_.push_back(static_cast<int>(test_indices_.size()));
3910 }
3911 
3912 // Runs every test in this TestCase.
3914  if (!should_run_) return;
3915 
3917  impl->set_current_test_case(this);
3918 
3920 
3921  repeater->OnTestCaseStart(*this);
3924  this, &TestCase::RunSetUpTestCase, "SetUpTestCase()");
3925 
3927  for (int i = 0; i < total_test_count(); i++) {
3928  GetMutableTestInfo(i)->Run();
3929  }
3931 
3934  this, &TestCase::RunTearDownTestCase, "TearDownTestCase()");
3935 
3936  repeater->OnTestCaseEnd(*this);
3937  impl->set_current_test_case(NULL);
3938 }
3939 
3940 // Clears the results of all tests in this test case.
3944 }
3945 
3946 // Shuffles the tests in this test case.
3948  Shuffle(random, &test_indices_);
3949 }
3950 
3951 // Restores the test order to before the first shuffle.
3953  for (size_t i = 0; i < test_indices_.size(); i++) {
3954  test_indices_[i] = static_cast<int>(i);
3955  }
3956 }
3957 
3958 // Formats a countable noun. Depending on its quantity, either the
3959 // singular form or the plural form is used. e.g.
3960 //
3961 // FormatCountableNoun(1, "formula", "formuli") returns "1 formula".
3962 // FormatCountableNoun(5, "book", "books") returns "5 books".
3964  const char * singular_form,
3965  const char * plural_form) {
3966  return internal::StreamableToString(count) + " " +
3967  (count == 1 ? singular_form : plural_form);
3968 }
3969 
3970 // Formats the count of tests.
3971 static std::string FormatTestCount(int test_count) {
3972  return FormatCountableNoun(test_count, "test", "tests");
3973 }
3974 
3975 // Formats the count of test cases.
3976 static std::string FormatTestCaseCount(int test_case_count) {
3977  return FormatCountableNoun(test_case_count, "test case", "test cases");
3978 }
3979 
3980 // Converts a TestPartResult::Type enum to human-friendly string
3981 // representation. Both kNonFatalFailure and kFatalFailure are translated
3982 // to "Failure", as the user usually doesn't care about the difference
3983 // between the two when viewing the test result.
3985  switch (type) {
3987  return "Success";
3988 
3991 #ifdef _MSC_VER
3992  return "error: ";
3993 #else
3994  return "Failure\n";
3995 #endif
3996  default:
3997  return "Unknown result type";
3998  }
3999 }
4000 
4001 namespace internal {
4002 
4003 // Prints a TestPartResult to an std::string.
4005  const TestPartResult& test_part_result) {
4006  return (Message()
4007  << internal::FormatFileLocation(test_part_result.file_name(),
4008  test_part_result.line_number())
4009  << " " << TestPartResultTypeToString(test_part_result.type())
4010  << test_part_result.message()).GetString();
4011 }
4012 
4013 // Prints a TestPartResult.
4014 static void PrintTestPartResult(const TestPartResult& test_part_result) {
4015  const std::string& result =
4016  PrintTestPartResultToString(test_part_result);
4017  printf("%s\n", result.c_str());
4018  fflush(stdout);
4019  // If the test program runs in Visual Studio or a debugger, the
4020  // following statements add the test part result message to the Output
4021  // window such that the user can double-click on it to jump to the
4022  // corresponding source code location; otherwise they do nothing.
4023 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
4024  // We don't call OutputDebugString*() on Windows Mobile, as printing
4025  // to stdout is done by OutputDebugString() there already - we don't
4026  // want the same message printed twice.
4027  ::OutputDebugStringA(result.c_str());
4028  ::OutputDebugStringA("\n");
4029 #endif
4030 }
4031 
4032 // class PrettyUnitTestResultPrinter
4033 
4039 };
4040 
4041 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
4042 
4043 // Returns the character attribute for the given color.
4044 WORD GetColorAttribute(GTestColor color) {
4045  switch (color) {
4046  case COLOR_RED: return FOREGROUND_RED;
4047  case COLOR_GREEN: return FOREGROUND_GREEN;
4048  case COLOR_YELLOW: return FOREGROUND_RED | FOREGROUND_GREEN;
4049  default: return 0;
4050  }
4051 }
4052 
4053 #else
4054 
4055 // Returns the ANSI color code for the given color. COLOR_DEFAULT is
4056 // an invalid input.
4057 const char* GetAnsiColorCode(GTestColor color) {
4058  switch (color) {
4059  case COLOR_RED: return "1";
4060  case COLOR_GREEN: return "2";
4061  case COLOR_YELLOW: return "3";
4062  default: return NULL;
4063  };
4064 }
4065 
4066 #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
4067 
4068 // Returns true iff Google Test should use colors in the output.
4069 bool ShouldUseColor(bool stdout_is_tty) {
4070  const char* const gtest_color = GTEST_FLAG(color).c_str();
4071 
4072  if (String::CaseInsensitiveCStringEquals(gtest_color, "auto")) {
4073 #if GTEST_OS_WINDOWS
4074  // On Windows the TERM variable is usually not set, but the
4075  // console there does support colors.
4076  return stdout_is_tty;
4077 #else
4078  // On non-Windows platforms, we rely on the TERM variable.
4079  const char* const term = posix::GetEnv("TERM");
4080  const bool term_supports_color =
4081  String::CStringEquals(term, "xterm") ||
4082  String::CStringEquals(term, "xterm-color") ||
4083  String::CStringEquals(term, "xterm-256color") ||
4084  String::CStringEquals(term, "screen") ||
4085  String::CStringEquals(term, "screen-256color") ||
4086  String::CStringEquals(term, "linux") ||
4087  String::CStringEquals(term, "cygwin");
4088  return stdout_is_tty && term_supports_color;
4089 #endif // GTEST_OS_WINDOWS
4090  }
4091 
4092  return String::CaseInsensitiveCStringEquals(gtest_color, "yes") ||
4093  String::CaseInsensitiveCStringEquals(gtest_color, "true") ||
4094  String::CaseInsensitiveCStringEquals(gtest_color, "t") ||
4095  String::CStringEquals(gtest_color, "1");
4096  // We take "yes", "true", "t", and "1" as meaning "yes". If the
4097  // value is neither one of these nor "auto", we treat it as "no" to
4098  // be conservative.
4099 }
4100 
4101 // Helpers for printing colored strings to stdout. Note that on Windows, we
4102 // cannot simply emit special characters and have the terminal change colors.
4103 // This routine must actually emit the characters rather than return a string
4104 // that would be colored when printed, as can be done on Linux.
4105 void ColoredPrintf(GTestColor color, const char* fmt, ...) {
4106  va_list args;
4107  va_start(args, fmt);
4108 
4109 #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS || GTEST_OS_IOS
4110  const bool use_color = false;
4111 #else
4112  static const bool in_color_mode =
4114  const bool use_color = in_color_mode && (color != COLOR_DEFAULT);
4115 #endif // GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS
4116  // The '!= 0' comparison is necessary to satisfy MSVC 7.1.
4117 
4118  if (!use_color) {
4119  vprintf(fmt, args);
4120  va_end(args);
4121  return;
4122  }
4123 
4124 #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
4125  const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
4126 
4127  // Gets the current text color.
4128  CONSOLE_SCREEN_BUFFER_INFO buffer_info;
4129  GetConsoleScreenBufferInfo(stdout_handle, &buffer_info);
4130  const WORD old_color_attrs = buffer_info.wAttributes;
4131 
4132  // We need to flush the stream buffers into the console before each
4133  // SetConsoleTextAttribute call lest it affect the text that is already
4134  // printed but has not yet reached the console.
4135  fflush(stdout);
4136  SetConsoleTextAttribute(stdout_handle,
4137  GetColorAttribute(color) | FOREGROUND_INTENSITY);
4138  vprintf(fmt, args);
4139 
4140  fflush(stdout);
4141  // Restores the text color.
4142  SetConsoleTextAttribute(stdout_handle, old_color_attrs);
4143 #else
4144  printf("\033[0;3%sm", GetAnsiColorCode(color));
4145  vprintf(fmt, args);
4146  printf("\033[m"); // Resets the terminal to default.
4147 #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
4148  va_end(args);
4149 }
4150 
4151 // Text printed in Google Test's text output and --gunit_list_tests
4152 // output to label the type parameter and value parameter for a test.
4153 static const char kTypeParamLabel[] = "TypeParam";
4154 static const char kValueParamLabel[] = "GetParam()";
4155 
4156 void PrintFullTestCommentIfPresent(const TestInfo& test_info) {
4157  const char* const type_param = test_info.type_param();
4158  const char* const value_param = test_info.value_param();
4159 
4160  if (type_param != NULL || value_param != NULL) {
4161  printf(", where ");
4162  if (type_param != NULL) {
4163  printf("%s = %s", kTypeParamLabel, type_param);
4164  if (value_param != NULL)
4165  printf(" and ");
4166  }
4167  if (value_param != NULL) {
4168  printf("%s = %s", kValueParamLabel, value_param);
4169  }
4170  }
4171 }
4172 
4173 // This class implements the TestEventListener interface.
4174 //
4175 // Class PrettyUnitTestResultPrinter is copyable.
4177  public:
4179  static void PrintTestName(const char * test_case, const char * test) {
4180  printf("%s.%s", test_case, test);
4181  }
4182 
4183  // The following methods override what's in the TestEventListener class.
4184  virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {}
4185  virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration);
4186  virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test);
4187  virtual void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) {}
4188  virtual void OnTestCaseStart(const TestCase& test_case);
4189  virtual void OnTestStart(const TestInfo& test_info);
4190  virtual void OnTestPartResult(const TestPartResult& result);
4191  virtual void OnTestEnd(const TestInfo& test_info);
4192  virtual void OnTestCaseEnd(const TestCase& test_case);
4193  virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test);
4194  virtual void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) {}
4195  virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
4196  virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) {}
4197 
4198  private:
4199  static void PrintFailedTests(const UnitTest& unit_test);
4200 };
4201 
4202  // Fired before each iteration of tests starts.
4203 void PrettyUnitTestResultPrinter::OnTestIterationStart(
4204  const UnitTest& unit_test, int iteration) {
4205  if (GTEST_FLAG(repeat) != 1)
4206  printf("\nRepeating all tests (iteration %d) . . .\n\n", iteration + 1);
4207 
4208  const char* const filter = GTEST_FLAG(filter).c_str();
4209 
4210  // Prints the filter if it's not *. This reminds the user that some
4211  // tests may be skipped.
4212  if (!String::CStringEquals(filter, kUniversalFilter)) {
4214  "Note: %s filter = %s\n", GTEST_NAME_, filter);
4215  }
4216 
4217  if (internal::ShouldShard(kTestTotalShards, kTestShardIndex, false)) {
4218  const Int32 shard_index = Int32FromEnvOrDie(kTestShardIndex, -1);
4220  "Note: This is test shard %d of %s.\n",
4221  static_cast<int>(shard_index) + 1,
4222  internal::posix::GetEnv(kTestTotalShards));
4223  }
4224 
4225  if (GTEST_FLAG(shuffle)) {
4227  "Note: Randomizing tests' orders with a seed of %d .\n",
4228  unit_test.random_seed());
4229  }
4230 
4231  ColoredPrintf(COLOR_GREEN, "[==========] ");
4232  printf("Running %s from %s.\n",
4233  FormatTestCount(unit_test.test_to_run_count()).c_str(),
4234  FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str());
4235  fflush(stdout);
4236 }
4237 
4238 void PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart(
4239  const UnitTest& /*unit_test*/) {
4240  ColoredPrintf(COLOR_GREEN, "[----------] ");
4241  printf("Global test environment set-up.\n");
4242  fflush(stdout);
4243 }
4244 
4245 void PrettyUnitTestResultPrinter::OnTestCaseStart(const TestCase& test_case) {
4246  const std::string counts =
4247  FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
4248  ColoredPrintf(COLOR_GREEN, "[----------] ");
4249  printf("%s from %s", counts.c_str(), test_case.name());
4250  if (test_case.type_param() == NULL) {
4251  printf("\n");
4252  } else {
4253  printf(", where %s = %s\n", kTypeParamLabel, test_case.type_param());
4254  }
4255  fflush(stdout);
4256 }
4257 
4258 void PrettyUnitTestResultPrinter::OnTestStart(const TestInfo& test_info) {
4259  ColoredPrintf(COLOR_GREEN, "[ RUN ] ");
4260  PrintTestName(test_info.test_case_name(), test_info.name());
4261  printf("\n");
4262  fflush(stdout);
4263 }
4264 
4265 // Called after an assertion failure.
4266 void PrettyUnitTestResultPrinter::OnTestPartResult(
4267  const TestPartResult& result) {
4268  // If the test part succeeded, we don't need to do anything.
4269  if (result.type() == TestPartResult::kSuccess)
4270  return;
4271 
4272  // Print failure message from the assertion (e.g. expected this and got that).
4273  PrintTestPartResult(result);
4274  fflush(stdout);
4275 }
4276 
4277 void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) {
4278  if (test_info.result()->Passed()) {
4279  ColoredPrintf(COLOR_GREEN, "[ OK ] ");
4280  } else {
4281  ColoredPrintf(COLOR_RED, "[ FAILED ] ");
4282  }
4283  PrintTestName(test_info.test_case_name(), test_info.name());
4284  if (test_info.result()->Failed())
4285  PrintFullTestCommentIfPresent(test_info);
4286 
4287  if (GTEST_FLAG(print_time)) {
4288  printf(" (%s ms)\n", internal::StreamableToString(
4289  test_info.result()->elapsed_time()).c_str());
4290  } else {
4291  printf("\n");
4292  }
4293  fflush(stdout);
4294 }
4295 
4296 void PrettyUnitTestResultPrinter::OnTestCaseEnd(const TestCase& test_case) {
4297  if (!GTEST_FLAG(print_time)) return;
4298 
4299  const std::string counts =
4300  FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
4301  ColoredPrintf(COLOR_GREEN, "[----------] ");
4302  printf("%s from %s (%s ms total)\n\n",
4303  counts.c_str(), test_case.name(),
4304  internal::StreamableToString(test_case.elapsed_time()).c_str());
4305  fflush(stdout);
4306 }
4307 
4308 void PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart(
4309  const UnitTest& /*unit_test*/) {
4310  ColoredPrintf(COLOR_GREEN, "[----------] ");
4311  printf("Global test environment tear-down\n");
4312  fflush(stdout);
4313 }
4314 
4315 // Internal helper for printing the list of failed tests.
4316 void PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest& unit_test) {
4317  const int failed_test_count = unit_test.failed_test_count();
4318  if (failed_test_count == 0) {
4319  return;
4320  }
4321 
4322  for (int i = 0; i < unit_test.total_test_case_count(); ++i) {
4323  const TestCase& test_case = *unit_test.GetTestCase(i);
4324  if (!test_case.should_run() || (test_case.failed_test_count() == 0)) {
4325  continue;
4326  }
4327  for (int j = 0; j < test_case.total_test_count(); ++j) {
4328  const TestInfo& test_info = *test_case.GetTestInfo(j);
4329  if (!test_info.should_run() || test_info.result()->Passed()) {
4330  continue;
4331  }
4332  ColoredPrintf(COLOR_RED, "[ FAILED ] ");
4333  printf("%s.%s", test_case.name(), test_info.name());
4334  PrintFullTestCommentIfPresent(test_info);
4335  printf("\n");
4336  }
4337  }
4338 }
4339 
4340 void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
4341  int /*iteration*/) {
4342  ColoredPrintf(COLOR_GREEN, "[==========] ");
4343  printf("%s from %s ran.",
4344  FormatTestCount(unit_test.test_to_run_count()).c_str(),
4345  FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str());
4346  if (GTEST_FLAG(print_time)) {
4347  printf(" (%s ms total)",
4348  internal::StreamableToString(unit_test.elapsed_time()).c_str());
4349  }
4350  printf("\n");
4351  ColoredPrintf(COLOR_GREEN, "[ PASSED ] ");
4352  printf("%s.\n", FormatTestCount(unit_test.successful_test_count()).c_str());
4353 
4354  int num_failures = unit_test.failed_test_count();
4355  if (!unit_test.Passed()) {
4356  const int failed_test_count = unit_test.failed_test_count();
4357  ColoredPrintf(COLOR_RED, "[ FAILED ] ");
4358  printf("%s, listed below:\n", FormatTestCount(failed_test_count).c_str());
4359  PrintFailedTests(unit_test);
4360  printf("\n%2d FAILED %s\n", num_failures,
4361  num_failures == 1 ? "TEST" : "TESTS");
4362  }
4363 
4364  int num_disabled = unit_test.reportable_disabled_test_count();
4365  if (num_disabled && !GTEST_FLAG(also_run_disabled_tests)) {
4366  if (!num_failures) {
4367  printf("\n"); // Add a spacer if no FAILURE banner is displayed.
4368  }
4370  " YOU HAVE %d DISABLED %s\n\n",
4371  num_disabled,
4372  num_disabled == 1 ? "TEST" : "TESTS");
4373  }
4374  // Ensure that Google Test output is printed before, e.g., heapchecker output.
4375  fflush(stdout);
4376 }
4377 
4378 // End PrettyUnitTestResultPrinter
4379 
4380 // class TestEventRepeater
4381 //
4382 // This class forwards events to other event listeners.
4384  public:
4385  TestEventRepeater() : forwarding_enabled_(true) {}
4386  virtual ~TestEventRepeater();
4387  void Append(TestEventListener *listener);
4388  TestEventListener* Release(TestEventListener* listener);
4389 
4390  // Controls whether events will be forwarded to listeners_. Set to false
4391  // in death test child processes.
4392  bool forwarding_enabled() const { return forwarding_enabled_; }
4393  void set_forwarding_enabled(bool enable) { forwarding_enabled_ = enable; }
4394 
4395  virtual void OnTestProgramStart(const UnitTest& unit_test);
4396  virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration);
4397  virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test);
4398  virtual void OnEnvironmentsSetUpEnd(const UnitTest& unit_test);
4399  virtual void OnTestCaseStart(const TestCase& test_case);
4400  virtual void OnTestStart(const TestInfo& test_info);
4401  virtual void OnTestPartResult(const TestPartResult& result);
4402  virtual void OnTestEnd(const TestInfo& test_info);
4403  virtual void OnTestCaseEnd(const TestCase& test_case);
4404  virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test);
4405  virtual void OnEnvironmentsTearDownEnd(const UnitTest& unit_test);
4406  virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
4407  virtual void OnTestProgramEnd(const UnitTest& unit_test);
4408 
4409  private:
4410  // Controls whether events will be forwarded to listeners_. Set to false
4411  // in death test child processes.
4413  // The list of listeners that receive events.
4414  std::vector<TestEventListener*> listeners_;
4415 
4417 };
4418 
4419 TestEventRepeater::~TestEventRepeater() {
4420  ForEach(listeners_, Delete<TestEventListener>);
4421 }
4422 
4423 void TestEventRepeater::Append(TestEventListener *listener) {
4424  listeners_.push_back(listener);
4425 }
4426 
4427 // TODO(vladl@google.com): Factor the search functionality into Vector::Find.
4428 TestEventListener* TestEventRepeater::Release(TestEventListener *listener) {
4429  for (size_t i = 0; i < listeners_.size(); ++i) {
4430  if (listeners_[i] == listener) {
4431  listeners_.erase(listeners_.begin() + i);
4432  return listener;
4433  }
4434  }
4435 
4436  return NULL;
4437 }
4438 
4439 // Since most methods are very similar, use macros to reduce boilerplate.
4440 // This defines a member that forwards the call to all listeners.
4441 #define GTEST_REPEATER_METHOD_(Name, Type) \
4442 void TestEventRepeater::Name(const Type& parameter) { \
4443  if (forwarding_enabled_) { \
4444  for (size_t i = 0; i < listeners_.size(); i++) { \
4445  listeners_[i]->Name(parameter); \
4446  } \
4447  } \
4448 }
4449 // This defines a member that forwards the call to all listeners in reverse
4450 // order.
4451 #define GTEST_REVERSE_REPEATER_METHOD_(Name, Type) \
4452 void TestEventRepeater::Name(const Type& parameter) { \
4453  if (forwarding_enabled_) { \
4454  for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) { \
4455  listeners_[i]->Name(parameter); \
4456  } \
4457  } \
4458 }
4459 
4460 GTEST_REPEATER_METHOD_(OnTestProgramStart, UnitTest)
4461 GTEST_REPEATER_METHOD_(OnEnvironmentsSetUpStart, UnitTest)
4462 GTEST_REPEATER_METHOD_(OnTestCaseStart, TestCase)
4463 GTEST_REPEATER_METHOD_(OnTestStart, TestInfo)
4464 GTEST_REPEATER_METHOD_(OnTestPartResult, TestPartResult)
4465 GTEST_REPEATER_METHOD_(OnEnvironmentsTearDownStart, UnitTest)
4466 GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsSetUpEnd, UnitTest)
4467 GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsTearDownEnd, UnitTest)
4468 GTEST_REVERSE_REPEATER_METHOD_(OnTestEnd, TestInfo)
4470 GTEST_REVERSE_REPEATER_METHOD_(OnTestProgramEnd, UnitTest)
4471 
4472 #undef GTEST_REPEATER_METHOD_
4473 #undef GTEST_REVERSE_REPEATER_METHOD_
4474 
4475 void TestEventRepeater::OnTestIterationStart(const UnitTest& unit_test,
4476  int iteration) {
4477  if (forwarding_enabled_) {
4478  for (size_t i = 0; i < listeners_.size(); i++) {
4479  listeners_[i]->OnTestIterationStart(unit_test, iteration);
4480  }
4481  }
4482 }
4483 
4484 void TestEventRepeater::OnTestIterationEnd(const UnitTest& unit_test,
4485  int iteration) {
4486  if (forwarding_enabled_) {
4487  for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) {
4488  listeners_[i]->OnTestIterationEnd(unit_test, iteration);
4489  }
4490  }
4491 }
4492 
4493 // End TestEventRepeater
4494 
4495 // This class generates an XML output file.
4497  public:
4498  explicit XmlUnitTestResultPrinter(const char* output_file);
4499 
4500  virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
4501 
4502  private:
4503  // Is c a whitespace character that is normalized to a space character
4504  // when it appears in an XML attribute value?
4505  static bool IsNormalizableWhitespace(char c) {
4506  return c == 0x9 || c == 0xA || c == 0xD;
4507  }
4508 
4509  // May c appear in a well-formed XML document?
4510  static bool IsValidXmlCharacter(char c) {
4511  return IsNormalizableWhitespace(c) || c >= 0x20;
4512  }
4513 
4514  // Returns an XML-escaped copy of the input string str. If
4515  // is_attribute is true, the text is meant to appear as an attribute
4516  // value, and normalizable whitespace is preserved by replacing it
4517  // with character references.
4518  static std::string EscapeXml(const std::string& str, bool is_attribute);
4519 
4520  // Returns the given string with all characters invalid in XML removed.
4521  static std::string RemoveInvalidXmlCharacters(const std::string& str);
4522 
4523  // Convenience wrapper around EscapeXml when str is an attribute value.
4525  return EscapeXml(str, true);
4526  }
4527 
4528  // Convenience wrapper around EscapeXml when str is not an attribute value.
4529  static std::string EscapeXmlText(const char* str) {
4530  return EscapeXml(str, false);
4531  }
4532 
4533  // Verifies that the given attribute belongs to the given element and
4534  // streams the attribute as XML.
4535  static void OutputXmlAttribute(std::ostream* stream,
4536  const std::string& element_name,
4537  const std::string& name,
4538  const std::string& value);
4539 
4540  // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
4541  static void OutputXmlCDataSection(::std::ostream* stream, const char* data);
4542 
4543  // Streams an XML representation of a TestInfo object.
4544  static void OutputXmlTestInfo(::std::ostream* stream,
4545  const char* test_case_name,
4546  const TestInfo& test_info);
4547 
4548  // Prints an XML representation of a TestCase object
4549  static void PrintXmlTestCase(::std::ostream* stream,
4550  const TestCase& test_case);
4551 
4552  // Prints an XML summary of unit_test to output stream out.
4553  static void PrintXmlUnitTest(::std::ostream* stream,
4554  const UnitTest& unit_test);
4555 
4556  // Produces a string representing the test properties in a result as space
4557  // delimited XML attributes based on the property key="value" pairs.
4558  // When the std::string is not empty, it includes a space at the beginning,
4559  // to delimit this attribute from prior attributes.
4560  static std::string TestPropertiesAsXmlAttributes(const TestResult& result);
4561 
4562  // The output file.
4564 
4566 };
4567 
4568 // Creates a new XmlUnitTestResultPrinter.
4569 XmlUnitTestResultPrinter::XmlUnitTestResultPrinter(const char* output_file)
4570  : output_file_(output_file) {
4571  if (output_file_.c_str() == NULL || output_file_.empty()) {
4572  fprintf(stderr, "XML output file may not be null\n");
4573  fflush(stderr);
4574  exit(EXIT_FAILURE);
4575  }
4576 }
4577 
4578 // Called after the unit test ends.
4580  int /*iteration*/) {
4581  FILE* xmlout = NULL;
4582  FilePath output_file(output_file_);
4583  FilePath output_dir(output_file.RemoveFileName());
4584 
4585  if (output_dir.CreateDirectoriesRecursively()) {
4586  xmlout = posix::FOpen(output_file_.c_str(), "w");
4587  }
4588  if (xmlout == NULL) {
4589  // TODO(wan): report the reason of the failure.
4590  //
4591  // We don't do it for now as:
4592  //
4593  // 1. There is no urgent need for it.
4594  // 2. It's a bit involved to make the errno variable thread-safe on
4595  // all three operating systems (Linux, Windows, and Mac OS).
4596  // 3. To interpret the meaning of errno in a thread-safe way,
4597  // we need the strerror_r() function, which is not available on
4598  // Windows.
4599  fprintf(stderr,
4600  "Unable to open file \"%s\"\n",
4601  output_file_.c_str());
4602  fflush(stderr);
4603  exit(EXIT_FAILURE);
4604  }
4605  std::stringstream stream;
4606  PrintXmlUnitTest(&stream, unit_test);
4607  fprintf(xmlout, "%s", StringStreamToString(&stream).c_str());
4608  fclose(xmlout);
4609 }
4610 
4611 // Returns an XML-escaped copy of the input string str. If is_attribute
4612 // is true, the text is meant to appear as an attribute value, and
4613 // normalizable whitespace is preserved by replacing it with character
4614 // references.
4615 //
4616 // Invalid XML characters in str, if any, are stripped from the output.
4617 // It is expected that most, if not all, of the text processed by this
4618 // module will consist of ordinary English text.
4619 // If this module is ever modified to produce version 1.1 XML output,
4620 // most invalid characters can be retained using character references.
4621 // TODO(wan): It might be nice to have a minimally invasive, human-readable
4622 // escaping scheme for invalid characters, rather than dropping them.
4624  const std::string& str, bool is_attribute) {
4625  Message m;
4626 
4627  for (size_t i = 0; i < str.size(); ++i) {
4628  const char ch = str[i];
4629  switch (ch) {
4630  case '<':
4631  m << "&lt;";
4632  break;
4633  case '>':
4634  m << "&gt;";
4635  break;
4636  case '&':
4637  m << "&amp;";
4638  break;
4639  case '\'':
4640  if (is_attribute)
4641  m << "&apos;";
4642  else
4643  m << '\'';
4644  break;
4645  case '"':
4646  if (is_attribute)
4647  m << "&quot;";
4648  else
4649  m << '"';
4650  break;
4651  default:
4652  if (IsValidXmlCharacter(ch)) {
4653  if (is_attribute && IsNormalizableWhitespace(ch))
4654  m << "&#x" << String::FormatByte(static_cast<unsigned char>(ch))
4655  << ";";
4656  else
4657  m << ch;
4658  }
4659  break;
4660  }
4661  }
4662 
4663  return m.GetString();
4664 }
4665 
4666 // Returns the given string with all characters invalid in XML removed.
4667 // Currently invalid characters are dropped from the string. An
4668 // alternative is to replace them with certain characters such as . or ?.
4670  const std::string& str) {
4671  std::string output;
4672  output.reserve(str.size());
4673  for (std::string::const_iterator it = str.begin(); it != str.end(); ++it)
4674  if (IsValidXmlCharacter(*it))
4675  output.push_back(*it);
4676 
4677  return output;
4678 }
4679 
4680 // The following routines generate an XML representation of a UnitTest
4681 // object.
4682 //
4683 // This is how Google Test concepts map to the DTD:
4684 //
4685 // <testsuites name="AllTests"> <-- corresponds to a UnitTest object
4686 // <testsuite name="testcase-name"> <-- corresponds to a TestCase object
4687 // <testcase name="test-name"> <-- corresponds to a TestInfo object
4688 // <failure message="...">...</failure>
4689 // <failure message="...">...</failure>
4690 // <failure message="...">...</failure>
4691 // <-- individual assertion failures
4692 // </testcase>
4693 // </testsuite>
4694 // </testsuites>
4695 
4696 // Formats the given time in milliseconds as seconds.
4698  ::std::stringstream ss;
4699  ss << ms/1000.0;
4700  return ss.str();
4701 }
4702 
4703 // Converts the given epoch time in milliseconds to a date string in the ISO
4704 // 8601 format, without the timezone information.
4706  // Using non-reentrant version as localtime_r is not portable.
4707  time_t seconds = static_cast<time_t>(ms / 1000);
4708 #ifdef _MSC_VER
4709 # pragma warning(push) // Saves the current warning state.
4710 # pragma warning(disable:4996) // Temporarily disables warning 4996
4711  // (function or variable may be unsafe).
4712  const struct tm* const time_struct = localtime(&seconds); // NOLINT
4713 # pragma warning(pop) // Restores the warning state again.
4714 #else
4715  const struct tm* const time_struct = localtime(&seconds); // NOLINT
4716 #endif
4717  if (time_struct == NULL)
4718  return ""; // Invalid ms value
4719 
4720  // YYYY-MM-DDThh:mm:ss
4721  return StreamableToString(time_struct->tm_year + 1900) + "-" +
4722  String::FormatIntWidth2(time_struct->tm_mon + 1) + "-" +
4723  String::FormatIntWidth2(time_struct->tm_mday) + "T" +
4724  String::FormatIntWidth2(time_struct->tm_hour) + ":" +
4725  String::FormatIntWidth2(time_struct->tm_min) + ":" +
4726  String::FormatIntWidth2(time_struct->tm_sec);
4727 }
4728 
4729 // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
4731  const char* data) {
4732  const char* segment = data;
4733  *stream << "<![CDATA[";
4734  for (;;) {
4735  const char* const next_segment = strstr(segment, "]]>");
4736  if (next_segment != NULL) {
4737  stream->write(
4738  segment, static_cast<std::streamsize>(next_segment - segment));
4739  *stream << "]]>]]&gt;<![CDATA[";
4740  segment = next_segment + strlen("]]>");
4741  } else {
4742  *stream << segment;
4743  break;
4744  }
4745  }
4746  *stream << "]]>";
4747 }
4748 
4750  std::ostream* stream,
4751  const std::string& element_name,
4752  const std::string& name,
4753  const std::string& value) {
4754  const std::vector<std::string>& allowed_names =
4755  GetReservedAttributesForElement(element_name);
4756 
4757  GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
4758  allowed_names.end())
4759  << "Attribute " << name << " is not allowed for element <" << element_name
4760  << ">.";
4761 
4762  *stream << " " << name << "=\"" << EscapeXmlAttribute(value) << "\"";
4763 }
4764 
4765 // Prints an XML representation of a TestInfo object.
4766 // TODO(wan): There is also value in printing properties with the plain printer.
4768  const char* test_case_name,
4769  const TestInfo& test_info) {
4770  const TestResult& result = *test_info.result();
4771  const std::string kTestcase = "testcase";
4772 
4773  *stream << " <testcase";
4774  OutputXmlAttribute(stream, kTestcase, "name", test_info.name());
4775 
4776  if (test_info.value_param() != NULL) {
4777  OutputXmlAttribute(stream, kTestcase, "value_param",
4778  test_info.value_param());
4779  }
4780  if (test_info.type_param() != NULL) {
4781  OutputXmlAttribute(stream, kTestcase, "type_param", test_info.type_param());
4782  }
4783 
4784  OutputXmlAttribute(stream, kTestcase, "status",
4785  test_info.should_run() ? "run" : "notrun");
4786  OutputXmlAttribute(stream, kTestcase, "time",
4788  OutputXmlAttribute(stream, kTestcase, "classname", test_case_name);
4789  *stream << TestPropertiesAsXmlAttributes(result);
4790 
4791  int failures = 0;
4792  for (int i = 0; i < result.total_part_count(); ++i) {
4793  const TestPartResult& part = result.GetTestPartResult(i);
4794  if (part.failed()) {
4795  if (++failures == 1) {
4796  *stream << ">\n";
4797  }
4798  const string location = internal::FormatCompilerIndependentFileLocation(
4799  part.file_name(), part.line_number());
4800  const string summary = location + "\n" + part.summary();
4801  *stream << " <failure message=\""
4802  << EscapeXmlAttribute(summary.c_str())
4803  << "\" type=\"\">";
4804  const string detail = location + "\n" + part.message();
4805  OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str());
4806  *stream << "</failure>\n";
4807  }
4808  }
4809 
4810  if (failures == 0)
4811  *stream << " />\n";
4812  else
4813  *stream << " </testcase>\n";
4814 }
4815 
4816 // Prints an XML representation of a TestCase object
4818  const TestCase& test_case) {
4819  const std::string kTestsuite = "testsuite";
4820  *stream << " <" << kTestsuite;
4821  OutputXmlAttribute(stream, kTestsuite, "name", test_case.name());
4822  OutputXmlAttribute(stream, kTestsuite, "tests",
4824  OutputXmlAttribute(stream, kTestsuite, "failures",
4825  StreamableToString(test_case.failed_test_count()));
4827  stream, kTestsuite, "disabled",
4829  OutputXmlAttribute(stream, kTestsuite, "errors", "0");
4830  OutputXmlAttribute(stream, kTestsuite, "time",
4832  *stream << TestPropertiesAsXmlAttributes(test_case.ad_hoc_test_result())
4833  << ">\n";
4834 
4835  for (int i = 0; i < test_case.total_test_count(); ++i) {
4836  if (test_case.GetTestInfo(i)->is_reportable())
4837  OutputXmlTestInfo(stream, test_case.name(), *test_case.GetTestInfo(i));
4838  }
4839  *stream << " </" << kTestsuite << ">\n";
4840 }
4841 
4842 // Prints an XML summary of unit_test to output stream out.
4844  const UnitTest& unit_test) {
4845  const std::string kTestsuites = "testsuites";
4846 
4847  *stream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
4848  *stream << "<" << kTestsuites;
4849 
4850  OutputXmlAttribute(stream, kTestsuites, "tests",
4852  OutputXmlAttribute(stream, kTestsuites, "failures",
4853  StreamableToString(unit_test.failed_test_count()));
4855  stream, kTestsuites, "disabled",
4857  OutputXmlAttribute(stream, kTestsuites, "errors", "0");
4859  stream, kTestsuites, "timestamp",
4861  OutputXmlAttribute(stream, kTestsuites, "time",
4863 
4864  if (GTEST_FLAG(shuffle)) {
4865  OutputXmlAttribute(stream, kTestsuites, "random_seed",
4866  StreamableToString(unit_test.random_seed()));
4867  }
4868 
4869  *stream << TestPropertiesAsXmlAttributes(unit_test.ad_hoc_test_result());
4870 
4871  OutputXmlAttribute(stream, kTestsuites, "name", "AllTests");
4872  *stream << ">\n";
4873 
4874  for (int i = 0; i < unit_test.total_test_case_count(); ++i) {
4875  if (unit_test.GetTestCase(i)->reportable_test_count() > 0)
4876  PrintXmlTestCase(stream, *unit_test.GetTestCase(i));
4877  }
4878  *stream << "</" << kTestsuites << ">\n";
4879 }
4880 
4881 // Produces a string representing the test properties in a result as space
4882 // delimited XML attributes based on the property key="value" pairs.
4884  const TestResult& result) {
4885  Message attributes;
4886  for (int i = 0; i < result.test_property_count(); ++i) {
4887  const TestProperty& property = result.GetTestProperty(i);
4888  attributes << " " << property.key() << "="
4889  << "\"" << EscapeXmlAttribute(property.value()) << "\"";
4890  }
4891  return attributes.GetString();
4892 }
4893 
4894 // End XmlUnitTestResultPrinter
4895 
4896 #if GTEST_CAN_STREAM_RESULTS_
4897 
4898 // Checks if str contains '=', '&', '%' or '\n' characters. If yes,
4899 // replaces them by "%xx" where xx is their hexadecimal value. For
4900 // example, replaces "=" with "%3D". This algorithm is O(strlen(str))
4901 // in both time and space -- important as the input str may contain an
4902 // arbitrarily long test failure message and stack trace.
4903 string StreamingListener::UrlEncode(const char* str) {
4904  string result;
4905  result.reserve(strlen(str) + 1);
4906  for (char ch = *str; ch != '\0'; ch = *++str) {
4907  switch (ch) {
4908  case '%':
4909  case '=':
4910  case '&':
4911  case '\n':
4912  result.append("%" + String::FormatByte(static_cast<unsigned char>(ch)));
4913  break;
4914  default:
4915  result.push_back(ch);
4916  break;
4917  }
4918  }
4919  return result;
4920 }
4921 
4922 void StreamingListener::SocketWriter::MakeConnection() {
4923  GTEST_CHECK_(sockfd_ == -1)
4924  << "MakeConnection() can't be called when there is already a connection.";
4925 
4926  addrinfo hints;
4927  memset(&hints, 0, sizeof(hints));
4928  hints.ai_family = AF_UNSPEC; // To allow both IPv4 and IPv6 addresses.
4929  hints.ai_socktype = SOCK_STREAM;
4930  addrinfo* servinfo = NULL;
4931 
4932  // Use the getaddrinfo() to get a linked list of IP addresses for
4933  // the given host name.
4934  const int error_num = getaddrinfo(
4935  host_name_.c_str(), port_num_.c_str(), &hints, &servinfo);
4936  if (error_num != 0) {
4937  GTEST_LOG_(WARNING) << "stream_result_to: getaddrinfo() failed: "
4938  << gai_strerror(error_num);
4939  }
4940 
4941  // Loop through all the results and connect to the first we can.
4942  for (addrinfo* cur_addr = servinfo; sockfd_ == -1 && cur_addr != NULL;
4943  cur_addr = cur_addr->ai_next) {
4944  sockfd_ = socket(
4945  cur_addr->ai_family, cur_addr->ai_socktype, cur_addr->ai_protocol);
4946  if (sockfd_ != -1) {
4947  // Connect the client socket to the server socket.
4948  if (connect(sockfd_, cur_addr->ai_addr, cur_addr->ai_addrlen) == -1) {
4949  close(sockfd_);
4950  sockfd_ = -1;
4951  }
4952  }
4953  }
4954 
4955  freeaddrinfo(servinfo); // all done with this structure
4956 
4957  if (sockfd_ == -1) {
4958  GTEST_LOG_(WARNING) << "stream_result_to: failed to connect to "
4959  << host_name_ << ":" << port_num_;
4960  }
4961 }
4962 
4963 // End of class Streaming Listener
4964 #endif // GTEST_CAN_STREAM_RESULTS__
4965 
4966 // Class ScopedTrace
4967 
4968 // Pushes the given source file location and message onto a per-thread
4969 // trace stack maintained by Google Test.
4970 ScopedTrace::ScopedTrace(const char* file, int line, const Message& message)
4972  TraceInfo trace;
4973  trace.file = file;
4974  trace.line = line;
4975  trace.message = message.GetString();
4976 
4978 }
4979 
4980 // Pops the info pushed by the c'tor.
4982  GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) {
4984 }
4985 
4986 
4987 // class OsStackTraceGetter
4988 
4989 // Returns the current OS stack trace as an std::string. Parameters:
4990 //
4991 // max_depth - the maximum number of stack frames to be included
4992 // in the trace.
4993 // skip_count - the number of top frames to be skipped; doesn't count
4994 // against max_depth.
4995 //
4996 string OsStackTraceGetter::CurrentStackTrace(int /* max_depth */,
4997  int /* skip_count */)
4998  GTEST_LOCK_EXCLUDED_(mutex_) {
4999  return "";
5000 }
5001 
5003  GTEST_LOCK_EXCLUDED_(mutex_) {
5004 }
5005 
5006 const char* const
5008  "... " GTEST_NAME_ " internal frames ...";
5009 
5010 // A helper class that creates the premature-exit file in its
5011 // constructor and deletes the file in its destructor.
5013  public:
5014  explicit ScopedPrematureExitFile(const char* premature_exit_filepath)
5015  : premature_exit_filepath_(premature_exit_filepath) {
5016  // If a path to the premature-exit file is specified...
5017  if (premature_exit_filepath != NULL && *premature_exit_filepath != '\0') {
5018  // create the file with a single "0" character in it. I/O
5019  // errors are ignored as there's nothing better we can do and we
5020  // don't want to fail the test because of this.
5021  FILE* pfile = posix::FOpen(premature_exit_filepath, "w");
5022  fwrite("0", 1, 1, pfile);
5023  fclose(pfile);
5024  }
5025  }
5026 
5028  if (premature_exit_filepath_ != NULL && *premature_exit_filepath_ != '\0') {
5029  remove(premature_exit_filepath_);
5030  }
5031  }
5032 
5033  private:
5034  const char* const premature_exit_filepath_;
5035 
5037 };
5038 
5039 } // namespace internal
5040 
5041 // class TestEventListeners
5042 
5044  : repeater_(new internal::TestEventRepeater()),
5045  default_result_printer_(NULL),
5046  default_xml_generator_(NULL) {
5047 }
5048 
5050 
5051 // Returns the standard listener responsible for the default console
5052 // output. Can be removed from the listeners list to shut down default
5053 // console output. Note that removing this object from the listener list
5054 // with Release transfers its ownership to the user.
5056  repeater_->Append(listener);
5057 }
5058 
5059 // Removes the given event listener from the list and returns it. It then
5060 // becomes the caller's responsibility to delete the listener. Returns
5061 // NULL if the listener is not found in the list.
5063  if (listener == default_result_printer_)
5064  default_result_printer_ = NULL;
5065  else if (listener == default_xml_generator_)
5066  default_xml_generator_ = NULL;
5067  return repeater_->Release(listener);
5068 }
5069 
5070 // Returns repeater that broadcasts the TestEventListener events to all
5071 // subscribers.
5073 
5074 // Sets the default_result_printer attribute to the provided listener.
5075 // The listener is also added to the listener list and previous
5076 // default_result_printer is removed from it and deleted. The listener can
5077 // also be NULL in which case it will not be added to the list. Does
5078 // nothing if the previous and the current listener objects are the same.
5080  if (default_result_printer_ != listener) {
5081  // It is an error to pass this method a listener that is already in the
5082  // list.
5084  default_result_printer_ = listener;
5085  if (listener != NULL)
5086  Append(listener);
5087  }
5088 }
5089 
5090 // Sets the default_xml_generator attribute to the provided listener. The
5091 // listener is also added to the listener list and previous
5092 // default_xml_generator is removed from it and deleted. The listener can
5093 // also be NULL in which case it will not be added to the list. Does
5094 // nothing if the previous and the current listener objects are the same.
5096  if (default_xml_generator_ != listener) {
5097  // It is an error to pass this method a listener that is already in the
5098  // list.
5100  default_xml_generator_ = listener;
5101  if (listener != NULL)
5102  Append(listener);
5103  }
5104 }
5105 
5106 // Controls whether events will be forwarded by the repeater to the
5107 // listeners in the list.
5109  return repeater_->forwarding_enabled();
5110 }
5111 
5114 }
5115 
5116 // class UnitTest
5117 
5118 // Gets the singleton UnitTest object. The first time this method is
5119 // called, a UnitTest object is constructed and returned. Consecutive
5120 // calls will return the same object.
5121 //
5122 // We don't protect this under mutex_ as a user is not supposed to
5123 // call this before main() starts, from which point on the return
5124 // value will never change.
5126  // When compiled with MSVC 7.1 in optimized mode, destroying the
5127  // UnitTest object upon exiting the program messes up the exit code,
5128  // causing successful tests to appear failed. We have to use a
5129  // different implementation in this case to bypass the compiler bug.
5130  // This implementation makes the compiler happy, at the cost of
5131  // leaking the UnitTest object.
5132 
5133  // CodeGear C++Builder insists on a public destructor for the
5134  // default implementation. Use this implementation to keep good OO
5135  // design with private destructor.
5136 
5137 #if (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)
5138  static UnitTest* const instance = new UnitTest;
5139  return instance;
5140 #else
5141  static UnitTest instance;
5142  return &instance;
5143 #endif // (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)
5144 }
5145 
5146 // Gets the number of successful test cases.
5148  return impl()->successful_test_case_count();
5149 }
5150 
5151 // Gets the number of failed test cases.
5153  return impl()->failed_test_case_count();
5154 }
5155 
5156 // Gets the number of all test cases.
5158  return impl()->total_test_case_count();
5159 }
5160 
5161 // Gets the number of all test cases that contain at least one test
5162 // that should run.
5164  return impl()->test_case_to_run_count();
5165 }
5166 
5167 // Gets the number of successful tests.
5169  return impl()->successful_test_count();
5170 }
5171 
5172 // Gets the number of failed tests.
5173 int UnitTest::failed_test_count() const { return impl()->failed_test_count(); }
5174 
5175 // Gets the number of disabled tests that will be reported in the XML report.
5177  return impl()->reportable_disabled_test_count();
5178 }
5179 
5180 // Gets the number of disabled tests.
5182  return impl()->disabled_test_count();
5183 }
5184 
5185 // Gets the number of tests to be printed in the XML report.
5187  return impl()->reportable_test_count();
5188 }
5189 
5190 // Gets the number of all tests.
5191 int UnitTest::total_test_count() const { return impl()->total_test_count(); }
5192 
5193 // Gets the number of tests that should run.
5194 int UnitTest::test_to_run_count() const { return impl()->test_to_run_count(); }
5195 
5196 // Gets the time of the test program start, in ms from the start of the
5197 // UNIX epoch.
5199  return impl()->start_timestamp();
5200 }
5201 
5202 // Gets the elapsed time, in milliseconds.
5204  return impl()->elapsed_time();
5205 }
5206 
5207 // Returns true iff the unit test passed (i.e. all test cases passed).
5208 bool UnitTest::Passed() const { return impl()->Passed(); }
5209 
5210 // Returns true iff the unit test failed (i.e. some test case failed
5211 // or something outside of all tests failed).
5212 bool UnitTest::Failed() const { return impl()->Failed(); }
5213 
5214 // Gets the i-th test case among all the test cases. i can range from 0 to
5215 // total_test_case_count() - 1. If i is not in that range, returns NULL.
5216 const TestCase* UnitTest::GetTestCase(int i) const {
5217  return impl()->GetTestCase(i);
5218 }
5219 
5220 // Returns the TestResult containing information on test failures and
5221 // properties logged outside of individual test cases.
5223  return *impl()->ad_hoc_test_result();
5224 }
5225 
5226 // Gets the i-th test case among all the test cases. i can range from 0 to
5227 // total_test_case_count() - 1. If i is not in that range, returns NULL.
5229  return impl()->GetMutableTestCase(i);
5230 }
5231 
5232 // Returns the list of event listeners that can be used to track events
5233 // inside Google Test.
5235  return *impl()->listeners();
5236 }
5237 
5238 // Registers and returns a global test environment. When a test
5239 // program is run, all global test environments will be set-up in the
5240 // order they were registered. After all tests in the program have
5241 // finished, all global test environments will be torn-down in the
5242 // *reverse* order they were registered.
5243 //
5244 // The UnitTest object takes ownership of the given environment.
5245 //
5246 // We don't protect this under mutex_, as we only support calling it
5247 // from the main thread.
5249  if (env == NULL) {
5250  return NULL;
5251  }
5252 
5253  impl_->environments().push_back(env);
5254  return env;
5255 }
5256 
5257 // Adds a TestPartResult to the current TestResult object. All Google Test
5258 // assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) eventually call
5259 // this to report their results. The user code should use the
5260 // assertion macros instead of calling this directly.
5262  TestPartResult::Type result_type,
5263  const char* file_name,
5264  int line_number,
5265  const std::string& message,
5266  const std::string& os_stack_trace) GTEST_LOCK_EXCLUDED_(mutex_) {
5267  Message msg;
5268  msg << message;
5269 
5270  internal::MutexLock lock(&mutex_);
5271  if (impl_->gtest_trace_stack().size() > 0) {
5272  msg << "\n" << GTEST_NAME_ << " trace:";
5273 
5274  for (int i = static_cast<int>(impl_->gtest_trace_stack().size());
5275  i > 0; --i) {
5276  const internal::TraceInfo& trace = impl_->gtest_trace_stack()[i - 1];
5277  msg << "\n" << internal::FormatFileLocation(trace.file, trace.line)
5278  << " " << trace.message;
5279  }
5280  }
5281 
5282  if (os_stack_trace.c_str() != NULL && !os_stack_trace.empty()) {
5283  msg << internal::kStackTraceMarker << os_stack_trace;
5284  }
5285 
5286  const TestPartResult result =
5287  TestPartResult(result_type, file_name, line_number,
5288  msg.GetString().c_str());
5289  impl_->GetTestPartResultReporterForCurrentThread()->
5290  ReportTestPartResult(result);
5291 
5292  if (result_type != TestPartResult::kSuccess) {
5293  // gtest_break_on_failure takes precedence over
5294  // gtest_throw_on_failure. This allows a user to set the latter
5295  // in the code (perhaps in order to use Google Test assertions
5296  // with another testing framework) and specify the former on the
5297  // command line for debugging.
5298  if (GTEST_FLAG(break_on_failure)) {
5299 #if GTEST_OS_WINDOWS
5300  // Using DebugBreak on Windows allows gtest to still break into a debugger
5301  // when a failure happens and both the --gtest_break_on_failure and
5302  // the --gtest_catch_exceptions flags are specified.
5303  DebugBreak();
5304 #else
5305  // Dereference NULL through a volatile pointer to prevent the compiler
5306  // from removing. We use this rather than abort() or __builtin_trap() for
5307  // portability: Symbian doesn't implement abort() well, and some debuggers
5308  // don't correctly trap abort().
5309  *static_cast<volatile int*>(NULL) = 1;
5310 #endif // GTEST_OS_WINDOWS
5311  } else if (GTEST_FLAG(throw_on_failure)) {
5312 #if GTEST_HAS_EXCEPTIONS
5313  throw internal::GoogleTestFailureException(result);
5314 #else
5315  // We cannot call abort() as it generates a pop-up in debug mode
5316  // that cannot be suppressed in VC 7.1 or below.
5317  exit(1);
5318 #endif
5319  }
5320  }
5321 }
5322 
5323 // Adds a TestProperty to the current TestResult object when invoked from
5324 // inside a test, to current TestCase's ad_hoc_test_result_ when invoked
5325 // from SetUpTestCase or TearDownTestCase, or to the global property set
5326 // when invoked elsewhere. If the result already contains a property with
5327 // the same key, the value will be updated.
5329  const std::string& value) {
5330  impl_->RecordProperty(TestProperty(key, value));
5331 }
5332 
5333 // Runs all tests in this UnitTest object and prints the result.
5334 // Returns 0 if successful, or 1 otherwise.
5335 //
5336 // We don't protect this under mutex_, as we only support calling it
5337 // from the main thread.
5339  const bool in_death_test_child_process =
5340  internal::GTEST_FLAG(internal_run_death_test).length() > 0;
5341 
5342  // Google Test implements this protocol for catching that a test
5343  // program exits before returning control to Google Test:
5344  //
5345  // 1. Upon start, Google Test creates a file whose absolute path
5346  // is specified by the environment variable
5347  // TEST_PREMATURE_EXIT_FILE.
5348  // 2. When Google Test has finished its work, it deletes the file.
5349  //
5350  // This allows a test runner to set TEST_PREMATURE_EXIT_FILE before
5351  // running a Google-Test-based test program and check the existence
5352  // of the file at the end of the test execution to see if it has
5353  // exited prematurely.
5354 
5355  // If we are in the child process of a death test, don't
5356  // create/delete the premature exit file, as doing so is unnecessary
5357  // and will confuse the parent process. Otherwise, create/delete
5358  // the file upon entering/leaving this function. If the program
5359  // somehow exits before this function has a chance to return, the
5360  // premature-exit file will be left undeleted, causing a test runner
5361  // that understands the premature-exit-file protocol to report the
5362  // test as having failed.
5363  const internal::ScopedPrematureExitFile premature_exit_file(
5364  in_death_test_child_process ?
5365  NULL : internal::posix::GetEnv("TEST_PREMATURE_EXIT_FILE"));
5366 
5367  // Captures the value of GTEST_FLAG(catch_exceptions). This value will be
5368  // used for the duration of the program.
5369  impl()->set_catch_exceptions(GTEST_FLAG(catch_exceptions));
5370 
5371 #if GTEST_HAS_SEH
5372  // Either the user wants Google Test to catch exceptions thrown by the
5373  // tests or this is executing in the context of death test child
5374  // process. In either case the user does not want to see pop-up dialogs
5375  // about crashes - they are expected.
5376  if (impl()->catch_exceptions() || in_death_test_child_process) {
5377 # if !GTEST_OS_WINDOWS_MOBILE
5378  // SetErrorMode doesn't exist on CE.
5379  SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT |
5380  SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);
5381 # endif // !GTEST_OS_WINDOWS_MOBILE
5382 
5383 # if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE
5384  // Death test children can be terminated with _abort(). On Windows,
5385  // _abort() can show a dialog with a warning message. This forces the
5386  // abort message to go to stderr instead.
5387  _set_error_mode(_OUT_TO_STDERR);
5388 # endif
5389 
5390 # if _MSC_VER >= 1400 && !GTEST_OS_WINDOWS_MOBILE
5391  // In the debug version, Visual Studio pops up a separate dialog
5392  // offering a choice to debug the aborted program. We need to suppress
5393  // this dialog or it will pop up for every EXPECT/ASSERT_DEATH statement
5394  // executed. Google Test will notify the user of any unexpected
5395  // failure via stderr.
5396  //
5397  // VC++ doesn't define _set_abort_behavior() prior to the version 8.0.
5398  // Users of prior VC versions shall suffer the agony and pain of
5399  // clicking through the countless debug dialogs.
5400  // TODO(vladl@google.com): find a way to suppress the abort dialog() in the
5401  // debug mode when compiled with VC 7.1 or lower.
5402  if (!GTEST_FLAG(break_on_failure))
5403  _set_abort_behavior(
5404  0x0, // Clear the following flags:
5405  _WRITE_ABORT_MSG | _CALL_REPORTFAULT); // pop-up window, core dump.
5406 # endif
5407  }
5408 #endif // GTEST_HAS_SEH
5409 
5411  impl(),
5413  "auxiliary test code (environments or event listeners)") ? 0 : 1;
5414 }
5415 
5416 // Returns the working directory when the first TEST() or TEST_F() was
5417 // executed.
5418 const char* UnitTest::original_working_dir() const {
5419  return impl_->original_working_dir_.c_str();
5420 }
5421 
5422 // Returns the TestCase object for the test that's currently running,
5423 // or NULL if no test is running.
5425  GTEST_LOCK_EXCLUDED_(mutex_) {
5426  internal::MutexLock lock(&mutex_);
5427  return impl_->current_test_case();
5428 }
5429 
5430 // Returns the TestInfo object for the test that's currently running,
5431 // or NULL if no test is running.
5433  GTEST_LOCK_EXCLUDED_(mutex_) {
5434  internal::MutexLock lock(&mutex_);
5435  return impl_->current_test_info();
5436 }
5437 
5438 // Returns the random seed used at the start of the current test run.
5439 int UnitTest::random_seed() const { return impl_->random_seed(); }
5440 
5441 #if GTEST_HAS_PARAM_TEST
5442 // Returns ParameterizedTestCaseRegistry object used to keep track of
5443 // value-parameterized tests and instantiate and register them.
5446  GTEST_LOCK_EXCLUDED_(mutex_) {
5447  return impl_->parameterized_test_registry();
5448 }
5449 #endif // GTEST_HAS_PARAM_TEST
5450 
5451 // Creates an empty UnitTest.
5453  impl_ = new internal::UnitTestImpl(this);
5454 }
5455 
5456 // Destructor of UnitTest.
5458  delete impl_;
5459 }
5460 
5461 // Pushes a trace defined by SCOPED_TRACE() on to the per-thread
5462 // Google Test trace stack.
5464  GTEST_LOCK_EXCLUDED_(mutex_) {
5465  internal::MutexLock lock(&mutex_);
5466  impl_->gtest_trace_stack().push_back(trace);
5467 }
5468 
5469 // Pops a trace from the per-thread Google Test trace stack.
5471  GTEST_LOCK_EXCLUDED_(mutex_) {
5472  internal::MutexLock lock(&mutex_);
5473  impl_->gtest_trace_stack().pop_back();
5474 }
5475 
5476 namespace internal {
5477 
5478 UnitTestImpl::UnitTestImpl(UnitTest* parent)
5479  : parent_(parent),
5480 #ifdef _MSC_VER
5481 # pragma warning(push) // Saves the current warning state.
5482 # pragma warning(disable:4355) // Temporarily disables warning 4355
5483  // (using this in initializer).
5484  default_global_test_part_result_reporter_(this),
5485  default_per_thread_test_part_result_reporter_(this),
5486 # pragma warning(pop) // Restores the warning state again.
5487 #else
5488  default_global_test_part_result_reporter_(this),
5489  default_per_thread_test_part_result_reporter_(this),
5490 #endif // _MSC_VER
5491  global_test_part_result_repoter_(
5492  &default_global_test_part_result_reporter_),
5493  per_thread_test_part_result_reporter_(
5494  &default_per_thread_test_part_result_reporter_),
5496  parameterized_test_registry_(),
5497  parameterized_tests_registered_(false),
5498 #endif // GTEST_HAS_PARAM_TEST
5499  last_death_test_case_(-1),
5500  current_test_case_(NULL),
5501  current_test_info_(NULL),
5502  ad_hoc_test_result_(),
5503  os_stack_trace_getter_(NULL),
5504  post_flag_parse_init_performed_(false),
5505  random_seed_(0), // Will be overridden by the flag before first use.
5506  random_(0), // Will be reseeded before first use.
5507  start_timestamp_(0),
5508  elapsed_time_(0),
5509 #if GTEST_HAS_DEATH_TEST
5510  death_test_factory_(new DefaultDeathTestFactory),
5511 #endif
5512  // Will be overridden by the flag before first use.
5513  catch_exceptions_(false) {
5515 }
5516 
5518  // Deletes every TestCase.
5519  ForEach(test_cases_, internal::Delete<TestCase>);
5520 
5521  // Deletes every Environment.
5522  ForEach(environments_, internal::Delete<Environment>);
5523 
5524  delete os_stack_trace_getter_;
5525 }
5526 
5527 // Adds a TestProperty to the current TestResult object when invoked in a
5528 // context of a test, to current test case's ad_hoc_test_result when invoke
5529 // from SetUpTestCase/TearDownTestCase, or to the global property set
5530 // otherwise. If the result already contains a property with the same key,
5531 // the value will be updated.
5532 void UnitTestImpl::RecordProperty(const TestProperty& test_property) {
5533  std::string xml_element;
5534  TestResult* test_result; // TestResult appropriate for property recording.
5535 
5536  if (current_test_info_ != NULL) {
5537  xml_element = "testcase";
5538  test_result = &(current_test_info_->result_);
5539  } else if (current_test_case_ != NULL) {
5540  xml_element = "testsuite";
5541  test_result = &(current_test_case_->ad_hoc_test_result_);
5542  } else {
5543  xml_element = "testsuites";
5544  test_result = &ad_hoc_test_result_;
5545  }
5546  test_result->RecordProperty(xml_element, test_property);
5547 }
5548 
5549 #if GTEST_HAS_DEATH_TEST
5550 // Disables event forwarding if the control is currently in a death test
5551 // subprocess. Must not be called before InitGoogleTest.
5552 void UnitTestImpl::SuppressTestEventsIfInSubprocess() {
5553  if (internal_run_death_test_flag_.get() != NULL)
5555 }
5556 #endif // GTEST_HAS_DEATH_TEST
5557 
5558 // Initializes event listeners performing XML output as specified by
5559 // UnitTestOptions. Must not be called before InitGoogleTest.
5561  const std::string& output_format = UnitTestOptions::GetOutputFormat();
5562  if (output_format == "xml") {
5565  } else if (output_format != "") {
5566  printf("WARNING: unrecognized output format \"%s\" ignored.\n",
5567  output_format.c_str());
5568  fflush(stdout);
5569  }
5570 }
5571 
5572 #if GTEST_CAN_STREAM_RESULTS_
5573 // Initializes event listeners for streaming test results in string form.
5574 // Must not be called before InitGoogleTest.
5575 void UnitTestImpl::ConfigureStreamingOutput() {
5576  const std::string& target = GTEST_FLAG(stream_result_to);
5577  if (!target.empty()) {
5578  const size_t pos = target.find(':');
5579  if (pos != std::string::npos) {
5580  listeners()->Append(new StreamingListener(target.substr(0, pos),
5581  target.substr(pos+1)));
5582  } else {
5583  printf("WARNING: unrecognized streaming target \"%s\" ignored.\n",
5584  target.c_str());
5585  fflush(stdout);
5586  }
5587  }
5588 }
5589 #endif // GTEST_CAN_STREAM_RESULTS_
5590 
5591 // Performs initialization dependent upon flag values obtained in
5592 // ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to
5593 // ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest
5594 // this function is also called from RunAllTests. Since this function can be
5595 // called more than once, it has to be idempotent.
5597  // Ensures that this function does not execute more than once.
5600 
5601 #if GTEST_HAS_DEATH_TEST
5602  InitDeathTestSubprocessControlInfo();
5603  SuppressTestEventsIfInSubprocess();
5604 #endif // GTEST_HAS_DEATH_TEST
5605 
5606  // Registers parameterized tests. This makes parameterized tests
5607  // available to the UnitTest reflection API without running
5608  // RUN_ALL_TESTS.
5610 
5611  // Configures listeners for XML output. This makes it possible for users
5612  // to shut down the default XML output before invoking RUN_ALL_TESTS.
5614 
5615 #if GTEST_CAN_STREAM_RESULTS_
5616  // Configures listeners for streaming test results to the specified server.
5617  ConfigureStreamingOutput();
5618 #endif // GTEST_CAN_STREAM_RESULTS_
5619  }
5620 }
5621 
5622 // A predicate that checks the name of a TestCase against a known
5623 // value.
5624 //
5625 // This is used for implementation of the UnitTest class only. We put
5626 // it in the anonymous namespace to prevent polluting the outer
5627 // namespace.
5628 //
5629 // TestCaseNameIs is copyable.
5631  public:
5632  // Constructor.
5633  explicit TestCaseNameIs(const std::string& name)
5634  : name_(name) {}
5635 
5636  // Returns true iff the name of test_case matches name_.
5637  bool operator()(const TestCase* test_case) const {
5638  return test_case != NULL && strcmp(test_case->