gmock-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());
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.
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.
1262 
1263  // Indicates whether RegisterParameterizedTests() has been called already.
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.
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
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) {
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
4817 void XmlUnitTestResultPrinter::PrintXmlTestCase(std::ostream* stream,
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.
4843 void XmlUnitTestResultPrinter::PrintXmlUnitTest(std::ostream* stream,
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.
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->name(), name_.c_str()) == 0;
5639  }
5640 
5641  private:
5643 };
5644 
5645 // Finds and returns a TestCase with the given name. If one doesn't
5646 // exist, creates one and returns it. It's the CALLER'S
5647 // RESPONSIBILITY to ensure that this function is only called WHEN THE
5648 // TESTS ARE NOT SHUFFLED.
5649 //
5650 // Arguments:
5651 //
5652 // test_case_name: name of the test case
5653 // type_param: the name of the test case's type parameter, or NULL if
5654 // this is not a typed or a type-parameterized test case.
5655 // set_up_tc: pointer to the function that sets up the test case
5656 // tear_down_tc: pointer to the function that tears down the test case
5657 TestCase* UnitTestImpl::GetTestCase(const char* test_case_name,
5658  const char* type_param,
5659  Test::SetUpTestCaseFunc set_up_tc,
5660  Test::TearDownTestCaseFunc tear_down_tc) {
5661  // Can we find a TestCase with the given name?
5662  const std::vector<TestCase*>::const_iterator test_case =
5663  std::find_if(test_cases_.begin(), test_cases_.end(),
5664  TestCaseNameIs(test_case_name));
5665 
5666  if (test_case != test_cases_.end())
5667  return *test_case;
5668 
5669  // No. Let's create one.
5670  TestCase* const new_test_case =
5671  new TestCase(test_case_name, type_param, set_up_tc, tear_down_tc);
5672 
5673  // Is this a death test case?
5674  if (internal::UnitTestOptions::MatchesFilter(test_case_name,
5675  kDeathTestCaseFilter)) {
5676  // Yes. Inserts the test case after the last death test case
5677  // defined so far. This only works when the test cases haven't
5678  // been shuffled. Otherwise we may end up running a death test
5679  // after a non-death test.
5682  new_test_case);
5683  } else {
5684  // No. Appends to the end of the list.
5685  test_cases_.push_back(new_test_case);
5686  }
5687 
5688  test_case_indices_.push_back(static_cast<int>(test_case_indices_.size()));
5689  return new_test_case;
5690 }
5691 
5692 // Helpers for setting up / tearing down the given environment. They
5693 // are for use in the ForEach() function.
5694 static void SetUpEnvironment(Environment* env) { env->SetUp(); }
5695 static void TearDownEnvironment(Environment* env) { env->TearDown(); }
5696 
5697 // Runs all tests in this UnitTest object, prints the result, and
5698 // returns true if all tests are successful. If any exception is
5699 // thrown during a test, the test is considered to be failed, but the
5700 // rest of the tests will still be run.
5701 //
5702 // When parameterized tests are enabled, it expands and registers
5703 // parameterized tests first in RegisterParameterizedTests().
5704 // All other functions called from RunAllTests() may safely assume that
5705 // parameterized tests are ready to be counted and run.
5707  // Makes sure InitGoogleTest() was called.
5708  if (!GTestIsInitialized()) {
5709  printf("%s",
5710  "\nThis test program did NOT call ::testing::InitGoogleTest "
5711  "before calling RUN_ALL_TESTS(). Please fix it.\n");
5712  return false;
5713  }
5714 
5715  // Do not run any test if the --help flag was specified.
5716  if (g_help_flag)
5717  return true;
5718 
5719  // Repeats the call to the post-flag parsing initialization in case the
5720  // user didn't call InitGoogleTest.
5722 
5723  // Even if sharding is not on, test runners may want to use the
5724  // GTEST_SHARD_STATUS_FILE to query whether the test supports the sharding
5725  // protocol.
5727 
5728  // True iff we are in a subprocess for running a thread-safe-style
5729  // death test.
5730  bool in_subprocess_for_death_test = false;
5731 
5732 #if GTEST_HAS_DEATH_TEST
5733  in_subprocess_for_death_test = (internal_run_death_test_flag_.get() != NULL);
5734 #endif // GTEST_HAS_DEATH_TEST
5735 
5736  const bool should_shard = ShouldShard(kTestTotalShards, kTestShardIndex,
5737  in_subprocess_for_death_test);
5738 
5739  // Compares the full test names with the filter to decide which
5740  // tests to run.
5741  const bool has_tests_to_run = FilterTests(should_shard
5743  : IGNORE_SHARDING_PROTOCOL) > 0;
5744 
5745  // Lists the tests and exits if the --gtest_list_tests flag was specified.
5746  if (GTEST_FLAG(list_tests)) {
5747  // This must be called *after* FilterTests() has been called.
5749  return true;
5750  }
5751 
5752  random_seed_ = GTEST_FLAG(shuffle) ?
5754 
5755  // True iff at least one test has failed.
5756  bool failed = false;
5757 
5758  TestEventListener* repeater = listeners()->repeater();
5759 
5761  repeater->OnTestProgramStart(*parent_);
5762 
5763  // How many times to repeat the tests? We don't want to repeat them
5764  // when we are inside the subprocess of a death test.
5765  const int repeat = in_subprocess_for_death_test ? 1 : GTEST_FLAG(repeat);
5766  // Repeats forever if the repeat count is negative.
5767  const bool forever = repeat < 0;
5768  for (int i = 0; forever || i != repeat; i++) {
5769  // We want to preserve failures generated by ad-hoc test
5770  // assertions executed before RUN_ALL_TESTS().
5772 
5774 
5775  // Shuffles test cases and tests if requested.
5776  if (has_tests_to_run && GTEST_FLAG(shuffle)) {
5778  // This should be done before calling OnTestIterationStart(),
5779  // such that a test event listener can see the actual test order
5780  // in the event.
5781  ShuffleTests();
5782  }
5783 
5784  // Tells the unit test event listeners that the tests are about to start.
5785  repeater->OnTestIterationStart(*parent_, i);
5786 
5787  // Runs each test case if there is at least one test to run.
5788  if (has_tests_to_run) {
5789  // Sets up all environments beforehand.
5790  repeater->OnEnvironmentsSetUpStart(*parent_);
5792  repeater->OnEnvironmentsSetUpEnd(*parent_);
5793 
5794  // Runs the tests only if there was no fatal failure during global
5795  // set-up.
5796  if (!Test::HasFatalFailure()) {
5797  for (int test_index = 0; test_index < total_test_case_count();
5798  test_index++) {
5799  GetMutableTestCase(test_index)->Run();
5800  }
5801  }
5802 
5803  // Tears down all environments in reverse order afterwards.
5805  std::for_each(environments_.rbegin(), environments_.rend(),
5807  repeater->OnEnvironmentsTearDownEnd(*parent_);
5808  }
5809 
5810  elapsed_time_ = GetTimeInMillis() - start;
5811 
5812  // Tells the unit test event listener that the tests have just finished.
5813  repeater->OnTestIterationEnd(*parent_, i);
5814 
5815  // Gets the result and clears it.
5816  if (!Passed()) {
5817  failed = true;
5818  }
5819 
5820  // Restores the original test order after the iteration. This
5821  // allows the user to quickly repro a failure that happens in the
5822  // N-th iteration without repeating the first (N - 1) iterations.
5823  // This is not enclosed in "if (GTEST_FLAG(shuffle)) { ... }", in
5824  // case the user somehow changes the value of the flag somewhere
5825  // (it's always safe to unshuffle the tests).
5826  UnshuffleTests();
5827 
5828  if (GTEST_FLAG(shuffle)) {
5829  // Picks a new random seed for each iteration.
5831  }
5832  }
5833 
5834  repeater->OnTestProgramEnd(*parent_);
5835 
5836  return !failed;
5837 }
5838 
5839 // Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
5840 // if the variable is present. If a file already exists at this location, this
5841 // function will write over it. If the variable is present, but the file cannot
5842 // be created, prints an error and exits.
5844  const char* const test_shard_file = posix::GetEnv(kTestShardStatusFile);
5845  if (test_shard_file != NULL) {
5846  FILE* const file = posix::FOpen(test_shard_file, "w");
5847  if (file == NULL) {
5849  "Could not write to the test shard status file \"%s\" "
5850  "specified by the %s environment variable.\n",
5851  test_shard_file, kTestShardStatusFile);
5852  fflush(stdout);
5853  exit(EXIT_FAILURE);
5854  }
5855  fclose(file);
5856  }
5857 }
5858 
5859 // Checks whether sharding is enabled by examining the relevant
5860 // environment variable values. If the variables are present,
5861 // but inconsistent (i.e., shard_index >= total_shards), prints
5862 // an error and exits. If in_subprocess_for_death_test, sharding is
5863 // disabled because it must only be applied to the original test
5864 // process. Otherwise, we could filter out death tests we intended to execute.
5865 bool ShouldShard(const char* total_shards_env,
5866  const char* shard_index_env,
5867  bool in_subprocess_for_death_test) {
5868  if (in_subprocess_for_death_test) {
5869  return false;
5870  }
5871 
5872  const Int32 total_shards = Int32FromEnvOrDie(total_shards_env, -1);
5873  const Int32 shard_index = Int32FromEnvOrDie(shard_index_env, -1);
5874 
5875  if (total_shards == -1 && shard_index == -1) {
5876  return false;
5877  } else if (total_shards == -1 && shard_index != -1) {
5878  const Message msg = Message()
5879  << "Invalid environment variables: you have "
5880  << kTestShardIndex << " = " << shard_index
5881  << ", but have left " << kTestTotalShards << " unset.\n";
5882  ColoredPrintf(COLOR_RED, msg.GetString().c_str());
5883  fflush(stdout);
5884  exit(EXIT_FAILURE);
5885  } else if (total_shards != -1 && shard_index == -1) {
5886  const Message msg = Message()
5887  << "Invalid environment variables: you have "
5888  << kTestTotalShards << " = " << total_shards
5889  << ", but have left " << kTestShardIndex << " unset.\n";
5890  ColoredPrintf(COLOR_RED, msg.GetString().c_str());
5891  fflush(stdout);
5892  exit(EXIT_FAILURE);
5893  } else if (shard_index < 0 || shard_index >= total_shards) {
5894  const Message msg = Message()
5895  << "Invalid environment variables: we require 0 <= "
5896  << kTestShardIndex << " < " << kTestTotalShards
5897  << ", but you have " << kTestShardIndex << "=" << shard_index
5898  << ", " << kTestTotalShards << "=" << total_shards << ".\n";
5899  ColoredPrintf(COLOR_RED, msg.GetString().c_str());
5900  fflush(stdout);
5901  exit(EXIT_FAILURE);
5902  }
5903 
5904  return total_shards > 1;
5905 }
5906 
5907 // Parses the environment variable var as an Int32. If it is unset,
5908 // returns default_val. If it is not an Int32, prints an error
5909 // and aborts.
5910 Int32 Int32FromEnvOrDie(const char* var, Int32 default_val) {
5911  const char* str_val = posix::GetEnv(var);
5912  if (str_val == NULL) {
5913  return default_val;
5914  }
5915 
5916  Int32 result;
5917  if (!ParseInt32(Message() << "The value of environment variable " << var,
5918  str_val, &result)) {
5919  exit(EXIT_FAILURE);
5920  }
5921  return result;
5922 }
5923 
5924 // Given the total number of shards, the shard index, and the test id,
5925 // returns true iff the test should be run on this shard. The test id is
5926 // some arbitrary but unique non-negative integer assigned to each test
5927 // method. Assumes that 0 <= shard_index < total_shards.
5928 bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) {
5929  return (test_id % total_shards) == shard_index;
5930 }
5931 
5932 // Compares the name of each test with the user-specified filter to
5933 // decide whether the test should be run, then records the result in
5934 // each TestCase and TestInfo object.
5935 // If shard_tests == true, further filters tests based on sharding
5936 // variables in the environment - see
5937 // http://code.google.com/p/googletest/wiki/GoogleTestAdvancedGuide.
5938 // Returns the number of tests that should run.
5940  const Int32 total_shards = shard_tests == HONOR_SHARDING_PROTOCOL ?
5941  Int32FromEnvOrDie(kTestTotalShards, -1) : -1;
5942  const Int32 shard_index = shard_tests == HONOR_SHARDING_PROTOCOL ?
5943  Int32FromEnvOrDie(kTestShardIndex, -1) : -1;
5944 
5945  // num_runnable_tests are the number of tests that will
5946  // run across all shards (i.e., match filter and are not disabled).
5947  // num_selected_tests are the number of tests to be run on
5948  // this shard.
5949  int num_runnable_tests = 0;
5950  int num_selected_tests = 0;
5951  for (size_t i = 0; i < test_cases_.size(); i++) {
5952  TestCase* const test_case = test_cases_[i];
5953  const std::string &test_case_name = test_case->name();
5954  test_case->set_should_run(false);
5955 
5956  for (size_t j = 0; j < test_case->test_info_list().size(); j++) {
5957  TestInfo* const test_info = test_case->test_info_list()[j];
5958  const std::string test_name(test_info->name());
5959  // A test is disabled if test case name or test name matches
5960  // kDisableTestFilter.
5961  const bool is_disabled =
5963  kDisableTestFilter) ||
5965  kDisableTestFilter);
5966  test_info->is_disabled_ = is_disabled;
5967 
5968  const bool matches_filter =
5970  test_name);
5971  test_info->matches_filter_ = matches_filter;
5972 
5973  const bool is_runnable =
5974  (GTEST_FLAG(also_run_disabled_tests) || !is_disabled) &&
5975  matches_filter;
5976 
5977  const bool is_selected = is_runnable &&
5978  (shard_tests == IGNORE_SHARDING_PROTOCOL ||
5979  ShouldRunTestOnShard(total_shards, shard_index,
5980  num_runnable_tests));
5981 
5982  num_runnable_tests += is_runnable;
5983  num_selected_tests += is_selected;
5984 
5985  test_info->should_run_ = is_selected;
5986  test_case->set_should_run(test_case->should_run() || is_selected);
5987  }
5988  }
5989  return num_selected_tests;
5990 }
5991 
5992 // Prints the given C-string on a single line by replacing all '\n'
5993 // characters with string "\\n". If the output takes more than
5994 // max_length characters, only prints the first max_length characters
5995 // and "...".
5996 static void PrintOnOneLine(const char* str, int max_length) {
5997  if (str != NULL) {
5998  for (int i = 0; *str != '\0'; ++str) {
5999  if (i >= max_length) {
6000  printf("...");
6001  break;
6002  }
6003  if (*str == '\n') {
6004  printf("\\n");
6005  i += 2;
6006  } else {
6007  printf("%c", *str);
6008  ++i;
6009  }
6010  }
6011  }
6012 }
6013 
6014 // Prints the names of the tests matching the user-specified filter flag.
6016  // Print at most this many characters for each type/value parameter.
6017  const int kMaxParamLength = 250;
6018 
6019  for (size_t i = 0; i < test_cases_.size(); i++) {
6020  const TestCase* const test_case = test_cases_[i];
6021  bool printed_test_case_name = false;
6022 
6023  for (size_t j = 0; j < test_case->test_info_list().size(); j++) {
6024  const TestInfo* const test_info =
6025  test_case->test_info_list()[j];
6026  if (test_info->matches_filter_) {
6027  if (!printed_test_case_name) {
6028  printed_test_case_name = true;
6029  printf("%s.", test_case->name());
6030  if (test_case->type_param() != NULL) {
6031  printf(" # %s = ", kTypeParamLabel);
6032  // We print the type parameter on a single line to make
6033  // the output easy to parse by a program.
6034  PrintOnOneLine(test_case->type_param(), kMaxParamLength);
6035  }
6036  printf("\n");
6037  }
6038  printf(" %s", test_info->name());
6039  if (test_info->value_param() != NULL) {
6040  printf(" # %s = ", kValueParamLabel);
6041  // We print the value parameter on a single line to make the
6042  // output easy to parse by a program.
6043  PrintOnOneLine(test_info->value_param(), kMaxParamLength);
6044  }
6045  printf("\n");
6046  }
6047  }
6048  }
6049  fflush(stdout);
6050 }
6051 
6052 // Sets the OS stack trace getter.
6053 //
6054 // Does nothing if the input and the current OS stack trace getter are
6055 // the same; otherwise, deletes the old getter and makes the input the
6056 // current getter.
6058  OsStackTraceGetterInterface* getter) {
6059  if (os_stack_trace_getter_ != getter) {
6060  delete os_stack_trace_getter_;
6061  os_stack_trace_getter_ = getter;
6062  }
6063 }
6064 
6065 // Returns the current OS stack trace getter if it is not NULL;
6066 // otherwise, creates an OsStackTraceGetter, makes it the current
6067 // getter, and returns it.
6069  if (os_stack_trace_getter_ == NULL) {
6071  }
6072 
6073  return os_stack_trace_getter_;
6074 }
6075 
6076 // Returns the TestResult for the test that's currently running, or
6077 // the TestResult for the ad hoc test if no test is running.
6079  return current_test_info_ ?
6081 }
6082 
6083 // Shuffles all test cases, and the tests within each test case,
6084 // making sure that death tests are still run first.
6086  // Shuffles the death test cases.
6088 
6089  // Shuffles the non-death test cases.
6091  static_cast<int>(test_cases_.size()), &test_case_indices_);
6092 
6093  // Shuffles the tests inside each test case.
6094  for (size_t i = 0; i < test_cases_.size(); i++) {
6095  test_cases_[i]->ShuffleTests(random());
6096  }
6097 }
6098 
6099 // Restores the test cases and tests to their order before the first shuffle.
6101  for (size_t i = 0; i < test_cases_.size(); i++) {
6102  // Unshuffles the tests in each test case.
6103  test_cases_[i]->UnshuffleTests();
6104  // Resets the index of each test case.
6105  test_case_indices_[i] = static_cast<int>(i);
6106  }
6107 }
6108 
6109 // Returns the current OS stack trace as an std::string.
6110 //
6111 // The maximum number of stack frames to be included is specified by
6112 // the gtest_stack_trace_depth flag. The skip_count parameter
6113 // specifies the number of top frames to be skipped, which doesn't
6114 // count against the number of frames to be included.
6115 //
6116 // For example, if Foo() calls Bar(), which in turn calls
6117 // GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in
6118 // the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.
6120  int skip_count) {
6121  // We pass skip_count + 1 to skip this wrapper function in addition
6122  // to what the user really wants to skip.
6123  return GetUnitTestImpl()->CurrentOsStackTraceExceptTop(skip_count + 1);
6124 }
6125 
6126 // Used by the GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_ macro to
6127 // suppress unreachable code warnings.
6128 namespace {
6129 class ClassUniqueToAlwaysTrue {};
6130 }
6131 
6132 bool IsTrue(bool condition) { return condition; }
6133 
6134 bool AlwaysTrue() {
6135 #if GTEST_HAS_EXCEPTIONS
6136  // This condition is always false so AlwaysTrue() never actually throws,
6137  // but it makes the compiler think that it may throw.
6138  if (IsTrue(false))
6139  throw ClassUniqueToAlwaysTrue();
6140 #endif // GTEST_HAS_EXCEPTIONS
6141  return true;
6142 }
6143 
6144 // If *pstr starts with the given prefix, modifies *pstr to be right
6145 // past the prefix and returns true; otherwise leaves *pstr unchanged
6146 // and returns false. None of pstr, *pstr, and prefix can be NULL.
6147 bool SkipPrefix(const char* prefix, const char** pstr) {
6148  const size_t prefix_len = strlen(prefix);
6149  if (strncmp(*pstr, prefix, prefix_len) == 0) {
6150  *pstr += prefix_len;
6151  return true;
6152  }
6153  return false;
6154 }
6155 
6156 // Parses a string as a command line flag. The string should have
6157 // the format "--flag=value". When def_optional is true, the "=value"
6158 // part can be omitted.
6159 //
6160 // Returns the value of the flag, or NULL if the parsing failed.
6161 const char* ParseFlagValue(const char* str,
6162  const char* flag,
6163  bool def_optional) {
6164  // str and flag must not be NULL.
6165  if (str == NULL || flag == NULL) return NULL;
6166 
6167  // The flag must start with "--" followed by GTEST_FLAG_PREFIX_.
6168  const std::string flag_str = std::string("--") + GTEST_FLAG_PREFIX_ + flag;
6169  const size_t flag_len = flag_str.length();
6170  if (strncmp(str, flag_str.c_str(), flag_len) != 0) return NULL;
6171 
6172  // Skips the flag name.
6173  const char* flag_end = str + flag_len;
6174 
6175  // When def_optional is true, it's OK to not have a "=value" part.
6176  if (def_optional && (flag_end[0] == '\0')) {
6177  return flag_end;
6178  }
6179 
6180  // If def_optional is true and there are more characters after the
6181  // flag name, or if def_optional is false, there must be a '=' after
6182  // the flag name.
6183  if (flag_end[0] != '=') return NULL;
6184 
6185  // Returns the string after "=".
6186  return flag_end + 1;
6187 }
6188 
6189 // Parses a string for a bool flag, in the form of either
6190 // "--flag=value" or "--flag".
6191 //
6192 // In the former case, the value is taken as true as long as it does
6193 // not start with '0', 'f', or 'F'.
6194 //
6195 // In the latter case, the value is taken as true.
6196 //
6197 // On success, stores the value of the flag in *value, and returns
6198 // true. On failure, returns false without changing *value.
6199 bool ParseBoolFlag(const char* str, const char* flag, bool* value) {
6200  // Gets the value of the flag as a string.
6201  const char* const value_str = ParseFlagValue(str, flag, true);
6202 
6203  // Aborts if the parsing failed.
6204  if (value_str == NULL) return false;
6205 
6206  // Converts the string value to a bool.
6207  *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F');
6208  return true;
6209 }
6210 
6211 // Parses a string for an Int32 flag, in the form of
6212 // "--flag=value".
6213 //
6214 // On success, stores the value of the flag in *value, and returns
6215 // true. On failure, returns false without changing *value.
6216 bool ParseInt32Flag(const char* str, const char* flag, Int32* value) {
6217  // Gets the value of the flag as a string.
6218  const char* const value_str = ParseFlagValue(str, flag, false);
6219 
6220  // Aborts if the parsing failed.
6221  if (value_str == NULL) return false;
6222 
6223  // Sets *value to the value of the flag.
6224  return ParseInt32(Message() << "The value of flag --" << flag,
6225  value_str, value);
6226 }
6227 
6228 // Parses a string for a string flag, in the form of
6229 // "--flag=value".
6230 //
6231 // On success, stores the value of the flag in *value, and returns
6232 // true. On failure, returns false without changing *value.
6233 bool ParseStringFlag(const char* str, const char* flag, std::string* value) {
6234  // Gets the value of the flag as a string.
6235  const char* const value_str = ParseFlagValue(str, flag, false);
6236 
6237  // Aborts if the parsing failed.
6238  if (value_str == NULL) return false;
6239 
6240  // Sets *value to the value of the flag.
6241  *value = value_str;
6242  return true;
6243 }
6244 
6245 // Determines whether a string has a prefix that Google Test uses for its
6246 // flags, i.e., starts with GTEST_FLAG_PREFIX_ or GTEST_FLAG_PREFIX_DASH_.
6247 // If Google Test detects that a command line flag has its prefix but is not
6248 // recognized, it will print its help message. Flags starting with
6249 // GTEST_INTERNAL_PREFIX_ followed by "internal_" are considered Google Test
6250 // internal flags and do not trigger the help message.
6251 static bool HasGoogleTestFlagPrefix(const char* str) {
6252  return (SkipPrefix("--", &str) ||
6253  SkipPrefix("-", &str) ||
6254  SkipPrefix("/", &str)) &&
6255  !SkipPrefix(GTEST_FLAG_PREFIX_ "internal_", &str) &&
6256  (SkipPrefix(GTEST_FLAG_PREFIX_, &str) ||
6258 }
6259 
6260 // Prints a string containing code-encoded text. The following escape
6261 // sequences can be used in the string to control the text color:
6262 //
6263 // @@ prints a single '@' character.
6264 // @R changes the color to red.
6265 // @G changes the color to green.
6266 // @Y changes the color to yellow.
6267 // @D changes to the default terminal text color.
6268 //
6269 // TODO(wan@google.com): Write tests for this once we add stdout
6270 // capturing to Google Test.
6271 static void PrintColorEncoded(const char* str) {
6272  GTestColor color = COLOR_DEFAULT; // The current color.
6273 
6274  // Conceptually, we split the string into segments divided by escape
6275  // sequences. Then we print one segment at a time. At the end of
6276  // each iteration, the str pointer advances to the beginning of the
6277  // next segment.
6278  for (;;) {
6279  const char* p = strchr(str, '@');
6280  if (p == NULL) {
6281  ColoredPrintf(color, "%s", str);
6282  return;
6283  }
6284 
6285  ColoredPrintf(color, "%s", std::string(str, p).c_str());
6286 
6287  const char ch = p[1];
6288  str = p + 2;
6289  if (ch == '@') {
6290  ColoredPrintf(color, "@");
6291  } else if (ch == 'D') {
6292  color = COLOR_DEFAULT;
6293  } else if (ch == 'R') {
6294  color = COLOR_RED;
6295  } else if (ch == 'G') {
6296  color = COLOR_GREEN;
6297  } else if (ch == 'Y') {
6298  color = COLOR_YELLOW;
6299  } else {
6300  --str;
6301  }
6302  }
6303 }
6304 
6305 static const char kColorEncodedHelpMessage[] =
6306 "This program contains tests written using " GTEST_NAME_ ". You can use the\n"
6307 "following command line flags to control its behavior:\n"
6308 "\n"
6309 "Test Selection:\n"
6310 " @G--" GTEST_FLAG_PREFIX_ "list_tests@D\n"
6311 " List the names of all tests instead of running them. The name of\n"
6312 " TEST(Foo, Bar) is \"Foo.Bar\".\n"
6313 " @G--" GTEST_FLAG_PREFIX_ "filter=@YPOSTIVE_PATTERNS"
6314  "[@G-@YNEGATIVE_PATTERNS]@D\n"
6315 " Run only the tests whose name matches one of the positive patterns but\n"
6316 " none of the negative patterns. '?' matches any single character; '*'\n"
6317 " matches any substring; ':' separates two patterns.\n"
6318 " @G--" GTEST_FLAG_PREFIX_ "also_run_disabled_tests@D\n"
6319 " Run all disabled tests too.\n"
6320 "\n"
6321 "Test Execution:\n"
6322 " @G--" GTEST_FLAG_PREFIX_ "repeat=@Y[COUNT]@D\n"
6323 " Run the tests repeatedly; use a negative count to repeat forever.\n"
6324 " @G--" GTEST_FLAG_PREFIX_ "shuffle@D\n"
6325 " Randomize tests' orders on every iteration.\n"
6326 " @G--" GTEST_FLAG_PREFIX_ "random_seed=@Y[NUMBER]@D\n"
6327 " Random number seed to use for shuffling test orders (between 1 and\n"
6328 " 99999, or 0 to use a seed based on the current time).\n"
6329 "\n"
6330 "Test Output:\n"
6331 " @G--" GTEST_FLAG_PREFIX_ "color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\n"
6332 " Enable/disable colored output. The default is @Gauto@D.\n"
6333 " -@G-" GTEST_FLAG_PREFIX_ "print_time=0@D\n"
6334 " Don't print the elapsed time of each test.\n"
6335 " @G--" GTEST_FLAG_PREFIX_ "output=xml@Y[@G:@YDIRECTORY_PATH@G"
6336  GTEST_PATH_SEP_ "@Y|@G:@YFILE_PATH]@D\n"
6337 " Generate an XML report in the given directory or with the given file\n"
6338 " name. @YFILE_PATH@D defaults to @Gtest_details.xml@D.\n"
6339 #if GTEST_CAN_STREAM_RESULTS_
6340 " @G--" GTEST_FLAG_PREFIX_ "stream_result_to=@YHOST@G:@YPORT@D\n"
6341 " Stream test results to the given server.\n"
6342 #endif // GTEST_CAN_STREAM_RESULTS_
6343 "\n"
6344 "Assertion Behavior:\n"
6345 #if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
6346 " @G--" GTEST_FLAG_PREFIX_ "death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n"
6347 " Set the default death test style.\n"
6348 #endif // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
6349 " @G--" GTEST_FLAG_PREFIX_ "break_on_failure@D\n"
6350 " Turn assertion failures into debugger break-points.\n"
6351 " @G--" GTEST_FLAG_PREFIX_ "throw_on_failure@D\n"
6352 " Turn assertion failures into C++ exceptions.\n"
6353 " @G--" GTEST_FLAG_PREFIX_ "catch_exceptions=0@D\n"
6354 " Do not report exceptions as test failures. Instead, allow them\n"
6355 " to crash the program or throw a pop-up (on Windows).\n"
6356 "\n"
6357 "Except for @G--" GTEST_FLAG_PREFIX_ "list_tests@D, you can alternatively set "
6358  "the corresponding\n"
6359 "environment variable of a flag (all letters in upper-case). For example, to\n"
6360 "disable colored text output, you can either specify @G--" GTEST_FLAG_PREFIX_
6361  "color=no@D or set\n"
6362 "the @G" GTEST_FLAG_PREFIX_UPPER_ "COLOR@D environment variable to @Gno@D.\n"
6363 "\n"
6364 "For more information, please read the " GTEST_NAME_ " documentation at\n"
6365 "@G" GTEST_PROJECT_URL_ "@D. If you find a bug in " GTEST_NAME_ "\n"
6366 "(not one in your own code or tests), please report it to\n"
6367 "@G<" GTEST_DEV_EMAIL_ ">@D.\n";
6368 
6369 // Parses the command line for Google Test flags, without initializing
6370 // other parts of Google Test. The type parameter CharType can be
6371 // instantiated to either char or wchar_t.
6372 template <typename CharType>
6373 void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) {
6374  for (int i = 1; i < *argc; i++) {
6375  const std::string arg_string = StreamableToString(argv[i]);
6376  const char* const arg = arg_string.c_str();
6377 
6381 
6382  // Do we see a Google Test flag?
6384  &GTEST_FLAG(also_run_disabled_tests)) ||
6386  &GTEST_FLAG(break_on_failure)) ||
6389  ParseStringFlag(arg, kColorFlag, &GTEST_FLAG(color)) ||
6391  &GTEST_FLAG(death_test_style)) ||
6393  &GTEST_FLAG(death_test_use_fork)) ||
6394  ParseStringFlag(arg, kFilterFlag, &GTEST_FLAG(filter)) ||
6396  &GTEST_FLAG(internal_run_death_test)) ||
6397  ParseBoolFlag(arg, kListTestsFlag, &GTEST_FLAG(list_tests)) ||
6399  ParseBoolFlag(arg, kPrintTimeFlag, &GTEST_FLAG(print_time)) ||
6401  ParseInt32Flag(arg, kRepeatFlag, &GTEST_FLAG(repeat)) ||
6402  ParseBoolFlag(arg, kShuffleFlag, &GTEST_FLAG(shuffle)) ||
6404  &GTEST_FLAG(stack_trace_depth)) ||
6406  &GTEST_FLAG(stream_result_to)) ||
6408  &GTEST_FLAG(throw_on_failure))
6409  ) {
6410  // Yes. Shift the remainder of the argv list left by one. Note
6411  // that argv has (*argc + 1) elements, the last one always being
6412  // NULL. The following loop moves the trailing NULL element as
6413  // well.
6414  for (int j = i; j != *argc; j++) {
6415  argv[j] = argv[j + 1];
6416  }
6417 
6418  // Decrements the argument count.
6419  (*argc)--;
6420 
6421  // We also need to decrement the iterator as we just removed
6422  // an element.
6423  i--;
6424  } else if (arg_string == "--help" || arg_string == "-h" ||
6425  arg_string == "-?" || arg_string == "/?" ||
6426  HasGoogleTestFlagPrefix(arg)) {
6427  // Both help flag and unrecognized Google Test flags (excluding
6428  // internal ones) trigger help display.
6429  g_help_flag = true;
6430  }
6431  }
6432 
6433  if (g_help_flag) {
6434  // We print the help here instead of in RUN_ALL_TESTS(), as the
6435  // latter may not be called at all if the user is using Google
6436  // Test with another testing framework.
6437  PrintColorEncoded(kColorEncodedHelpMessage);
6438  }
6439 }
6440 
6441 // Parses the command line for Google Test flags, without initializing
6442 // other parts of Google Test.
6443 void ParseGoogleTestFlagsOnly(int* argc, char** argv) {
6444  ParseGoogleTestFlagsOnlyImpl(argc, argv);
6445 }
6446 void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv) {
6447  ParseGoogleTestFlagsOnlyImpl(argc, argv);
6448 }
6449 
6450 // The internal implementation of InitGoogleTest().
6451 //
6452 // The type parameter CharType can be instantiated to either char or
6453 // wchar_t.
6454 template <typename CharType>
6455 void InitGoogleTestImpl(int* argc, CharType** argv) {
6456  g_init_gtest_count++;
6457 
6458  // We don't want to run the initialization code twice.
6459  if (g_init_gtest_count != 1) return;
6460 
6461  if (*argc <= 0) return;
6462 
6464 
6465 #if GTEST_HAS_DEATH_TEST
6466 
6467  g_argvs.clear();
6468  for (int i = 0; i != *argc; i++) {
6469  g_argvs.push_back(StreamableToString(argv[i]));
6470  }
6471 
6472 #endif // GTEST_HAS_DEATH_TEST
6473 
6474  ParseGoogleTestFlagsOnly(argc, argv);
6476 }
6477 
6478 } // namespace internal
6479 
6480 // Initializes Google Test. This must be called before calling
6481 // RUN_ALL_TESTS(). In particular, it parses a command line for the
6482 // flags that Google Test recognizes. Whenever a Google Test flag is
6483 // seen, it is removed from argv, and *argc is decremented.
6484 //
6485 // No value is returned. Instead, the Google Test flag variables are
6486 // updated.
6487 //
6488 // Calling the function for the second time has no user-visible effect.
6489 void InitGoogleTest(int* argc, char** argv) {
6490  internal::InitGoogleTestImpl(argc, argv);
6491 }
6492 
6493 // This overloaded version can be used in Windows programs compiled in
6494 // UNICODE mode.
6495 void InitGoogleTest(int* argc, wchar_t** argv) {
6496  internal::InitGoogleTestImpl(argc, argv);
6497 }
6498 
6499 } // namespace testing
6500 // Copyright 2005, Google Inc.
6501 // All rights reserved.
6502 //
6503 // Redistribution and use in source and binary forms, with or without
6504 // modification, are permitted provided that the following conditions are
6505 // met:
6506 //
6507 // * Redistributions of source code must retain the above copyright
6508 // notice, this list of conditions and the following disclaimer.
6509 // * Redistributions in binary form must reproduce the above
6510 // copyright notice, this list of conditions and the following disclaimer
6511 // in the documentation and/or other materials provided with the
6512 // distribution.
6513 // * Neither the name of Google Inc. nor the names of its
6514 // contributors may be used to endorse or promote products derived from
6515 // this software without specific prior written permission.
6516 //
6517 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
6518 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
6519 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
6520 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
6521 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
6522 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
6523 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
6524 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
6525 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
6526 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
6527 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
6528 //
6529 // Author: wan@google.com (Zhanyong Wan), vladl@google.com (Vlad Losev)
6530 //
6531 // This file implements death tests.
6532 
6533 
6534 #if GTEST_HAS_DEATH_TEST
6535 
6536 # if GTEST_OS_MAC
6537 # include <crt_externs.h>
6538 # endif // GTEST_OS_MAC
6539 
6540 # include <errno.h>
6541 # include <fcntl.h>
6542 # include <limits.h>
6543 
6544 # if GTEST_OS_LINUX
6545 # include <signal.h>
6546 # endif // GTEST_OS_LINUX
6547 
6548 # include <stdarg.h>
6549 
6550 # if GTEST_OS_WINDOWS
6551 # include <windows.h>
6552 # else
6553 # include <sys/mman.h>
6554 # include <sys/wait.h>
6555 # endif // GTEST_OS_WINDOWS
6556 
6557 # if GTEST_OS_QNX
6558 # include <spawn.h>
6559 # endif // GTEST_OS_QNX
6560 
6561 #endif // GTEST_HAS_DEATH_TEST
6562 
6563 
6564 // Indicates that this translation unit is part of Google Test's
6565 // implementation. It must come before gtest-internal-inl.h is
6566 // included, or there will be a compiler error. This trick is to
6567 // prevent a user from accidentally including gtest-internal-inl.h in
6568 // his code.
6569 #define GTEST_IMPLEMENTATION_ 1
6570 #undef GTEST_IMPLEMENTATION_
6571 
6572 namespace testing {
6573 
6574 // Constants.
6575 
6576 // The default death test style.
6577 static const char kDefaultDeathTestStyle[] = "fast";
6578 
6580  death_test_style,
6581  internal::StringFromGTestEnv("death_test_style", kDefaultDeathTestStyle),
6582  "Indicates how to run a death test in a forked child process: "
6583  "\"threadsafe\" (child process re-executes the test binary "
6584  "from the beginning, running only the specific death test) or "
6585  "\"fast\" (child process runs the death test immediately "
6586  "after forking).");
6587 
6589  death_test_use_fork,
6590  internal::BoolFromGTestEnv("death_test_use_fork", false),
6591  "Instructs to use fork()/_exit() instead of clone() in death tests. "
6592  "Ignored and always uses fork() on POSIX systems where clone() is not "
6593  "implemented. Useful when running under valgrind or similar tools if "
6594  "those do not support clone(). Valgrind 3.3.1 will just fail if "
6595  "it sees an unsupported combination of clone() flags. "
6596  "It is not recommended to use this flag w/o valgrind though it will "
6597  "work in 99% of the cases. Once valgrind is fixed, this flag will "
6598  "most likely be removed.");
6599 
6600 namespace internal {
6602  internal_run_death_test, "",
6603  "Indicates the file, line number, temporal index of "
6604  "the single death test to run, and a file descriptor to "
6605  "which a success code may be sent, all separated by "
6606  "the '|' characters. This flag is specified if and only if the current "
6607  "process is a sub-process launched for running a thread-safe "
6608  "death test. FOR INTERNAL USE ONLY.");
6609 } // namespace internal
6610 
6611 #if GTEST_HAS_DEATH_TEST
6612 
6613 namespace internal {
6614 
6615 // Valid only for fast death tests. Indicates the code is running in the
6616 // child process of a fast style death test.
6617 static bool g_in_fast_death_test_child = false;
6618 
6619 // Returns a Boolean value indicating whether the caller is currently
6620 // executing in the context of the death test child process. Tools such as
6621 // Valgrind heap checkers may need this to modify their behavior in death
6622 // tests. IMPORTANT: This is an internal utility. Using it may break the
6623 // implementation of death tests. User code MUST NOT use it.
6624 bool InDeathTestChild() {
6625 # if GTEST_OS_WINDOWS
6626 
6627  // On Windows, death tests are thread-safe regardless of the value of the
6628  // death_test_style flag.
6629  return !GTEST_FLAG(internal_run_death_test).empty();
6630 
6631 # else
6632 
6633  if (GTEST_FLAG(death_test_style) == "threadsafe")
6634  return !GTEST_FLAG(internal_run_death_test).empty();
6635  else
6636  return g_in_fast_death_test_child;
6637 #endif
6638 }
6639 
6640 } // namespace internal
6641 
6642 // ExitedWithCode constructor.
6643 ExitedWithCode::ExitedWithCode(int exit_code) : exit_code_(exit_code) {
6644 }
6645 
6646 // ExitedWithCode function-call operator.
6647 bool ExitedWithCode::operator()(int exit_status) const {
6648 # if GTEST_OS_WINDOWS
6649 
6650  return exit_status == exit_code_;
6651 
6652 # else
6653 
6654  return WIFEXITED(exit_status) && WEXITSTATUS(exit_status) == exit_code_;
6655 
6656 # endif // GTEST_OS_WINDOWS
6657 }
6658 
6659 # if !GTEST_OS_WINDOWS
6660 // KilledBySignal constructor.
6661 KilledBySignal::KilledBySignal(int signum) : signum_(signum) {
6662 }
6663 
6664 // KilledBySignal function-call operator.
6665 bool KilledBySignal::operator()(int exit_status) const {
6666  return WIFSIGNALED(exit_status) && WTERMSIG(exit_status) == signum_;
6667 }
6668 # endif // !GTEST_OS_WINDOWS
6669 
6670 namespace internal {
6671 
6672 // Utilities needed for death tests.
6673 
6674 // Generates a textual description of a given exit code, in the format
6675 // specified by wait(2).
6676 static std::string ExitSummary(int exit_code) {
6677  Message m;
6678 
6679 # if GTEST_OS_WINDOWS
6680 
6681  m << "Exited with exit status " << exit_code;
6682 
6683 # else
6684 
6685  if (WIFEXITED(exit_code)) {
6686  m << "Exited with exit status " << WEXITSTATUS(exit_code);
6687  } else if (WIFSIGNALED(exit_code)) {
6688  m << "Terminated by signal " << WTERMSIG(exit_code);
6689  }
6690 # ifdef WCOREDUMP
6691  if (WCOREDUMP(exit_code)) {
6692  m << " (core dumped)";
6693  }
6694 # endif
6695 # endif // GTEST_OS_WINDOWS
6696 
6697  return m.GetString();
6698 }
6699 
6700 // Returns true if exit_status describes a process that was terminated
6701 // by a signal, or exited normally with a nonzero exit code.
6702 bool ExitedUnsuccessfully(int exit_status) {
6703  return !ExitedWithCode(0)(exit_status);
6704 }
6705 
6706 # if !GTEST_OS_WINDOWS
6707 // Generates a textual failure message when a death test finds more than
6708 // one thread running, or cannot determine the number of threads, prior
6709 // to executing the given statement. It is the responsibility of the
6710 // caller not to pass a thread_count of 1.
6711 static std::string DeathTestThreadWarning(size_t thread_count) {
6712  Message msg;
6713  msg << "Death tests use fork(), which is unsafe particularly"
6714  << " in a threaded context. For this test, " << GTEST_NAME_ << " ";
6715  if (thread_count == 0)
6716  msg << "couldn't detect the number of threads.";
6717  else
6718  msg << "detected " << thread_count << " threads.";
6719  return msg.GetString();
6720 }
6721 # endif // !GTEST_OS_WINDOWS
6722 
6723 // Flag characters for reporting a death test that did not die.
6724 static const char kDeathTestLived = 'L';
6725 static const char kDeathTestReturned = 'R';
6726 static const char kDeathTestThrew = 'T';
6727 static const char kDeathTestInternalError = 'I';
6728 
6729 // An enumeration describing all of the possible ways that a death test can
6730 // conclude. DIED means that the process died while executing the test
6731 // code; LIVED means that process lived beyond the end of the test code;
6732 // RETURNED means that the test statement attempted to execute a return
6733 // statement, which is not allowed; THREW means that the test statement
6734 // returned control by throwing an exception. IN_PROGRESS means the test
6735 // has not yet concluded.
6736 // TODO(vladl@google.com): Unify names and possibly values for
6737 // AbortReason, DeathTestOutcome, and flag characters above.
6738 enum DeathTestOutcome { IN_PROGRESS, DIED, LIVED, RETURNED, THREW };
6739 
6740 // Routine for aborting the program which is safe to call from an
6741 // exec-style death test child process, in which case the error
6742 // message is propagated back to the parent process. Otherwise, the
6743 // message is simply printed to stderr. In either case, the program
6744 // then exits with status 1.
6745 void DeathTestAbort(const std::string& message) {
6746  // On a POSIX system, this function may be called from a threadsafe-style
6747  // death test child process, which operates on a very small stack. Use
6748  // the heap for any additional non-minuscule memory requirements.
6749  const InternalRunDeathTestFlag* const flag =
6750  GetUnitTestImpl()->internal_run_death_test_flag();
6751  if (flag != NULL) {
6752  FILE* parent = posix::FDOpen(flag->write_fd(), "w");
6753  fputc(kDeathTestInternalError, parent);
6754  fprintf(parent, "%s", message.c_str());
6755  fflush(parent);
6756  _exit(1);
6757  } else {
6758  fprintf(stderr, "%s", message.c_str());
6759  fflush(stderr);
6760  posix::Abort();
6761  }
6762 }
6763 
6764 // A replacement for CHECK that calls DeathTestAbort if the assertion
6765 // fails.
6766 # define GTEST_DEATH_TEST_CHECK_(expression) \
6767  do { \
6768  if (!::testing::internal::IsTrue(expression)) { \
6769  DeathTestAbort( \
6770  ::std::string("CHECK failed: File ") + __FILE__ + ", line " \
6771  + ::testing::internal::StreamableToString(__LINE__) + ": " \
6772  + #expression); \
6773  } \
6774  } while (::testing::internal::AlwaysFalse())
6775 
6776 // This macro is similar to GTEST_DEATH_TEST_CHECK_, but it is meant for
6777 // evaluating any system call that fulfills two conditions: it must return
6778 // -1 on failure, and set errno to EINTR when it is interrupted and
6779 // should be tried again. The macro expands to a loop that repeatedly
6780 // evaluates the expression as long as it evaluates to -1 and sets
6781 // errno to EINTR. If the expression evaluates to -1 but errno is
6782 // something other than EINTR, DeathTestAbort is called.
6783 # define GTEST_DEATH_TEST_CHECK_SYSCALL_(expression) \
6784  do { \
6785  int gtest_retval; \
6786  do { \
6787  gtest_retval = (expression); \
6788  } while (gtest_retval == -1 && errno == EINTR); \
6789  if (gtest_retval == -1) { \
6790  DeathTestAbort( \
6791  ::std::string("CHECK failed: File ") + __FILE__ + ", line " \
6792  + ::testing::internal::StreamableToString(__LINE__) + ": " \
6793  + #expression + " != -1"); \
6794  } \
6795  } while (::testing::internal::AlwaysFalse())
6796 
6797 // Returns the message describing the last system error in errno.
6798 std::string GetLastErrnoDescription() {
6799  return errno == 0 ? "" : posix::StrError(errno);
6800 }
6801 
6802 // This is called from a death test parent process to read a failure
6803 // message from the death test child process and log it with the FATAL
6804 // severity. On Windows, the message is read from a pipe handle. On other
6805 // platforms, it is read from a file descriptor.
6806 static void FailFromInternalError(int fd) {
6807  Message error;
6808  char buffer[256];
6809  int num_read;
6810 
6811  do {
6812  while ((num_read = posix::Read(fd, buffer, 255)) > 0) {
6813  buffer[num_read] = '\0';
6814  error << buffer;
6815  }
6816  } while (num_read == -1 && errno == EINTR);
6817 
6818  if (num_read == 0) {
6819  GTEST_LOG_(FATAL) << error.GetString();
6820  } else {
6821  const int last_error = errno;
6822  GTEST_LOG_(FATAL) << "Error while reading death test internal: "
6823  << GetLastErrnoDescription() << " [" << last_error << "]";
6824  }
6825 }
6826 
6827 // Death test constructor. Increments the running death test count
6828 // for the current test.
6829 DeathTest::DeathTest() {
6831  if (info == NULL) {
6832  DeathTestAbort("Cannot run a death test outside of a TEST or "
6833  "TEST_F construct");
6834  }
6835 }
6836 
6837 // Creates and returns a death test by dispatching to the current
6838 // death test factory.
6839 bool DeathTest::Create(const char* statement, const RE* regex,
6840  const char* file, int line, DeathTest** test) {
6841  return GetUnitTestImpl()->death_test_factory()->Create(
6842  statement, regex, file, line, test);
6843 }
6844 
6845 const char* DeathTest::LastMessage() {
6846  return last_death_test_message_.c_str();
6847 }
6848 
6849 void DeathTest::set_last_death_test_message(const std::string& message) {
6850  last_death_test_message_ = message;
6851 }
6852 
6853 std::string DeathTest::last_death_test_message_;
6854 
6855 // Provides cross platform implementation for some death functionality.
6856 class DeathTestImpl : public DeathTest {
6857  protected:
6858  DeathTestImpl(const char* a_statement, const RE* a_regex)
6859  : statement_(a_statement),
6860  regex_(a_regex),
6861  spawned_(false),
6862  status_(-1),
6863  outcome_(IN_PROGRESS),
6864  read_fd_(-1),
6865  write_fd_(-1) {}
6866 
6867  // read_fd_ is expected to be closed and cleared by a derived class.
6868  ~DeathTestImpl() { GTEST_DEATH_TEST_CHECK_(read_fd_ == -1); }
6869 
6870  void Abort(AbortReason reason);
6871  virtual bool Passed(bool status_ok);
6872 
6873  const char* statement() const { return statement_; }
6874  const RE* regex() const { return regex_; }
6875  bool spawned() const { return spawned_; }
6876  void set_spawned(bool is_spawned) { spawned_ = is_spawned; }
6877  int status() const { return status_; }
6878  void set_status(int a_status) { status_ = a_status; }
6879  DeathTestOutcome outcome() const { return outcome_; }
6880  void set_outcome(DeathTestOutcome an_outcome) { outcome_ = an_outcome; }
6881  int read_fd() const { return read_fd_; }
6882  void set_read_fd(int fd) { read_fd_ = fd; }
6883  int write_fd() const { return write_fd_; }
6884  void set_write_fd(int fd) { write_fd_ = fd; }
6885 
6886  // Called in the parent process only. Reads the result code of the death
6887  // test child process via a pipe, interprets it to set the outcome_
6888  // member, and closes read_fd_. Outputs diagnostics and terminates in
6889  // case of unexpected codes.
6890  void ReadAndInterpretStatusByte();
6891 
6892  private:
6893  // The textual content of the code this object is testing. This class
6894  // doesn't own this string and should not attempt to delete it.
6895  const char* const statement_;
6896  // The regular expression which test output must match. DeathTestImpl
6897  // doesn't own this object and should not attempt to delete it.
6898  const RE* const regex_;
6899  // True if the death test child process has been successfully spawned.
6900  bool spawned_;
6901  // The exit status of the child process.
6902  int status_;
6903  // How the death test concluded.
6904  DeathTestOutcome outcome_;
6905  // Descriptor to the read end of the pipe to the child process. It is
6906  // always -1 in the child process. The child keeps its write end of the
6907  // pipe in write_fd_.
6908  int read_fd_;
6909  // Descriptor to the child's write end of the pipe to the parent process.
6910  // It is always -1 in the parent process. The parent keeps its end of the
6911  // pipe in read_fd_.
6912  int write_fd_;
6913 };
6914 
6915 // Called in the parent process only. Reads the result code of the death
6916 // test child process via a pipe, interprets it to set the outcome_
6917 // member, and closes read_fd_. Outputs diagnostics and terminates in
6918 // case of unexpected codes.
6919 void DeathTestImpl::ReadAndInterpretStatusByte() {
6920  char flag;
6921  int bytes_read;
6922 
6923  // The read() here blocks until data is available (signifying the
6924  // failure of the death test) or until the pipe is closed (signifying
6925  // its success), so it's okay to call this in the parent before
6926  // the child process has exited.
6927  do {
6928  bytes_read = posix::Read(read_fd(), &flag, 1);
6929  } while (bytes_read == -1 && errno == EINTR);
6930 
6931  if (bytes_read == 0) {
6932  set_outcome(DIED);
6933  } else if (bytes_read == 1) {
6934  switch (flag) {
6935  case kDeathTestReturned:
6936  set_outcome(RETURNED);
6937  break;
6938  case kDeathTestThrew:
6939  set_outcome(THREW);
6940  break;
6941  case kDeathTestLived:
6942  set_outcome(LIVED);
6943  break;
6944  case kDeathTestInternalError:
6945  FailFromInternalError(read_fd()); // Does not return.
6946  break;
6947  default:
6948  GTEST_LOG_(FATAL) << "Death test child process reported "
6949  << "unexpected status byte ("
6950  << static_cast<unsigned int>(flag) << ")";
6951  }
6952  } else {
6953  GTEST_LOG_(FATAL) << "Read from death test child process failed: "
6954  << GetLastErrnoDescription();
6955  }
6956  GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Close(read_fd()));
6957  set_read_fd(-1);
6958 }
6959 
6960 // Signals that the death test code which should have exited, didn't.
6961 // Should be called only in a death test child process.
6962 // Writes a status byte to the child's status file descriptor, then
6963 // calls _exit(1).
6964 void DeathTestImpl::Abort(AbortReason reason) {
6965  // The parent process considers the death test to be a failure if
6966  // it finds any data in our pipe. So, here we write a single flag byte
6967  // to the pipe, then exit.
6968  const char status_ch =
6969  reason == TEST_DID_NOT_DIE ? kDeathTestLived :
6970  reason == TEST_THREW_EXCEPTION ? kDeathTestThrew : kDeathTestReturned;
6971 
6972  GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Write(write_fd(), &status_ch, 1));
6973  // We are leaking the descriptor here because on some platforms (i.e.,
6974  // when built as Windows DLL), destructors of global objects will still
6975  // run after calling _exit(). On such systems, write_fd_ will be
6976  // indirectly closed from the destructor of UnitTestImpl, causing double
6977  // close if it is also closed here. On debug configurations, double close
6978  // may assert. As there are no in-process buffers to flush here, we are
6979  // relying on the OS to close the descriptor after the process terminates
6980  // when the destructors are not run.
6981  _exit(1); // Exits w/o any normal exit hooks (we were supposed to crash)
6982 }
6983 
6984 // Returns an indented copy of stderr output for a death test.
6985 // This makes distinguishing death test output lines from regular log lines
6986 // much easier.
6987 static ::std::string FormatDeathTestOutput(const ::std::string& output) {
6988  ::std::string ret;
6989  for (size_t at = 0; ; ) {
6990  const size_t line_end = output.find('\n', at);
6991  ret += "[ DEATH ] ";
6992  if (line_end == ::std::string::npos) {
6993  ret += output.substr(at);
6994  break;
6995  }
6996  ret += output.substr(at, line_end + 1 - at);
6997  at = line_end + 1;
6998  }
6999  return ret;
7000 }
7001 
7002 // Assesses the success or failure of a death test, using both private
7003 // members which have previously been set, and one argument:
7004 //
7005 // Private data members:
7006 // outcome: An enumeration describing how the death test
7007 // concluded: DIED, LIVED, THREW, or RETURNED. The death test
7008 // fails in the latter three cases.
7009 // status: The exit status of the child process. On *nix, it is in the
7010 // in the format specified by wait(2). On Windows, this is the
7011 // value supplied to the ExitProcess() API or a numeric code
7012 // of the exception that terminated the program.
7013 // regex: A regular expression object to be applied to
7014 // the test's captured standard error output; the death test
7015 // fails if it does not match.
7016 //
7017 // Argument:
7018 // status_ok: true if exit_status is acceptable in the context of
7019 // this particular death test, which fails if it is false
7020 //
7021 // Returns true iff all of the above conditions are met. Otherwise, the
7022 // first failing condition, in the order given above, is the one that is
7023 // reported. Also sets the last death test message string.
7024 bool DeathTestImpl::Passed(bool status_ok) {
7025  if (!spawned())
7026  return false;
7027 
7028  const std::string error_message = GetCapturedStderr();
7029 
7030  bool success = false;
7031  Message buffer;
7032 
7033  buffer << "Death test: " << statement() << "\n";
7034  switch (outcome()) {
7035  case LIVED:
7036  buffer << " Result: failed to die.\n"
7037  << " Error msg:\n" << FormatDeathTestOutput(error_message);
7038  break;
7039  case THREW:
7040  buffer << " Result: threw an exception.\n"
7041  << " Error msg:\n" << FormatDeathTestOutput(error_message);
7042  break;
7043  case RETURNED:
7044  buffer << " Result: illegal return in test statement.\n"
7045  << " Error msg:\n" << FormatDeathTestOutput(error_message);
7046  break;
7047  case DIED:
7048  if (status_ok) {
7049  const bool matched = RE::PartialMatch(error_message.c_str(), *regex());
7050  if (matched) {
7051  success = true;
7052  } else {
7053  buffer << " Result: died but not with expected error.\n"
7054  << " Expected: " << regex()->pattern() << "\n"
7055  << "Actual msg:\n" << FormatDeathTestOutput(error_message);
7056  }
7057  } else {
7058  buffer << " Result: died but not with expected exit code:\n"
7059  << " " << ExitSummary(status()) << "\n"
7060  << "Actual msg:\n" << FormatDeathTestOutput(error_message);
7061  }
7062  break;
7063  case IN_PROGRESS:
7064  default:
7065  GTEST_LOG_(FATAL)
7066  << "DeathTest::Passed somehow called before conclusion of test";
7067  }
7068 
7069  DeathTest::set_last_death_test_message(buffer.GetString());
7070  return success;
7071 }
7072 
7073 # if GTEST_OS_WINDOWS
7074 // WindowsDeathTest implements death tests on Windows. Due to the
7075 // specifics of starting new processes on Windows, death tests there are
7076 // always threadsafe, and Google Test considers the
7077 // --gtest_death_test_style=fast setting to be equivalent to
7078 // --gtest_death_test_style=threadsafe there.
7079 //
7080 // A few implementation notes: Like the Linux version, the Windows
7081 // implementation uses pipes for child-to-parent communication. But due to
7082 // the specifics of pipes on Windows, some extra steps are required:
7083 //
7084 // 1. The parent creates a communication pipe and stores handles to both
7085 // ends of it.
7086 // 2. The parent starts the child and provides it with the information
7087 // necessary to acquire the handle to the write end of the pipe.
7088 // 3. The child acquires the write end of the pipe and signals the parent
7089 // using a Windows event.
7090 // 4. Now the parent can release the write end of the pipe on its side. If
7091 // this is done before step 3, the object's reference count goes down to
7092 // 0 and it is destroyed, preventing the child from acquiring it. The
7093 // parent now has to release it, or read operations on the read end of
7094 // the pipe will not return when the child terminates.
7095 // 5. The parent reads child's output through the pipe (outcome code and
7096 // any possible error messages) from the pipe, and its stderr and then
7097 // determines whether to fail the test.
7098 //
7099 // Note: to distinguish Win32 API calls from the local method and function
7100 // calls, the former are explicitly resolved in the global namespace.
7101 //
7102 class WindowsDeathTest : public DeathTestImpl {
7103  public:
7104  WindowsDeathTest(const char* a_statement,
7105  const RE* a_regex,
7106  const char* file,
7107  int line)
7108  : DeathTestImpl(a_statement, a_regex), file_(file), line_(line) {}
7109 
7110  // All of these virtual functions are inherited from DeathTest.
7111  virtual int Wait();
7112  virtual TestRole AssumeRole();
7113 
7114  private:
7115  // The name of the file in which the death test is located.
7116  const char* const file_;
7117  // The line number on which the death test is located.
7118  const int line_;
7119  // Handle to the write end of the pipe to the child process.
7120  AutoHandle write_handle_;
7121  // Child process handle.
7122  AutoHandle child_handle_;
7123  // Event the child process uses to signal the parent that it has
7124  // acquired the handle to the write end of the pipe. After seeing this
7125  // event the parent can release its own handles to make sure its
7126  // ReadFile() calls return when the child terminates.
7127  AutoHandle event_handle_;
7128 };
7129 
7130 // Waits for the child in a death test to exit, returning its exit
7131 // status, or 0 if no child process exists. As a side effect, sets the
7132 // outcome data member.
7133 int WindowsDeathTest::Wait() {
7134  if (!spawned())
7135  return 0;
7136 
7137  // Wait until the child either signals that it has acquired the write end
7138  // of the pipe or it dies.
7139  const HANDLE wait_handles[2] = { child_handle_.Get(), event_handle_.Get() };
7140  switch (::WaitForMultipleObjects(2,
7141  wait_handles,
7142  FALSE, // Waits for any of the handles.
7143  INFINITE)) {
7144  case WAIT_OBJECT_0:
7145  case WAIT_OBJECT_0 + 1:
7146  break;
7147  default:
7148  GTEST_DEATH_TEST_CHECK_(false); // Should not get here.
7149  }
7150 
7151  // The child has acquired the write end of the pipe or exited.
7152  // We release the handle on our side and continue.
7153  write_handle_.Reset();
7154  event_handle_.Reset();
7155 
7156  ReadAndInterpretStatusByte();
7157 
7158  // Waits for the child process to exit if it haven't already. This
7159  // returns immediately if the child has already exited, regardless of
7160  // whether previous calls to WaitForMultipleObjects synchronized on this
7161  // handle or not.
7162  GTEST_DEATH_TEST_CHECK_(
7163  WAIT_OBJECT_0 == ::WaitForSingleObject(child_handle_.Get(),
7164  INFINITE));
7165  DWORD status_code;
7166  GTEST_DEATH_TEST_CHECK_(
7167  ::GetExitCodeProcess(child_handle_.Get(), &status_code) != FALSE);
7168  child_handle_.Reset();
7169  set_status(static_cast<int>(status_code));
7170  return status();
7171 }
7172 
7173 // The AssumeRole process for a Windows death test. It creates a child
7174 // process with the same executable as the current process to run the
7175 // death test. The child process is given the --gtest_filter and
7176 // --gtest_internal_run_death_test flags such that it knows to run the
7177 // current death test only.
7178 DeathTest::TestRole WindowsDeathTest::AssumeRole() {
7179  const UnitTestImpl* const impl = GetUnitTestImpl();
7180  const InternalRunDeathTestFlag* const flag =
7181  impl->internal_run_death_test_flag();
7182  const TestInfo* const info = impl->current_test_info();
7183  const int death_test_index = info->result()->death_test_count();
7184 
7185  if (flag != NULL) {
7186  // ParseInternalRunDeathTestFlag() has performed all the necessary
7187  // processing.
7188  set_write_fd(flag->write_fd());
7189  return EXECUTE_TEST;
7190  }
7191 
7192  // WindowsDeathTest uses an anonymous pipe to communicate results of
7193  // a death test.
7194  SECURITY_ATTRIBUTES handles_are_inheritable = {
7195  sizeof(SECURITY_ATTRIBUTES), NULL, TRUE };
7196  HANDLE read_handle, write_handle;
7197  GTEST_DEATH_TEST_CHECK_(
7198  ::CreatePipe(&read_handle, &write_handle, &handles_are_inheritable,
7199  0) // Default buffer size.
7200  != FALSE);
7201  set_read_fd(::_open_osfhandle(reinterpret_cast<intptr_t>(read_handle),
7202  O_RDONLY));
7203  write_handle_.Reset(write_handle);
7204  event_handle_.Reset(::CreateEvent(
7205  &handles_are_inheritable,
7206  TRUE, // The event will automatically reset to non-signaled state.
7207  FALSE, // The initial state is non-signalled.
7208  NULL)); // The even is unnamed.
7209  GTEST_DEATH_TEST_CHECK_(event_handle_.Get() != NULL);
7210  const std::string filter_flag =
7211  std::string("--") + GTEST_FLAG_PREFIX_ + kFilterFlag + "=" +
7212  info->test_case_name() + "." + info->name();
7213  const std::string internal_flag =
7215  "=" + file_ + "|" + StreamableToString(line_) + "|" +
7216  StreamableToString(death_test_index) + "|" +
7217  StreamableToString(static_cast<unsigned int>(::GetCurrentProcessId())) +
7218  // size_t has the same width as pointers on both 32-bit and 64-bit
7219  // Windows platforms.
7220  // See http://msdn.microsoft.com/en-us/library/tcxf1dw6.aspx.
7221  "|" + StreamableToString(reinterpret_cast<size_t>(write_handle)) +
7222  "|" + StreamableToString(reinterpret_cast<size_t>(event_handle_.Get()));
7223 
7224  char executable_path[_MAX_PATH + 1]; // NOLINT
7225  GTEST_DEATH_TEST_CHECK_(
7226  _MAX_PATH + 1 != ::GetModuleFileNameA(NULL,
7227  executable_path,
7228  _MAX_PATH));
7229 
7230  std::string command_line =
7231  std::string(::GetCommandLineA()) + " " + filter_flag + " \"" +
7232  internal_flag + "\"";
7233 
7234  DeathTest::set_last_death_test_message("");
7235 
7236  CaptureStderr();
7237  // Flush the log buffers since the log streams are shared with the child.
7238  FlushInfoLog();
7239 
7240  // The child process will share the standard handles with the parent.
7241  STARTUPINFOA startup_info;
7242  memset(&startup_info, 0, sizeof(STARTUPINFO));
7243  startup_info.dwFlags = STARTF_USESTDHANDLES;
7244  startup_info.hStdInput = ::GetStdHandle(STD_INPUT_HANDLE);
7245  startup_info.hStdOutput = ::GetStdHandle(STD_OUTPUT_HANDLE);
7246  startup_info.hStdError = ::GetStdHandle(STD_ERROR_HANDLE);
7247 
7248  PROCESS_INFORMATION process_info;
7249  GTEST_DEATH_TEST_CHECK_(::CreateProcessA(
7250  executable_path,
7251  const_cast<char*>(command_line.c_str()),
7252  NULL, // Retuned process handle is not inheritable.
7253  NULL, // Retuned thread handle is not inheritable.
7254  TRUE, // Child inherits all inheritable handles (for write_handle_).
7255  0x0, // Default creation flags.
7256  NULL, // Inherit the parent's environment.
7258  &startup_info,
7259  &process_info) != FALSE);
7260  child_handle_.Reset(process_info.hProcess);
7261  ::CloseHandle(process_info.hThread);
7262  set_spawned(true);
7263  return OVERSEE_TEST;
7264 }
7265 # else // We are not on Windows.
7266 
7267 // ForkingDeathTest provides implementations for most of the abstract
7268 // methods of the DeathTest interface. Only the AssumeRole method is
7269 // left undefined.
7270 class ForkingDeathTest : public DeathTestImpl {
7271  public:
7272  ForkingDeathTest(const char* statement, const RE* regex);
7273 
7274  // All of these virtual functions are inherited from DeathTest.
7275  virtual int Wait();
7276 
7277  protected:
7278  void set_child_pid(pid_t child_pid) { child_pid_ = child_pid; }
7279 
7280  private:
7281  // PID of child process during death test; 0 in the child process itself.
7282  pid_t child_pid_;
7283 };
7284 
7285 // Constructs a ForkingDeathTest.
7286 ForkingDeathTest::ForkingDeathTest(const char* a_statement, const RE* a_regex)
7287  : DeathTestImpl(a_statement, a_regex),
7288  child_pid_(-1) {}
7289 
7290 // Waits for the child in a death test to exit, returning its exit
7291 // status, or 0 if no child process exists. As a side effect, sets the
7292 // outcome data member.
7293 int ForkingDeathTest::Wait() {
7294  if (!spawned())
7295  return 0;
7296 
7297  ReadAndInterpretStatusByte();
7298 
7299  int status_value;
7300  GTEST_DEATH_TEST_CHECK_SYSCALL_(waitpid(child_pid_, &status_value, 0));
7301  set_status(status_value);
7302  return status_value;
7303 }
7304 
7305 // A concrete death test class that forks, then immediately runs the test
7306 // in the child process.
7307 class NoExecDeathTest : public ForkingDeathTest {
7308  public:
7309  NoExecDeathTest(const char* a_statement, const RE* a_regex) :
7310  ForkingDeathTest(a_statement, a_regex) { }
7311  virtual TestRole AssumeRole();
7312 };
7313 
7314 // The AssumeRole process for a fork-and-run death test. It implements a
7315 // straightforward fork, with a simple pipe to transmit the status byte.
7316 DeathTest::TestRole NoExecDeathTest::AssumeRole() {
7317  const size_t thread_count = GetThreadCount();
7318  if (thread_count != 1) {
7319  GTEST_LOG_(WARNING) << DeathTestThreadWarning(thread_count);
7320  }
7321 
7322  int pipe_fd[2];
7323  GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
7324 
7325  DeathTest::set_last_death_test_message("");
7326  CaptureStderr();
7327  // When we fork the process below, the log file buffers are copied, but the
7328  // file descriptors are shared. We flush all log files here so that closing
7329  // the file descriptors in the child process doesn't throw off the
7330  // synchronization between descriptors and buffers in the parent process.
7331  // This is as close to the fork as possible to avoid a race condition in case
7332  // there are multiple threads running before the death test, and another
7333  // thread writes to the log file.
7334  FlushInfoLog();
7335 
7336  const pid_t child_pid = fork();
7337  GTEST_DEATH_TEST_CHECK_(child_pid != -1);
7338  set_child_pid(child_pid);
7339  if (child_pid == 0) {
7340  GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[0]));
7341  set_write_fd(pipe_fd[1]);
7342  // Redirects all logging to stderr in the child process to prevent
7343  // concurrent writes to the log files. We capture stderr in the parent
7344  // process and append the child process' output to a log.
7345  LogToStderr();
7346  // Event forwarding to the listeners of event listener API mush be shut
7347  // down in death test subprocesses.
7349  g_in_fast_death_test_child = true;
7350  return EXECUTE_TEST;
7351  } else {
7352  GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
7353  set_read_fd(pipe_fd[0]);
7354  set_spawned(true);
7355  return OVERSEE_TEST;
7356  }
7357 }
7358 
7359 // A concrete death test class that forks and re-executes the main
7360 // program from the beginning, with command-line flags set that cause
7361 // only this specific death test to be run.
7362 class ExecDeathTest : public ForkingDeathTest {
7363  public:
7364  ExecDeathTest(const char* a_statement, const RE* a_regex,
7365  const char* file, int line) :
7366  ForkingDeathTest(a_statement, a_regex), file_(file), line_(line) { }
7367  virtual TestRole AssumeRole();
7368  private:
7369  static ::std::vector<testing::internal::string>
7370  GetArgvsForDeathTestChildProcess() {
7371  ::std::vector<testing::internal::string> args = GetInjectableArgvs();
7372  return args;
7373  }
7374  // The name of the file in which the death test is located.
7375  const char* const file_;
7376  // The line number on which the death test is located.
7377  const int line_;
7378 };
7379 
7380 // Utility class for accumulating command-line arguments.
7381 class Arguments {
7382  public:
7383  Arguments() {
7384  args_.push_back(NULL);
7385  }
7386 
7387  ~Arguments() {
7388  for (std::vector<char*>::iterator i = args_.begin(); i != args_.end();
7389  ++i) {
7390  free(*i);
7391  }
7392  }
7393  void AddArgument(const char* argument) {
7394  args_.insert(args_.end() - 1, posix::StrDup(argument));
7395  }
7396 
7397  template <typename Str>
7398  void AddArguments(const ::std::vector<Str>& arguments) {
7399  for (typename ::std::vector<Str>::const_iterator i = arguments.begin();
7400  i != arguments.end();
7401  ++i) {
7402  args_.insert(args_.end() - 1, posix::StrDup(i->c_str()));
7403  }
7404  }
7405  char* const* Argv() {
7406  return &args_[0];
7407  }
7408 
7409  private:
7410  std::vector<char*> args_;
7411 };
7412 
7413 // A struct that encompasses the arguments to the child process of a
7414 // threadsafe-style death test process.
7415 struct ExecDeathTestArgs {
7416  char* const* argv; // Command-line arguments for the child's call to exec
7417  int close_fd; // File descriptor to close; the read end of a pipe
7418 };
7419 
7420 # if GTEST_OS_MAC
7421 inline char** GetEnviron() {
7422  // When Google Test is built as a framework on MacOS X, the environ variable
7423  // is unavailable. Apple's documentation (man environ) recommends using
7424  // _NSGetEnviron() instead.
7425  return *_NSGetEnviron();
7426 }
7427 # else
7428 // Some POSIX platforms expect you to declare environ. extern "C" makes
7429 // it reside in the global namespace.
7430 extern "C" char** environ;
7431 inline char** GetEnviron() { return environ; }
7432 # endif // GTEST_OS_MAC
7433 
7434 # if !GTEST_OS_QNX
7435 // The main function for a threadsafe-style death test child process.
7436 // This function is called in a clone()-ed process and thus must avoid
7437 // any potentially unsafe operations like malloc or libc functions.
7438 static int ExecDeathTestChildMain(void* child_arg) {
7439  ExecDeathTestArgs* const args = static_cast<ExecDeathTestArgs*>(child_arg);
7440  GTEST_DEATH_TEST_CHECK_SYSCALL_(close(args->close_fd));
7441 
7442  // We need to execute the test program in the same environment where
7443  // it was originally invoked. Therefore we change to the original
7444  // working directory first.
7445  const char* const original_dir =
7447  // We can safely call chdir() as it's a direct system call.
7448  if (chdir(original_dir) != 0) {
7449  DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " +
7450  GetLastErrnoDescription());
7451  return EXIT_FAILURE;
7452  }
7453 
7454  // We can safely call execve() as it's a direct system call. We
7455  // cannot use execvp() as it's a libc function and thus potentially
7456  // unsafe. Since execve() doesn't search the PATH, the user must
7457  // invoke the test program via a valid path that contains at least
7458  // one path separator.
7459  execve(args->argv[0], args->argv, GetEnviron());
7460  DeathTestAbort(std::string("execve(") + args->argv[0] + ", ...) in " +
7461  original_dir + " failed: " +
7462  GetLastErrnoDescription());
7463  return EXIT_FAILURE;
7464 }
7465 # endif // !GTEST_OS_QNX
7466 
7467 // Two utility routines that together determine the direction the stack
7468 // grows.
7469 // This could be accomplished more elegantly by a single recursive
7470 // function, but we want to guard against the unlikely possibility of
7471 // a smart compiler optimizing the recursion away.
7472 //
7473 // GTEST_NO_INLINE_ is required to prevent GCC 4.6 from inlining
7474 // StackLowerThanAddress into StackGrowsDown, which then doesn't give
7475 // correct answer.
7476 void StackLowerThanAddress(const void* ptr, bool* result) GTEST_NO_INLINE_;
7477 void StackLowerThanAddress(const void* ptr, bool* result) {
7478  int dummy;
7479  *result = (&dummy < ptr);
7480 }
7481 
7482 bool StackGrowsDown() {
7483  int dummy;
7484  bool result;
7485  StackLowerThanAddress(&dummy, &result);
7486  return result;
7487 }
7488 
7489 // Spawns a child process with the same executable as the current process in
7490 // a thread-safe manner and instructs it to run the death test. The
7491 // implementation uses fork(2) + exec. On systems where clone(2) is
7492 // available, it is used instead, being slightly more thread-safe. On QNX,
7493 // fork supports only single-threaded environments, so this function uses
7494 // spawn(2) there instead. The function dies with an error message if
7495 // anything goes wrong.
7496 static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) {
7497  ExecDeathTestArgs args = { argv, close_fd };
7498  pid_t child_pid = -1;
7499 
7500 # if GTEST_OS_QNX
7501  // Obtains the current directory and sets it to be closed in the child
7502  // process.
7503  const int cwd_fd = open(".", O_RDONLY);
7504  GTEST_DEATH_TEST_CHECK_(cwd_fd != -1);
7505  GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(cwd_fd, F_SETFD, FD_CLOEXEC));
7506  // We need to execute the test program in the same environment where
7507  // it was originally invoked. Therefore we change to the original
7508  // working directory first.
7509  const char* const original_dir =
7511  // We can safely call chdir() as it's a direct system call.
7512  if (chdir(original_dir) != 0) {
7513  DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " +
7514  GetLastErrnoDescription());
7515  return EXIT_FAILURE;
7516  }
7517 
7518  int fd_flags;
7519  // Set close_fd to be closed after spawn.
7520  GTEST_DEATH_TEST_CHECK_SYSCALL_(fd_flags = fcntl(close_fd, F_GETFD));
7521  GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(close_fd, F_SETFD,
7522  fd_flags | FD_CLOEXEC));
7523  struct inheritance inherit = {0};
7524  // spawn is a system call.
7525  child_pid = spawn(args.argv[0], 0, NULL, &inherit, args.argv, GetEnviron());
7526  // Restores the current working directory.
7527  GTEST_DEATH_TEST_CHECK_(fchdir(cwd_fd) != -1);
7528  GTEST_DEATH_TEST_CHECK_SYSCALL_(close(cwd_fd));
7529 
7530 # else // GTEST_OS_QNX
7531 # if GTEST_OS_LINUX
7532  // When a SIGPROF signal is received while fork() or clone() are executing,
7533  // the process may hang. To avoid this, we ignore SIGPROF here and re-enable
7534  // it after the call to fork()/clone() is complete.
7535  struct sigaction saved_sigprof_action;
7536  struct sigaction ignore_sigprof_action;
7537  memset(&ignore_sigprof_action, 0, sizeof(ignore_sigprof_action));
7538  sigemptyset(&ignore_sigprof_action.sa_mask);
7539  ignore_sigprof_action.sa_handler = SIG_IGN;
7540  GTEST_DEATH_TEST_CHECK_SYSCALL_(sigaction(
7541  SIGPROF, &ignore_sigprof_action, &saved_sigprof_action));
7542 # endif // GTEST_OS_LINUX
7543 
7544 # if GTEST_HAS_CLONE
7545  const bool use_fork = GTEST_FLAG(death_test_use_fork);
7546 
7547  if (!use_fork) {
7548  static const bool stack_grows_down = StackGrowsDown();
7549  const size_t stack_size = getpagesize();
7550  // MMAP_ANONYMOUS is not defined on Mac, so we use MAP_ANON instead.
7551  void* const stack = mmap(NULL, stack_size, PROT_READ | PROT_WRITE,
7552  MAP_ANON | MAP_PRIVATE, -1, 0);
7553  GTEST_DEATH_TEST_CHECK_(stack != MAP_FAILED);
7554 
7555  // Maximum stack alignment in bytes: For a downward-growing stack, this
7556  // amount is subtracted from size of the stack space to get an address
7557  // that is within the stack space and is aligned on all systems we care
7558  // about. As far as I know there is no ABI with stack alignment greater
7559  // than 64. We assume stack and stack_size already have alignment of
7560  // kMaxStackAlignment.
7561  const size_t kMaxStackAlignment = 64;
7562  void* const stack_top =
7563  static_cast<char*>(stack) +
7564  (stack_grows_down ? stack_size - kMaxStackAlignment : 0);
7565  GTEST_DEATH_TEST_CHECK_(stack_size > kMaxStackAlignment &&
7566  reinterpret_cast<intptr_t>(stack_top) % kMaxStackAlignment == 0);
7567 
7568  child_pid = clone(&ExecDeathTestChildMain, stack_top, SIGCHLD, &args);
7569 
7570  GTEST_DEATH_TEST_CHECK_(munmap(stack, stack_size) != -1);
7571  }
7572 # else
7573  const bool use_fork = true;
7574 # endif // GTEST_HAS_CLONE
7575 
7576  if (use_fork && (child_pid = fork()) == 0) {
7577  ExecDeathTestChildMain(&args);
7578  _exit(0);
7579  }
7580 # endif // GTEST_OS_QNX
7581 # if GTEST_OS_LINUX
7582  GTEST_DEATH_TEST_CHECK_SYSCALL_(
7583  sigaction(SIGPROF, &saved_sigprof_action, NULL));
7584 # endif // GTEST_OS_LINUX
7585 
7586  GTEST_DEATH_TEST_CHECK_(child_pid != -1);
7587  return child_pid;
7588 }
7589 
7590 // The AssumeRole process for a fork-and-exec death test. It re-executes the
7591 // main program from the beginning, setting the --gtest_filter
7592 // and --gtest_internal_run_death_test flags to cause only the current
7593 // death test to be re-run.
7594 DeathTest::TestRole ExecDeathTest::AssumeRole() {
7595  const UnitTestImpl* const impl = GetUnitTestImpl();
7596  const InternalRunDeathTestFlag* const flag =
7597  impl->internal_run_death_test_flag();
7598  const TestInfo* const info = impl->current_test_info();
7599  const int death_test_index = info->result()->death_test_count();
7600 
7601  if (flag != NULL) {
7602  set_write_fd(flag->write_fd());
7603  return EXECUTE_TEST;
7604  }
7605 
7606  int pipe_fd[2];
7607  GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
7608  // Clear the close-on-exec flag on the write end of the pipe, lest
7609  // it be closed when the child process does an exec:
7610  GTEST_DEATH_TEST_CHECK_(fcntl(pipe_fd[1], F_SETFD, 0) != -1);
7611 
7612  const std::string filter_flag =
7614  + info->test_case_name() + "." + info->name();
7615  const std::string internal_flag =
7617  + file_ + "|" + StreamableToString(line_) + "|"
7618  + StreamableToString(death_test_index) + "|"
7619  + StreamableToString(pipe_fd[1]);
7620  Arguments args;
7621  args.AddArguments(GetArgvsForDeathTestChildProcess());
7622  args.AddArgument(filter_flag.c_str());
7623  args.AddArgument(internal_flag.c_str());
7624 
7625  DeathTest::set_last_death_test_message("");
7626 
7627  CaptureStderr();
7628  // See the comment in NoExecDeathTest::AssumeRole for why the next line
7629  // is necessary.
7630  FlushInfoLog();
7631 
7632  const pid_t child_pid = ExecDeathTestSpawnChild(args.Argv(), pipe_fd[0]);
7633  GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
7634  set_child_pid(child_pid);
7635  set_read_fd(pipe_fd[0]);
7636  set_spawned(true);
7637  return OVERSEE_TEST;
7638 }
7639 
7640 # endif // !GTEST_OS_WINDOWS
7641 
7642 // Creates a concrete DeathTest-derived class that depends on the
7643 // --gtest_death_test_style flag, and sets the pointer pointed to
7644 // by the "test" argument to its address. If the test should be
7645 // skipped, sets that pointer to NULL. Returns true, unless the
7646 // flag is set to an invalid value.
7647 bool DefaultDeathTestFactory::Create(const char* statement, const RE* regex,
7648  const char* file, int line,
7649  DeathTest** test) {
7650  UnitTestImpl* const impl = GetUnitTestImpl();
7651  const InternalRunDeathTestFlag* const flag =
7652  impl->internal_run_death_test_flag();
7653  const int death_test_index = impl->current_test_info()
7654  ->increment_death_test_count();
7655 
7656  if (flag != NULL) {
7657  if (death_test_index > flag->index()) {
7658  DeathTest::set_last_death_test_message(
7659  "Death test count (" + StreamableToString(death_test_index)
7660  + ") somehow exceeded expected maximum ("
7661  + StreamableToString(flag->index()) + ")");
7662  return false;
7663  }
7664 
7665  if (!(flag->file() == file && flag->line() == line &&
7666  flag->index() == death_test_index)) {
7667  *test = NULL;
7668  return true;
7669  }
7670  }
7671 
7672 # if GTEST_OS_WINDOWS
7673 
7674  if (GTEST_FLAG(death_test_style) == "threadsafe" ||
7675  GTEST_FLAG(death_test_style) == "fast") {
7676  *test = new WindowsDeathTest(statement, regex, file, line);
7677  }
7678 
7679 # else
7680 
7681  if (GTEST_FLAG(death_test_style) == "threadsafe") {
7682  *test = new ExecDeathTest(statement, regex, file, line);
7683  } else if (GTEST_FLAG(death_test_style) == "fast") {
7684  *test = new NoExecDeathTest(statement, regex);
7685  }
7686 
7687 # endif // GTEST_OS_WINDOWS
7688 
7689  else { // NOLINT - this is more readable than unbalanced brackets inside #if.
7690  DeathTest::set_last_death_test_message(
7691  "Unknown death test style \"" + GTEST_FLAG(death_test_style)
7692  + "\" encountered");
7693  return false;
7694  }
7695 
7696  return true;
7697 }
7698 
7699 // Splits a given string on a given delimiter, populating a given
7700 // vector with the fields. GTEST_HAS_DEATH_TEST implies that we have
7701 // ::std::string, so we can use it here.
7702 static void SplitString(const ::std::string& str, char delimiter,
7703  ::std::vector< ::std::string>* dest) {
7704  ::std::vector< ::std::string> parsed;
7705  ::std::string::size_type pos = 0;
7706  while (::testing::internal::AlwaysTrue()) {
7707  const ::std::string::size_type colon = str.find(delimiter, pos);
7708  if (colon == ::std::string::npos) {
7709  parsed.push_back(str.substr(pos));
7710  break;
7711  } else {
7712  parsed.push_back(str.substr(pos, colon - pos));
7713  pos = colon + 1;
7714  }
7715  }
7716  dest->swap(parsed);
7717 }
7718 
7719 # if GTEST_OS_WINDOWS
7720 // Recreates the pipe and event handles from the provided parameters,
7721 // signals the event, and returns a file descriptor wrapped around the pipe
7722 // handle. This function is called in the child process only.
7723 int GetStatusFileDescriptor(unsigned int parent_process_id,
7724  size_t write_handle_as_size_t,
7725  size_t event_handle_as_size_t) {
7726  AutoHandle parent_process_handle(::OpenProcess(PROCESS_DUP_HANDLE,
7727  FALSE, // Non-inheritable.
7728  parent_process_id));
7729  if (parent_process_handle.Get() == INVALID_HANDLE_VALUE) {
7730  DeathTestAbort("Unable to open parent process " +
7731  StreamableToString(parent_process_id));
7732  }
7733 
7734  // TODO(vladl@google.com): Replace the following check with a
7735  // compile-time assertion when available.
7736  GTEST_CHECK_(sizeof(HANDLE) <= sizeof(size_t));
7737 
7738  const HANDLE write_handle =
7739  reinterpret_cast<HANDLE>(write_handle_as_size_t);
7740  HANDLE dup_write_handle;
7741 
7742  // The newly initialized handle is accessible only in in the parent
7743  // process. To obtain one accessible within the child, we need to use
7744  // DuplicateHandle.
7745  if (!::DuplicateHandle(parent_process_handle.Get(), write_handle,
7746  ::GetCurrentProcess(), &dup_write_handle,
7747  0x0, // Requested privileges ignored since
7748  // DUPLICATE_SAME_ACCESS is used.
7749  FALSE, // Request non-inheritable handler.
7750  DUPLICATE_SAME_ACCESS)) {
7751  DeathTestAbort("Unable to duplicate the pipe handle " +
7752  StreamableToString(write_handle_as_size_t) +
7753  " from the parent process " +
7754  StreamableToString(parent_process_id));
7755  }
7756 
7757  const HANDLE event_handle = reinterpret_cast<HANDLE>(event_handle_as_size_t);
7758  HANDLE dup_event_handle;
7759 
7760  if (!::DuplicateHandle(parent_process_handle.Get(), event_handle,
7761  ::GetCurrentProcess(), &dup_event_handle,
7762  0x0,
7763  FALSE,
7764  DUPLICATE_SAME_ACCESS)) {
7765  DeathTestAbort("Unable to duplicate the event handle " +
7766  StreamableToString(event_handle_as_size_t) +
7767  " from the parent process " +
7768  StreamableToString(parent_process_id));
7769  }
7770 
7771  const int write_fd =
7772  ::_open_osfhandle(reinterpret_cast<intptr_t>(dup_write_handle), O_APPEND);
7773  if (write_fd == -1) {
7774  DeathTestAbort("Unable to convert pipe handle " +
7775  StreamableToString(write_handle_as_size_t) +
7776  " to a file descriptor");
7777  }
7778 
7779  // Signals the parent that the write end of the pipe has been acquired
7780  // so the parent can release its own write end.
7781  ::SetEvent(dup_event_handle);
7782 
7783  return write_fd;
7784 }
7785 # endif // GTEST_OS_WINDOWS
7786 
7787 // Returns a newly created InternalRunDeathTestFlag object with fields
7788 // initialized from the GTEST_FLAG(internal_run_death_test) flag if
7789 // the flag is specified; otherwise returns NULL.
7790 InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() {
7791  if (GTEST_FLAG(internal_run_death_test) == "") return NULL;
7792 
7793  // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we
7794  // can use it here.
7795  int line = -1;
7796  int index = -1;
7797  ::std::vector< ::std::string> fields;
7798  SplitString(GTEST_FLAG(internal_run_death_test).c_str(), '|', &fields);
7799  int write_fd = -1;
7800 
7801 # if GTEST_OS_WINDOWS
7802 
7803  unsigned int parent_process_id = 0;
7804  size_t write_handle_as_size_t = 0;
7805  size_t event_handle_as_size_t = 0;
7806 
7807  if (fields.size() != 6
7808  || !ParseNaturalNumber(fields[1], &line)
7809  || !ParseNaturalNumber(fields[2], &index)
7810  || !ParseNaturalNumber(fields[3], &parent_process_id)
7811  || !ParseNaturalNumber(fields[4], &write_handle_as_size_t)
7812  || !ParseNaturalNumber(fields[5], &event_handle_as_size_t)) {
7813  DeathTestAbort("Bad --gtest_internal_run_death_test flag: " +
7814  GTEST_FLAG(internal_run_death_test));
7815  }
7816  write_fd = GetStatusFileDescriptor(parent_process_id,
7817  write_handle_as_size_t,
7818  event_handle_as_size_t);
7819 # else
7820 
7821  if (fields.size() != 4
7822  || !ParseNaturalNumber(fields[1], &line)
7823  || !ParseNaturalNumber(fields[2], &index)
7824  || !ParseNaturalNumber(fields[3], &write_fd)) {
7825  DeathTestAbort("Bad --gtest_internal_run_death_test flag: "
7826  + GTEST_FLAG(internal_run_death_test));
7827  }
7828 
7829 # endif // GTEST_OS_WINDOWS
7830 
7831  return new InternalRunDeathTestFlag(fields[0], line, index, write_fd);
7832 }
7833 
7834 } // namespace internal
7835 
7836 #endif // GTEST_HAS_DEATH_TEST
7837 
7838 } // namespace testing
7839 // Copyright 2008, Google Inc.
7840 // All rights reserved.
7841 //
7842 // Redistribution and use in source and binary forms, with or without
7843 // modification, are permitted provided that the following conditions are
7844 // met:
7845 //
7846 // * Redistributions of source code must retain the above copyright
7847 // notice, this list of conditions and the following disclaimer.
7848 // * Redistributions in binary form must reproduce the above
7849 // copyright notice, this list of conditions and the following disclaimer
7850 // in the documentation and/or other materials provided with the
7851 // distribution.
7852 // * Neither the name of Google Inc. nor the names of its
7853 // contributors may be used to endorse or promote products derived from
7854 // this software without specific prior written permission.
7855 //
7856 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
7857 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
7858 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
7859 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
7860 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
7861 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
7862 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
7863 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
7864 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
7865 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
7866 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
7867 //
7868 // Authors: keith.ray@gmail.com (Keith Ray)
7869 
7870 
7871 #include <stdlib.h>
7872 
7873 #if GTEST_OS_WINDOWS_MOBILE
7874 # include <windows.h>
7875 #elif GTEST_OS_WINDOWS
7876 # include <direct.h>
7877 # include <io.h>
7878 #elif GTEST_OS_SYMBIAN
7879 // Symbian OpenC has PATH_MAX in sys/syslimits.h
7880 # include <sys/syslimits.h>
7881 #else
7882 # include <limits.h>
7883 # include <climits> // Some Linux distributions define PATH_MAX here.
7884 #endif // GTEST_OS_WINDOWS_MOBILE
7885 
7886 #if GTEST_OS_WINDOWS
7887 # define GTEST_PATH_MAX_ _MAX_PATH
7888 #elif defined(PATH_MAX)
7889 # define GTEST_PATH_MAX_ PATH_MAX
7890 #elif defined(_XOPEN_PATH_MAX)
7891 # define GTEST_PATH_MAX_ _XOPEN_PATH_MAX
7892 #else
7893 # define GTEST_PATH_MAX_ _POSIX_PATH_MAX
7894 #endif // GTEST_OS_WINDOWS
7895 
7896 
7897 namespace testing {
7898 namespace internal {
7899 
7900 #if GTEST_OS_WINDOWS
7901 // On Windows, '\\' is the standard path separator, but many tools and the
7902 // Windows API also accept '/' as an alternate path separator. Unless otherwise
7903 // noted, a file path can contain either kind of path separators, or a mixture
7904 // of them.
7905 const char kPathSeparator = '\\';
7906 const char kAlternatePathSeparator = '/';
7907 const char kPathSeparatorString[] = "\\";
7908 const char kAlternatePathSeparatorString[] = "/";
7909 # if GTEST_OS_WINDOWS_MOBILE
7910 // Windows CE doesn't have a current directory. You should not use
7911 // the current directory in tests on Windows CE, but this at least
7912 // provides a reasonable fallback.
7913 const char kCurrentDirectoryString[] = "\\";
7914 // Windows CE doesn't define INVALID_FILE_ATTRIBUTES
7915 const DWORD kInvalidFileAttributes = 0xffffffff;
7916 # else
7917 const char kCurrentDirectoryString[] = ".\\";
7918 # endif // GTEST_OS_WINDOWS_MOBILE
7919 #else
7920 const char kPathSeparator = '/';
7921 const char kPathSeparatorString[] = "/";
7922 const char kCurrentDirectoryString[] = "./";
7923 #endif // GTEST_OS_WINDOWS
7924 
7925 // Returns whether the given character is a valid path separator.
7926 static bool IsPathSeparator(char c) {
7927 #if GTEST_HAS_ALT_PATH_SEP_
7928  return (c == kPathSeparator) || (c == kAlternatePathSeparator);
7929 #else
7930  return c == kPathSeparator;
7931 #endif
7932 }
7933 
7934 // Returns the current working directory, or "" if unsuccessful.
7935 FilePath FilePath::GetCurrentDir() {
7936 #if GTEST_OS_WINDOWS_MOBILE
7937  // Windows CE doesn't have a current directory, so we just return
7938  // something reasonable.
7939  return FilePath(kCurrentDirectoryString);
7940 #elif GTEST_OS_WINDOWS
7941  char cwd[GTEST_PATH_MAX_ + 1] = { '\0' };
7942  return FilePath(_getcwd(cwd, sizeof(cwd)) == NULL ? "" : cwd);
7943 #else
7944  char cwd[GTEST_PATH_MAX_ + 1] = { '\0' };
7945  return FilePath(getcwd(cwd, sizeof(cwd)) == NULL ? "" : cwd);
7946 #endif // GTEST_OS_WINDOWS_MOBILE
7947 }
7948 
7949 // Returns a copy of the FilePath with the case-insensitive extension removed.
7950 // Example: FilePath("dir/file.exe").RemoveExtension("EXE") returns
7951 // FilePath("dir/file"). If a case-insensitive extension is not
7952 // found, returns a copy of the original FilePath.
7953 FilePath FilePath::RemoveExtension(const char* extension) const {
7954  const std::string dot_extension = std::string(".") + extension;
7955  if (String::EndsWithCaseInsensitive(pathname_, dot_extension)) {
7956  return FilePath(pathname_.substr(
7957  0, pathname_.length() - dot_extension.length()));
7958  }
7959  return *this;
7960 }
7961 
7962 // Returns a pointer to the last occurence of a valid path separator in
7963 // the FilePath. On Windows, for example, both '/' and '\' are valid path
7964 // separators. Returns NULL if no path separator was found.
7965 const char* FilePath::FindLastPathSeparator() const {
7966  const char* const last_sep = strrchr(c_str(), kPathSeparator);
7967 #if GTEST_HAS_ALT_PATH_SEP_
7968  const char* const last_alt_sep = strrchr(c_str(), kAlternatePathSeparator);
7969  // Comparing two pointers of which only one is NULL is undefined.
7970  if (last_alt_sep != NULL &&
7971  (last_sep == NULL || last_alt_sep > last_sep)) {
7972  return last_alt_sep;
7973  }
7974 #endif
7975  return last_sep;
7976 }
7977 
7978 // Returns a copy of the FilePath with the directory part removed.
7979 // Example: FilePath("path/to/file").RemoveDirectoryName() returns
7980 // FilePath("file"). If there is no directory part ("just_a_file"), it returns
7981 // the FilePath unmodified. If there is no file part ("just_a_dir/") it
7982 // returns an empty FilePath ("").
7983 // On Windows platform, '\' is the path separator, otherwise it is '/'.
7984 FilePath FilePath::RemoveDirectoryName() const {
7985  const char* const last_sep = FindLastPathSeparator();
7986  return last_sep ? FilePath(last_sep + 1) : *this;
7987 }
7988 
7989 // RemoveFileName returns the directory path with the filename removed.
7990 // Example: FilePath("path/to/file").RemoveFileName() returns "path/to/".
7991 // If the FilePath is "a_file" or "/a_file", RemoveFileName returns
7992 // FilePath("./") or, on Windows, FilePath(".\\"). If the filepath does
7993 // not have a file, like "just/a/dir/", it returns the FilePath unmodified.
7994 // On Windows platform, '\' is the path separator, otherwise it is '/'.
7995 FilePath FilePath::RemoveFileName() const {
7996  const char* const last_sep = FindLastPathSeparator();
7997  std::string dir;
7998  if (last_sep) {
7999  dir = std::string(c_str(), last_sep + 1 - c_str());
8000  } else {
8002  }
8003  return FilePath(dir);
8004 }
8005 
8006 // Helper functions for naming files in a directory for xml output.
8007 
8008 // Given directory = "dir", base_name = "test", number = 0,
8009 // extension = "xml", returns "dir/test.xml". If number is greater
8010 // than zero (e.g., 12), returns "dir/test_12.xml".
8011 // On Windows platform, uses \ as the separator rather than /.
8012 FilePath FilePath::MakeFileName(const FilePath& directory,
8013  const FilePath& base_name,
8014  int number,
8015  const char* extension) {
8016  std::string file;
8017  if (number == 0) {
8018  file = base_name.string() + "." + extension;
8019  } else {
8020  file = base_name.string() + "_" + StreamableToString(number)
8021  + "." + extension;
8022  }
8023  return ConcatPaths(directory, FilePath(file));
8024 }
8025 
8026 // Given directory = "dir", relative_path = "test.xml", returns "dir/test.xml".
8027 // On Windows, uses \ as the separator rather than /.
8028 FilePath FilePath::ConcatPaths(const FilePath& directory,
8029  const FilePath& relative_path) {
8030  if (directory.IsEmpty())
8031  return relative_path;
8032  const FilePath dir(directory.RemoveTrailingPathSeparator());
8033  return FilePath(dir.string() + kPathSeparator + relative_path.string());
8034 }
8035 
8036 // Returns true if pathname describes something findable in the file-system,
8037 // either a file, directory, or whatever.
8038 bool FilePath::FileOrDirectoryExists() const {
8039 #if GTEST_OS_WINDOWS_MOBILE
8040  LPCWSTR unicode = String::AnsiToUtf16(pathname_.c_str());
8041  const DWORD attributes = GetFileAttributes(unicode);
8042  delete [] unicode;
8043  return attributes != kInvalidFileAttributes;
8044 #else
8045  posix::StatStruct file_stat;
8046  return posix::Stat(pathname_.c_str(), &file_stat) == 0;
8047 #endif // GTEST_OS_WINDOWS_MOBILE
8048 }
8049 
8050 // Returns true if pathname describes a directory in the file-system
8051 // that exists.
8052 bool FilePath::DirectoryExists() const {
8053  bool result = false;
8054 #if GTEST_OS_WINDOWS
8055  // Don't strip off trailing separator if path is a root directory on
8056  // Windows (like "C:\\").
8057  const FilePath& path(IsRootDirectory() ? *this :
8058  RemoveTrailingPathSeparator());
8059 #else
8060  const FilePath& path(*this);
8061 #endif
8062 
8063 #if GTEST_OS_WINDOWS_MOBILE
8064  LPCWSTR unicode = String::AnsiToUtf16(path.c_str());
8065  const DWORD attributes = GetFileAttributes(unicode);
8066  delete [] unicode;
8067  if ((attributes != kInvalidFileAttributes) &&
8068  (attributes & FILE_ATTRIBUTE_DIRECTORY)) {
8069  result = true;
8070  }
8071 #else
8072  posix::StatStruct file_stat;
8073  result = posix::Stat(path.c_str(), &file_stat) == 0 &&
8074  posix::IsDir(file_stat);
8075 #endif // GTEST_OS_WINDOWS_MOBILE
8076 
8077  return result;
8078 }
8079 
8080 // Returns true if pathname describes a root directory. (Windows has one
8081 // root directory per disk drive.)
8082 bool FilePath::IsRootDirectory() const {
8083 #if GTEST_OS_WINDOWS
8084  // TODO(wan@google.com): on Windows a network share like
8085  // \\server\share can be a root directory, although it cannot be the
8086  // current directory. Handle this properly.
8087  return pathname_.length() == 3 && IsAbsolutePath();
8088 #else
8089  return pathname_.length() == 1 && IsPathSeparator(pathname_.c_str()[0]);
8090 #endif
8091 }
8092 
8093 // Returns true if pathname describes an absolute path.
8094 bool FilePath::IsAbsolutePath() const {
8095  const char* const name = pathname_.c_str();
8096 #if GTEST_OS_WINDOWS
8097  return pathname_.length() >= 3 &&
8098  ((name[0] >= 'a' && name[0] <= 'z') ||
8099  (name[0] >= 'A' && name[0] <= 'Z')) &&
8100  name[1] == ':' &&
8101  IsPathSeparator(name[2]);
8102 #else
8103  return IsPathSeparator(name[0]);
8104 #endif
8105 }
8106 
8107 // Returns a pathname for a file that does not currently exist. The pathname
8108 // will be directory/base_name.extension or
8109 // directory/base_name_<number>.extension if directory/base_name.extension
8110 // already exists. The number will be incremented until a pathname is found
8111 // that does not already exist.
8112 // Examples: 'dir/foo_test.xml' or 'dir/foo_test_1.xml'.
8113 // There could be a race condition if two or more processes are calling this
8114 // function at the same time -- they could both pick the same filename.
8115 FilePath FilePath::GenerateUniqueFileName(const FilePath& directory,
8116  const FilePath& base_name,
8117  const char* extension) {
8118  FilePath full_pathname;
8119  int number = 0;
8120  do {
8121  full_pathname.Set(MakeFileName(directory, base_name, number++, extension));
8122  } while (full_pathname.FileOrDirectoryExists());
8123  return full_pathname;
8124 }
8125 
8126 // Returns true if FilePath ends with a path separator, which indicates that
8127 // it is intended to represent a directory. Returns false otherwise.
8128 // This does NOT check that a directory (or file) actually exists.
8129 bool FilePath::IsDirectory() const {
8130  return !pathname_.empty() &&
8131  IsPathSeparator(pathname_.c_str()[pathname_.length() - 1]);
8132 }
8133 
8134 // Create directories so that path exists. Returns true if successful or if
8135 // the directories already exist; returns false if unable to create directories
8136 // for any reason.
8137 bool FilePath::CreateDirectoriesRecursively() const {
8138  if (!this->IsDirectory()) {
8139  return false;
8140  }
8141 
8142  if (pathname_.length() == 0 || this->DirectoryExists()) {
8143  return true;
8144  }
8145 
8146  const FilePath parent(this->RemoveTrailingPathSeparator().RemoveFileName());
8147  return parent.CreateDirectoriesRecursively() && this->CreateFolder();
8148 }
8149 
8150 // Create the directory so that path exists. Returns true if successful or
8151 // if the directory already exists; returns false if unable to create the
8152 // directory for any reason, including if the parent directory does not
8153 // exist. Not named "CreateDirectory" because that's a macro on Windows.
8154 bool FilePath::CreateFolder() const {
8155 #if GTEST_OS_WINDOWS_MOBILE
8156  FilePath removed_sep(this->RemoveTrailingPathSeparator());
8157  LPCWSTR unicode = String::AnsiToUtf16(removed_sep.c_str());
8158  int result = CreateDirectory(unicode, NULL) ? 0 : -1;
8159  delete [] unicode;
8160 #elif GTEST_OS_WINDOWS
8161  int result = _mkdir(pathname_.c_str());
8162 #else
8163  int result = mkdir(pathname_.c_str(), 0777);
8164 #endif // GTEST_OS_WINDOWS_MOBILE
8165 
8166  if (result == -1) {
8167  return this->DirectoryExists(); // An error is OK if the directory exists.
8168  }
8169  return true; // No error.
8170 }
8171 
8172 // If input name has a trailing separator character, remove it and return the
8173 // name, otherwise return the name string unmodified.
8174 // On Windows platform, uses \ as the separator, other platforms use /.
8175 FilePath FilePath::RemoveTrailingPathSeparator() const {
8176  return IsDirectory()
8177  ? FilePath(pathname_.substr(0, pathname_.length() - 1))
8178  : *this;
8179 }
8180 
8181 // Removes any redundant separators that might be in the pathname.
8182 // For example, "bar///foo" becomes "bar/foo". Does not eliminate other
8183 // redundancies that might be in a pathname involving "." or "..".
8184 // TODO(wan@google.com): handle Windows network shares (e.g. \\server\share).
8185 void FilePath::Normalize() {
8186  if (pathname_.c_str() == NULL) {
8187  pathname_ = "";
8188  return;
8189  }
8190  const char* src = pathname_.c_str();
8191  char* const dest = new char[pathname_.length() + 1];
8192  char* dest_ptr = dest;
8193  memset(dest_ptr, 0, pathname_.length() + 1);
8194 
8195  while (*src != '\0') {
8196  *dest_ptr = *src;
8197  if (!IsPathSeparator(*src)) {
8198  src++;
8199  } else {
8200 #if GTEST_HAS_ALT_PATH_SEP_
8201  if (*dest_ptr == kAlternatePathSeparator) {
8202  *dest_ptr = kPathSeparator;
8203  }
8204 #endif
8205  while (IsPathSeparator(*src))
8206  src++;
8207  }
8208  dest_ptr++;
8209  }
8210  *dest_ptr = '\0';
8211  pathname_ = dest;
8212  delete[] dest;
8213 }
8214 
8215 } // namespace internal
8216 } // namespace testing
8217 // Copyright 2008, Google Inc.
8218 // All rights reserved.
8219 //
8220 // Redistribution and use in source and binary forms, with or without
8221 // modification, are permitted provided that the following conditions are
8222 // met:
8223 //
8224 // * Redistributions of source code must retain the above copyright
8225 // notice, this list of conditions and the following disclaimer.
8226 // * Redistributions in binary form must reproduce the above
8227 // copyright notice, this list of conditions and the following disclaimer
8228 // in the documentation and/or other materials provided with the
8229 // distribution.
8230 // * Neither the name of Google Inc. nor the names of its
8231 // contributors may be used to endorse or promote products derived from
8232 // this software without specific prior written permission.
8233 //
8234 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
8235 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
8236 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
8237 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
8238 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
8239 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
8240 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
8241 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
8242 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
8243 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
8244 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
8245 //
8246 // Author: wan@google.com (Zhanyong Wan)
8247 
8248 
8249 #include <limits.h>
8250 #include <stdlib.h>
8251 #include <stdio.h>
8252 #include <string.h>
8253 
8254 #if GTEST_OS_WINDOWS_MOBILE
8255 # include <windows.h> // For TerminateProcess()
8256 #elif GTEST_OS_WINDOWS
8257 # include <io.h>
8258 # include <sys/stat.h>
8259 #else
8260 # include <unistd.h>
8261 #endif // GTEST_OS_WINDOWS_MOBILE
8262 
8263 #if GTEST_OS_MAC
8264 # include <mach/mach_init.h>
8265 # include <mach/task.h>
8266 # include <mach/vm_map.h>
8267 #endif // GTEST_OS_MAC
8268 
8269 #if GTEST_OS_QNX
8270 # include <devctl.h>
8271 # include <sys/procfs.h>
8272 #endif // GTEST_OS_QNX
8273 
8274 
8275 // Indicates that this translation unit is part of Google Test's
8276 // implementation. It must come before gtest-internal-inl.h is
8277 // included, or there will be a compiler error. This trick is to
8278 // prevent a user from accidentally including gtest-internal-inl.h in
8279 // his code.
8280 #define GTEST_IMPLEMENTATION_ 1
8281 #undef GTEST_IMPLEMENTATION_
8282 
8283 namespace testing {
8284 namespace internal {
8285 
8286 #if defined(_MSC_VER) || defined(__BORLANDC__)
8287 // MSVC and C++Builder do not provide a definition of STDERR_FILENO.
8288 const int kStdOutFileno = 1;
8289 const int kStdErrFileno = 2;
8290 #else
8291 const int kStdOutFileno = STDOUT_FILENO;
8292 const int kStdErrFileno = STDERR_FILENO;
8293 #endif // _MSC_VER
8294 
8295 #if GTEST_OS_MAC
8296 
8297 // Returns the number of threads running in the process, or 0 to indicate that
8298 // we cannot detect it.
8299 size_t GetThreadCount() {
8300  const task_t task = mach_task_self();
8301  mach_msg_type_number_t thread_count;
8302  thread_act_array_t thread_list;
8303  const kern_return_t status = task_threads(task, &thread_list, &thread_count);
8304  if (status == KERN_SUCCESS) {
8305  // task_threads allocates resources in thread_list and we need to free them
8306  // to avoid leaks.
8307  vm_deallocate(task,
8308  reinterpret_cast<vm_address_t>(thread_list),
8309  sizeof(thread_t) * thread_count);
8310  return static_cast<size_t>(thread_count);
8311  } else {
8312  return 0;
8313  }
8314 }
8315 
8316 #elif GTEST_OS_QNX
8317 
8318 // Returns the number of threads running in the process, or 0 to indicate that
8319 // we cannot detect it.
8320 size_t GetThreadCount() {
8321  const int fd = open("/proc/self/as", O_RDONLY);
8322  if (fd < 0) {
8323  return 0;
8324  }
8325  procfs_info process_info;
8326  const int status =
8327  devctl(fd, DCMD_PROC_INFO, &process_info, sizeof(process_info), NULL);
8328  close(fd);
8329  if (status == EOK) {
8330  return static_cast<size_t>(process_info.num_threads);
8331  } else {
8332  return 0;
8333  }
8334 }
8335 
8336 #else
8337 
8338 size_t GetThreadCount() {
8339  // There's no portable way to detect the number of threads, so we just
8340  // return 0 to indicate that we cannot detect it.
8341  return 0;
8342 }
8343 
8344 #endif // GTEST_OS_MAC
8345 
8346 #if GTEST_USES_POSIX_RE
8347 
8348 // Implements RE. Currently only needed for death tests.
8349 
8350 RE::~RE() {
8351  if (is_valid_) {
8352  // regfree'ing an invalid regex might crash because the content
8353  // of the regex is undefined. Since the regex's are essentially
8354  // the same, one cannot be valid (or invalid) without the other
8355  // being so too.
8356  regfree(&partial_regex_);
8357  regfree(&full_regex_);
8358  }
8359  free(const_cast<char*>(pattern_));
8360 }
8361 
8362 // Returns true iff regular expression re matches the entire str.
8363 bool RE::FullMatch(const char* str, const RE& re) {
8364  if (!re.is_valid_) return false;
8365 
8366  regmatch_t match;
8367  return regexec(&re.full_regex_, str, 1, &match, 0) == 0;
8368 }
8369 
8370 // Returns true iff regular expression re matches a substring of str
8371 // (including str itself).
8372 bool RE::PartialMatch(const char* str, const RE& re) {
8373  if (!re.is_valid_) return false;
8374 
8375  regmatch_t match;
8376  return regexec(&re.partial_regex_, str, 1, &match, 0) == 0;
8377 }
8378 
8379 // Initializes an RE from its string representation.
8380 void RE::Init(const char* regex) {
8381  pattern_ = posix::StrDup(regex);
8382 
8383  // Reserves enough bytes to hold the regular expression used for a
8384  // full match.
8385  const size_t full_regex_len = strlen(regex) + 10;
8386  char* const full_pattern = new char[full_regex_len];
8387 
8388  snprintf(full_pattern, full_regex_len, "^(%s)$", regex);
8389  is_valid_ = regcomp(&full_regex_, full_pattern, REG_EXTENDED) == 0;
8390  // We want to call regcomp(&partial_regex_, ...) even if the
8391  // previous expression returns false. Otherwise partial_regex_ may
8392  // not be properly initialized can may cause trouble when it's
8393  // freed.
8394  //
8395  // Some implementation of POSIX regex (e.g. on at least some
8396  // versions of Cygwin) doesn't accept the empty string as a valid
8397  // regex. We change it to an equivalent form "()" to be safe.
8398  if (is_valid_) {
8399  const char* const partial_regex = (*regex == '\0') ? "()" : regex;
8400  is_valid_ = regcomp(&partial_regex_, partial_regex, REG_EXTENDED) == 0;
8401  }
8402  EXPECT_TRUE(is_valid_)
8403  << "Regular expression \"" << regex
8404  << "\" is not a valid POSIX Extended regular expression.";
8405 
8406  delete[] full_pattern;
8407 }
8408 
8409 #elif GTEST_USES_SIMPLE_RE
8410 
8411 // Returns true iff ch appears anywhere in str (excluding the
8412 // terminating '\0' character).
8413 bool IsInSet(char ch, const char* str) {
8414  return ch != '\0' && strchr(str, ch) != NULL;
8415 }
8416 
8417 // Returns true iff ch belongs to the given classification. Unlike
8418 // similar functions in <ctype.h>, these aren't affected by the
8419 // current locale.
8420 bool IsAsciiDigit(char ch) { return '0' <= ch && ch <= '9'; }
8421 bool IsAsciiPunct(char ch) {
8422  return IsInSet(ch, "^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~");
8423 }
8424 bool IsRepeat(char ch) { return IsInSet(ch, "?*+"); }
8425 bool IsAsciiWhiteSpace(char ch) { return IsInSet(ch, " \f\n\r\t\v"); }
8426 bool IsAsciiWordChar(char ch) {
8427  return ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') ||
8428  ('0' <= ch && ch <= '9') || ch == '_';
8429 }
8430 
8431 // Returns true iff "\\c" is a supported escape sequence.
8432 bool IsValidEscape(char c) {
8433  return (IsAsciiPunct(c) || IsInSet(c, "dDfnrsStvwW"));
8434 }
8435 
8436 // Returns true iff the given atom (specified by escaped and pattern)
8437 // matches ch. The result is undefined if the atom is invalid.
8438 bool AtomMatchesChar(bool escaped, char pattern_char, char ch) {
8439  if (escaped) { // "\\p" where p is pattern_char.
8440  switch (pattern_char) {
8441  case 'd': return IsAsciiDigit(ch);
8442  case 'D': return !IsAsciiDigit(ch);
8443  case 'f': return ch == '\f';
8444  case 'n': return ch == '\n';
8445  case 'r': return ch == '\r';
8446  case 's': return IsAsciiWhiteSpace(ch);
8447  case 'S': return !IsAsciiWhiteSpace(ch);
8448  case 't': return ch == '\t';
8449  case 'v': return ch == '\v';
8450  case 'w': return IsAsciiWordChar(ch);
8451  case 'W': return !IsAsciiWordChar(ch);
8452  }
8453  return IsAsciiPunct(pattern_char) && pattern_char == ch;
8454  }
8455 
8456  return (pattern_char == '.' && ch != '\n') || pattern_char == ch;
8457 }
8458 
8459 // Helper function used by ValidateRegex() to format error messages.
8460 std::string FormatRegexSyntaxError(const char* regex, int index) {
8461  return (Message() << "Syntax error at index " << index
8462  << " in simple regular expression \"" << regex << "\": ").GetString();
8463 }
8464 
8465 // Generates non-fatal failures and returns false if regex is invalid;
8466 // otherwise returns true.
8467 bool ValidateRegex(const char* regex) {
8468  if (regex == NULL) {
8469  // TODO(wan@google.com): fix the source file location in the
8470  // assertion failures to match where the regex is used in user
8471  // code.
8472  ADD_FAILURE() << "NULL is not a valid simple regular expression.";
8473  return false;
8474  }
8475 
8476  bool is_valid = true;
8477 
8478  // True iff ?, *, or + can follow the previous atom.
8479  bool prev_repeatable = false;
8480  for (int i = 0; regex[i]; i++) {
8481  if (regex[i] == '\\') { // An escape sequence
8482  i++;
8483  if (regex[i] == '\0') {
8484  ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
8485  << "'\\' cannot appear at the end.";
8486  return false;
8487  }
8488 
8489  if (!IsValidEscape(regex[i])) {
8490  ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
8491  << "invalid escape sequence \"\\" << regex[i] << "\".";
8492  is_valid = false;
8493  }
8494  prev_repeatable = true;
8495  } else { // Not an escape sequence.
8496  const char ch = regex[i];
8497 
8498  if (ch == '^' && i > 0) {
8499  ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
8500  << "'^' can only appear at the beginning.";
8501  is_valid = false;
8502  } else if (ch == '$' && regex[i + 1] != '\0') {
8503  ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
8504  << "'$' can only appear at the end.";
8505  is_valid = false;
8506  } else if (IsInSet(ch, "()[]{}|")) {
8507  ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
8508  << "'" << ch << "' is unsupported.";
8509  is_valid = false;
8510  } else if (IsRepeat(ch) && !prev_repeatable) {
8511  ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
8512  << "'" << ch << "' can only follow a repeatable token.";
8513  is_valid = false;
8514  }
8515 
8516  prev_repeatable = !IsInSet(ch, "^$?*+");
8517  }
8518  }
8519 
8520  return is_valid;
8521 }
8522 
8523 // Matches a repeated regex atom followed by a valid simple regular
8524 // expression. The regex atom is defined as c if escaped is false,
8525 // or \c otherwise. repeat is the repetition meta character (?, *,
8526 // or +). The behavior is undefined if str contains too many
8527 // characters to be indexable by size_t, in which case the test will
8528 // probably time out anyway. We are fine with this limitation as
8529 // std::string has it too.
8530 bool MatchRepetitionAndRegexAtHead(
8531  bool escaped, char c, char repeat, const char* regex,
8532  const char* str) {
8533  const size_t min_count = (repeat == '+') ? 1 : 0;
8534  const size_t max_count = (repeat == '?') ? 1 :
8535  static_cast<size_t>(-1) - 1;
8536  // We cannot call numeric_limits::max() as it conflicts with the
8537  // max() macro on Windows.
8538 
8539  for (size_t i = 0; i <= max_count; ++i) {
8540  // We know that the atom matches each of the first i characters in str.
8541  if (i >= min_count && MatchRegexAtHead(regex, str + i)) {
8542  // We have enough matches at the head, and the tail matches too.
8543  // Since we only care about *whether* the pattern matches str
8544  // (as opposed to *how* it matches), there is no need to find a
8545  // greedy match.
8546  return true;
8547  }
8548  if (str[i] == '\0' || !AtomMatchesChar(escaped, c, str[i]))
8549  return false;
8550  }
8551  return false;
8552 }
8553 
8554 // Returns true iff regex matches a prefix of str. regex must be a
8555 // valid simple regular expression and not start with "^", or the
8556 // result is undefined.
8557 bool MatchRegexAtHead(const char* regex, const char* str) {
8558  if (*regex == '\0') // An empty regex matches a prefix of anything.
8559  return true;
8560 
8561  // "$" only matches the end of a string. Note that regex being
8562  // valid guarantees that there's nothing after "$" in it.
8563  if (*regex == '$')
8564  return *str == '\0';
8565 
8566  // Is the first thing in regex an escape sequence?
8567  const bool escaped = *regex == '\\';
8568  if (escaped)
8569  ++regex;
8570  if (IsRepeat(regex[1])) {
8571  // MatchRepetitionAndRegexAtHead() calls MatchRegexAtHead(), so
8572  // here's an indirect recursion. It terminates as the regex gets
8573  // shorter in each recursion.
8574  return MatchRepetitionAndRegexAtHead(
8575  escaped, regex[0], regex[1], regex + 2, str);
8576  } else {
8577  // regex isn't empty, isn't "$", and doesn't start with a
8578  // repetition. We match the first atom of regex with the first
8579  // character of str and recurse.
8580  return (*str != '\0') && AtomMatchesChar(escaped, *regex, *str) &&
8581  MatchRegexAtHead(regex + 1, str + 1);
8582  }
8583 }
8584 
8585 // Returns true iff regex matches any substring of str. regex must be
8586 // a valid simple regular expression, or the result is undefined.
8587 //
8588 // The algorithm is recursive, but the recursion depth doesn't exceed
8589 // the regex length, so we won't need to worry about running out of
8590 // stack space normally. In rare cases the time complexity can be
8591 // exponential with respect to the regex length + the string length,
8592 // but usually it's must faster (often close to linear).
8593 bool MatchRegexAnywhere(const char* regex, const char* str) {
8594  if (regex == NULL || str == NULL)
8595  return false;
8596 
8597  if (*regex == '^')
8598  return MatchRegexAtHead(regex + 1, str);
8599 
8600  // A successful match can be anywhere in str.
8601  do {
8602  if (MatchRegexAtHead(regex, str))
8603  return true;
8604  } while (*str++ != '\0');
8605  return false;
8606 }
8607 
8608 // Implements the RE class.
8609 
8610 RE::~RE() {
8611  free(const_cast<char*>(pattern_));
8612  free(const_cast<char*>(full_pattern_));
8613 }
8614 
8615 // Returns true iff regular expression re matches the entire str.
8616 bool RE::FullMatch(const char* str, const RE& re) {
8617  return re.is_valid_ && MatchRegexAnywhere(re.full_pattern_, str);
8618 }
8619 
8620 // Returns true iff regular expression re matches a substring of str
8621 // (including str itself).
8622 bool RE::PartialMatch(const char* str, const RE& re) {
8623  return re.is_valid_ && MatchRegexAnywhere(re.pattern_, str);
8624 }
8625 
8626 // Initializes an RE from its string representation.
8627 void RE::Init(const char* regex) {
8628  pattern_ = full_pattern_ = NULL;
8629  if (regex != NULL) {
8630  pattern_ = posix::StrDup(regex);
8631  }
8632 
8633  is_valid_ = ValidateRegex(regex);
8634  if (!is_valid_) {
8635  // No need to calculate the full pattern when the regex is invalid.
8636  return;
8637  }
8638 
8639  const size_t len = strlen(regex);
8640  // Reserves enough bytes to hold the regular expression used for a
8641  // full match: we need space to prepend a '^', append a '$', and
8642  // terminate the string with '\0'.
8643  char* buffer = static_cast<char*>(malloc(len + 3));
8644  full_pattern_ = buffer;
8645 
8646  if (*regex != '^')
8647  *buffer++ = '^'; // Makes sure full_pattern_ starts with '^'.
8648 
8649  // We don't use snprintf or strncpy, as they trigger a warning when
8650  // compiled with VC++ 8.0.
8651  memcpy(buffer, regex, len);
8652  buffer += len;
8653 
8654  if (len == 0 || regex[len - 1] != '$')
8655  *buffer++ = '$'; // Makes sure full_pattern_ ends with '$'.
8656 
8657  *buffer = '\0';
8658 }
8659 
8660 #endif // GTEST_USES_POSIX_RE
8661 
8662 const char kUnknownFile[] = "unknown file";
8663 
8664 // Formats a source file path and a line number as they would appear
8665 // in an error message from the compiler used to compile this code.
8666 GTEST_API_ ::std::string FormatFileLocation(const char* file, int line) {
8667  const std::string file_name(file == NULL ? kUnknownFile : file);
8668 
8669  if (line < 0) {
8670  return file_name + ":";
8671  }
8672 #ifdef _MSC_VER
8673  return file_name + "(" + StreamableToString(line) + "):";
8674 #else
8675  return file_name + ":" + StreamableToString(line) + ":";
8676 #endif // _MSC_VER
8677 }
8678 
8679 // Formats a file location for compiler-independent XML output.
8680 // Although this function is not platform dependent, we put it next to
8681 // FormatFileLocation in order to contrast the two functions.
8682 // Note that FormatCompilerIndependentFileLocation() does NOT append colon
8683 // to the file location it produces, unlike FormatFileLocation().
8685  const char* file, int line) {
8686  const std::string file_name(file == NULL ? kUnknownFile : file);
8687 
8688  if (line < 0)
8689  return file_name;
8690  else
8691  return file_name + ":" + StreamableToString(line);
8692 }
8693 
8694 
8695 GTestLog::GTestLog(GTestLogSeverity severity, const char* file, int line)
8696  : severity_(severity) {
8697  const char* const marker =
8698  severity == GTEST_INFO ? "[ INFO ]" :
8699  severity == GTEST_WARNING ? "[WARNING]" :
8700  severity == GTEST_ERROR ? "[ ERROR ]" : "[ FATAL ]";
8701  GetStream() << ::std::endl << marker << " "
8702  << FormatFileLocation(file, line).c_str() << ": ";
8703 }
8704 
8705 // Flushes the buffers and, if severity is GTEST_FATAL, aborts the program.
8707  GetStream() << ::std::endl;
8708  if (severity_ == GTEST_FATAL) {
8709  fflush(stderr);
8710  posix::Abort();
8711  }
8712 }
8713 // Disable Microsoft deprecation warnings for POSIX functions called from
8714 // this class (creat, dup, dup2, and close)
8715 #ifdef _MSC_VER
8716 # pragma warning(push)
8717 # pragma warning(disable: 4996)
8718 #endif // _MSC_VER
8719 
8720 #if GTEST_HAS_STREAM_REDIRECTION
8721 
8722 // Object that captures an output stream (stdout/stderr).
8724  public:
8725  // The ctor redirects the stream to a temporary file.
8726  explicit CapturedStream(int fd) : fd_(fd), uncaptured_fd_(dup(fd)) {
8727 # if GTEST_OS_WINDOWS
8728  char temp_dir_path[MAX_PATH + 1] = { '\0' }; // NOLINT
8729  char temp_file_path[MAX_PATH + 1] = { '\0' }; // NOLINT
8730 
8731  ::GetTempPathA(sizeof(temp_dir_path), temp_dir_path);
8732  const UINT success = ::GetTempFileNameA(temp_dir_path,
8733  "gtest_redir",
8734  0, // Generate unique file name.
8735  temp_file_path);
8736  GTEST_CHECK_(success != 0)
8737  << "Unable to create a temporary file in " << temp_dir_path;
8738  const int captured_fd = creat(temp_file_path, _S_IREAD | _S_IWRITE);
8739  GTEST_CHECK_(captured_fd != -1) << "Unable to open temporary file "
8740  << temp_file_path;
8741  filename_ = temp_file_path;
8742 # else
8743  // There's no guarantee that a test has write access to the current
8744  // directory, so we create the temporary file in the /tmp directory
8745  // instead. We use /tmp on most systems, and /sdcard on Android.
8746  // That's because Android doesn't have /tmp.
8747 # if GTEST_OS_LINUX_ANDROID
8748  // Note: Android applications are expected to call the framework's
8749  // Context.getExternalStorageDirectory() method through JNI to get
8750  // the location of the world-writable SD Card directory. However,
8751  // this requires a Context handle, which cannot be retrieved
8752  // globally from native code. Doing so also precludes running the
8753  // code as part of a regular standalone executable, which doesn't
8754  // run in a Dalvik process (e.g. when running it through 'adb shell').
8755  //
8756  // The location /sdcard is directly accessible from native code
8757  // and is the only location (unofficially) supported by the Android
8758  // team. It's generally a symlink to the real SD Card mount point
8759  // which can be /mnt/sdcard, /mnt/sdcard0, /system/media/sdcard, or
8760  // other OEM-customized locations. Never rely on these, and always
8761  // use /sdcard.
8762  char name_template[] = "/sdcard/gtest_captured_stream.XXXXXX";
8763 # else
8764  char name_template[] = "/tmp/captured_stream.XXXXXX";
8765 # endif // GTEST_OS_LINUX_ANDROID
8766  const int captured_fd = mkstemp(name_template);
8767  filename_ = name_template;
8768 # endif // GTEST_OS_WINDOWS
8769  fflush(NULL);
8770  dup2(captured_fd, fd_);
8771  close(captured_fd);
8772  }
8773 
8775  remove(filename_.c_str());
8776  }
8777 
8779  if (uncaptured_fd_ != -1) {
8780  // Restores the original stream.
8781  fflush(NULL);
8782  dup2(uncaptured_fd_, fd_);
8783  close(uncaptured_fd_);
8784  uncaptured_fd_ = -1;
8785  }
8786 
8787  FILE* const file = posix::FOpen(filename_.c_str(), "r");
8788  const std::string content = ReadEntireFile(file);
8789  posix::FClose(file);
8790  return content;
8791  }
8792 
8793  private:
8794  // Reads the entire content of a file as an std::string.
8795  static std::string ReadEntireFile(FILE* file);
8796 
8797  // Returns the size (in bytes) of a file.
8798  static size_t GetFileSize(FILE* file);
8799 
8800  const int fd_; // A stream to capture.
8802  // Name of the temporary file holding the stderr output.
8804 
8806 };
8807 
8808 // Returns the size (in bytes) of a file.
8809 size_t CapturedStream::GetFileSize(FILE* file) {
8810  fseek(file, 0, SEEK_END);
8811  return static_cast<size_t>(ftell(file));
8812 }
8813 
8814 // Reads the entire content of a file as a string.
8816  const size_t file_size = GetFileSize(file);
8817  char* const buffer = new char[file_size];
8818 
8819  size_t bytes_last_read = 0; // # of bytes read in the last fread()
8820  size_t bytes_read = 0; // # of bytes read so far
8821 
8822  fseek(file, 0, SEEK_SET);
8823 
8824  // Keeps reading the file until we cannot read further or the
8825  // pre-determined file size is reached.
8826  do {
8827  bytes_last_read = fread(buffer+bytes_read, 1, file_size-bytes_read, file);
8828  bytes_read += bytes_last_read;
8829  } while (bytes_last_read > 0 && bytes_read < file_size);
8830 
8831  const std::string content(buffer, bytes_read);
8832  delete[] buffer;
8833 
8834  return content;
8835 }
8836 
8837 # ifdef _MSC_VER
8838 # pragma warning(pop)
8839 # endif // _MSC_VER
8840 
8843 
8844 // Starts capturing an output stream (stdout/stderr).
8845 void CaptureStream(int fd, const char* stream_name, CapturedStream** stream) {
8846  if (*stream != NULL) {
8847  GTEST_LOG_(FATAL) << "Only one " << stream_name
8848  << " capturer can exist at a time.";
8849  }
8850  *stream = new CapturedStream(fd);
8851 }
8852 
8853 // Stops capturing the output stream and returns the captured string.
8855  const std::string content = (*captured_stream)->GetCapturedString();
8856 
8857  delete *captured_stream;
8858  *captured_stream = NULL;
8859 
8860  return content;
8861 }
8862 
8863 // Starts capturing stdout.
8865  CaptureStream(kStdOutFileno, "stdout", &g_captured_stdout);
8866 }
8867 
8868 // Starts capturing stderr.
8870  CaptureStream(kStdErrFileno, "stderr", &g_captured_stderr);
8871 }
8872 
8873 // Stops capturing stdout and returns the captured string.
8875  return GetCapturedStream(&g_captured_stdout);
8876 }
8877 
8878 // Stops capturing stderr and returns the captured string.
8880  return GetCapturedStream(&g_captured_stderr);
8881 }
8882 
8883 #endif // GTEST_HAS_STREAM_REDIRECTION
8884 
8885 #if GTEST_HAS_DEATH_TEST
8886 
8887 // A copy of all command line arguments. Set by InitGoogleTest().
8888 ::std::vector<testing::internal::string> g_argvs;
8889 
8890 static const ::std::vector<testing::internal::string>* g_injected_test_argvs =
8891  NULL; // Owned.
8892 
8893 void SetInjectableArgvs(const ::std::vector<testing::internal::string>* argvs) {
8894  if (g_injected_test_argvs != argvs)
8895  delete g_injected_test_argvs;
8896  g_injected_test_argvs = argvs;
8897 }
8898 
8899 const ::std::vector<testing::internal::string>& GetInjectableArgvs() {
8900  if (g_injected_test_argvs != NULL) {
8901  return *g_injected_test_argvs;
8902  }
8903  return g_argvs;
8904 }
8905 #endif // GTEST_HAS_DEATH_TEST
8906 
8907 #if GTEST_OS_WINDOWS_MOBILE
8908 namespace posix {
8909 void Abort() {
8910  DebugBreak();
8911  TerminateProcess(GetCurrentProcess(), 1);
8912 }
8913 } // namespace posix
8914 #endif // GTEST_OS_WINDOWS_MOBILE
8915 
8916 // Returns the name of the environment variable corresponding to the
8917 // given flag. For example, FlagToEnvVar("foo") will return
8918 // "GTEST_FOO" in the open-source version.
8919 static std::string FlagToEnvVar(const char* flag) {
8920  const std::string full_flag =
8921  (Message() << GTEST_FLAG_PREFIX_ << flag).GetString();
8922 
8923  Message env_var;
8924  for (size_t i = 0; i != full_flag.length(); i++) {
8925  env_var << ToUpper(full_flag.c_str()[i]);
8926  }
8927 
8928  return env_var.GetString();
8929 }
8930 
8931 // Parses 'str' for a 32-bit signed integer. If successful, writes
8932 // the result to *value and returns true; otherwise leaves *value
8933 // unchanged and returns false.
8934 bool ParseInt32(const Message& src_text, const char* str, Int32* value) {
8935  // Parses the environment variable as a decimal integer.
8936  char* end = NULL;
8937  const long long_value = strtol(str, &end, 10); // NOLINT
8938 
8939  // Has strtol() consumed all characters in the string?
8940  if (*end != '\0') {
8941  // No - an invalid character was encountered.
8942  Message msg;
8943  msg << "WARNING: " << src_text
8944  << " is expected to be a 32-bit integer, but actually"
8945  << " has value \"" << str << "\".\n";
8946  printf("%s", msg.GetString().c_str());
8947  fflush(stdout);
8948  return false;
8949  }
8950 
8951  // Is the parsed value in the range of an Int32?
8952  const Int32 result = static_cast<Int32>(long_value);
8953  if (long_value == LONG_MAX || long_value == LONG_MIN ||
8954  // The parsed value overflows as a long. (strtol() returns
8955  // LONG_MAX or LONG_MIN when the input overflows.)
8956  result != long_value
8957  // The parsed value overflows as an Int32.
8958  ) {
8959  Message msg;
8960  msg << "WARNING: " << src_text
8961  << " is expected to be a 32-bit integer, but actually"
8962  << " has value " << str << ", which overflows.\n";
8963  printf("%s", msg.GetString().c_str());
8964  fflush(stdout);
8965  return false;
8966  }
8967 
8968  *value = result;
8969  return true;
8970 }
8971 
8972 // Reads and returns the Boolean environment variable corresponding to
8973 // the given flag; if it's not set, returns default_value.
8974 //
8975 // The value is considered true iff it's not "0".
8976 bool BoolFromGTestEnv(const char* flag, bool default_value) {
8977  const std::string env_var = FlagToEnvVar(flag);
8978  const char* const string_value = posix::GetEnv(env_var.c_str());
8979  return string_value == NULL ?
8980  default_value : strcmp(string_value, "0") != 0;
8981 }
8982 
8983 // Reads and returns a 32-bit integer stored in the environment
8984 // variable corresponding to the given flag; if it isn't set or
8985 // doesn't represent a valid 32-bit integer, returns default_value.
8986 Int32 Int32FromGTestEnv(const char* flag, Int32 default_value) {
8987  const std::string env_var = FlagToEnvVar(flag);
8988  const char* const string_value = posix::GetEnv(env_var.c_str());
8989  if (string_value == NULL) {
8990  // The environment variable is not set.
8991  return default_value;
8992  }
8993 
8994  Int32 result = default_value;
8995  if (!ParseInt32(Message() << "Environment variable " << env_var,
8996  string_value, &result)) {
8997  printf("The default value %s is used.\n",
8998  (Message() << default_value).GetString().c_str());
8999  fflush(stdout);
9000  return default_value;
9001  }
9002 
9003  return result;
9004 }
9005 
9006 // Reads and returns the string environment variable corresponding to
9007 // the given flag; if it's not set, returns default_value.
9008 const char* StringFromGTestEnv(const char* flag, const char* default_value) {
9009  const std::string env_var = FlagToEnvVar(flag);
9010  const char* const value = posix::GetEnv(env_var.c_str());
9011  return value == NULL ? default_value : value;
9012 }
9013 
9014 } // namespace internal
9015 } // namespace testing
9016 // Copyright 2007, Google Inc.
9017 // All rights reserved.
9018 //
9019 // Redistribution and use in source and binary forms, with or without
9020 // modification, are permitted provided that the following conditions are
9021 // met:
9022 //
9023 // * Redistributions of source code must retain the above copyright
9024 // notice, this list of conditions and the following disclaimer.
9025 // * Redistributions in binary form must reproduce the above
9026 // copyright notice, this list of conditions and the following disclaimer
9027 // in the documentation and/or other materials provided with the
9028 // distribution.
9029 // * Neither the name of Google Inc. nor the names of its
9030 // contributors may be used to endorse or promote products derived from
9031 // this software without specific prior written permission.
9032 //
9033 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
9034 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
9035 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
9036 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9037 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
9038 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9039 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
9040 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
9041 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
9042 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
9043 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
9044 //
9045 // Author: wan@google.com (Zhanyong Wan)
9046 
9047 // Google Test - The Google C++ Testing Framework
9048 //
9049 // This file implements a universal value printer that can print a
9050 // value of any type T:
9051 //
9052 // void ::testing::internal::UniversalPrinter<T>::Print(value, ostream_ptr);
9053 //
9054 // It uses the << operator when possible, and prints the bytes in the
9055 // object otherwise. A user can override its behavior for a class
9056 // type Foo by defining either operator<<(::std::ostream&, const Foo&)
9057 // or void PrintTo(const Foo&, ::std::ostream*) in the namespace that
9058 // defines Foo.
9059 
9060 #include <ctype.h>
9061 #include <stdio.h>
9062 #include <ostream> // NOLINT
9063 #include <string>
9064 
9065 namespace testing {
9066 
9067 namespace {
9068 
9069 using ::std::ostream;
9070 
9071 // Prints a segment of bytes in the given object.
9072 void PrintByteSegmentInObjectTo(const unsigned char* obj_bytes, size_t start,
9073  size_t count, ostream* os) {
9074  char text[5] = "";
9075  for (size_t i = 0; i != count; i++) {
9076  const size_t j = start + i;
9077  if (i != 0) {
9078  // Organizes the bytes into groups of 2 for easy parsing by
9079  // human.
9080  if ((j % 2) == 0)
9081  *os << ' ';
9082  else
9083  *os << '-';
9084  }
9085  GTEST_SNPRINTF_(text, sizeof(text), "%02X", obj_bytes[j]);
9086  *os << text;
9087  }
9088 }
9089 
9090 // Prints the bytes in the given value to the given ostream.
9091 void PrintBytesInObjectToImpl(const unsigned char* obj_bytes, size_t count,
9092  ostream* os) {
9093  // Tells the user how big the object is.
9094  *os << count << "-byte object <";
9095 
9096  const size_t kThreshold = 132;
9097  const size_t kChunkSize = 64;
9098  // If the object size is bigger than kThreshold, we'll have to omit
9099  // some details by printing only the first and the last kChunkSize
9100  // bytes.
9101  // TODO(wan): let the user control the threshold using a flag.
9102  if (count < kThreshold) {
9103  PrintByteSegmentInObjectTo(obj_bytes, 0, count, os);
9104  } else {
9105  PrintByteSegmentInObjectTo(obj_bytes, 0, kChunkSize, os);
9106  *os << " ... ";
9107  // Rounds up to 2-byte boundary.
9108  const size_t resume_pos = (count - kChunkSize + 1)/2*2;
9109  PrintByteSegmentInObjectTo(obj_bytes, resume_pos, count - resume_pos, os);
9110  }
9111  *os << ">";
9112 }
9113 
9114 } // namespace
9115 
9116 namespace internal2 {
9117 
9118 // Delegates to PrintBytesInObjectToImpl() to print the bytes in the
9119 // given object. The delegation simplifies the implementation, which
9120 // uses the << operator and thus is easier done outside of the
9121 // ::testing::internal namespace, which contains a << operator that
9122 // sometimes conflicts with the one in STL.
9123 void PrintBytesInObjectTo(const unsigned char* obj_bytes, size_t count,
9124  ostream* os) {
9125  PrintBytesInObjectToImpl(obj_bytes, count, os);
9126 }
9127 
9128 } // namespace internal2
9129 
9130 namespace internal {
9131 
9132 // Depending on the value of a char (or wchar_t), we print it in one
9133 // of three formats:
9134 // - as is if it's a printable ASCII (e.g. 'a', '2', ' '),
9135 // - as a hexidecimal escape sequence (e.g. '\x7F'), or
9136 // - as a special escape sequence (e.g. '\r', '\n').
9141 };
9142 
9143 // Returns true if c is a printable ASCII character. We test the
9144 // value of c directly instead of calling isprint(), which is buggy on
9145 // Windows Mobile.
9146 inline bool IsPrintableAscii(wchar_t c) {
9147  return 0x20 <= c && c <= 0x7E;
9148 }
9149 
9150 // Prints a wide or narrow char c as a character literal without the
9151 // quotes, escaping it when necessary; returns how c was formatted.
9152 // The template argument UnsignedChar is the unsigned version of Char,
9153 // which is the type of c.
9154 template <typename UnsignedChar, typename Char>
9155 static CharFormat PrintAsCharLiteralTo(Char c, ostream* os) {
9156  switch (static_cast<wchar_t>(c)) {
9157  case L'\0':
9158  *os << "\\0";
9159  break;
9160  case L'\'':
9161  *os << "\\'";
9162  break;
9163  case L'\\':
9164  *os << "\\\\";
9165  break;
9166  case L'\a':
9167  *os << "\\a";
9168  break;
9169  case L'\b':
9170  *os << "\\b";
9171  break;
9172  case L'\f':
9173  *os << "\\f";
9174  break;
9175  case L'\n':
9176  *os << "\\n";
9177  break;
9178  case L'\r':
9179  *os << "\\r";
9180  break;
9181  case L'\t':
9182  *os << "\\t";
9183  break;
9184  case L'\v':
9185  *os << "\\v";
9186  break;
9187  default:
9188  if (IsPrintableAscii(c)) {
9189  *os << static_cast<char>(c);
9190  return kAsIs;
9191  } else {
9192  *os << "\\x" + String::FormatHexInt(static_cast<UnsignedChar>(c));
9193  return kHexEscape;
9194  }
9195  }
9196  return kSpecialEscape;
9197 }
9198 
9199 // Prints a wchar_t c as if it's part of a string literal, escaping it when
9200 // necessary; returns how c was formatted.
9201 static CharFormat PrintAsStringLiteralTo(wchar_t c, ostream* os) {
9202  switch (c) {
9203  case L'\'':
9204  *os << "'";
9205  return kAsIs;
9206  case L'"':
9207  *os << "\\\"";
9208  return kSpecialEscape;
9209  default:
9210  return PrintAsCharLiteralTo<wchar_t>(c, os);
9211  }
9212 }
9213 
9214 // Prints a char c as if it's part of a string literal, escaping it when
9215 // necessary; returns how c was formatted.
9216 static CharFormat PrintAsStringLiteralTo(char c, ostream* os) {
9217  return PrintAsStringLiteralTo(
9218  static_cast<wchar_t>(static_cast<unsigned char>(c)), os);
9219 }
9220 
9221 // Prints a wide or narrow character c and its code. '\0' is printed
9222 // as "'\\0'", other unprintable characters are also properly escaped
9223 // using the standard C++ escape sequence. The template argument
9224 // UnsignedChar is the unsigned version of Char, which is the type of c.
9225 template <typename UnsignedChar, typename Char>
9226 void PrintCharAndCodeTo(Char c, ostream* os) {
9227  // First, print c as a literal in the most readable form we can find.
9228  *os << ((sizeof(c) > 1) ? "L'" : "'");
9229  const CharFormat format = PrintAsCharLiteralTo<UnsignedChar>(c, os);
9230  *os << "'";
9231 
9232  // To aid user debugging, we also print c's code in decimal, unless
9233  // it's 0 (in which case c was printed as '\\0', making the code
9234  // obvious).
9235  if (c == 0)
9236  return;
9237  *os << " (" << static_cast<int>(c);
9238 
9239  // For more convenience, we print c's code again in hexidecimal,
9240  // unless c was already printed in the form '\x##' or the code is in
9241  // [1, 9].
9242  if (format == kHexEscape || (1 <= c && c <= 9)) {
9243  // Do nothing.
9244  } else {
9245  *os << ", 0x" << String::FormatHexInt(static_cast<UnsignedChar>(c));
9246  }
9247  *os << ")";
9248 }
9249 
9250 void PrintTo(unsigned char c, ::std::ostream* os) {
9251  PrintCharAndCodeTo<unsigned char>(c, os);
9252 }
9253 void PrintTo(signed char c, ::std::ostream* os) {
9254  PrintCharAndCodeTo<unsigned char>(c, os);
9255 }
9256 
9257 // Prints a wchar_t as a symbol if it is printable or as its internal
9258 // code otherwise and also as its code. L'\0' is printed as "L'\\0'".
9259 void PrintTo(wchar_t wc, ostream* os) {
9260  PrintCharAndCodeTo<wchar_t>(wc, os);
9261 }
9262 
9263 // Prints the given array of characters to the ostream. CharType must be either
9264 // char or wchar_t.
9265 // The array starts at begin, the length is len, it may include '\0' characters
9266 // and may not be NUL-terminated.
9267 template <typename CharType>
9269  const CharType* begin, size_t len, ostream* os) {
9270  const char* const kQuoteBegin = sizeof(CharType) == 1 ? "\"" : "L\"";
9271  *os << kQuoteBegin;
9272  bool is_previous_hex = false;
9273  for (size_t index = 0; index < len; ++index) {
9274  const CharType cur = begin[index];
9275  if (is_previous_hex && IsXDigit(cur)) {
9276  // Previous character is of '\x..' form and this character can be
9277  // interpreted as another hexadecimal digit in its number. Break string to
9278  // disambiguate.
9279  *os << "\" " << kQuoteBegin;
9280  }
9281  is_previous_hex = PrintAsStringLiteralTo(cur, os) == kHexEscape;
9282  }
9283  *os << "\"";
9284 }
9285 
9286 // Prints a (const) char/wchar_t array of 'len' elements, starting at address
9287 // 'begin'. CharType must be either char or wchar_t.
9288 template <typename CharType>
9290  const CharType* begin, size_t len, ostream* os) {
9291  // The code
9292  // const char kFoo[] = "foo";
9293  // generates an array of 4, not 3, elements, with the last one being '\0'.
9294  //
9295  // Therefore when printing a char array, we don't print the last element if
9296  // it's '\0', such that the output matches the string literal as it's
9297  // written in the source code.
9298  if (len > 0 && begin[len - 1] == '\0') {
9299  PrintCharsAsStringTo(begin, len - 1, os);
9300  return;
9301  }
9302 
9303  // If, however, the last element in the array is not '\0', e.g.
9304  // const char kFoo[] = { 'f', 'o', 'o' };
9305  // we must print the entire array. We also print a message to indicate
9306  // that the array is not NUL-terminated.
9307  PrintCharsAsStringTo(begin, len, os);
9308  *os << " (no terminating NUL)";
9309 }
9310 
9311 // Prints a (const) char array of 'len' elements, starting at address 'begin'.
9312 void UniversalPrintArray(const char* begin, size_t len, ostream* os) {
9313  UniversalPrintCharArray(begin, len, os);
9314 }
9315 
9316 // Prints a (const) wchar_t array of 'len' elements, starting at address
9317 // 'begin'.
9318 void UniversalPrintArray(const wchar_t* begin, size_t len, ostream* os) {
9319  UniversalPrintCharArray(begin, len, os);
9320 }
9321 
9322 // Prints the given C string to the ostream.
9323 void PrintTo(const char* s, ostream* os) {
9324  if (s == NULL) {
9325  *os << "NULL";
9326  } else {
9327  *os << ImplicitCast_<const void*>(s) << " pointing to ";
9328  PrintCharsAsStringTo(s, strlen(s), os);
9329  }
9330 }
9331 
9332 // MSVC compiler can be configured to define whar_t as a typedef
9333 // of unsigned short. Defining an overload for const wchar_t* in that case
9334 // would cause pointers to unsigned shorts be printed as wide strings,
9335 // possibly accessing more memory than intended and causing invalid
9336 // memory accesses. MSVC defines _NATIVE_WCHAR_T_DEFINED symbol when
9337 // wchar_t is implemented as a native type.
9338 #if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED)
9339 // Prints the given wide C string to the ostream.
9340 void PrintTo(const wchar_t* s, ostream* os) {
9341  if (s == NULL) {
9342  *os << "NULL";
9343  } else {
9344  *os << ImplicitCast_<const void*>(s) << " pointing to ";
9345  PrintCharsAsStringTo(s, wcslen(s), os);
9346  }
9347 }
9348 #endif // wchar_t is native
9349 
9350 // Prints a ::string object.
9351 #if GTEST_HAS_GLOBAL_STRING
9352 void PrintStringTo(const ::string& s, ostream* os) {
9353  PrintCharsAsStringTo(s.data(), s.size(), os);
9354 }
9355 #endif // GTEST_HAS_GLOBAL_STRING
9356 
9357 void PrintStringTo(const ::std::string& s, ostream* os) {
9358  PrintCharsAsStringTo(s.data(), s.size(), os);
9359 }
9360 
9361 // Prints a ::wstring object.
9362 #if GTEST_HAS_GLOBAL_WSTRING
9363 void PrintWideStringTo(const ::wstring& s, ostream* os) {
9364  PrintCharsAsStringTo(s.data(), s.size(), os);
9365 }
9366 #endif // GTEST_HAS_GLOBAL_WSTRING
9367 
9368 #if GTEST_HAS_STD_WSTRING
9370  PrintCharsAsStringTo(s.data(), s.size(), os);
9371 }
9372 #endif // GTEST_HAS_STD_WSTRING
9373 
9374 } // namespace internal
9375 
9376 } // namespace testing
9377 // Copyright 2008, Google Inc.
9378 // All rights reserved.
9379 //
9380 // Redistribution and use in source and binary forms, with or without
9381 // modification, are permitted provided that the following conditions are
9382 // met:
9383 //
9384 // * Redistributions of source code must retain the above copyright
9385 // notice, this list of conditions and the following disclaimer.
9386 // * Redistributions in binary form must reproduce the above
9387 // copyright notice, this list of conditions and the following disclaimer
9388 // in the documentation and/or other materials provided with the
9389 // distribution.
9390 // * Neither the name of Google Inc. nor the names of its
9391 // contributors may be used to endorse or promote products derived from
9392 // this software without specific prior written permission.
9393 //
9394 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
9395 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
9396 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
9397 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9398 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
9399 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9400 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
9401 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
9402 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
9403 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
9404 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
9405 //
9406 // Author: mheule@google.com (Markus Heule)
9407 //
9408 // The Google C++ Testing Framework (Google Test)
9409 
9410 
9411 // Indicates that this translation unit is part of Google Test's
9412 // implementation. It must come before gtest-internal-inl.h is
9413 // included, or there will be a compiler error. This trick is to
9414 // prevent a user from accidentally including gtest-internal-inl.h in
9415 // his code.
9416 #define GTEST_IMPLEMENTATION_ 1
9417 #undef GTEST_IMPLEMENTATION_
9418 
9419 namespace testing {
9420 
9422 
9423 // Gets the summary of the failure message by omitting the stack trace
9424 // in it.
9426  const char* const stack_trace = strstr(message, internal::kStackTraceMarker);
9427  return stack_trace == NULL ? message :
9428  std::string(message, stack_trace);
9429 }
9430 
9431 // Prints a TestPartResult object.
9432 std::ostream& operator<<(std::ostream& os, const TestPartResult& result) {
9433  return os
9434  << result.file_name() << ":" << result.line_number() << ": "
9435  << (result.type() == TestPartResult::kSuccess ? "Success" :
9436  result.type() == TestPartResult::kFatalFailure ? "Fatal failure" :
9437  "Non-fatal failure") << ":\n"
9438  << result.message() << std::endl;
9439 }
9440 
9441 // Appends a TestPartResult to the array.
9443  array_.push_back(result);
9444 }
9445 
9446 // Returns the TestPartResult at the given index (0-based).
9448  if (index < 0 || index >= size()) {
9449  printf("\nInvalid index (%d) into TestPartResultArray.\n", index);
9451  }
9452 
9453  return array_[index];
9454 }
9455 
9456 // Returns the number of TestPartResult objects in the array.
9458  return static_cast<int>(array_.size());
9459 }
9460 
9461 namespace internal {
9462 
9464  : has_new_fatal_failure_(false),
9465  original_reporter_(GetUnitTestImpl()->
9466  GetTestPartResultReporterForCurrentThread()) {
9468 }
9469 
9473 }
9474 
9476  const TestPartResult& result) {
9477  if (result.fatally_failed())
9478  has_new_fatal_failure_ = true;
9480 }
9481 
9482 } // namespace internal
9483 
9484 } // namespace testing
9485 // Copyright 2008 Google Inc.
9486 // All Rights Reserved.
9487 //
9488 // Redistribution and use in source and binary forms, with or without
9489 // modification, are permitted provided that the following conditions are
9490 // met:
9491 //
9492 // * Redistributions of source code must retain the above copyright
9493 // notice, this list of conditions and the following disclaimer.
9494 // * Redistributions in binary form must reproduce the above
9495 // copyright notice, this list of conditions and the following disclaimer
9496 // in the documentation and/or other materials provided with the
9497 // distribution.
9498 // * Neither the name of Google Inc. nor the names of its
9499 // contributors may be used to endorse or promote products derived from
9500 // this software without specific prior written permission.
9501 //
9502 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
9503 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
9504 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
9505 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9506 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
9507 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9508 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
9509 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
9510 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
9511 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
9512 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
9513 //
9514 // Author: wan@google.com (Zhanyong Wan)
9515 
9516 
9517 namespace testing {
9518 namespace internal {
9519 
9520 #if GTEST_HAS_TYPED_TEST_P
9521 
9522 // Skips to the first non-space char in str. Returns an empty string if str
9523 // contains only whitespace characters.
9524 static const char* SkipSpaces(const char* str) {
9525  while (IsSpace(*str))
9526  str++;
9527  return str;
9528 }
9529 
9530 // Verifies that registered_tests match the test names in
9531 // defined_test_names_; returns registered_tests if successful, or
9532 // aborts the program otherwise.
9533 const char* TypedTestCasePState::VerifyRegisteredTestNames(
9534  const char* file, int line, const char* registered_tests) {
9535  typedef ::std::set<const char*>::const_iterator DefinedTestIter;
9536  registered_ = true;
9537 
9538  // Skip initial whitespace in registered_tests since some
9539  // preprocessors prefix stringizied literals with whitespace.
9540  registered_tests = SkipSpaces(registered_tests);
9541 
9542  Message errors;
9543  ::std::set<std::string> tests;
9544  for (const char* names = registered_tests; names != NULL;
9545  names = SkipComma(names)) {
9546  const std::string name = GetPrefixUntilComma(names);
9547  if (tests.count(name) != 0) {
9548  errors << "Test " << name << " is listed more than once.\n";
9549  continue;
9550  }
9551 
9552  bool found = false;
9553  for (DefinedTestIter it = defined_test_names_.begin();
9554  it != defined_test_names_.end();
9555  ++it) {
9556  if (name == *it) {
9557  found = true;
9558  break;
9559  }
9560  }
9561 
9562  if (found) {
9563  tests.insert(name);
9564  } else {
9565  errors << "No test named " << name
9566  << " can be found in this test case.\n";
9567  }
9568  }
9569 
9570  for (DefinedTestIter it = defined_test_names_.begin();
9571  it != defined_test_names_.end();
9572  ++it) {
9573  if (tests.count(*it) == 0) {
9574  errors << "You forgot to list test " << *it << ".\n";
9575  }
9576  }
9577 
9578  const std::string& errors_str = errors.GetString();
9579  if (errors_str != "") {
9580  fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(),
9581  errors_str.c_str());
9582  fflush(stderr);
9583  posix::Abort();
9584  }
9585 
9586  return registered_tests;
9587 }
9588 
9589 #endif // GTEST_HAS_TYPED_TEST_P
9590 
9591 } // namespace internal
9592 } // namespace testing
9593 // Copyright 2008, Google Inc.
9594 // All rights reserved.
9595 //
9596 // Redistribution and use in source and binary forms, with or without
9597 // modification, are permitted provided that the following conditions are
9598 // met:
9599 //
9600 // * Redistributions of source code must retain the above copyright
9601 // notice, this list of conditions and the following disclaimer.
9602 // * Redistributions in binary form must reproduce the above
9603 // copyright notice, this list of conditions and the following disclaimer
9604 // in the documentation and/or other materials provided with the
9605 // distribution.
9606 // * Neither the name of Google Inc. nor the names of its
9607 // contributors may be used to endorse or promote products derived from
9608 // this software without specific prior written permission.
9609 //
9610 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
9611 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
9612 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
9613 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9614 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
9615 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9616 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
9617 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
9618 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
9619 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
9620 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
9621 //
9622 // Author: wan@google.com (Zhanyong Wan)
9623 //
9624 // Google C++ Mocking Framework (Google Mock)
9625 //
9626 // This file #includes all Google Mock implementation .cc files. The
9627 // purpose is to allow a user to build Google Mock by compiling this
9628 // file alone.
9629 
9630 // This line ensures that gmock.h can be compiled on its own, even
9631 // when it's fused.
9632 #include "gmock/gmock.h"
9633 
9634 // The following lines pull in the real gmock *.cc files.
9635 // Copyright 2007, Google Inc.
9636 // All rights reserved.
9637 //
9638 // Redistribution and use in source and binary forms, with or without
9639 // modification, are permitted provided that the following conditions are
9640 // met:
9641 //
9642 // * Redistributions of source code must retain the above copyright
9643 // notice, this list of conditions and the following disclaimer.
9644 // * Redistributions in binary form must reproduce the above
9645 // copyright notice, this list of conditions and the following disclaimer
9646 // in the documentation and/or other materials provided with the
9647 // distribution.
9648 // * Neither the name of Google Inc. nor the names of its
9649 // contributors may be used to endorse or promote products derived from
9650 // this software without specific prior written permission.
9651 //
9652 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
9653 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
9654 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
9655 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9656 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
9657 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9658 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
9659 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
9660 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
9661 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
9662 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
9663 //
9664 // Author: wan@google.com (Zhanyong Wan)
9665 
9666 // Google Mock - a framework for writing C++ mock classes.
9667 //
9668 // This file implements cardinalities.
9669 
9670 
9671 #include <limits.h>
9672 #include <ostream> // NOLINT
9673 #include <sstream>
9674 #include <string>
9675 
9676 namespace testing {
9677 
9678 namespace {
9679 
9680 // Implements the Between(m, n) cardinality.
9681 class BetweenCardinalityImpl : public CardinalityInterface {
9682  public:
9683  BetweenCardinalityImpl(int min, int max)
9684  : min_(min >= 0 ? min : 0),
9685  max_(max >= min_ ? max : min_) {
9686  std::stringstream ss;
9687  if (min < 0) {
9688  ss << "The invocation lower bound must be >= 0, "
9689  << "but is actually " << min << ".";
9690  internal::Expect(false, __FILE__, __LINE__, ss.str());
9691  } else if (max < 0) {
9692  ss << "The invocation upper bound must be >= 0, "
9693  << "but is actually " << max << ".";
9694  internal::Expect(false, __FILE__, __LINE__, ss.str());
9695  } else if (min > max) {
9696  ss << "The invocation upper bound (" << max
9697  << ") must be >= the invocation lower bound (" << min
9698  << ").";
9699  internal::Expect(false, __FILE__, __LINE__, ss.str());
9700  }
9701  }
9702 
9703  // Conservative estimate on the lower/upper bound of the number of
9704  // calls allowed.
9705  virtual int ConservativeLowerBound() const { return min_; }
9706  virtual int ConservativeUpperBound() const { return max_; }
9707 
9708  virtual bool IsSatisfiedByCallCount(int call_count) const {
9709  return min_ <= call_count && call_count <= max_;
9710  }
9711 
9712  virtual bool IsSaturatedByCallCount(int call_count) const {
9713  return call_count >= max_;
9714  }
9715 
9716  virtual void DescribeTo(::std::ostream* os) const;
9717 
9718  private:
9719  const int min_;
9720  const int max_;
9721 
9722  GTEST_DISALLOW_COPY_AND_ASSIGN_(BetweenCardinalityImpl);
9723 };
9724 
9725 // Formats "n times" in a human-friendly way.
9726 inline internal::string FormatTimes(int n) {
9727  if (n == 1) {
9728  return "once";
9729  } else if (n == 2) {
9730  return "twice";
9731  } else {
9732  std::stringstream ss;
9733  ss << n << " times";
9734  return ss.str();
9735  }
9736 }
9737 
9738 // Describes the Between(m, n) cardinality in human-friendly text.
9739 void BetweenCardinalityImpl::DescribeTo(::std::ostream* os) const {
9740  if (min_ == 0) {
9741  if (max_ == 0) {
9742  *os << "never called";
9743  } else if (max_ == INT_MAX) {
9744  *os << "called any number of times";
9745  } else {
9746  *os << "called at most " << FormatTimes(max_);
9747  }
9748  } else if (min_ == max_) {
9749  *os << "called " << FormatTimes(min_);
9750  } else if (max_ == INT_MAX) {
9751  *os << "called at least " << FormatTimes(min_);
9752  } else {
9753  // 0 < min_ < max_ < INT_MAX
9754  *os << "called between " << min_ << " and " << max_ << " times";
9755  }
9756 }
9757 
9758 } // Unnamed namespace
9759 
9760 // Describes the given call count to an ostream.
9761 void Cardinality::DescribeActualCallCountTo(int actual_call_count,
9762  ::std::ostream* os) {
9763  if (actual_call_count > 0) {
9764  *os << "called " << FormatTimes(actual_call_count);
9765  } else {
9766  *os << "never called";
9767  }
9768 }
9769 
9770 // Creates a cardinality that allows at least n calls.
9771 GTEST_API_ Cardinality AtLeast(int n) { return Between(n, INT_MAX); }
9772 
9773 // Creates a cardinality that allows at most n calls.
9774 GTEST_API_ Cardinality AtMost(int n) { return Between(0, n); }
9775 
9776 // Creates a cardinality that allows any number of calls.
9778 
9779 // Creates a cardinality that allows between min and max calls.
9780 GTEST_API_ Cardinality Between(int min, int max) {
9781  return Cardinality(new BetweenCardinalityImpl(min, max));
9782 }
9783 
9784 // Creates a cardinality that allows exactly n calls.
9785 GTEST_API_ Cardinality Exactly(int n) { return Between(n, n); }
9786 
9787 } // namespace testing
9788 // Copyright 2007, Google Inc.
9789 // All rights reserved.
9790 //
9791 // Redistribution and use in source and binary forms, with or without
9792 // modification, are permitted provided that the following conditions are
9793 // met:
9794 //
9795 // * Redistributions of source code must retain the above copyright
9796 // notice, this list of conditions and the following disclaimer.
9797 // * Redistributions in binary form must reproduce the above
9798 // copyright notice, this list of conditions and the following disclaimer
9799 // in the documentation and/or other materials provided with the
9800 // distribution.
9801 // * Neither the name of Google Inc. nor the names of its
9802 // contributors may be used to endorse or promote products derived from
9803 // this software without specific prior written permission.
9804 //
9805 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
9806 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
9807 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
9808 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9809 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
9810 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9811 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
9812 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
9813 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
9814 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
9815 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
9816 //
9817 // Author: wan@google.com (Zhanyong Wan)
9818 
9819 // Google Mock - a framework for writing C++ mock classes.
9820 //
9821 // This file defines some utilities useful for implementing Google
9822 // Mock. They are subject to change without notice, so please DO NOT
9823 // USE THEM IN USER CODE.
9824 
9825 
9826 #include <ctype.h>
9827 #include <ostream> // NOLINT
9828 #include <string>
9829 
9830 namespace testing {
9831 namespace internal {
9832 
9833 // Converts an identifier name to a space-separated list of lower-case
9834 // words. Each maximum substring of the form [A-Za-z][a-z]*|\d+ is
9835 // treated as one word. For example, both "FooBar123" and
9836 // "foo_bar_123" are converted to "foo bar 123".
9837 GTEST_API_ string ConvertIdentifierNameToWords(const char* id_name) {
9838  string result;
9839  char prev_char = '\0';
9840  for (const char* p = id_name; *p != '\0'; prev_char = *(p++)) {
9841  // We don't care about the current locale as the input is
9842  // guaranteed to be a valid C++ identifier name.
9843  const bool starts_new_word = IsUpper(*p) ||
9844  (!IsAlpha(prev_char) && IsLower(*p)) ||
9845  (!IsDigit(prev_char) && IsDigit(*p));
9846 
9847  if (IsAlNum(*p)) {
9848  if (starts_new_word && result != "")
9849  result += ' ';
9850  result += ToLower(*p);
9851  }
9852  }
9853  return result;
9854 }
9855 
9856 // This class reports Google Mock failures as Google Test failures. A
9857 // user can define another class in a similar fashion if he intends to
9858 // use Google Mock with a testing framework other than Google Test.
9859 class GoogleTestFailureReporter : public FailureReporterInterface {
9860  public:
9861  virtual void ReportFailure(FailureType type, const char* file, int line,
9862  const string& message) {
9863  AssertHelper(type == kFatal ?
9866  file,
9867  line,
9868  message.c_str()) = Message();
9869  if (type == kFatal) {
9870  posix::Abort();
9871  }
9872  }
9873 };
9874 
9875 // Returns the global failure reporter. Will create a
9876 // GoogleTestFailureReporter and return it the first time called.
9877 GTEST_API_ FailureReporterInterface* GetFailureReporter() {
9878  // Points to the global failure reporter used by Google Mock. gcc
9879  // guarantees that the following use of failure_reporter is
9880  // thread-safe. We may need to add additional synchronization to
9881  // protect failure_reporter if we port Google Mock to other
9882  // compilers.
9883  static FailureReporterInterface* const failure_reporter =
9885  return failure_reporter;
9886 }
9887 
9888 // Protects global resources (stdout in particular) used by Log().
9889 static GTEST_DEFINE_STATIC_MUTEX_(g_log_mutex);
9890 
9891 // Returns true iff a log with the given severity is visible according
9892 // to the --gmock_verbose flag.
9894  if (GMOCK_FLAG(verbose) == kInfoVerbosity) {
9895  // Always show the log if --gmock_verbose=info.
9896  return true;
9897  } else if (GMOCK_FLAG(verbose) == kErrorVerbosity) {
9898  // Always hide it if --gmock_verbose=error.
9899  return false;
9900  } else {
9901  // If --gmock_verbose is neither "info" nor "error", we treat it
9902  // as "warning" (its default value).
9903  return severity == kWarning;
9904  }
9905 }
9906 
9907 // Prints the given message to stdout iff 'severity' >= the level
9908 // specified by the --gmock_verbose flag. If stack_frames_to_skip >=
9909 // 0, also prints the stack trace excluding the top
9910 // stack_frames_to_skip frames. In opt mode, any positive
9911 // stack_frames_to_skip is treated as 0, since we don't know which
9912 // function calls will be inlined by the compiler and need to be
9913 // conservative.
9915  const string& message,
9916  int stack_frames_to_skip) {
9917  if (!LogIsVisible(severity))
9918  return;
9919 
9920  // Ensures that logs from different threads don't interleave.
9921  MutexLock l(&g_log_mutex);
9922 
9923  // "using ::std::cout;" doesn't work with Symbian's STLport, where cout is a
9924  // macro.
9925 
9926  if (severity == kWarning) {
9927  // Prints a GMOCK WARNING marker to make the warnings easily searchable.
9928  std::cout << "\nGMOCK WARNING:";
9929  }
9930  // Pre-pends a new-line to message if it doesn't start with one.
9931  if (message.empty() || message[0] != '\n') {
9932  std::cout << "\n";
9933  }
9934  std::cout << message;
9935  if (stack_frames_to_skip >= 0) {
9936 #ifdef NDEBUG
9937  // In opt mode, we have to be conservative and skip no stack frame.
9938  const int actual_to_skip = 0;
9939 #else
9940  // In dbg mode, we can do what the caller tell us to do (plus one
9941  // for skipping this function's stack frame).
9942  const int actual_to_skip = stack_frames_to_skip + 1;
9943 #endif // NDEBUG
9944 
9945  // Appends a new-line to message if it doesn't end with one.
9946  if (!message.empty() && *message.rbegin() != '\n') {
9947  std::cout << "\n";
9948  }
9949  std::cout << "Stack trace:\n"
9951  ::testing::UnitTest::GetInstance(), actual_to_skip);
9952  }
9953  std::cout << ::std::flush;
9954 }
9955 
9956 } // namespace internal
9957 } // namespace testing
9958 // Copyright 2007, Google Inc.
9959 // All rights reserved.
9960 //
9961 // Redistribution and use in source and binary forms, with or without
9962 // modification, are permitted provided that the following conditions are
9963 // met:
9964 //
9965 // * Redistributions of source code must retain the above copyright
9966 // notice, this list of conditions and the following disclaimer.
9967 // * Redistributions in binary form must reproduce the above
9968 // copyright notice, this list of conditions and the following disclaimer
9969 // in the documentation and/or other materials provided with the
9970 // distribution.
9971 // * Neither the name of Google Inc. nor the names of its
9972 // contributors may be used to endorse or promote products derived from
9973 // this software without specific prior written permission.
9974 //
9975 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
9976 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
9977 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
9978 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9979 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
9980 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9981 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
9982 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
9983 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
9984 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
9985 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
9986 //
9987 // Author: wan@google.com (Zhanyong Wan)
9988 
9989 // Google Mock - a framework for writing C++ mock classes.
9990 //
9991 // This file implements Matcher<const string&>, Matcher<string>, and
9992 // utilities for defining matchers.
9993 
9994 
9995 #include <string.h>
9996 #include <sstream>
9997 #include <string>
9998 
9999 namespace testing {
10000 
10001 // Constructs a matcher that matches a const string& whose value is
10002 // equal to s.
10004  *this = Eq(s);
10005 }
10006 
10007 // Constructs a matcher that matches a const string& whose value is
10008 // equal to s.
10010  *this = Eq(internal::string(s));
10011 }
10012 
10013 // Constructs a matcher that matches a string whose value is equal to s.
10015 
10016 // Constructs a matcher that matches a string whose value is equal to s.
10018  *this = Eq(internal::string(s));
10019 }
10020 
10021 #if GTEST_HAS_STRING_PIECE_
10022 // Constructs a matcher that matches a const StringPiece& whose value is
10023 // equal to s.
10025  *this = Eq(s);
10026 }
10027 
10028 // Constructs a matcher that matches a const StringPiece& whose value is
10029 // equal to s.
10030 Matcher<const StringPiece&>::Matcher(const char* s) {
10031  *this = Eq(internal::string(s));
10032 }
10033 
10034 // Constructs a matcher that matches a const StringPiece& whose value is
10035 // equal to s.
10036 Matcher<const StringPiece&>::Matcher(StringPiece s) {
10037  *this = Eq(s.ToString());
10038 }
10039 
10040 // Constructs a matcher that matches a StringPiece whose value is equal to s.
10042  *this = Eq(s);
10043 }
10044 
10045 // Constructs a matcher that matches a StringPiece whose value is equal to s.
10046 Matcher<StringPiece>::Matcher(const char* s) {
10047  *this = Eq(internal::string(s));
10048 }
10049 
10050 // Constructs a matcher that matches a StringPiece whose value is equal to s.
10051 Matcher<StringPiece>::Matcher(StringPiece s) {
10052  *this = Eq(s.ToString());
10053 }
10054 #endif // GTEST_HAS_STRING_PIECE_
10055 
10056 namespace internal {
10057 
10058 // Joins a vector of strings as if they are fields of a tuple; returns
10059 // the joined string.
10060 GTEST_API_ string JoinAsTuple(const Strings& fields) {
10061  switch (fields.size()) {
10062  case 0:
10063  return "";
10064  case 1:
10065  return fields[0];
10066  default:
10067  string result = "(" + fields[0];
10068  for (size_t i = 1; i < fields.size(); i++) {
10069  result += ", ";
10070  result += fields[i];
10071  }
10072  result += ")";
10073  return result;
10074  }
10075 }
10076 
10077 // Returns the description for a matcher defined using the MATCHER*()
10078 // macro where the user-supplied description string is "", if
10079 // 'negation' is false; otherwise returns the description of the
10080 // negation of the matcher. 'param_values' contains a list of strings
10081 // that are the print-out of the matcher's parameters.
10083  const char* matcher_name,
10084  const Strings& param_values) {
10085  string result = ConvertIdentifierNameToWords(matcher_name);
10086  if (param_values.size() >= 1)
10087  result += " " + JoinAsTuple(param_values);
10088  return negation ? "not (" + result + ")" : result;
10089 }
10090 
10091 // FindMaxBipartiteMatching and its helper class.
10092 //
10093 // Uses the well-known Ford-Fulkerson max flow method to find a maximum
10094 // bipartite matching. Flow is considered to be from left to right.
10095 // There is an implicit source node that is connected to all of the left
10096 // nodes, and an implicit sink node that is connected to all of the
10097 // right nodes. All edges have unit capacity.
10098 //
10099 // Neither the flow graph nor the residual flow graph are represented
10100 // explicitly. Instead, they are implied by the information in 'graph' and
10101 // a vector<int> called 'left_' whose elements are initialized to the
10102 // value kUnused. This represents the initial state of the algorithm,
10103 // where the flow graph is empty, and the residual flow graph has the
10104 // following edges:
10105 // - An edge from source to each left_ node
10106 // - An edge from each right_ node to sink
10107 // - An edge from each left_ node to each right_ node, if the
10108 // corresponding edge exists in 'graph'.
10109 //
10110 // When the TryAugment() method adds a flow, it sets left_[l] = r for some
10111 // nodes l and r. This induces the following changes:
10112 // - The edges (source, l), (l, r), and (r, sink) are added to the
10113 // flow graph.
10114 // - The same three edges are removed from the residual flow graph.
10115 // - The reverse edges (l, source), (r, l), and (sink, r) are added
10116 // to the residual flow graph, which is a directional graph
10117 // representing unused flow capacity.
10118 //
10119 // When the method augments a flow (moving left_[l] from some r1 to some
10120 // other r2), this can be thought of as "undoing" the above steps with
10121 // respect to r1 and "redoing" them with respect to r2.
10122 //
10123 // It bears repeating that the flow graph and residual flow graph are
10124 // never represented explicitly, but can be derived by looking at the
10125 // information in 'graph' and in left_.
10126 //
10127 // As an optimization, there is a second vector<int> called right_ which
10128 // does not provide any new information. Instead, it enables more
10129 // efficient queries about edges entering or leaving the right-side nodes
10130 // of the flow or residual flow graphs. The following invariants are
10131 // maintained:
10132 //
10133 // left[l] == kUnused or right[left[l]] == l
10134 // right[r] == kUnused or left[right[r]] == r
10135 //
10136 // . [ source ] .
10137 // . ||| .
10138 // . ||| .
10139 // . ||\--> left[0]=1 ---\ right[0]=-1 ----\ .
10140 // . || | | .
10141 // . |\---> left[1]=-1 \--> right[1]=0 ---\| .
10142 // . | || .
10143 // . \----> left[2]=2 ------> right[2]=2 --\|| .
10144 // . ||| .
10145 // . elements matchers vvv .
10146 // . [ sink ] .
10147 //
10148 // See Also:
10149 // [1] Cormen, et al (2001). "Section 26.2: The Ford–Fulkerson method".
10150 // "Introduction to Algorithms (Second ed.)", pp. 651–664.
10151 // [2] "Ford–Fulkerson algorithm", Wikipedia,
10152 // 'http://en.wikipedia.org/wiki/Ford%E2%80%93Fulkerson_algorithm'
10154  public:
10155  explicit MaxBipartiteMatchState(const MatchMatrix& graph)
10156  : graph_(&graph),
10157  left_(graph_->LhsSize(), kUnused),
10158  right_(graph_->RhsSize(), kUnused) {
10159  }
10160 
10161  // Returns the edges of a maximal match, each in the form {left, right}.
10163  // 'seen' is used for path finding { 0: unseen, 1: seen }.
10164  ::std::vector<char> seen;
10165  // Searches the residual flow graph for a path from each left node to
10166  // the sink in the residual flow graph, and if one is found, add flow
10167  // to the graph. It's okay to search through the left nodes once. The
10168  // edge from the implicit source node to each previously-visited left
10169  // node will have flow if that left node has any path to the sink
10170  // whatsoever. Subsequent augmentations can only add flow to the
10171  // network, and cannot take away that previous flow unit from the source.
10172  // Since the source-to-left edge can only carry one flow unit (or,
10173  // each element can be matched to only one matcher), there is no need
10174  // to visit the left nodes more than once looking for augmented paths.
10175  // The flow is known to be possible or impossible by looking at the
10176  // node once.
10177  for (size_t ilhs = 0; ilhs < graph_->LhsSize(); ++ilhs) {
10178  // Reset the path-marking vector and try to find a path from
10179  // source to sink starting at the left_[ilhs] node.
10180  GTEST_CHECK_(left_[ilhs] == kUnused)
10181  << "ilhs: " << ilhs << ", left_[ilhs]: " << left_[ilhs];
10182  // 'seen' initialized to 'graph_->RhsSize()' copies of 0.
10183  seen.assign(graph_->RhsSize(), 0);
10184  TryAugment(ilhs, &seen);
10185  }
10186  ElementMatcherPairs result;
10187  for (size_t ilhs = 0; ilhs < left_.size(); ++ilhs) {
10188  size_t irhs = left_[ilhs];
10189  if (irhs == kUnused) continue;
10190  result.push_back(ElementMatcherPair(ilhs, irhs));
10191  }
10192  return result;
10193  }
10194 
10195  private:
10196  static const size_t kUnused = static_cast<size_t>(-1);
10197 
10198  // Perform a depth-first search from left node ilhs to the sink. If a
10199  // path is found, flow is added to the network by linking the left and
10200  // right vector elements corresponding each segment of the path.
10201  // Returns true if a path to sink was found, which means that a unit of
10202  // flow was added to the network. The 'seen' vector elements correspond
10203  // to right nodes and are marked to eliminate cycles from the search.
10204  //
10205  // Left nodes will only be explored at most once because they
10206  // are accessible from at most one right node in the residual flow
10207  // graph.
10208  //
10209  // Note that left_[ilhs] is the only element of left_ that TryAugment will
10210  // potentially transition from kUnused to another value. Any other
10211  // left_ element holding kUnused before TryAugment will be holding it
10212  // when TryAugment returns.
10213  //
10214  bool TryAugment(size_t ilhs, ::std::vector<char>* seen) {
10215  for (size_t irhs = 0; irhs < graph_->RhsSize(); ++irhs) {
10216  if ((*seen)[irhs])
10217  continue;
10218  if (!graph_->HasEdge(ilhs, irhs))
10219  continue;
10220  // There's an available edge from ilhs to irhs.
10221  (*seen)[irhs] = 1;
10222  // Next a search is performed to determine whether
10223  // this edge is a dead end or leads to the sink.
10224  //
10225  // right_[irhs] == kUnused means that there is residual flow from
10226  // right node irhs to the sink, so we can use that to finish this
10227  // flow path and return success.
10228  //
10229  // Otherwise there is residual flow to some ilhs. We push flow
10230  // along that path and call ourselves recursively to see if this
10231  // ultimately leads to sink.
10232  if (right_[irhs] == kUnused || TryAugment(right_[irhs], seen)) {
10233  // Add flow from left_[ilhs] to right_[irhs].
10234  left_[ilhs] = irhs;
10235  right_[irhs] = ilhs;
10236  return true;
10237  }
10238  }
10239  return false;
10240  }
10241 
10242  const MatchMatrix* graph_; // not owned
10243  // Each element of the left_ vector represents a left hand side node
10244  // (i.e. an element) and each element of right_ is a right hand side
10245  // node (i.e. a matcher). The values in the left_ vector indicate
10246  // outflow from that node to a node on the the right_ side. The values
10247  // in the right_ indicate inflow, and specify which left_ node is
10248  // feeding that right_ node, if any. For example, left_[3] == 1 means
10249  // there's a flow from element #3 to matcher #1. Such a flow would also
10250  // be redundantly represented in the right_ vector as right_[1] == 3.
10251  // Elements of left_ and right_ are either kUnused or mutually
10252  // referent. Mutually referent means that left_[right_[i]] = i and
10253  // right_[left_[i]] = i.
10254  ::std::vector<size_t> left_;
10255  ::std::vector<size_t> right_;
10256 
10258 };
10259 
10260 const size_t MaxBipartiteMatchState::kUnused;
10261 
10264  return MaxBipartiteMatchState(g).Compute();
10265 }
10266 
10268  ::std::ostream* stream) {
10269  typedef ElementMatcherPairs::const_iterator Iter;
10270  ::std::ostream& os = *stream;
10271  os << "{";
10272  const char *sep = "";
10273  for (Iter it = pairs.begin(); it != pairs.end(); ++it) {
10274  os << sep << "\n ("
10275  << "element #" << it->first << ", "
10276  << "matcher #" << it->second << ")";
10277  sep = ",";
10278  }
10279  os << "\n}";
10280 }
10281 
10282 // Tries to find a pairing, and explains the result.
10284  MatchResultListener* listener) {
10286 
10287  size_t max_flow = matches.size();
10288  bool result = (max_flow == matrix.RhsSize());
10289 
10290  if (!result) {
10291  if (listener->IsInterested()) {
10292  *listener << "where no permutation of the elements can "
10293  "satisfy all matchers, and the closest match is "
10294  << max_flow << " of " << matrix.RhsSize()
10295  << " matchers with the pairings:\n";
10296  LogElementMatcherPairVec(matches, listener->stream());
10297  }
10298  return false;
10299  }
10300 
10301  if (matches.size() > 1) {
10302  if (listener->IsInterested()) {
10303  const char *sep = "where:\n";
10304  for (size_t mi = 0; mi < matches.size(); ++mi) {
10305  *listener << sep << " - element #" << matches[mi].first
10306  << " is matched by matcher #" << matches[mi].second;
10307  sep = ",\n";
10308  }
10309  }
10310  }
10311  return true;
10312 }
10313 
10315  for (size_t ilhs = 0; ilhs < LhsSize(); ++ilhs) {
10316  for (size_t irhs = 0; irhs < RhsSize(); ++irhs) {
10317  char& b = matched_[SpaceIndex(ilhs, irhs)];
10318  if (!b) {
10319  b = 1;
10320  return true;
10321  }
10322  b = 0;
10323  }
10324  }
10325  return false;
10326 }
10327 
10329  for (size_t ilhs = 0; ilhs < LhsSize(); ++ilhs) {
10330  for (size_t irhs = 0; irhs < RhsSize(); ++irhs) {
10331  char& b = matched_[SpaceIndex(ilhs, irhs)];
10332  b = static_cast<char>(rand() & 1); // NOLINT
10333  }
10334  }
10335 }
10336 
10338  ::std::stringstream ss;
10339  const char *sep = "";
10340  for (size_t i = 0; i < LhsSize(); ++i) {
10341  ss << sep;
10342  for (size_t j = 0; j < RhsSize(); ++j) {
10343  ss << HasEdge(i, j);
10344  }
10345  sep = ";";
10346  }
10347  return ss.str();
10348 }
10349 
10351  ::std::ostream* os) const {
10352  if (matcher_describers_.empty()) {
10353  *os << "is empty";
10354  return;
10355  }
10356  if (matcher_describers_.size() == 1) {
10357  *os << "has " << Elements(1) << " and that element ";
10358  matcher_describers_[0]->DescribeTo(os);
10359  return;
10360  }
10361  *os << "has " << Elements(matcher_describers_.size())
10362  << " and there exists some permutation of elements such that:\n";
10363  const char* sep = "";
10364  for (size_t i = 0; i != matcher_describers_.size(); ++i) {
10365  *os << sep << " - element #" << i << " ";
10366  matcher_describers_[i]->DescribeTo(os);
10367  sep = ", and\n";
10368  }
10369 }
10370 
10372  ::std::ostream* os) const {
10373  if (matcher_describers_.empty()) {
10374  *os << "isn't empty";
10375  return;
10376  }
10377  if (matcher_describers_.size() == 1) {
10378  *os << "doesn't have " << Elements(1)
10379  << ", or has " << Elements(1) << " that ";
10380  matcher_describers_[0]->DescribeNegationTo(os);
10381  return;
10382  }
10383  *os << "doesn't have " << Elements(matcher_describers_.size())
10384  << ", or there exists no permutation of elements such that:\n";
10385  const char* sep = "";
10386  for (size_t i = 0; i != matcher_describers_.size(); ++i) {
10387  *os << sep << " - element #" << i << " ";
10388  matcher_describers_[i]->DescribeTo(os);
10389  sep = ", and\n";
10390  }
10391 }
10392 
10393 // Checks that all matchers match at least one element, and that all
10394 // elements match at least one matcher. This enables faster matching
10395 // and better error reporting.
10396 // Returns false, writing an explanation to 'listener', if and only
10397 // if the success criteria are not met.
10400  const ::std::vector<string>& element_printouts,
10401  const MatchMatrix& matrix,
10402  MatchResultListener* listener) const {
10403  bool result = true;
10404  ::std::vector<char> element_matched(matrix.LhsSize(), 0);
10405  ::std::vector<char> matcher_matched(matrix.RhsSize(), 0);
10406 
10407  for (size_t ilhs = 0; ilhs < matrix.LhsSize(); ilhs++) {
10408  for (size_t irhs = 0; irhs < matrix.RhsSize(); irhs++) {
10409  char matched = matrix.HasEdge(ilhs, irhs);
10410  element_matched[ilhs] |= matched;
10411  matcher_matched[irhs] |= matched;
10412  }
10413  }
10414 
10415  {
10416  const char* sep =
10417  "where the following matchers don't match any elements:\n";
10418  for (size_t mi = 0; mi < matcher_matched.size(); ++mi) {
10419  if (matcher_matched[mi])
10420  continue;
10421  result = false;
10422  if (listener->IsInterested()) {
10423  *listener << sep << "matcher #" << mi << ": ";
10424  matcher_describers_[mi]->DescribeTo(listener->stream());
10425  sep = ",\n";
10426  }
10427  }
10428  }
10429 
10430  {
10431  const char* sep =
10432  "where the following elements don't match any matchers:\n";
10433  const char* outer_sep = "";
10434  if (!result) {
10435  outer_sep = "\nand ";
10436  }
10437  for (size_t ei = 0; ei < element_matched.size(); ++ei) {
10438  if (element_matched[ei])
10439  continue;
10440  result = false;
10441  if (listener->IsInterested()) {
10442  *listener << outer_sep << sep << "element #" << ei << ": "
10443  << element_printouts[ei];
10444  sep = ",\n";
10445  outer_sep = "";
10446  }
10447  }
10448  }
10449  return result;
10450 }
10451 
10452 } // namespace internal
10453 } // namespace testing
10454 // Copyright 2007, Google Inc.
10455 // All rights reserved.
10456 //
10457 // Redistribution and use in source and binary forms, with or without
10458 // modification, are permitted provided that the following conditions are
10459 // met:
10460 //
10461 // * Redistributions of source code must retain the above copyright
10462 // notice, this list of conditions and the following disclaimer.
10463 // * Redistributions in binary form must reproduce the above
10464 // copyright notice, this list of conditions and the following disclaimer
10465 // in the documentation and/or other materials provided with the
10466 // distribution.
10467 // * Neither the name of Google Inc. nor the names of its
10468 // contributors may be used to endorse or promote products derived from
10469 // this software without specific prior written permission.
10470 //
10471 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
10472 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
10473 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
10474 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
10475 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
10476 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
10477 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
10478 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
10479 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
10480 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
10481 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
10482 //
10483 // Author: wan@google.com (Zhanyong Wan)
10484 
10485 // Google Mock - a framework for writing C++ mock classes.
10486 //
10487 // This file implements the spec builder syntax (ON_CALL and
10488 // EXPECT_CALL).
10489 
10490 
10491 #include <stdlib.h>
10492 #include <iostream> // NOLINT
10493 #include <map>
10494 #include <set>
10495 #include <string>
10496 
10497 #if GTEST_OS_CYGWIN || GTEST_OS_LINUX || GTEST_OS_MAC
10498 # include <unistd.h> // NOLINT
10499 #endif
10500 
10501 namespace testing {
10502 namespace internal {
10503 
10504 // Protects the mock object registry (in class Mock), all function
10505 // mockers, and all expectations.
10506 GTEST_API_ GTEST_DEFINE_STATIC_MUTEX_(g_gmock_mutex);
10507 
10508 // Logs a message including file and line number information.
10510  const char* file, int line,
10511  const string& message) {
10512  ::std::ostringstream s;
10513  s << file << ":" << line << ": " << message << ::std::endl;
10514  Log(severity, s.str(), 0);
10515 }
10516 
10517 // Constructs an ExpectationBase object.
10519  int a_line,
10520  const string& a_source_text)
10521  : file_(a_file),
10522  line_(a_line),
10523  source_text_(a_source_text),
10524  cardinality_specified_(false),
10525  cardinality_(Exactly(1)),
10526  call_count_(0),
10527  retired_(false),
10528  extra_matcher_specified_(false),
10529  repeated_action_specified_(false),
10530  retires_on_saturation_(false),
10531  last_clause_(kNone),
10532  action_count_checked_(false) {}
10533 
10534 // Destructs an ExpectationBase object.
10536 
10537 // Explicitly specifies the cardinality of this expectation. Used by
10538 // the subclasses to implement the .Times() clause.
10540  cardinality_specified_ = true;
10541  cardinality_ = a_cardinality;
10542 }
10543 
10544 // Retires all pre-requisites of this expectation.
10546  GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
10547  if (is_retired()) {
10548  // We can take this short-cut as we never retire an expectation
10549  // until we have retired all its pre-requisites.
10550  return;
10551  }
10552 
10554  it != immediate_prerequisites_.end(); ++it) {
10555  ExpectationBase* const prerequisite = it->expectation_base().get();
10556  if (!prerequisite->is_retired()) {
10557  prerequisite->RetireAllPreRequisites();
10558  prerequisite->Retire();
10559  }
10560  }
10561 }
10562 
10563 // Returns true iff all pre-requisites of this expectation have been
10564 // satisfied.
10566  GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
10567  g_gmock_mutex.AssertHeld();
10569  it != immediate_prerequisites_.end(); ++it) {
10570  if (!(it->expectation_base()->IsSatisfied()) ||
10571  !(it->expectation_base()->AllPrerequisitesAreSatisfied()))
10572  return false;
10573  }
10574  return true;
10575 }
10576 
10577 // Adds unsatisfied pre-requisites of this expectation to 'result'.
10579  GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
10580  g_gmock_mutex.AssertHeld();
10582  it != immediate_prerequisites_.end(); ++it) {
10583  if (it->expectation_base()->IsSatisfied()) {
10584  // If *it is satisfied and has a call count of 0, some of its
10585  // pre-requisites may not be satisfied yet.
10586  if (it->expectation_base()->call_count_ == 0) {
10587  it->expectation_base()->FindUnsatisfiedPrerequisites(result);
10588  }
10589  } else {
10590  // Now that we know *it is unsatisfied, we are not so interested
10591  // in whether its pre-requisites are satisfied. Therefore we
10592  // don't recursively call FindUnsatisfiedPrerequisites() here.
10593  *result += *it;
10594  }
10595  }
10596 }
10597 
10598 // Describes how many times a function call matching this
10599 // expectation has occurred.
10600 void ExpectationBase::DescribeCallCountTo(::std::ostream* os) const
10601  GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
10602  g_gmock_mutex.AssertHeld();
10603 
10604  // Describes how many times the function is expected to be called.
10605  *os << " Expected: to be ";
10606  cardinality().DescribeTo(os);
10607  *os << "\n Actual: ";
10609 
10610  // Describes the state of the expectation (e.g. is it satisfied?
10611  // is it active?).
10612  *os << " - " << (IsOverSaturated() ? "over-saturated" :
10613  IsSaturated() ? "saturated" :
10614  IsSatisfied() ? "satisfied" : "unsatisfied")
10615  << " and "
10616  << (is_retired() ? "retired" : "active");
10617 }
10618 
10619 // Checks the action count (i.e. the number of WillOnce() and
10620 // WillRepeatedly() clauses) against the cardinality if this hasn't
10621 // been done before. Prints a warning if there are too many or too
10622 // few actions.
10625  bool should_check = false;
10626  {
10627  MutexLock l(&mutex_);
10628  if (!action_count_checked_) {
10629  action_count_checked_ = true;
10630  should_check = true;
10631  }
10632  }
10633 
10634  if (should_check) {
10635  if (!cardinality_specified_) {
10636  // The cardinality was inferred - no need to check the action
10637  // count against it.
10638  return;
10639  }
10640 
10641  // The cardinality was explicitly specified.
10642  const int action_count = static_cast<int>(untyped_actions_.size());
10643  const int upper_bound = cardinality().ConservativeUpperBound();
10644  const int lower_bound = cardinality().ConservativeLowerBound();
10645  bool too_many; // True if there are too many actions, or false
10646  // if there are too few.
10647  if (action_count > upper_bound ||
10648  (action_count == upper_bound && repeated_action_specified_)) {
10649  too_many = true;
10650  } else if (0 < action_count && action_count < lower_bound &&
10652  too_many = false;
10653  } else {
10654  return;
10655  }
10656 
10657  ::std::stringstream ss;
10658  DescribeLocationTo(&ss);
10659  ss << "Too " << (too_many ? "many" : "few")
10660  << " actions specified in " << source_text() << "...\n"
10661  << "Expected to be ";
10662  cardinality().DescribeTo(&ss);
10663  ss << ", but has " << (too_many ? "" : "only ")
10664  << action_count << " WillOnce()"
10665  << (action_count == 1 ? "" : "s");
10667  ss << " and a WillRepeatedly()";
10668  }
10669  ss << ".";
10670  Log(kWarning, ss.str(), -1); // -1 means "don't print stack trace".
10671  }
10672 }
10673 
10674 // Implements the .Times() clause.
10675 void ExpectationBase::UntypedTimes(const Cardinality& a_cardinality) {
10676  if (last_clause_ == kTimes) {
10677  ExpectSpecProperty(false,
10678  ".Times() cannot appear "
10679  "more than once in an EXPECT_CALL().");
10680  } else {
10682  ".Times() cannot appear after "
10683  ".InSequence(), .WillOnce(), .WillRepeatedly(), "
10684  "or .RetiresOnSaturation().");
10685  }
10686  last_clause_ = kTimes;
10687 
10688  SpecifyCardinality(a_cardinality);
10689 }
10690 
10691 // Points to the implicit sequence introduced by a living InSequence
10692 // object (if any) in the current thread or NULL.
10694 
10695 // Reports an uninteresting call (whose description is in msg) in the
10696 // manner specified by 'reaction'.
10697 void ReportUninterestingCall(CallReaction reaction, const string& msg) {
10698  switch (reaction) {
10699  case kAllow:
10700  Log(kInfo, msg, 3);
10701  break;
10702  case kWarn:
10703  Log(kWarning, msg, 3);
10704  break;
10705  default: // FAIL
10706  Expect(false, NULL, -1, msg);
10707  }
10708 }
10709 
10711  : mock_obj_(NULL), name_("") {}
10712 
10714 
10715 // Sets the mock object this mock method belongs to, and registers
10716 // this information in the global mock registry. Will be called
10717 // whenever an EXPECT_CALL() or ON_CALL() is executed on this mock
10718 // method.
10720  GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
10721  {
10722  MutexLock l(&g_gmock_mutex);
10723  mock_obj_ = mock_obj;
10724  }
10725  Mock::Register(mock_obj, this);
10726 }
10727 
10728 // Sets the mock object this mock method belongs to, and sets the name
10729 // of the mock function. Will be called upon each invocation of this
10730 // mock function.
10732  const char* name)
10733  GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
10734  // We protect name_ under g_gmock_mutex in case this mock function
10735  // is called from two threads concurrently.
10736  MutexLock l(&g_gmock_mutex);
10737  mock_obj_ = mock_obj;
10738  name_ = name;
10739 }
10740 
10741 // Returns the name of the function being mocked. Must be called
10742 // after RegisterOwner() or SetOwnerAndName() has been called.
10744  GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
10745  const void* mock_obj;
10746  {
10747  // We protect mock_obj_ under g_gmock_mutex in case this mock
10748  // function is called from two threads concurrently.
10749  MutexLock l(&g_gmock_mutex);
10750  Assert(mock_obj_ != NULL, __FILE__, __LINE__,
10751  "MockObject() must not be called before RegisterOwner() or "
10752  "SetOwnerAndName() has been called.");
10753  mock_obj = mock_obj_;
10754  }
10755  return mock_obj;
10756 }
10757 
10758 // Returns the name of this mock method. Must be called after
10759 // SetOwnerAndName() has been called.
10761  GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
10762  const char* name;
10763  {
10764  // We protect name_ under g_gmock_mutex in case this mock
10765  // function is called from two threads concurrently.
10766  MutexLock l(&g_gmock_mutex);
10767  Assert(name_ != NULL, __FILE__, __LINE__,
10768  "Name() must not be called before SetOwnerAndName() has "
10769  "been called.");
10770  name = name_;
10771  }
10772  return name;
10773 }
10774 
10775 // Calculates the result of invoking this mock function with the given
10776 // arguments, prints it, and returns it. The caller is responsible
10777 // for deleting the result.
10779 UntypedFunctionMockerBase::UntypedInvokeWith(const void* const untyped_args)
10780  GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
10781  if (untyped_expectations_.size() == 0) {
10782  // No expectation is set on this mock method - we have an
10783  // uninteresting call.
10784 
10785  // We must get Google Mock's reaction on uninteresting calls
10786  // made on this mock object BEFORE performing the action,
10787  // because the action may DELETE the mock object and make the
10788  // following expression meaningless.
10789  const CallReaction reaction =
10790  Mock::GetReactionOnUninterestingCalls(MockObject());
10791 
10792  // True iff we need to print this call's arguments and return
10793  // value. This definition must be kept in sync with
10794  // the behavior of ReportUninterestingCall().
10795  const bool need_to_report_uninteresting_call =
10796  // If the user allows this uninteresting call, we print it
10797  // only when he wants informational messages.
10798  reaction == kAllow ? LogIsVisible(kInfo) :
10799  // If the user wants this to be a warning, we print it only
10800  // when he wants to see warnings.
10801  reaction == kWarn ? LogIsVisible(kWarning) :
10802  // Otherwise, the user wants this to be an error, and we
10803  // should always print detailed information in the error.
10804  true;
10805 
10806  if (!need_to_report_uninteresting_call) {
10807  // Perform the action without printing the call information.
10808  return this->UntypedPerformDefaultAction(untyped_args, "");
10809  }
10810 
10811  // Warns about the uninteresting call.
10812  ::std::stringstream ss;
10813  this->UntypedDescribeUninterestingCall(untyped_args, &ss);
10814 
10815  // Calculates the function result.
10816  const UntypedActionResultHolderBase* const result =
10817  this->UntypedPerformDefaultAction(untyped_args, ss.str());
10818 
10819  // Prints the function result.
10820  if (result != NULL)
10821  result->PrintAsActionResult(&ss);
10822 
10823  ReportUninterestingCall(reaction, ss.str());
10824  return result;
10825  }
10826 
10827  bool is_excessive = false;
10828  ::std::stringstream ss;
10829  ::std::stringstream why;
10830  ::std::stringstream loc;
10831  const void* untyped_action = NULL;
10832 
10833  // The UntypedFindMatchingExpectation() function acquires and
10834  // releases g_gmock_mutex.
10835  const ExpectationBase* const untyped_expectation =
10837  untyped_args, &untyped_action, &is_excessive,
10838  &ss, &why);
10839  const bool found = untyped_expectation != NULL;
10840 
10841  // True iff we need to print the call's arguments and return value.
10842  // This definition must be kept in sync with the uses of Expect()
10843  // and Log() in this function.
10844  const bool need_to_report_call =
10845  !found || is_excessive || LogIsVisible(kInfo);
10846  if (!need_to_report_call) {
10847  // Perform the action without printing the call information.
10848  return
10849  untyped_action == NULL ?
10850  this->UntypedPerformDefaultAction(untyped_args, "") :
10851  this->UntypedPerformAction(untyped_action, untyped_args);
10852  }
10853 
10854  ss << " Function call: " << Name();
10855  this->UntypedPrintArgs(untyped_args, &ss);
10856 
10857  // In case the action deletes a piece of the expectation, we
10858  // generate the message beforehand.
10859  if (found && !is_excessive) {
10860  untyped_expectation->DescribeLocationTo(&loc);
10861  }
10862 
10863  const UntypedActionResultHolderBase* const result =
10864  untyped_action == NULL ?
10865  this->UntypedPerformDefaultAction(untyped_args, ss.str()) :
10866  this->UntypedPerformAction(untyped_action, untyped_args);
10867  if (result != NULL)
10868  result->PrintAsActionResult(&ss);
10869  ss << "\n" << why.str();
10870 
10871  if (!found) {
10872  // No expectation matches this call - reports a failure.
10873  Expect(false, NULL, -1, ss.str());
10874  } else if (is_excessive) {
10875  // We had an upper-bound violation and the failure message is in ss.
10876  Expect(false, untyped_expectation->file(),
10877  untyped_expectation->line(), ss.str());
10878  } else {
10879  // We had an expected call and the matching expectation is
10880  // described in ss.
10881  Log(kInfo, loc.str() + ss.str(), 2);
10882  }
10883 
10884  return result;
10885 }
10886 
10887 // Returns an Expectation object that references and co-owns exp,
10888 // which must be an expectation on this mock function.
10890  for (UntypedExpectations::const_iterator it =
10891  untyped_expectations_.begin();
10892  it != untyped_expectations_.end(); ++it) {
10893  if (it->get() == exp) {
10894  return Expectation(*it);
10895  }
10896  }
10897 
10898  Assert(false, __FILE__, __LINE__, "Cannot find expectation.");
10899  return Expectation();
10900  // The above statement is just to make the code compile, and will
10901  // never be executed.
10902 }
10903 
10904 // Verifies that all expectations on this mock function have been
10905 // satisfied. Reports one or more Google Test non-fatal failures
10906 // and returns false if not.
10908  GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
10909  g_gmock_mutex.AssertHeld();
10910  bool expectations_met = true;
10911  for (UntypedExpectations::const_iterator it =
10912  untyped_expectations_.begin();
10913  it != untyped_expectations_.end(); ++it) {
10914  ExpectationBase* const untyped_expectation = it->get();
10915  if (untyped_expectation->IsOverSaturated()) {
10916  // There was an upper-bound violation. Since the error was
10917  // already reported when it occurred, there is no need to do
10918  // anything here.
10919  expectations_met = false;
10920  } else if (!untyped_expectation->IsSatisfied()) {
10921  expectations_met = false;
10922  ::std::stringstream ss;
10923  ss << "Actual function call count doesn't match "
10924  << untyped_expectation->source_text() << "...\n";
10925  // No need to show the source file location of the expectation
10926  // in the description, as the Expect() call that follows already
10927  // takes care of it.
10928  untyped_expectation->MaybeDescribeExtraMatcherTo(&ss);
10929  untyped_expectation->DescribeCallCountTo(&ss);
10930  Expect(false, untyped_expectation->file(),
10931  untyped_expectation->line(), ss.str());
10932  }
10933  }
10934 
10935  // Deleting our expectations may trigger other mock objects to be deleted, for
10936  // example if an action contains a reference counted smart pointer to that
10937  // mock object, and that is the last reference. So if we delete our
10938  // expectations within the context of the global mutex we may deadlock when
10939  // this method is called again. Instead, make a copy of the set of
10940  // expectations to delete, clear our set within the mutex, and then clear the
10941  // copied set outside of it.
10942  UntypedExpectations expectations_to_delete;
10943  untyped_expectations_.swap(expectations_to_delete);
10944 
10945  g_gmock_mutex.Unlock();
10946  expectations_to_delete.clear();
10947  g_gmock_mutex.Lock();
10948 
10949  return expectations_met;
10950 }
10951 
10952 } // namespace internal
10953 
10954 // Class Mock.
10955 
10956 namespace {
10957 
10958 typedef std::set<internal::UntypedFunctionMockerBase*> FunctionMockers;
10959 
10960 // The current state of a mock object. Such information is needed for
10961 // detecting leaked mock objects and explicitly verifying a mock's
10962 // expectations.
10963 struct MockObjectState {
10964  MockObjectState()
10965  : first_used_file(NULL), first_used_line(-1), leakable(false) {}
10966 
10967  // Where in the source file an ON_CALL or EXPECT_CALL is first
10968  // invoked on this mock object.
10969  const char* first_used_file;
10973  bool leakable; // true iff it's OK to leak the object.
10974  FunctionMockers function_mockers; // All registered methods of the object.
10975 };
10976 
10977 // A global registry holding the state of all mock objects that are
10978 // alive. A mock object is added to this registry the first time
10979 // Mock::AllowLeak(), ON_CALL(), or EXPECT_CALL() is called on it. It
10980 // is removed from the registry in the mock object's destructor.
10981 class MockObjectRegistry {
10982  public:
10983  // Maps a mock object (identified by its address) to its state.
10984  typedef std::map<const void*, MockObjectState> StateMap;
10985 
10986  // This destructor will be called when a program exits, after all
10987  // tests in it have been run. By then, there should be no mock
10988  // object alive. Therefore we report any living object as test
10989  // failure, unless the user explicitly asked us to ignore it.
10990  ~MockObjectRegistry() {
10991  // "using ::std::cout;" doesn't work with Symbian's STLport, where cout is
10992  // a macro.
10993 
10994  if (!GMOCK_FLAG(catch_leaked_mocks))
10995  return;
10996 
10997  int leaked_count = 0;
10998  for (StateMap::const_iterator it = states_.begin(); it != states_.end();
10999  ++it) {
11000  if (it->second.leakable) // The user said it's fine to leak this object.
11001  continue;
11002 
11003  // TODO(wan@google.com): Print the type of the leaked object.
11004  // This can help the user identify the leaked object.
11005  std::cout << "\n";
11006  const MockObjectState& state = it->second;
11007  std::cout << internal::FormatFileLocation(state.first_used_file,
11008  state.first_used_line);
11009  std::cout << " ERROR: this mock object";
11010  if (state.first_used_test != "") {
11011  std::cout << " (used in test " << state.first_used_test_case << "."
11012  << state.first_used_test << ")";
11013  }
11014  std::cout << " should be deleted but never is. Its address is @"
11015  << it->first << ".";
11016  leaked_count++;
11017  }
11018  if (leaked_count > 0) {
11019  std::cout << "\nERROR: " << leaked_count
11020  << " leaked mock " << (leaked_count == 1 ? "object" : "objects")
11021  << " found at program exit.\n";
11022  std::cout.flush();
11023  ::std::cerr.flush();
11024  // RUN_ALL_TESTS() has already returned when this destructor is
11025  // called. Therefore we cannot use the normal Google Test
11026  // failure reporting mechanism.
11027  _exit(1); // We cannot call exit() as it is not reentrant and
11028  // may already have been called.
11029  }
11030  }
11031 
11032  StateMap& states() { return states_; }
11033 
11034  private:
11035  StateMap states_;
11036 };
11037 
11038 // Protected by g_gmock_mutex.
11039 MockObjectRegistry g_mock_object_registry;
11040 
11041 // Maps a mock object to the reaction Google Mock should have when an
11042 // uninteresting method is called. Protected by g_gmock_mutex.
11043 std::map<const void*, internal::CallReaction> g_uninteresting_call_reaction;
11044 
11045 // Sets the reaction Google Mock should have when an uninteresting
11046 // method of the given mock object is called.
11047 void SetReactionOnUninterestingCalls(const void* mock_obj,
11048  internal::CallReaction reaction)
11049  GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
11050  internal::MutexLock l(&internal::g_gmock_mutex);
11051  g_uninteresting_call_reaction[mock_obj] = reaction;
11052 }
11053 
11054 } // namespace
11055 
11056 // Tells Google Mock to allow uninteresting calls on the given mock
11057 // object.
11058 void Mock::AllowUninterestingCalls(const void* mock_obj)
11059  GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
11060  SetReactionOnUninterestingCalls(mock_obj, internal::kAllow);
11061 }
11062 
11063 // Tells Google Mock to warn the user about uninteresting calls on the
11064 // given mock object.
11065 void Mock::WarnUninterestingCalls(const void* mock_obj)
11066  GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
11067  SetReactionOnUninterestingCalls(mock_obj, internal::kWarn);
11068 }
11069 
11070 // Tells Google Mock to fail uninteresting calls on the given mock
11071 // object.
11072 void Mock::FailUninterestingCalls(const void* mock_obj)
11073  GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
11074  SetReactionOnUninterestingCalls(mock_obj, internal::kFail);
11075 }
11076 
11077 // Tells Google Mock the given mock object is being destroyed and its
11078 // entry in the call-reaction table should be removed.
11079 void Mock::UnregisterCallReaction(const void* mock_obj)
11080  GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
11081  internal::MutexLock l(&internal::g_gmock_mutex);
11082  g_uninteresting_call_reaction.erase(mock_obj);
11083 }
11084 
11085 // Returns the reaction Google Mock will have on uninteresting calls
11086 // made on the given mock object.
11087 internal::CallReaction Mock::GetReactionOnUninterestingCalls(
11088  const void* mock_obj)
11089  GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
11090  internal::MutexLock l(&internal::g_gmock_mutex);
11091  return (g_uninteresting_call_reaction.count(mock_obj) == 0) ?
11092  internal::kDefault : g_uninteresting_call_reaction[mock_obj];
11093 }
11094 
11095 // Tells Google Mock to ignore mock_obj when checking for leaked mock
11096 // objects.
11097 void Mock::AllowLeak(const void* mock_obj)
11098  GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
11099  internal::MutexLock l(&internal::g_gmock_mutex);
11100  g_mock_object_registry.states()[mock_obj].leakable = true;
11101 }
11102 
11103 // Verifies and clears all expectations on the given mock object. If
11104 // the expectations aren't satisfied, generates one or more Google
11105 // Test non-fatal failures and returns false.
11106 bool Mock::VerifyAndClearExpectations(void* mock_obj)
11107  GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
11108  internal::MutexLock l(&internal::g_gmock_mutex);
11109  return VerifyAndClearExpectationsLocked(mock_obj);
11110 }
11111 
11112 // Verifies all expectations on the given mock object and clears its
11113 // default actions and expectations. Returns true iff the
11114 // verification was successful.
11115 bool Mock::VerifyAndClear(void* mock_obj)
11116  GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
11117  internal::MutexLock l(&internal::g_gmock_mutex);
11118  ClearDefaultActionsLocked(mock_obj);
11119  return VerifyAndClearExpectationsLocked(mock_obj);
11120 }
11121 
11122 // Verifies and clears all expectations on the given mock object. If
11123 // the expectations aren't satisfied, generates one or more Google
11124 // Test non-fatal failures and returns false.
11125 bool Mock::VerifyAndClearExpectationsLocked(void* mock_obj)
11126  GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) {
11127  internal::g_gmock_mutex.AssertHeld();
11128  if (g_mock_object_registry.states().count(mock_obj) == 0) {
11129  // No EXPECT_CALL() was set on the given mock object.
11130  return true;
11131  }
11132 
11133  // Verifies and clears the expectations on each mock method in the
11134  // given mock object.
11135  bool expectations_met = true;
11136  FunctionMockers& mockers =
11137  g_mock_object_registry.states()[mock_obj].function_mockers;
11138  for (FunctionMockers::const_iterator it = mockers.begin();
11139  it != mockers.end(); ++it) {
11140  if (!(*it)->VerifyAndClearExpectationsLocked()) {
11141  expectations_met = false;
11142  }
11143  }
11144 
11145  // We don't clear the content of mockers, as they may still be
11146  // needed by ClearDefaultActionsLocked().
11147  return expectations_met;
11148 }
11149 
11150 // Registers a mock object and a mock method it owns.
11151 void Mock::Register(const void* mock_obj,
11152  internal::UntypedFunctionMockerBase* mocker)
11153  GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
11154  internal::MutexLock l(&internal::g_gmock_mutex);
11155  g_mock_object_registry.states()[mock_obj].function_mockers.insert(mocker);
11156 }
11157 
11158 // Tells Google Mock where in the source code mock_obj is used in an
11159 // ON_CALL or EXPECT_CALL. In case mock_obj is leaked, this
11160 // information helps the user identify which object it is.
11161 void Mock::RegisterUseByOnCallOrExpectCall(const void* mock_obj,
11162  const char* file, int line)
11163  GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
11164  internal::MutexLock l(&internal::g_gmock_mutex);
11165  MockObjectState& state = g_mock_object_registry.states()[mock_obj];
11166  if (state.first_used_file == NULL) {
11167  state.first_used_file = file;
11168  state.first_used_line = line;
11169  const TestInfo* const test_info =
11171  if (test_info != NULL) {
11172  // TODO(wan@google.com): record the test case name when the
11173  // ON_CALL or EXPECT_CALL is invoked from SetUpTestCase() or
11174  // TearDownTestCase().
11175  state.first_used_test_case = test_info->test_case_name();
11176  state.first_used_test = test_info->name();
11177  }
11178  }
11179 }
11180 
11181 // Unregisters a mock method; removes the owning mock object from the
11182 // registry when the last mock method associated with it has been
11183 // unregistered. This is called only in the destructor of
11184 // FunctionMockerBase.
11185 void Mock::UnregisterLocked(internal::UntypedFunctionMockerBase* mocker)
11186  GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) {
11187  internal::g_gmock_mutex.AssertHeld();
11188  for (MockObjectRegistry::StateMap::iterator it =
11189  g_mock_object_registry.states().begin();
11190  it != g_mock_object_registry.states().end(); ++it) {
11191  FunctionMockers& mockers = it->second.function_mockers;
11192  if (mockers.erase(mocker) > 0) {
11193  // mocker was in mockers and has been just removed.
11194  if (mockers.empty()) {
11195  g_mock_object_registry.states().erase(it);
11196  }
11197  return;
11198  }
11199  }
11200 }
11201 
11202 // Clears all ON_CALL()s set on the given mock object.
11203 void Mock::ClearDefaultActionsLocked(void* mock_obj)
11204  GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) {
11205  internal::g_gmock_mutex.AssertHeld();
11206 
11207  if (g_mock_object_registry.states().count(mock_obj) == 0) {
11208  // No ON_CALL() was set on the given mock object.
11209  return;
11210  }
11211 
11212  // Clears the default actions for each mock method in the given mock
11213  // object.
11214  FunctionMockers& mockers =
11215  g_mock_object_registry.states()[mock_obj].function_mockers;
11216  for (FunctionMockers::const_iterator it = mockers.begin();
11217  it != mockers.end(); ++it) {
11218  (*it)->ClearDefaultActionsLocked();
11219  }
11220 
11221  // We don't clear the content of mockers, as they may still be
11222  // needed by VerifyAndClearExpectationsLocked().
11223 }
11224 
11226 
11228  const internal::linked_ptr<internal::ExpectationBase>& an_expectation_base)
11229  : expectation_base_(an_expectation_base) {}
11230 
11232 
11233 // Adds an expectation to a sequence.
11234 void Sequence::AddExpectation(const Expectation& expectation) const {
11235  if (*last_expectation_ != expectation) {
11236  if (last_expectation_->expectation_base() != NULL) {
11238  += *last_expectation_;
11239  }
11240  *last_expectation_ = expectation;
11241  }
11242 }
11243 
11244 // Creates the implicit sequence if there isn't one.
11246  if (internal::g_gmock_implicit_sequence.get() == NULL) {
11248  sequence_created_ = true;
11249  } else {
11250  sequence_created_ = false;
11251  }
11252 }
11253 
11254 // Deletes the implicit sequence if it was created by the constructor
11255 // of this object.
11257  if (sequence_created_) {
11260  }
11261 }
11262 
11263 } // namespace testing
11264 // Copyright 2008, Google Inc.
11265 // All rights reserved.
11266 //
11267 // Redistribution and use in source and binary forms, with or without
11268 // modification, are permitted provided that the following conditions are
11269 // met:
11270 //
11271 // * Redistributions of source code must retain the above copyright
11272 // notice, this list of conditions and the following disclaimer.
11273 // * Redistributions in binary form must reproduce the above
11274 // copyright notice, this list of conditions and the following disclaimer
11275 // in the documentation and/or other materials provided with the
11276 // distribution.
11277 // * Neither the name of Google Inc. nor the names of its
11278 // contributors may be used to endorse or promote products derived from
11279 // this software without specific prior written permission.
11280 //
11281 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
11282 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
11283 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
11284 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
11285 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
11286 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
11287 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
11288 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
11289 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
11290 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
11291 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
11292 //
11293 // Author: wan@google.com (Zhanyong Wan)
11294 
11295 
11296 namespace testing {
11297 
11298 // TODO(wan@google.com): support using environment variables to
11299 // control the flag values, like what Google Test does.
11300 
11301 GMOCK_DEFINE_bool_(catch_leaked_mocks, true,
11302  "true iff Google Mock should report leaked mock objects "
11303  "as failures.");
11304 
11306  "Controls how verbose Google Mock's output is."
11307  " Valid values:\n"
11308  " info - prints all messages.\n"
11309  " warning - prints warnings and errors.\n"
11310  " error - prints errors only.");
11311 
11312 namespace internal {
11313 
11314 // Parses a string as a command line flag. The string should have the
11315 // format "--gmock_flag=value". When def_optional is true, the
11316 // "=value" part can be omitted.
11317 //
11318 // Returns the value of the flag, or NULL if the parsing failed.
11319 static const char* ParseGoogleMockFlagValue(const char* str,
11320  const char* flag,
11321  bool def_optional) {
11322  // str and flag must not be NULL.
11323  if (str == NULL || flag == NULL) return NULL;
11324 
11325  // The flag must start with "--gmock_".
11326  const std::string flag_str = std::string("--gmock_") + flag;
11327  const size_t flag_len = flag_str.length();
11328  if (strncmp(str, flag_str.c_str(), flag_len) != 0) return NULL;
11329 
11330  // Skips the flag name.
11331  const char* flag_end = str + flag_len;
11332 
11333  // When def_optional is true, it's OK to not have a "=value" part.
11334  if (def_optional && (flag_end[0] == '\0')) {
11335  return flag_end;
11336  }
11337 
11338  // If def_optional is true and there are more characters after the
11339  // flag name, or if def_optional is false, there must be a '=' after
11340  // the flag name.
11341  if (flag_end[0] != '=') return NULL;
11342 
11343  // Returns the string after "=".
11344  return flag_end + 1;
11345 }
11346 
11347 // Parses a string for a Google Mock bool flag, in the form of
11348 // "--gmock_flag=value".
11349 //
11350 // On success, stores the value of the flag in *value, and returns
11351 // true. On failure, returns false without changing *value.
11352 static bool ParseGoogleMockBoolFlag(const char* str, const char* flag,
11353  bool* value) {
11354  // Gets the value of the flag as a string.
11355  const char* const value_str = ParseGoogleMockFlagValue(str, flag, true);
11356 
11357  // Aborts if the parsing failed.
11358  if (value_str == NULL) return false;
11359 
11360  // Converts the string value to a bool.
11361  *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F');
11362  return true;
11363 }
11364 
11365 // Parses a string for a Google Mock string flag, in the form of
11366 // "--gmock_flag=value".
11367 //
11368 // On success, stores the value of the flag in *value, and returns
11369 // true. On failure, returns false without changing *value.
11370 static bool ParseGoogleMockStringFlag(const char* str, const char* flag,
11371  std::string* value) {
11372  // Gets the value of the flag as a string.
11373  const char* const value_str = ParseGoogleMockFlagValue(str, flag, false);
11374 
11375  // Aborts if the parsing failed.
11376  if (value_str == NULL) return false;
11377 
11378  // Sets *value to the value of the flag.
11379  *value = value_str;
11380  return true;
11381 }
11382 
11383 // The internal implementation of InitGoogleMock().
11384 //
11385 // The type parameter CharType can be instantiated to either char or
11386 // wchar_t.
11387 template <typename CharType>
11388 void InitGoogleMockImpl(int* argc, CharType** argv) {
11389  // Makes sure Google Test is initialized. InitGoogleTest() is
11390  // idempotent, so it's fine if the user has already called it.
11391  InitGoogleTest(argc, argv);
11392  if (*argc <= 0) return;
11393 
11394  for (int i = 1; i != *argc; i++) {
11395  const std::string arg_string = StreamableToString(argv[i]);
11396  const char* const arg = arg_string.c_str();
11397 
11398  // Do we see a Google Mock flag?
11399  if (ParseGoogleMockBoolFlag(arg, "catch_leaked_mocks",
11400  &GMOCK_FLAG(catch_leaked_mocks)) ||
11401  ParseGoogleMockStringFlag(arg, "verbose", &GMOCK_FLAG(verbose))) {
11402  // Yes. Shift the remainder of the argv list left by one. Note
11403  // that argv has (*argc + 1) elements, the last one always being
11404  // NULL. The following loop moves the trailing NULL element as
11405  // well.
11406  for (int j = i; j != *argc; j++) {
11407  argv[j] = argv[j + 1];
11408  }
11409 
11410  // Decrements the argument count.
11411  (*argc)--;
11412 
11413  // We also need to decrement the iterator as we just removed
11414  // an element.
11415  i--;
11416  }
11417  }
11418 }
11419 
11420 } // namespace internal
11421 
11422 // Initializes Google Mock. This must be called before running the
11423 // tests. In particular, it parses a command line for the flags that
11424 // Google Mock recognizes. Whenever a Google Mock flag is seen, it is
11425 // removed from argv, and *argc is decremented.
11426 //
11427 // No value is returned. Instead, the Google Mock flag variables are
11428 // updated.
11429 //
11430 // Since Google Test is needed for Google Mock to work, this function
11431 // also initializes Google Test and parses its flags, if that hasn't
11432 // been done.
11433 GTEST_API_ void InitGoogleMock(int* argc, char** argv) {
11434  internal::InitGoogleMockImpl(argc, argv);
11435 }
11436 
11437 // This overloaded version can be used in Windows programs compiled in
11438 // UNICODE mode.
11439 GTEST_API_ void InitGoogleMock(int* argc, wchar_t** argv) {
11440  internal::InitGoogleMockImpl(argc, argv);
11441 }
11442 
11443 } // namespace testing
void ExpectSpecProperty(bool property, const string &failure_message) const
GTEST_API_ bool g_help_flag
void PrintCharAndCodeTo(Char c, ostream *os)
static CharFormat PrintAsStringLiteralTo(wchar_t c, ostream *os)
int failed_test_count() const
void SetDefaultResultPrinter(TestEventListener *listener)
TestPartResultReporterInterface * GetTestPartResultReporterForCurrentThread()
UnitTestImpl * GetUnitTestImpl()
internal::SetUpTestCaseFunc SetUpTestCaseFunc
const char * type_param() const
const void * MockObject() const GTEST_LOCK_EXCLUDED_(g_gmock_mutex)
GTEST_API_ ThreadLocal< Sequence * > g_gmock_implicit_sequence
std::vector< Environment * > & environments()
bool IsTrue(bool condition)
void RecordProperty(const std::string &xml_element, const TestProperty &test_property)
const char * original_working_dir() const
virtual void MaybeDescribeExtraMatcherTo(::std::ostream *os)=0
static const std::vector< testing::TestPartResult > & test_part_results(const TestResult &test_result)
void ReportFailureInUnknownLocation(TestPartResult::Type result_type, const std::string &message)
ScopedPrematureExitFile(const char *premature_exit_filepath)
int GetRandomSeedFromFlag(Int32 random_seed_flag)
Result HandleExceptionsInMethodIfSupported(T *object, Result(T::*method)(), const char *location)
std::string GetCapturedStdout()
GTEST_DEFINE_int32_(random_seed, internal::Int32FromGTestEnv("random_seed", 0),"Random number seed to use when shuffling test orders. Must be in range ""[1, 99999], or 0 to use a seed based on the current time.")
std::string GetCapturedStderr()
static bool HasFatalFailure()
static std::string ReadEntireFile(FILE *file)
TimeInMillis elapsed_time() const
std::vector< TestCase * > test_cases_
static bool HasGoogleTestFlagPrefix(const char *str)
const internal::linked_ptr< internal::ExpectationBase > & expectation_base() const
#define GTEST_DISALLOW_COPY_AND_ASSIGN_(type)
static int SumOverTestCaseList(const std::vector< TestCase * > &case_list, int(TestCase::*method)() const)
const TestResult * ad_hoc_test_result() const
void RetireAllPreRequisites() GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex)
TestPropertyKeyIs(const std::string &key)
GTEST_API_ std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms)
AssertionResult CmpHelperSTREQ(const char *expected_expression, const char *actual_expression, const wchar_t *expected, const wchar_t *actual)
static const char kDisableTestFilter[]
E GetElementOr(const std::vector< E > &v, int i, E default_value)
GTEST_API_ string ConvertIdentifierNameToWords(const char *id_name)
GTEST_API_ Cardinality AtLeast(int n)
AssertionResult AssertionFailure()
const char kAlsoRunDisabledTestsFlag[]
int * count
UInt32 ChopLowBits(UInt32 *bits, int n)
const int min_
ROSCPP_DECL void start()
virtual void OnEnvironmentsTearDownStart(const UnitTest &unit_test)=0
virtual void ReportTestPartResult(const TestPartResult &result)
const TestInfo * GetTestInfo(int i) const
static FilePath ConcatPaths(const FilePath &directory, const FilePath &relative_path)
static std::string ExtractSummary(const char *message)
static const char * TestPartResultTypeToString(TestPartResult::Type type)
static std::string EscapeXmlAttribute(const std::string &str)
#define GTEST_SNPRINTF_
static std::string EscapeXml(const std::string &str, bool is_attribute)
GTEST_DISALLOW_COPY_AND_ASSIGN_(GTestLog)
const char kListTestsFlag[]
#define GTEST_HAS_GETTIMEOFDAY_
void PrintFullTestCommentIfPresent(const TestInfo &test_info)
#define GTEST_API_
GTEST_API_ Cardinality AtMost(int n)
void set_current_test_info(TestInfo *a_current_test_info)
TestPartResultReporterInterface * GetGlobalTestPartResultReporter()
IntFormatSpec< int, TypeSpec<'x'> > hex(int value)
internal::EqMatcher< T > Eq(T x)
static void DescribeActualCallCountTo(int actual_call_count,::std::ostream *os)
::std::string PrintToString(const T &value)
static const char kDefaultDeathTestStyle[]
const char kStreamResultToFlag[]
TypeWithSize< 4 >::Int Int32
const char Message[]
Definition: strings.h:102
FILE * FOpen(const char *path, const char *mode)
#define EXPECT_PRED_FORMAT3(pred_format, v1, v2, v3)
TestCase(const char *name, const char *a_type_param, Test::SetUpTestCaseFunc set_up_tc, Test::TearDownTestCaseFunc tear_down_tc)
int GetNextRandomSeed(int seed)
static void ClearTestResult(TestInfo *test_info)
bool IsSatisfied() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex)
const char kFilterFlag[]
bool BoolFromGTestEnv(const char *flag, bool default_value)
GTEST_API_ void InitGoogleMock(int *argc, char **argv)
const std::vector< TestPartResult > & test_part_results() const
void DescribeLocationTo(::std::ostream *os) const
std::vector< internal::linked_ptr< ExpectationBase > > UntypedExpectations
GTEST_API_ int g_init_gtest_count
virtual void PrintAsActionResult(::std::ostream *os) const =0
GTEST_API_::std::string FormatFileLocation(const char *file, int line)
static CapturedStream * g_captured_stdout
virtual void ReportTestPartResult(const TestPartResult &result)
GTEST_API_ FailureReporterInterface * GetFailureReporter()
GTEST_API_ bool ShouldUseColor(bool stdout_is_tty)
static void PrintXmlTestCase(::std::ostream *stream, const TestCase &test_case)
ScopedFakeTestPartResultReporter(TestPartResultArray *result)
AssertionResult CmpHelperSTRCASENE(const char *s1_expression, const char *s2_expression, const char *s1, const char *s2)
TypeWithSize< 4 >::UInt UInt32
TestEventListener * Release(TestEventListener *listener)
Definition: test.py:1
std::vector< TestEventListener * > listeners_
GTEST_API_ bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id)
GTEST_API_ bool FindPairing(const MatchMatrix &matrix, MatchResultListener *listener)
void DescribeTo(::std::ostream *os) const
void FindUnsatisfiedPrerequisites(ExpectationSet *result) const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex)
static const char * GetDefaultFilter()
std::string format(CStringRef format_str, ArgList args)
Definition: format.h:3686
XmlRpcServer s
bool operator()(const TestCase *test_case) const
static bool TestPartNonfatallyFailed(const TestPartResult &result)
TestEventListener * repeater()
TimeInMillis start_timestamp() const
bool ParseInt32(const Message &src_text, const char *str, Int32 *value)
const UntypedActionResultHolderBase * UntypedInvokeWith(const void *untyped_args) GTEST_LOCK_EXCLUDED_(g_gmock_mutex)
const Graph * graph_
std::vector< TestInfo * > & test_info_list()
virtual void OnTestIterationStart(const UnitTest &unit_test, int iteration)=0
internal::Mutex global_test_part_result_reporter_mutex_
void SetGlobalTestPartResultReporter(TestPartResultReporterInterface *reporter)
bool connect(ros_opcua_srvs::Connect::Request &req, ros_opcua_srvs::Connect::Response &res)
void RecordProperty(const std::string &key, const std::string &value)
std::string StringStreamToString(::std::stringstream *ss)
static void PrintXmlUnitTest(::std::ostream *stream, const UnitTest &unit_test)
#define GTEST_NO_INLINE_
std::vector< TestInfo * > test_info_list_
virtual UntypedActionResultHolderBase * UntypedPerformAction(const void *untyped_action, const void *untyped_args) const =0
bool HasEdge(size_t ilhs, size_t irhs) const
void ColoredPrintf(GTestColor color, const char *fmt,...)
Result HandleSehExceptionsInMethodIfSupported(T *object, Result(T::*method)(), const char *location)
static const char *const kReservedTestSuiteAttributes[]
GTEST_DEFINE_bool_(also_run_disabled_tests, internal::BoolFromGTestEnv("also_run_disabled_tests", false),"Run disabled tests too, in addition to the tests normally being run.")
ExpectationBase(const char *file, int line, const string &source_text)
virtual void OnEnvironmentsSetUpStart(const UnitTest &unit_test)=0
virtual void OnTestCaseEnd(const TestCase &test_case)=0
bool is_retired() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex)
void set_elapsed_time(TimeInMillis elapsed)
int Stat(const char *path, StatStruct *buf)
virtual void OnEnvironmentsSetUpEnd(const UnitTest &)
#define ADD_FAILURE()
AssertionResult DoubleNearPredFormat(const char *expr1, const char *expr2, const char *abs_error_expr, double val1, double val2, double abs_error)
static std::string GetAbsolutePathToOutputFile()
virtual void UponLeavingGTest() GTEST_LOCK_EXCLUDED_(mutex_)
Message & operator<<(const T &val)
bool SkipPrefix(const char *prefix, const char **pstr)
GTEST_API_ std::string FormatTimeInMillisAsSeconds(TimeInMillis ms)
virtual void OnTestStart(const TestInfo &test_info)=0
void set_current_test_case(TestCase *a_current_test_case)
static bool ValidateTestProperty(const std::string &xml_element, const TestProperty &test_property)
void operator=(const Message &message) const
int reportable_disabled_test_count() const
bool CreateDirectoriesRecursively() const
const TestPartResult & GetTestPartResult(int i) const
const TestProperty & GetTestProperty(int i) const
bool IsUtf16SurrogatePair(wchar_t first, wchar_t second)
internal::TearDownTestCaseFunc TearDownTestCaseFunc
void Append(TestEventListener *listener)
const char * first_used_file
static void ClearTestPartResults(TestResult *test_result)
GTEST_API_ bool ShouldShard(const char *total_shards_str, const char *shard_index_str, bool in_subprocess_for_death_test)
static void SetUpEnvironment(Environment *env)
internal::ParameterizedTestCaseRegistry & parameterized_test_registry()
void PrintStringTo(const ::std::string &s, ostream *os)
void UntypedTimes(const Cardinality &a_cardinality)
GTEST_API_ std::string CodePointToUtf8(UInt32 code_point)
#define GTEST_PATH_SEP_
const char kBreakOnFailureFlag[]
static const char kTestTotalShards[]
TestInfo * MakeAndRegisterTestInfo(const char *test_case_name, const char *name, const char *type_param, const char *value_param, TypeId fixture_class_id, SetUpTestCaseFunc set_up_tc, TearDownTestCaseFunc tear_down_tc, TestFactoryBase *factory)
static bool PatternMatchesString(const char *pattern, const char *str)
#define EXPECT_TRUE(condition)
#define GTEST_REVERSE_REPEATER_METHOD_(Name, Type)
std::string FormatForComparisonFailureMessage(const T1 &value, const T2 &)
const internal::scoped_ptr< ::std::stringstream > ss_
bool ParseBoolFlag(const char *str, const char *flag, bool *value)
name
Definition: setup.py:38
MaxBipartiteMatchState(const MatchMatrix &graph)
#define GTEST_FLAG(name)
internal::FilePath original_working_dir_
static std::string FormatByte(unsigned char value)
int reportable_test_count() const
static bool PartialMatch(const ::std::string &str, const RE &re)
spdlog::log_clock::time_point now()
Definition: os.h:64
int disabled_test_count() const
int total_test_count() const
AssertionResult HasOneFailure(const char *, const char *, const char *, const TestPartResultArray &results, TestPartResult::Type type, const string &substr)
const UInt32 kMaxCodePoint3
std::ostream & operator<<(std::ostream &os, const TestPartResult &result)
static std::vector< std::string > GetReservedAttributesForElement(const std::string &xml_element)
void ReportInvalidTestCaseType(const char *test_case_name, const char *file, int line)
OStream< ChannelType > & flush(OStream< ChannelType > &os)
Definition: stream.h:147
virtual void OnTestProgramStart(const UnitTest &)
void PushGTestTrace(const internal::TraceInfo &trace) GTEST_LOCK_EXCLUDED_(mutex_)
void CheckActionCountIfNotDone() const GTEST_LOCK_EXCLUDED_(mutex_)
static std::string FormatHexInt(int value)
static std::string FlagToEnvVar(const char *flag)
GMOCK_DEFINE_bool_(catch_leaked_mocks, true,"true iff Google Mock should report leaked mock objects ""as failures.")
GTEST_DISALLOW_COPY_AND_ASSIGN_(XmlUnitTestResultPrinter)
GTEST_API_ string JoinAsTuple(const Strings &fields)
const char kRandomSeedFlag[]
TimeInMillis start_timestamp() const
std::string StreamableToString(const T &streamable)
const int max_
virtual void SetUp()
::std::vector< ElementMatcherPair > ElementMatcherPairs
internal::ThreadLocal< TestPartResultReporterInterface * > per_thread_test_part_result_reporter_
AssertionResult(const AssertionResult &other)
const char kShuffleFlag[]
static const char kTestShardStatusFile[]
GTEST_DISALLOW_COPY_AND_ASSIGN_(HasNewFatalFailureHelper)
bool HasNonfatalFailure() const
internal::TimeInMillis TimeInMillis
bool write(ros_opcua_srvs::Write::Request &req, ros_opcua_srvs::Write::Response &res)
const char kCurrentDirectoryString[]
static CharFormat PrintAsCharLiteralTo(Char c, ostream *os)
#define GTEST_FLAG_PREFIX_DASH_
Expectation::Set::const_iterator const_iterator
const char * StringFromGTestEnv(const char *flag, const char *default_value)
int Write(int fd, const void *buf, unsigned int count)
int call_count() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex)
const internal::TypeId fixture_class_id_
void PrintBytesInObjectTo(const unsigned char *obj_bytes, size_t count, ostream *os)
void AddTestInfo(TestInfo *test_info)
virtual string CurrentStackTrace(int max_depth, int skip_count) GTEST_LOCK_EXCLUDED_(mutex_)
AssertionResult CmpHelperEQ(const char *expected_expression, const char *actual_expression, BiggestInt expected, BiggestInt actual)
void ReportUninterestingCall(CallReaction reaction, const string &msg)
bool AllPrerequisitesAreSatisfied() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex)
void set_os_stack_trace_getter(OsStackTraceGetterInterface *getter)
std::vector< Environment * > environments_
virtual void ClearDefaultActionsLocked() GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex)=0
const internal::scoped_ptr< const ::std::string > type_param_
const char kColorFlag[]
static std::string TestPropertiesAsXmlAttributes(const TestResult &result)
GTEST_DECLARE_bool_(death_test_use_fork)
static std::string FormatCountableNoun(int count, const char *singular_form, const char *plural_form)
GTEST_API_ GTEST_DEFINE_STATIC_MUTEX_(g_linked_ptr_mutex)
bool VerifyAllElementsAndMatchersAreMatched(const ::std::vector< string > &element_printouts, const MatchMatrix &matrix, MatchResultListener *listener) const
const char kPathSeparatorString[]
int test_case_to_run_count() const
const std::vector< TraceInfo > & gtest_trace_stack() const
virtual void OnTestIterationEnd(const UnitTest &unit_test, int iteration)=0
description
Definition: setup.py:43
int test_to_run_count() const
GTEST_DISALLOW_COPY_AND_ASSIGN_(TestCase)
virtual void OnTestProgramEnd(const UnitTest &unit_test)=0
TestCase * GetMutableTestCase(int i)
OsStackTraceGetterInterface * os_stack_trace_getter()
virtual void UntypedDescribeUninterestingCall(const void *untyped_args,::std::ostream *os) const GTEST_LOCK_EXCLUDED_(g_gmock_mutex)=0
void Expect(bool condition, const char *file, int line, const string &msg)
static bool ParseGoogleMockBoolFlag(const char *str, const char *flag, bool *value)
AssertionResult AssertionSuccess()
static CapturedStream * g_captured_stderr
const char kWarningVerbosity[]
TestPartResultReporterInterface * global_test_part_result_repoter_
message
Definition: server.py:50
std::tm localtime(const std::time_t &time_tt)
Definition: os.h:80
const UInt32 kMaxCodePoint1
static void LogElementMatcherPairVec(const ElementMatcherPairs &pairs,::std::ostream *stream)
const char * Name() const GTEST_LOCK_EXCLUDED_(g_gmock_mutex)
void SetOwnerAndName(const void *mock_obj, const char *name) GTEST_LOCK_EXCLUDED_(g_gmock_mutex)
AssertionResult CmpHelperSTRNE(const char *s1_expression, const char *s2_expression, const wchar_t *s1, const wchar_t *s2)
internal::ThreadLocal< std::vector< TraceInfo > > gtest_trace_stack_
std::vector< TestProperty > test_properties_
TestEventListeners & listeners()
int first_used_line
void SetDefaultXmlGenerator(TestEventListener *listener)
#define GTEST_EXCLUSIVE_LOCK_REQUIRED_(locks)
virtual void ReportTestPartResult(const TestPartResult &result)
void AddTestInfo(Test::SetUpTestCaseFunc set_up_tc, Test::TearDownTestCaseFunc tear_down_tc, TestInfo *test_info)
static const char kValueParamLabel[]
static const char kDeathTestCaseFilter[]
UInt32 Generate(UInt32 range)
AssertionResult AssertionFailure(const Message &message)
static bool CStringEquals(const char *lhs, const char *rhs)
#define GTEST_IMPL_CMP_HELPER_(op_name, op)
bool TryAugment(size_t ilhs,::std::vector< char > *seen)
int reportable_test_count() const
void RecordProperty(const TestProperty &test_property)
FilePath RemoveFileName() const
void SetTestPartResultReporterForCurrentThread(TestPartResultReporterInterface *reporter)
TestInfo(const std::string &test_case_name, const std::string &name, const char *a_type_param, const char *a_value_param, internal::TypeId fixture_class_id, internal::TestFactoryBase *factory)
static const char *const kReservedTestSuitesAttributes[]
void AddExpectation(const Expectation &expectation) const
int successful_test_count() const
std::string GetCurrentOsStackTraceExceptTop(UnitTest *, int skip_count)
GTEST_API_ void ParseGoogleTestFlagsOnly(int *argc, wchar_t **argv)
GTEST_API_ const TypeId kTestTypeIdInGoogleTest
void InitGoogleMockImpl(int *argc, CharType **argv)
int Read(int fd, void *buf, unsigned int count)
static bool GTestIsInitialized()
const std::string & string() const
handle
Definition: client.py:58
GTEST_API_ void LogWithLocation(testing::internal::LogSeverity severity, const char *file, int line, const string &message)
bool CaseInsensitiveCStringEquals(const char *lhs, const char *rhs)
#define GTEST_PROJECT_URL_
static void RecordProperty(TestResult *test_result, const std::string &xml_element, const TestProperty &property)
const TestCase * GetTestCase(int i) const
TestInfo * GetMutableTestInfo(int i)
virtual void TearDown()
static void PrintColorEncoded(const char *str)
GTEST_API_ void Log(LogSeverity severity, const string &message, int stack_frames_to_skip)
::std::pair< size_t, size_t > ElementMatcherPair
AssertionResult FloatingPointLE(const char *expr1, const char *expr2, RawType val1, RawType val2)
void AddTestPartResult(const TestPartResult &test_part_result)
class GTEST_API_ testing::InSequence GTEST_ATTRIBUTE_UNUSED_
const TestCase * current_test_case() const
#define GTEST_DISALLOW_ASSIGN_(type)
void SpecifyCardinality(const Cardinality &cardinality)
internal::ParameterizedTestCaseRegistry & parameterized_test_registry() GTEST_LOCK_EXCLUDED_(mutex_)
static std::string FormatTestCaseCount(int test_case_count)
GMOCK_DEFINE_string_(verbose, internal::kWarningVerbosity,"Controls how verbose Google Mock's output is."" Valid values:\n"" info - prints all messages.\n"" warning - prints warnings and errors.\n"" error - prints errors only.")
int StrCaseCmp(const char *s1, const char *s2)
GTEST_API_ string FormatMatcherDescription(bool negation, const char *matcher_name, const Strings &param_values)
bool HasFatalFailure() const
UInt32 CreateCodePointFromUtf16SurrogatePair(wchar_t first, wchar_t second)
void RegisterOwner(const void *mock_obj) GTEST_LOCK_EXCLUDED_(g_gmock_mutex)
static void OutputXmlAttribute(std::ostream *stream, const std::string &element_name, const std::string &name, const std::string &value)
FilePath RemoveTrailingPathSeparator() const
#define GMOCK_FLAG(name)
ScopedTrace(const char *file, int line, const Message &message)
bool ParseStringFlag(const char *str, const char *flag, std::string *value)
const char * value_param() const
std::string GetString() const
#define GTEST_HAS_PARAM_TEST
int failed_test_count() const
static const char kUniversalFilter[]
bool IsDir(const StatStruct &st)
AssertionResult IsSubstring(const char *needle_expr, const char *haystack_expr, const char *needle, const char *haystack)
GTEST_API_ FilePath GetCurrentExecutableName()
bool IsPrintableAscii(wchar_t c)
static const char * ParseGoogleMockFlagValue(const char *str, const char *flag, bool def_optional)
int test_to_run_count() const
GTEST_API_ TimeInMillis GetTimeInMillis()
bool Failed() const
AssertionResult CmpHelperSTRCASEEQ(const char *expected_expression, const char *actual_expression, const char *expected, const char *actual)
int total_test_case_count() const
static void PrintOnOneLine(const char *str, int max_length)
static std::string FormatTestCount(int test_count)
virtual void ReportTestPartResult(const TestPartResult &result)
const TestInfo * current_test_info() const
internal::TestFactoryBase *const factory_
static std::string RemoveInvalidXmlCharacters(const std::string &str)
void ShuffleTests(internal::Random *random)
bool Passed() const
void CaptureStream(int fd, const char *stream_name, CapturedStream **stream)
const char * test_case_name() const
Expectation GetHandleOf(ExpectationBase *exp)
static bool TestPartFatallyFailed(const TestPartResult &result)
const TestCase * GetTestCase(int i) const
const TestPartResult & GetTestPartResult(int index) const
const TestInfo * current_test_info() const GTEST_LOCK_EXCLUDED_(mutex_)
const char kRepeatFlag[]
static const char *const kReservedTestCaseAttributes[]
static std::string EscapeXmlText(const char *str)
virtual void OnEnvironmentsTearDownEnd(const UnitTest &unit_test)=0
static FilePath GenerateUniqueFileName(const FilePath &directory, const FilePath &base_name, const char *extension)
GTEST_API_ std::string WideStringToUtf8(const wchar_t *str, int num_chars)
GTEST_API_ Cardinality Between(int min, int max)
const char * ParseFlagValue(const char *str, const char *flag, bool def_optional)
GTEST_API_::std::string FormatCompilerIndependentFileLocation(const char *file, int line)
void Retire() GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex)
internal::scoped_ptr< ::std::string > message_
const TestResult & ad_hoc_test_result() const
const char kStackTraceMarker[]
static void PrintTestPartResult(const TestPartResult &test_part_result)
int test_property_count() const
FILE * FDOpen(int fd, const char *mode)
wchar_t type_
Definition: format.cc:302
void ShuffleRange(internal::Random *random, int begin, int end, std::vector< E > *v)
GTEST_API_ bool LogIsVisible(LogSeverity severity)
bool IsSaturated() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex)
void PopGTestTrace() GTEST_LOCK_EXCLUDED_(mutex_)
std::string AppendUserMessage(const std::string &gtest_msg, const Message &user_msg)
static const char kDefaultOutputFile[]
GTEST_API_ Cardinality Exactly(int n)
static size_t GetFileSize(FILE *file)
Environment * AddEnvironment(Environment *env)
const_iterator end() const
TestCaseNameIs(const std::string &name)
static void StreamWideCharsToMessage(const wchar_t *wstr, size_t length, Message *msg)
static bool ShouldRunTestCase(const TestCase *test_case)
int reportable_disabled_test_count() const
std::vector< TestPartResult > test_part_results_
virtual void OnTestIterationEnd(const UnitTest &unit_test, int iteration)
int CountIf(const Container &c, Predicate predicate)
int disabled_test_count() const
internal::NamedArg< char > arg(StringRef name, const T &arg)
Definition: format.h:3918
void AddTestPartResult(TestPartResult::Type result_type, const char *file_name, int line_number, const std::string &message, const std::string &os_stack_trace) GTEST_LOCK_EXCLUDED_(mutex_)
internal::UnitTestImpl * impl()
const char kStackTraceDepthFlag[]
const char * GetAnsiColorCode(GTestColor color)
virtual const ExpectationBase * UntypedFindMatchingExpectation(const void *untyped_args, const void **untyped_action, bool *is_excessive,::std::ostream *what,::std::ostream *why) GTEST_LOCK_EXCLUDED_(g_gmock_mutex)=0
const char kCatchExceptionsFlag[]
GTEST_API_ Cardinality AnyNumber()
OsStackTraceGetterInterface * os_stack_trace_getter_
bool operator()(const TestProperty &test_property) const
const_iterator begin() const
static void ClearTestCaseResult(TestCase *test_case)
internal::TestEventRepeater * repeater_
void InitGoogleTestImpl(int *argc, CharType **argv)
int Run() GTEST_MUST_USE_RESULT_
void UniversalPrintArray(const char *begin, size_t len, ostream *os)
void ParseGoogleTestFlagsOnlyImpl(int *argc, CharType **argv)
int FilterTests(ReactionToSharding shard_tests)
long getpagesize()
Definition: posix.cc:227
void Assert(bool condition, const char *file, int line)
AssertionResult EqFailure(const char *expected_expression, const char *actual_expression, const std::string &expected_value, const std::string &actual_value, bool ignoring_case)
virtual void UntypedPrintArgs(const void *untyped_args,::std::ostream *os) const =0
TestEventListeners * listeners()
TestEventListener * Release(TestEventListener *listener)
DefaultPerThreadTestPartResultReporter default_per_thread_test_part_result_reporter_
static std::string FormatWordList(const std::vector< std::string > &words)
GTEST_API_ void ParseGoogleTestFlagsOnly(int *argc, char **argv)
#define GTEST_NAME_
virtual void ReportTestPartResult(const TestPartResult &result)=0
GTEST_API_ ElementMatcherPairs FindMaxBipartiteMatching(const MatchMatrix &g)
static bool HasSameFixtureClass()
void Shuffle(internal::Random *random, std::vector< E > *v)
virtual void OnTestCaseStart(const TestCase &test_case)=0
std::string GetBoolAssertionFailureMessage(const AssertionResult &assertion_result, const char *expression_text, const char *actual_predicate_value, const char *expected_predicate_value)
int successful_test_count() const
int total_test_count() const
::std::string first_used_test
static const char kTestShardIndex[]
virtual void OnEnvironmentsTearDownEnd(const UnitTest &)
virtual void OnTestPartResult(const TestPartResult &test_part_result)=0
#define GTEST_PATH_MAX_
::std::vector< string > Strings
std::vector< TraceInfo > & gtest_trace_stack()
static bool TestCasePassed(const TestCase *test_case)
StateMap states_
virtual void OnEnvironmentsSetUpEnd(const UnitTest &unit_test)=0
#define GTEST_FLAG_PREFIX_
const TestPartResultArray *const results_
static const char kColorEncodedHelpMessage[]
int total_part_count() const
AssertionResult operator!() const
static const char *const kElidedFramesMarker
static void TearDownEnvironment(Environment *env)
void PrintWideStringTo(const ::std::wstring &s, ostream *os)
virtual void OnTestEnd(const TestInfo &test_info)=0
virtual void OnTestProgramStart(const UnitTest &unit_test)=0
AssertionResult DoubleLE(const char *expr1, const char *expr2, double val1, double val2)
const UInt32 kMaxCodePoint4
virtual void ReportFailure(FailureType type, const char *file, int line, const string &message)
bool VerifyAndClearExpectationsLocked() GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex)
void InitGoogleTest(int *argc, char **argv)
int failed_test_case_count() const
int successful_test_case_count() const
Int32 Int32FromGTestEnv(const char *flag, Int32 default_value)
TimeInMillis elapsed_time() const
FMT_API int fprintf(std::FILE *f, CStringRef format, ArgList args)
Definition: format.cc:891
std::string g_executable_path
const TestResult * result() const
Definition: format.cc:81
AssertionResult IsNotSubstring(const char *needle_expr, const char *haystack_expr, const char *needle, const char *haystack)
static UnitTest * GetInstance()
#define GTEST_DEV_EMAIL_
void Append(const TestPartResult &result)
static bool IsPathSeparator(char c)
GTEST_DEFINE_string_(internal_run_death_test,"","Indicates the file, line number, temporal index of ""the single death test to run, and a file descriptor to ""which a success code may be sent, all separated by ""the '|' characters. This flag is specified if and only if the current ""process is a sub-process launched for running a thread-safe ""death test. FOR INTERNAL USE ONLY.")
int random_seed() const
const UInt32 kMaxCodePoint2
static void PrintTestName(const char *test_case, const char *test)
const internal::GTestFlagSaver *const gtest_flag_saver_
const char * type_param() const
std::string GetCapturedStream(CapturedStream **captured_stream)
TypeWithSize< 8 >::Int TimeInMillis
static void OutputXmlTestInfo(::std::ostream *stream, const char *test_case_name, const TestInfo &test_info)
DefaultGlobalTestPartResultReporter default_global_test_part_result_reporter_
static bool TestCaseFailed(const TestCase *test_case)
void ForEach(const Container &c, Functor functor)
FilePath RemoveDirectoryName() const
bool leakable
static void RecordProperty(const std::string &key, const std::string &value)
const TestResult & ad_hoc_test_result() const
#define GTEST_CHECK_(condition)
static bool FilterMatchesTest(const std::string &test_case_name, const std::string &test_name)
const char * GetEnv(const char *name)
GTEST_API_ Int32 Int32FromEnvOrDie(const char *env_var, Int32 default_val)
virtual void TestBody()=0
TimeInMillis elapsed_time() const
static std::string FormatIntWidth2(int value)
void WriteToShardStatusFileIfNeeded()
#define GTEST_FLAG_PREFIX_UPPER_
virtual UntypedActionResultHolderBase * UntypedPerformDefaultAction(const void *untyped_args, const string &call_description) const =0
TestPartResultReporterInterface * old_reporter_
const Cardinality & cardinality() const
void DescribeCallCountTo(::std::ostream *os) const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex)
static std::string ShowWideCString(const wchar_t *wide_c_str)
bool IsOverSaturated() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex)
const char kUnknownFile[]
static const size_t kUnused
const char kOutputFlag[]
#define GTEST_LOG_(severity)
static bool MatchesFilter(const std::string &name, const char *filter)
std::vector< std::string > ArrayAsVector(const char *const (&array)[kSize])
const TestCase * current_test_case() const GTEST_LOCK_EXCLUDED_(mutex_)
internal::ParameterizedTestCaseRegistry parameterized_test_registry_
static void PrintCharsAsStringTo(const CharType *begin, size_t len, ostream *os)
static bool HasNonfatalFailure()
const char kPrintTimeFlag[]
FunctionMockers function_mockers
const char kThrowOnFailureFlag[]
void PrintTo(const ReferenceWrapper< T > &ref,::std::ostream *os)
bool ValidateTestPropertyName(const std::string &property_name, const std::vector< std::string > &reserved_names)
std::string name_
static bool ParseGoogleMockStringFlag(const char *str, const char *flag, std::string *value)
void Append(TestEventListener *listener)
static std::string PrintTestPartResultToString(const TestPartResult &test_part_result)
static void Delete(T *x)
#define GTEST_REPEATER_METHOD_(Name, Type)
GTEST_API_ bool ParseInt32Flag(const char *str, const char *flag, Int32 *value)
FilePath original_working_dir_
::std::string first_used_test_case
GTEST_DEFINE_string_(color, internal::StringFromGTestEnv("color","auto"),"Whether to use colors in the output. Valid values: yes, no, ""and auto. 'auto' means to use colors if the output is ""being sent to a terminal and the TERM environment variable ""is set to a terminal type that supports colors.")
virtual void OnTestProgramEnd(const UnitTest &)
#define GTEST_LOCK_EXCLUDED_(locks)
AssertionResult FloatLE(const char *expr1, const char *expr2, float val1, float val2)
std::string CurrentOsStackTraceExceptTop(int skip_count) GTEST_NO_INLINE_
void printf(BasicWriter< Char > &w, BasicCStringRef< Char > format, ArgList args)
Definition: format.h:3723
static void UniversalPrintCharArray(const CharType *begin, size_t len, ostream *os)
static void OutputXmlCDataSection(::std::ostream *stream, const char *data)
TimeInMillis elapsed_time() const
static const char kTypeParamLabel[]


ros_opcua_impl_freeopcua
Author(s): Denis Štogl
autogenerated on Tue Jan 19 2021 03:06:06